retry_ut.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "retry.h"
  2. #include <library/cpp/testing/unittest/registar.h>
  3. using namespace NYql;
  4. namespace {
  5. class TMyError : public yexception {
  6. };
  7. }
  8. Y_UNIT_TEST_SUITE(TRetryTests) {
  9. Y_UNIT_TEST(ZeroAttempts) {
  10. auto r = WithRetry<TMyError>(0,
  11. []() { return TString("abc"); },
  12. [](auto, auto, auto) { UNIT_FAIL("Exception handler invoked"); });
  13. UNIT_ASSERT_VALUES_EQUAL("abc", r);
  14. }
  15. Y_UNIT_TEST(NoRetries) {
  16. auto r = WithRetry<TMyError>(5,
  17. []() { return TString("abc"); },
  18. [](auto, auto, auto) { UNIT_FAIL("Exception handler invoked"); });
  19. UNIT_ASSERT_VALUES_EQUAL("abc", r);
  20. }
  21. Y_UNIT_TEST(NoRetriesButException) {
  22. UNIT_ASSERT_EXCEPTION_CONTAINS(WithRetry<TMyError>(5,
  23. []() { throw yexception() << "xxxx"; },
  24. [](auto, auto, auto) { UNIT_FAIL("Exception handler invoked"); }), yexception, "xxxx");
  25. }
  26. Y_UNIT_TEST(FewRetries) {
  27. int counter = 0;
  28. int exceptions = 0;
  29. auto r = WithRetry<TMyError>(3, [&]() {
  30. if (counter++ < 2) {
  31. throw TMyError() << "yyyy";
  32. }
  33. return counter;
  34. }, [&](const auto& e, int attempt, int attemptCount) {
  35. ++exceptions;
  36. UNIT_ASSERT_VALUES_EQUAL(e.what(), "yyyy");
  37. UNIT_ASSERT_VALUES_EQUAL(attempt, counter);
  38. UNIT_ASSERT_VALUES_EQUAL(attemptCount, 3);
  39. });
  40. UNIT_ASSERT_VALUES_EQUAL(2, exceptions);
  41. UNIT_ASSERT_VALUES_EQUAL(3, r);
  42. UNIT_ASSERT_VALUES_EQUAL(3, counter);
  43. }
  44. Y_UNIT_TEST(ManyRetries) {
  45. int counter = 0;
  46. int exceptions = 0;
  47. UNIT_ASSERT_EXCEPTION_CONTAINS(WithRetry<TMyError>(3, [&]() {
  48. throw TMyError() << "yyyy" << counter++;
  49. }, [&](const auto& e, int attempt, int attemptCount) {
  50. ++exceptions;
  51. UNIT_ASSERT_STRING_CONTAINS(e.what(), "yyyy");
  52. UNIT_ASSERT_VALUES_EQUAL(attempt, counter);
  53. UNIT_ASSERT_VALUES_EQUAL(attemptCount, 3);
  54. }), TMyError, "yyyy2");
  55. UNIT_ASSERT_VALUES_EQUAL(2, exceptions);
  56. UNIT_ASSERT_VALUES_EQUAL(3, counter);
  57. }
  58. }