-
Notifications
You must be signed in to change notification settings - Fork 3
/
RetryOnTestException.php
94 lines (77 loc) · 2.24 KB
/
RetryOnTestException.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace League\Flysystem\AdapterTestUtilities;
use const PHP_EOL;
use const STDOUT;
use League\Flysystem\FilesystemException;
use Throwable;
/**
* @codeCoverageIgnore
*/
trait RetryOnTestException
{
/**
* @var string
*/
protected $exceptionTypeToRetryOn;
/**
* @var int
*/
protected $timeoutForExceptionRetry = 2;
protected function retryOnException(string $className, int $timout = 2): void
{
$this->exceptionTypeToRetryOn = $className;
$this->timeoutForExceptionRetry = $timout;
}
protected function retryScenarioOnException(string $className, callable $scenario, int $timeout = 2): void
{
$this->retryOnException($className, $timeout);
$this->runScenario($scenario);
}
protected function dontRetryOnException(): void
{
$this->exceptionTypeToRetryOn = null;
}
/**
* @internal
*
* @throws Throwable
*/
protected function runSetup(callable $scenario): void
{
$previousException = $this->exceptionTypeToRetryOn;
$previousTimeout = $this->timeoutForExceptionRetry;
$this->retryOnException(FilesystemException::class);
try {
$this->runScenario($scenario);
} finally {
$this->exceptionTypeToRetryOn = $previousException;
$this->timeoutForExceptionRetry = $previousTimeout;
}
}
protected function runScenario(callable $scenario): void
{
if ($this->exceptionTypeToRetryOn === null) {
$scenario();
return;
}
$firstTryAt = \time();
$lastTryAt = $firstTryAt + 60;
while (time() <= $lastTryAt) {
try {
$scenario();
return;
} catch (Throwable $exception) {
if ( ! $exception instanceof $this->exceptionTypeToRetryOn) {
throw $exception;
}
fwrite(STDOUT, 'Retrying ...' . PHP_EOL);
sleep($this->timeoutForExceptionRetry);
}
}
$this->exceptionTypeToRetryOn = null;
if (isset($exception) && $exception instanceof Throwable) {
throw $exception;
}
}
}