HelpersTest.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace STS\Backoff;
  3. use PHPUnit\Framework\TestCase;
  4. use STS\Backoff\Strategies\ConstantStrategy;
  5. class HelpersTest extends TestCase
  6. {
  7. public function testSuccessWithDefaults()
  8. {
  9. $result = backoff(function() {
  10. return "success";
  11. });
  12. $this->assertEquals("success", $result);
  13. }
  14. public function testFailureWithDefaults()
  15. {
  16. $this->expectException(\Exception::class);
  17. $this->expectExceptionMessage("failure");
  18. backoff(function() {
  19. throw new \Exception("failure");
  20. }, 2);
  21. }
  22. public function testStrategy()
  23. {
  24. $start = microtime(true);
  25. // We're going to run a test for 100 attempts, just to verify we were able to
  26. // set our own strategy with a low sleep time.
  27. try {
  28. backoff(function() {
  29. throw new \Exception("failure");
  30. }, 100, new ConstantStrategy(1));
  31. } catch(\Exception $e) {}
  32. $end = microtime(true);
  33. $elapsedMS = ($end - $start) * 1000;
  34. // We expect that this took just a bit over the 100ms that we slept
  35. $this->assertTrue($elapsedMS > 100 && $elapsedMS < 200);
  36. }
  37. public function testWaitCap()
  38. {
  39. $start = microtime(true);
  40. // We're going to specify a really long sleep time, but with a short cap to override.
  41. try {
  42. backoff(function() {
  43. throw new \Exception("failure");
  44. }, 2, new ConstantStrategy(100000), 100);
  45. } catch(\Exception $e) {}
  46. $end = microtime(true);
  47. $elapsedMS = ($end - $start) * 1000;
  48. // We expect that this took just a bit over the 100ms that we slept
  49. $this->assertTrue($elapsedMS > 90 && $elapsedMS < 150,
  50. sprintf("Expected elapsedMS between 90 & 200, got: $elapsedMS\n"));
  51. }
  52. }