【发布时间】:2016-06-02 13:14:02
【问题描述】:
我想模拟一个用于初始化类级(而非实例)属性的模块级函数。这是一个简化的示例:
# a.py
def fn():
return 'asdf'
class C:
cls_var = fn()
这是一个试图模拟 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'
我相信问题出在where to patch,但我已经尝试了两种导入变体,但都没有运气。我什至尝试将 import 语句移动到 test_mock_fn() 中,以便模拟的 a.fn() 在 a.C 进入范围之前“存在” - 不,仍然失败。
任何见解将不胜感激!
【问题讨论】:
-
您是否尝试过将导入更改为使用 from 语句?从导入 fn
-
嗨 Ranier - 是的,试过了;没有运气。 (当我提到“......导入的两种变体......”时,我应该更清楚。mock 上的 Python 文档给出了使用
import a和from a import SomeClass的示例。我尝试了两种风格)
标签: python static-members python-mock class-attributes