【发布时间】:2019-11-07 20:42:09
【问题描述】:
我有一个带有装饰器的函数。装饰器接受参数,参数的值是从另一个函数调用派生的。
example.py
from cachetools import cached
from cachetools import TTLCache
from other import get_value
@cached(cache=TTLCache(maxsize=1, ttl=get_value('cache_ttl')))
def my_func():
return 'result'
其他.py
def get_value(key):
data = {
'cache_ttl': 10,
}
# Let's assume here we launch a shuttle to the space too.
return data[key]
我想模拟对get_value() 的调用。我在测试中使用了以下内容:
example_test.py
import mock
import pytest
from example import my_func
@pytest.fixture
def mock_get_value():
with mock.patch(
"example.get_value",
autospec=True,
) as _mock:
yield _mock
def test_my_func(mock_get_value):
assert my_func() == 'result'
在这里,我将mock_get_value 注入到 test_my_func。但是,由于我的装饰器在第一次导入时被调用,get_value() 会立即被调用。知道是否有办法在使用 pytest 立即导入模块之前模拟对 get_value() 的调用?
【问题讨论】:
标签: python module mocking pytest decorator