小编Nei*_*ais的帖子

使用Python mock监视对现有对象的调用

我正在使用Python模拟模块进行测试.我想用模拟替换活动对象,并自动将对模拟对象的所有调用转发到原始对象.我认为这在标准测试术语中被称为"间谍".目前我正在测试中:

# Insert a mock replacement
orig_active_attr = server.active_attr
server.active_attr = mock.Mock()

# Set up side effects to 'proxy' to the original object
server.active_attr.meth1.side_effect = orig_active_attr.meth1
server.active_attr.meth2.side_effect = orig_active_attr.meth2

# Call the method being tested
server.method_being_tested()

# Assert stuff on the mock.
server.active_attr.meth2.assert_called_once()
Run Code Online (Sandbox Code Playgroud)

如果模拟的所有方法调用都可以在没有样板的情况下自动转发到活动对象,那将是很好的.

python unit-testing mocking

28
推荐指数
2
解决办法
1万
查看次数

使用Python Mock库监视内部方法调用

我正在使用Python模拟模块进行测试.我想监视由活动对象进行的内部方法调用.我发现'wraps'kwarg可用于设置一个模拟,该模拟侦测对活动对象的方法调用:

使用Python mock监视对现有对象的调用

但这不适用于内部呼叫.我想用它来测试更高级别的方法以正确的顺序调用低级方法.

鉴于:

class ClassUnderTest(object):
    def lower_1(self):
        print 'lower_1'

    def lower_2(self):
        print 'lower_2'

    def higher(self):
        self.lower_1()
        self.lower_2()
Run Code Online (Sandbox Code Playgroud)

我想能够测试它

import mock

DUT = ClassUnderTest()
mock_DUT = mock.Mock(wraps=DUT)
# test call
mock_DUT.higher()

# Assert that lower_1 was called before lower_2
assert mock_DUT.mock_calls[1:] = [mock.call.lower_1(), mock.call.lower_2()]
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为'self'参数更高()绑定到原始DUT对象,而不是mock_DUT间谍.因此,只有初始的high()调用被记录到mock_calls.有没有一种方便的方法来使用python mock模块执行这种断言?

python unit-testing mocking

6
推荐指数
1
解决办法
4468
查看次数

标签 统计

mocking ×2

python ×2

unit-testing ×2