【问题标题】:mocking/patching the value of a computed attribute from a classmethod从类方法模拟/修补计算属性的值
【发布时间】:2020-08-06 15:15:18
【问题描述】:

我正在尝试为调用对象的类方法的函数编写测试——该类方法继续返回该类的新实例。

在 stackoverflow 和其他地方都有很多修补类属性的示例,但我很难理解如何修补属性/值以便我可以测试我的功能。我已经提到了this的答案。

本质上,我正在尝试修补 Foo 实例的属性 xxxx(在 myFn 内),以便我可以测试/断言调用 some_other_function() 的后续值

下面的代码是独立的“可运行”问题:我收到 AttributeError: Foo 没有属性“xxxx”

import time
import unittest
from unittest.mock import patch, PropertyMock

class Foo(object):
    def __init__(self, xxxx):
        """long running task"""
        time.sleep(5)
        self.xxxx = xxxx

    @classmethod
    def get(cls):
        """also a long running task"""
        time.sleep(5)
        xxxx = 555
        return cls(xxxx)

def myFn():
    v = Foo.get().xxxx
    # the patched `xxxx` should be 666 at this point
    return some_other_function(v)

class Test(unittest.TestCase):

    @patch('__main__.Foo', autospec=True)
    def test_myFn(self, mock_Foo):
        with patch('__main__.Foo.xxxx', new_callable=PropertyMock, return_value=666):
            x = myFn()
            self.assertEqual(x, 666)

if __name__ == '__main__':
    unittest.main()

非常感谢任何人的帮助!

【问题讨论】:

    标签: python unit-testing mocking patch


    【解决方案1】:

    您应该使用create 参数,该参数将在属性不存在时强制创建:

    def test_myFn(self):
        with patch('__main__.xxxx', new_callable=PropertyMock, create=True, return_value=666):
            x = myFn()
            self.assertEqual(666,x)
    

    【讨论】:

    • 谢谢。这是我错过的创作
    猜你喜欢
    • 2020-06-17
    • 2018-11-10
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多