我正在编写单元测试,并希望禁用坚韧,我以前曾经能够禁用坚韧时,它的装饰:
@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一起使用时,有什么正确的方法来禁用坚韧呢?
发布于 2022-09-29 05:24:20
建议在你的测试中包括坚韧。只是假装坚韧不拔的睡眠,比如:
@pytest.fixture(autouse=True)
def tenacity_wait(mocker):
mocker.patch('tenacity.nap.time')您可以将它添加到单元测试的根文件夹中的conftest.py中。
https://stackoverflow.com/questions/73034657
复制相似问题