-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathSpeedTrapListener.php
More file actions
300 lines (253 loc) · 7.78 KB
/
SpeedTrapListener.php
File metadata and controls
300 lines (253 loc) · 7.78 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
declare(strict_types=1);
namespace JohnKary\PHPUnit\Listener;
use PHPUnit\Framework\{TestListener, TestListenerDefaultImplementation, TestSuite, Test, TestCase};
use PHPUnit\Util\Test as TestUtil;
/**
* A PHPUnit TestListener that exposes your slowest running tests by outputting
* results directly to the console.
*/
class SpeedTrapListener implements TestListener
{
use TestListenerDefaultImplementation;
/**
* Slowness profiling enabled by default. Set to false to disable profiling
* and reporting.
*
* Use environment variable "PHPUNIT_SPEEDTRAP" set to value "disabled" to
* disable profiling.
*
* @var boolean
*/
protected $enabled = true;
/**
* Internal tracking for test suites.
*
* Increments as more suites are run, then decremented as they finish. All
* suites have been run when returns to 0.
*/
protected $suites = 0;
/**
* Test execution time (milliseconds) after which a test will be considered
* "slow" and be included in the slowness report.
*
* @var int
*/
protected $slowThreshold;
/**
* Number of tests to print in slowness report.
*
* @var int
*/
protected $reportLength;
/**
* Whether the test runner should halt running additional tests after
* finding a slow test.
*
* @var bool
*/
protected $stopOnSlow;
/**
* Collection of slow tests.
* Keys (string) => Printable label describing the test
* Values (int) => Test execution time, in milliseconds
*/
protected $slow = [];
/**
* Total test execution time so far, in milliseconds
* @var int
*/
protected $totalTime = 0;
public function __construct(array $options = [])
{
$this->enabled = getenv('PHPUNIT_SPEEDTRAP') === 'disabled' ? false : true;
$this->loadOptions($options);
}
/**
* A test ended.
*
* @param Test $test
* @param float $time
*/
public function endTest(Test $test, float $time): void
{
if (!$this->enabled) return;
if (!$test instanceof TestCase) return;
$timeInMilliseconds = $this->toMilliseconds($time);
$threshold = $this->getSlowThreshold($test);
if ($this->isSlow($timeInMilliseconds, $threshold)) {
$this->addSlowTest($test, $timeInMilliseconds);
}
$this->totalTime += $timeInMilliseconds;
}
/**
* A test suite started.
*
* @param TestSuite $suite
*/
public function startTestSuite(TestSuite $suite): void
{
if (!$this->enabled) return;
$this->suites++;
}
/**
* A test suite ended.
*
* @param TestSuite $suite
*/
public function endTestSuite(TestSuite $suite): void
{
if (!$this->enabled) return;
$this->suites--;
if (0 === $this->suites && $this->hasSlowTests()) {
arsort($this->slow); // Sort longest running tests to the top
$this->renderHeader();
$this->renderBody();
$this->renderAnyHiddenSlowTest();
$this->renderStats();
}
}
/**
* Whether the given test execution time is considered slow.
*
* @param int $time Test execution time in milliseconds
* @param int $slowThreshold Test execution time at which a test should be considered slow, in milliseconds
*/
protected function isSlow(int $time, int $slowThreshold): bool
{
return $slowThreshold && $time >= $slowThreshold;
}
/**
* Stores a test as slow.
*/
protected function addSlowTest(TestCase $test, int $time)
{
$label = $this->makeLabel($test);
$this->slow[$label] = $time;
if ($this->stopOnSlow) {
$test->getTestResultObject()->stop();
}
}
/**
* Whether at least one test has been considered slow.
*/
protected function hasSlowTests(): bool
{
return !empty($this->slow);
}
/**
* Convert PHPUnit's reported test time (microseconds) to milliseconds.
*/
protected function toMilliseconds(float $time): int
{
return (int) round($time * 1000);
}
/**
* Label describing a slow test case. Formatted to support copy/paste with
* PHPUnit's --filter CLI option:
*
* vendor/bin/phpunit --filter 'JohnKary\\PHPUnit\\Listener\\Tests\\SomeSlowTest::testWithDataProvider with data set "Rock"'
*/
protected function makeLabel(TestCase $test): string
{
return sprintf('%s::%s', addslashes(get_class($test)), $test->getName());
}
/**
* Calculate number of tests to include in slowness report.
*/
protected function getReportLength(): int
{
return min(count($this->slow), $this->reportLength);
}
/**
* Calculate number of slow tests to be hidden from the slowness report
* due to list length.
*/
protected function getHiddenCount(): int
{
$total = count($this->slow);
$showing = $this->getReportLength();
$hidden = 0;
if ($total > $showing) {
$hidden = $total - $showing;
}
return $hidden;
}
/**
* Renders slowness report header.
*/
protected function renderHeader()
{
echo sprintf("\n\nYou should really speed up these slow tests (>%sms)...\n", $this->slowThreshold);
}
/**
* Renders slowness report body.
*/
protected function renderBody()
{
$slowTests = $this->slow;
$length = $this->getReportLength();
for ($i = 1; $i <= $length; ++$i) {
$label = key($slowTests);
$time = array_shift($slowTests);
echo sprintf(" %s. %sms to run %s\n", $i, $time, $label);
}
}
/**
* Renders slowness report footer.
*/
protected function renderAnyHiddenSlowTest()
{
if ($hidden = $this->getHiddenCount()) {
printf("...and there %s %s more above your threshold hidden from view\n", $hidden == 1 ? 'is' : 'are', $hidden);
}
}
/**
* Populate options into class internals.
*/
protected function loadOptions(array $options)
{
$this->slowThreshold = $options['slowThreshold'] ?? 500;
$this->reportLength = $options['reportLength'] ?? 10;
$this->stopOnSlow = $options['stopOnSlow'] ?? false;
}
/**
* Calculate slow test threshold for given test. A TestCase may override the
* suite-wide slowness threshold by using the annotation {@slowThreshold}
* with a threshold value in milliseconds.
*
* For example, the following test would be considered slow if its execution
* time meets or exceeds 5000ms (5 seconds):
*
* <code>
* \@slowThreshold 5000
* public function testLongRunningProcess() {}
* </code>
*/
protected function getSlowThreshold(TestCase $test): int
{
$ann = TestUtil::parseTestMethodAnnotations(
get_class($test),
$test->getName(false)
);
return isset($ann['method']['slowThreshold'][0]) ? (int) $ann['method']['slowThreshold'][0] : $this->slowThreshold;
}
private function renderStats(): void
{
$totalSlowTimeMs = array_sum($this->slow);
$totalFastTimeMs = $this->totalTime - $totalSlowTimeMs;
$totalFastTimeSeconds = $totalFastTimeMs / 1000;
$totalSlowTimeSeconds = $totalSlowTimeMs / 1000;
echo PHP_EOL;
printf(
" Fast tests: %.1f seconds (%.2f%%)\n",
$totalFastTimeSeconds,
100 * $totalFastTimeMs / $this->totalTime
);
printf(
" Slow tests: %.1f seconds (%.2f%%)\n",
$totalSlowTimeSeconds,
100 * $totalSlowTimeMs / $this->totalTime
);
}
}