【发布时间】:2018-01-09 13:14:21
【问题描述】:
我有一个函数,我正在编写使用 pytest 的单元测试。唯一的问题是,由于我正在为同一个函数编写多个测试,因此有几个测试由于 cachetools.ttl_cache 装饰器而失败。这个装饰器使函数每次运行时都返回相同的值,这会弄乱测试。这个装饰器不存在于我正在测试的函数中,而是存在于由我正在测试的函数调用的函数中。我无法从我正在测试的函数中删除这个装饰器。这是测试:
@patch('load_balancer.model_helpers.DBSession')
def test_returns_true_if_split_test_is_external(self, dbsession, group_ctx):
group_ctx.group_id = '{}-{}'.format('2222222222', '123456789')
split_test = Mock()
split_test.state = 'external'
config = {
'query.return_value.filter.return_value.first.return_value': split_test
}
dbsession.configure_mock(**config)
assert group_ctx.is_in_variation_group('foo') == True
这里是要测试的功能:
def is_in_variation_group(self, split_test=None):
try:
split_test = get_split_test(split_test) # This function has the
#decorator
log.info('Split test {} is set to {}'.format(split_test.name,
split_test.state))
if not split_test or split_test.state == 'off':
return False
phone_number = int(self.group_id.split('-')[0])
if split_test.state == 'internal':
return True if str(phone_number) in INTERNAL_GUINEA_PIGS else False
if split_test.state == 'external':
return True if phone_number % 2 == 0 else False
except Exception as e:
log.warning("A {} occurred while evaluating membership into {}'s variation "
"group".format(e.__class__.__name__, split_test))
获取拆分测试函数:
@cachetools.ttl_cache(maxsize=1024, ttl=60)
def get_split_test(name):
return (DBSession.query(SplitTest)
.filter(SplitTest.name == name)
.first())
我怎样才能让这个缓存装饰器被忽略?非常感谢任何帮助
【问题讨论】:
-
我认为您需要在运行测试之前修补
cachetools并将ttl_cache替换为不缓存任何内容的函数。
标签: python unit-testing mocking pytest