【问题标题】:Python mock class instance variablePython模拟类实例变量
【发布时间】:2013-07-17 21:02:21
【问题描述】:

我正在使用 Python 的 mock 库。我知道如何按照document 模拟类实例方法:

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'

但是,尝试模拟类实例变量但不起作用(以下示例中的instance.labels):

>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     instance.labels = [1, 1, 2, 2]
...     result = some_function()
...     assert result == 'the result'

基本上我希望instance.labelssome_function下得到我想要的值。有什么提示吗?

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    此版本的some_function() 打印模拟labels 属性:

    def some_function():
        instance = module.Foo()
        print instance.labels
        return instance.method()
    

    我的module.py

    class Foo(object):
    
        labels = [5, 6, 7]
    
        def method(self):
            return 'some'
    

    补丁和你的一样:

    with patch('module.Foo') as mock:
        instance = mock.return_value
        instance.method.return_value = 'the result'
        instance.labels = [1,2,3,4,5]
        result = some_function()
        assert result == 'the result
    

    完整的控制台会话:

    >>> from mock import patch
    >>> import module
    >>> 
    >>> def some_function():
    ...     instance = module.Foo()
    ...     print instance.labels
    ...     return instance.method()
    ... 
    >>> some_function()
    [5, 6, 7]
    'some'
    >>> 
    >>> with patch('module.Foo') as mock:
    ...     instance = mock.return_value
    ...     instance.method.return_value = 'the result'
    ...     instance.labels = [1,2,3,4,5]
    ...     result = some_function()
    ...     assert result == 'the result'
    ...     
    ... 
    [1, 2, 3, 4, 5]
    >>>
    

    对我来说,您的代码正在工作。

    【讨论】:

    • 它不起作用。我得到了与instance.labels = [1, 1, 2, 2] 相同的结果,这是some_function 没有使用这个模拟变量。在文档中,它模拟的是方法而不是变量。
    • 更新了我的答案。现在我迷路了,因为您的代码正在运行。
    • 在我的代码中,labels 仅在调用某些函数后出现。并且该函数在我要测试的函数中被调用。也许这就是原因。我最终模拟了类的初始化,以便它返回具有我想要的行为的模拟对象。
    • 我想在创建 dule.Foo 实例时引发异常。所以我尝试了 mock.side_effect 和 mock.return_value。两者都没有工作。为什么?
    • 那是一个不同的问题,没有我们可以查看的代码,但我想这个问题就是你要找的stackoverflow.com/questions/28305406/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多