在阅读了 tenacity repo 中的帖子后(感谢@DanEEStar 启动它!),我想出了以下代码:
@retry(
stop=stop_after_delay(20.0),
wait=wait_incrementing(
start=0,
increment=0.25,
),
retry=retry_if_exception_type(SomeExpectedException),
reraise=True,
)
def func() -> None:
raise SomeExpectedException()
def test_func_should_retry(monkeypatch: MonkeyPatch) -> None:
# Use monkeypatch to patch retry behavior.
# It will automatically revert patches when test finishes.
# Also, it doesn't create nested blocks as `unittest.mock.patch` does.
# Originally, it was `stop_after_delay` but the test could be
# unreasonably slow this way. After all, I don't care so much
# about which policy is applied exactly in this test.
monkeypatch.setattr(
func.retry, "stop", stop_after_attempt(3)
)
# Disable pauses between retries.
monkeypatch.setattr(func.retry, "wait", wait_none())
with pytest.raises(SomeExpectedException):
func()
# Ensure that there were retries.
stats: Dict[str, Any] = func.retry.statistics
assert "attempt_number" in stats
assert stats["attempt_number"] == 3
我pytest
在此测试中使用 - 特定功能。也许,它可以作为某人的一个例子,至少对未来的我来说是有用的。