模拟实例属性 [英] Mocking instance attributes

查看:33
本文介绍了模拟实例属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我理解为什么以下方法不起作用.特别是 - 测试类的实例属性对 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)

这篇关于模拟实例属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆