【问题标题】:Disable Tenacity for loop `for attempt in Retrying` in unit tests在单元测试中禁用循环“尝试重试”的韧性
【发布时间】: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


    【解决方案1】:

    建议在您的测试中加入韧性。 只是模拟坚韧的睡眠,例如:

    @pytest.fixture(autouse=True)
    def tenacity_wait(mocker):
        mocker.patch('tenacity.nap.time')
    

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

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 1970-01-01
      • 2015-01-25
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多