|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace igorw; |
| 4 | + |
| 5 | +class RetryTest extends \PHPUnit_Framework_TestCase |
| 6 | +{ |
| 7 | + function testRetryWithoutFailing() |
| 8 | + { |
| 9 | + $i = 0; |
| 10 | + $value = retry(1, function () use (&$i) { |
| 11 | + $i++; |
| 12 | + return 5; |
| 13 | + }); |
| 14 | + $this->assertSame(1, $i); |
| 15 | + $this->assertSame(5, $value); |
| 16 | + } |
| 17 | + |
| 18 | + function testRetryFailingOnce() |
| 19 | + { |
| 20 | + $i = 0; |
| 21 | + $failed = false; |
| 22 | + $value = retry(1, function () use (&$i, &$failed) { |
| 23 | + $i++; |
| 24 | + if (!$failed) { |
| 25 | + $failed = true; |
| 26 | + throw new \RuntimeException('roflcopter'); |
| 27 | + } |
| 28 | + return 5; |
| 29 | + }); |
| 30 | + $this->assertSame(2, $i); |
| 31 | + $this->assertSame(5, $value); |
| 32 | + } |
| 33 | + |
| 34 | + function testRetryFailingTooHard() |
| 35 | + { |
| 36 | + $e = null; |
| 37 | + $i = 0; |
| 38 | + try { |
| 39 | + retry(1, function () use (&$i) { |
| 40 | + $i++; |
| 41 | + throw new \RuntimeException('rofl'); |
| 42 | + }); |
| 43 | + } catch (\Exception $e) { |
| 44 | + } |
| 45 | + |
| 46 | + $this->assertInstanceof('igorw\FailingTooHardException', $e); |
| 47 | + $this->assertInstanceof('RuntimeException', $e->getPrevious()); |
| 48 | + $this->assertSame('rofl', $e->getPrevious()->getMessage()); |
| 49 | + $this->assertSame(2, $i); |
| 50 | + } |
| 51 | + |
| 52 | + function testRetryManyTimes() |
| 53 | + { |
| 54 | + $e = null; |
| 55 | + $i = 0; |
| 56 | + try { |
| 57 | + retry(1000, function () use (&$i, &$failed) { |
| 58 | + $i++; |
| 59 | + throw new \RuntimeException('dogecoin'); |
| 60 | + }); |
| 61 | + } catch (\Exception $e) { |
| 62 | + } |
| 63 | + |
| 64 | + $this->assertInstanceof('igorw\FailingTooHardException', $e); |
| 65 | + $this->assertInstanceof('RuntimeException', $e->getPrevious()); |
| 66 | + $this->assertSame('dogecoin', $e->getPrevious()->getMessage()); |
| 67 | + $this->assertSame(1001, $i); |
| 68 | + } |
| 69 | +} |
0 commit comments