模拟实例属性

模拟实例属性

问题描述:

请帮助我理解为什么以下方法不起作用.特别是 - 测试类的实例属性对 Python 的 unittest.Mock 不可见.

Please help me understand why the following doesn't work. In particular - instance attributes of a tested class are not visible to Python's unittest.Mock.

在下面的例子中,bar 实例属性是不可访问的.返回的错误是:

In the example below bar instance attribute is not accessible. The error returned is:

AttributeError: <class 'temp.Foo'> does not have the attribute 'bar'

import unittest
from unittest.mock import patch

class Foo:
    def __init__(self):
        super().__init__(self)
        self.bar = some_external_function_returning_list()

    def do_someting(self):
        calculate(self.bar)

class TestFoo(unittest.TestCase):

    @patch('temp.Foo.bar')
    def test_do_something(self, patched_bar):
        patched_bar.return_value = ['list_elem1', 'list_elem2']

Patching 用于修改名称或属性查找.在这种情况下,没有 bar 类的 temp.Foo 属性.

Patching is used to modify name or attribute lookup. In this case, there is no bar attribute of the class temp.Foo.

如果目的是修补 instance 变量,您要么需要一个现有的实例来修改

If the intent is to patch the instance variable, you either need an existing instance to modify

def test(self):
    f = Foo()
    with patch.object(f, 'bar', 3):
        self.assertEqual(f.bar, 3)

或者您可能想要修补首先初始化实例属性的函数调用.

or you may want to patch the function call that initializes the instance attribute in the first place.

def test(self):
    with patch('some_external_function_returning_list', return_value=3):
        f = Foo()
    self.assertEqual(f.bar, 3)