-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAsyncTestCase.php
More file actions
192 lines (157 loc) · 6.07 KB
/
AsyncTestCase.php
File metadata and controls
192 lines (157 loc) · 6.07 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<?php declare(strict_types=1);
namespace Amp\PHPUnit;
use Amp\DeferredFuture;
use Amp\Future;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
use Revolt\EventLoop;
use Revolt\EventLoop\Driver\TracingDriver;
use function Amp\async;
use function Amp\now;
abstract class AsyncTestCase extends PHPUnitTestCase
{
private const RUNTIME_PRECISION = 2;
private DeferredFuture $deferredFuture;
private string $timeoutId;
/** @var float Minimum runtime in seconds. */
private float $minimumRuntime = 0;
/** @var string Temporary storage for actual test name. */
private string $realTestName;
private bool $setUpInvoked = false;
protected function setUp(): void
{
$this->setUpInvoked = true;
$this->deferredFuture = new DeferredFuture();
EventLoop::setErrorHandler(function (\Throwable $exception): void {
if ($this->deferredFuture->isComplete()) {
return;
}
$this->deferredFuture->error(new UnhandledException($exception));
});
}
/** @internal */
final protected function runAsyncTest(mixed ...$args): mixed
{
if (!$this->setUpInvoked) {
self::fail(\sprintf(
'%s::setUp() overrides %s::setUp() without calling the parent method',
\str_replace("\0", '@', static::class), // replace NUL-byte in anonymous class name
self::class
));
}
parent::setName($this->realTestName);
$start = now();
try {
[, $returnValue] = Future\await([
$this->deferredFuture->getFuture(),
async(function () use ($args): mixed {
try {
$result = ([$this, $this->realTestName])(...$args);
if ($result instanceof Future) {
$result = $result->await();
}
// Force an extra tick of the event loop to ensure any uncaught exceptions are
// forwarded to the event loop handler before the test ends.
$deferred = new DeferredFuture();
EventLoop::defer(static fn () => $deferred->complete());
$deferred->getFuture()->await();
return $result;
} finally {
if (!$this->deferredFuture->isComplete()) {
$this->deferredFuture->complete();
}
}
}),
]);
} finally {
if (isset($this->timeoutId)) {
EventLoop::cancel($this->timeoutId);
}
\gc_collect_cycles(); // Throw from as many destructors as possible.
}
$end = now();
if ($this->minimumRuntime > 0) {
$actualRuntime = \round($end - $start, self::RUNTIME_PRECISION);
$msg = 'Expected test to take at least %0.3fs but instead took %0.3fs';
self::assertGreaterThanOrEqual(
$this->minimumRuntime,
$actualRuntime,
\sprintf($msg, $this->minimumRuntime, $actualRuntime)
);
}
return $returnValue;
}
final protected function runTest(): mixed
{
$this->realTestName = $this->name();
parent::setName('runAsyncTest');
return parent::runTest();
}
/**
* Fails the test if it does not run for at least the given amount of time.
*
* @param float $seconds Required runtime in seconds.
*/
final protected function setMinimumRuntime(float $seconds): void
{
if ($seconds <= 0) {
throw new \Error('Minimum runtime must be greater than 0, got ' . $seconds);
}
$this->minimumRuntime = \round($seconds, self::RUNTIME_PRECISION);
}
/**
* Fails the test (and stops the event loop) after the given timeout.
*
* @param float $seconds Timeout in seconds.
*/
final protected function setTimeout(float $seconds): void
{
if (isset($this->timeoutId)) {
EventLoop::cancel($this->timeoutId);
}
$this->timeoutId = EventLoop::delay($seconds, function () use ($seconds): void {
EventLoop::setErrorHandler(null);
$additionalInfo = '';
$driver = EventLoop::getDriver();
if ($driver instanceof TracingDriver) {
$additionalInfo .= "\r\n\r\n" . $driver->dump();
} else {
$additionalInfo .= "\r\n\r\nSet REVOLT_DEBUG_TRACE_WATCHERS=true as environment variable to trace watchers keeping the loop running.";
}
if ($this->deferredFuture->isComplete()) {
return;
}
try {
$this->fail(\sprintf(
'Expected test to complete before %0.3fs time limit%s',
$seconds,
$additionalInfo
));
} catch (AssertionFailedError $e) {
$this->deferredFuture->error($e);
}
});
EventLoop::unreference($this->timeoutId);
}
/**
* @param int $invocationCount Number of times the callback must be invoked or the test will fail.
* @param callable|null $returnCallback Callable providing a return value for the callback.
* @param array $expectArgs Arguments expected to be passed to the callback.
*/
final protected function createCallback(
int $invocationCount,
?callable $returnCallback = null,
array $expectArgs = [],
): \Closure {
$mock = $this->createMock(CallbackStub::class);
$invocationMocker = $mock->expects(self::exactly($invocationCount))
->method('__invoke');
if ($returnCallback) {
$invocationMocker->willReturnCallback($returnCallback);
}
if ($expectArgs) {
$invocationMocker->with(...$expectArgs);
}
return \Closure::fromCallable($mock);
}
}