【发布时间】:2022-09-29 13:24:20
【问题描述】:
我正在编写单元测试并想禁用韧性,我以前能够在装饰器时禁用韧性,即:
@retry(stop=stop_after_attempt(3),wait=wait_fixed(5))
def function_that_retries(param) -> None:
<function implementation>
和:
def test_function(self):
# disable tenacity retry
function.retry.retry = tenacity.retry_if_not_result(lambda x: True)
现在我想禁用这种循环的韧性:
@property
def is_ready(self) -> bool:
try:
for attempt in Retrying(stop=stop_after_delay(60), wait=wait_fixed(3)):
with attempt:
# The ping command is cheap and does not require auth.
self.client.admin.command(\"ping\")
except RetryError:
return False
return True
同时嘲笑self.client.admin.command 引发ConnectionFailure 错误(即我不想通过为self.client.admin.command 引发RetryError 来解决这个问题)
现在我的测试看起来像这样
class TestMongoServer(unittest.TestCase):
@patch(\"lib.charms.mongodb_libs.v0.mongodb.MongoClient\")
@patch(\"lib.charms.mongodb_libs.v0.mongodb.MongoDBConfiguration\")
def test_is_ready_error_handling(self, config, mock_client):
# TODO figure out how to disable tenacity for faster unit testing
with MongoDBConnection(config) as mongo:
mock_client.return_value.admin.command.side_effect = ConnectionFailure()
# verify ready is false when an error occurs
ready = mongo.is_ready
self.assertEqual(ready, False)
# verify we close connection
(mock_client.return_value.close).assert_called()
但它不会禁用韧度,当它与for attempt in Retrying 一起使用时,禁用韧度的正确方法是什么?
标签: python unit-testing mocking python-tenacity tenacity