Skip to content

Instantly share code, notes, and snippets.

@makasim
Last active June 3, 2022 15:42
Show Gist options
  • Save makasim/989fcaa6da8ff579f7914d973e68280c to your computer and use it in GitHub Desktop.
Save makasim/989fcaa6da8ff579f7914d973e68280c to your computer and use it in GitHub Desktop.
Phpunit. Retry tests
<?php
use PHPUnit\Framework\TestCase;
use Enqueue\Test\RetryTrait;
class FooTest extends TestCase
{
use RetryTrait;
/**
* @retry 5
*/
public function testFoo()
{
// it will be executed five times before it finaly marked as failed.
$this->fail();
}
}
<?php
namespace Enqueue\Test;
trait RetryTrait
{
public function runBare()
{
$e = null;
$numberOfRetires = $this->getNumberOfRetries();
if (false == is_numeric($numberOfRetires)) {
throw new \LogicException(sprintf('The $numberOfRetires must be a number but got "%s"', var_export($numberOfRetires, true)));
}
$numberOfRetires = (int) $numberOfRetires;
if ($numberOfRetires <= 0) {
throw new \LogicException(sprintf('The $numberOfRetires must be a positive number greater than 0 but got "%s".', $numberOfRetires));
}
for ($i = 0; $i < $numberOfRetires; ++$i) {
try {
parent::runBare();
return;
} catch (\PHPUnit_Framework_IncompleteTestError $e) {
throw $e;
} catch (\PHPUnit_Framework_SkippedTestError $e) {
throw $e;
} catch (\Throwable $e) {
// last one thrown below
} catch (\Exception $e) {
// last one thrown below
}
}
if ($e) {
throw $e;
}
}
/**
* @return int
*/
private function getNumberOfRetries()
{
$annotations = $this->getAnnotations();
if (isset($annotations['method']['retry'][0])) {
return $annotations['method']['retry'][0];
}
if (isset($annotations['class']['retry'][0])) {
return $annotations['class']['retry'][0];
}
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment