首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在单元测试中禁用循环“在重试中的尝试”的坚韧性

在单元测试中禁用循环“在重试中的尝试”的坚韧性
EN

Stack Overflow用户
提问于 2022-07-19 09:41:46
回答 1查看 117关注 0票数 0

我正在编写单元测试,并希望禁用坚韧,我以前曾经能够禁用坚韧时,它的装饰:

代码语言:javascript
复制
@retry(stop=stop_after_attempt(3),wait=wait_fixed(5))
def function_that_retries(param) -> None:
    <function implementation>

通过以下方式:

代码语言:javascript
复制
    def test_function(self):
       # disable tenacity retry
       function.retry.retry = tenacity.retry_if_not_result(lambda x: True)

现在,我想禁用循环的这种坚韧性:

代码语言:javascript
复制
    @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来绕过这一问题)

现在我的测试是这样的

代码语言:javascript
复制
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一起使用时,有什么正确的方法来禁用坚韧呢?

EN

回答 1

Stack Overflow用户

发布于 2022-09-29 05:24:20

建议在你的测试中包括坚韧。只是假装坚韧不拔的睡眠,比如:

代码语言:javascript
复制
@pytest.fixture(autouse=True)
def tenacity_wait(mocker):
    mocker.patch('tenacity.nap.time')

您可以将它添加到单元测试的根文件夹中的conftest.py中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73034657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档