Skip to content

Commit

Permalink
allow reusing the same instance of ExponentialBackoff multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
deminy committed May 5, 2023
1 parent fb5d1f0 commit 72b8937
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/ExponentialBackoff.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ public function __construct(AbstractRetryCondition $retryCondition, int $sapi =
*/
public function run(Closure $c, ...$params)
{
$this->currentAttempts = 1; // Force to reset # of current attempts.

do {
$result = $e = null;

Expand Down
18 changes: 13 additions & 5 deletions tests/unit/ExponentialBackoffTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,23 @@ public function __construct(Helper $helper)
}
public function met($result, ?Exception $e): bool
{
return $this->helper->reachExpectedAttempts();
return $this->helper->getCurrentAttempts() - 1 > $this->helper->getExpectedFailedAttempts();
}
}
),
function () use ($helper) {
return $helper->getValue();
return $helper->getValueAfterExpectedNumberOfFailedAttemptsWithEmptyReturnValuesReturned();
},
'fetch a value after 3 failed attempts through a self-defined retry function.',
],
];
}

/**
* There are two cases covered in this test:
* 1. Test successful retries with exponential backoff.
* 2. Test reusing the same instance of ExponentialBackoff multiple times.
*
* @dataProvider dataSuccessfulRetries
* @covers \CrowdStar\Backoff\ExponentialBackoff::run()
*/
Expand All @@ -88,10 +92,14 @@ public function testSuccessfulRetries(
Closure $c,
string $message
): void {
$helper->reset();
$this->assertSame(1, getCurrentAttempts($backoff), 'current iteration should be 1 (not yet started)');
$this->assertSame($helper->getValue(), $backoff->run($c), $message);
$this->assertSame(4, getCurrentAttempts($backoff), 'current iteration should be 4 (after 4 attempts)');

// Reuse the same instance of ExponentialBackoff multiple times.
for ($i = 0; $i < 2; $i++) {
$helper->reset();
$this->assertSame($helper->getValue(), $backoff->run($c), $message);
$this->assertSame(4, getCurrentAttempts($backoff), 'current iteration should be 4 (after 4 attempts)');
}
}

public function dataDelays(): array
Expand Down

0 comments on commit 72b8937

Please sign in to comment.