我想模拟一个用于初始化类级(非实例)属性的模块级函数.这是一个简化的例子:
# a.py
def fn():
return 'asdf'
class C:
cls_var = fn()
Run Code Online (Sandbox Code Playgroud)
这是一个试图模拟a.fn()的单元测试:
# test_a.py
import unittest, mock
import a
class TestStuff(unittest.TestCase):
# we want to mock a.fn so that the class variable
# C.cls_var gets assigned the output of our mock
@mock.patch('a.fn', return_value='1234')
def test_mock_fn(self, mocked_fn):
print mocked_fn(), " -- as expected, prints '1234'"
self.assertEqual('1234', a.C.cls_var) # fails! C.cls_var is 'asdf'
Run Code Online (Sandbox Code Playgroud)
我相信问题是在哪里修补,但我已尝试导入两个变种没有运气.我甚至尝试将import语句移动到test_mock_fn()中,以便在aC进入作用域之前,模拟的a.fn()将"存在" - nope仍然失败.
任何见解将不胜感激!