-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathSpeedTrap.php
More file actions
257 lines (219 loc) · 6.89 KB
/
Copy pathSpeedTrap.php
File metadata and controls
257 lines (219 loc) · 6.89 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
<?php
declare(strict_types=1);
namespace JohnKary\PHPUnit\Extension;
use PHPUnit\Runner\AfterLastTestHook;
use PHPUnit\Runner\AfterSuccessfulTestHook;
use PHPUnit\Runner\BeforeFirstTestHook;
use PHPUnit\Util\Test as TestUtil;
/**
* A PHPUnit Extension that exposes your slowest running tests by outputting
* results directly to the console.
*/
class SpeedTrap implements AfterSuccessfulTestHook, BeforeFirstTestHook, AfterLastTestHook
{
/**
* 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;
/**
* Collection of slow tests.
* Keys (string) => Printable label describing the test
* Values (int) => Test execution time, in milliseconds
*/
protected $slow = [];
public function __construct(array $options = [])
{
$this->enabled = getenv('PHPUNIT_SPEEDTRAP') === 'disabled' ? false : true;
$this->loadOptions($options);
}
/**
* A test successfully ended.
*
* @param string $test
* @param float $time
*/
public function executeAfterSuccessfulTest(string $test, float $time): void
{
if (!$this->enabled) return;
$timeMS = $this->toMilliseconds($time);
$threshold = $this->getSlowThreshold($test);
if ($this->isSlow($timeMS, $threshold)) {
$this->addSlowTest($test, $timeMS);
}
}
/**
* A test suite started.
*/
public function executeBeforeFirstTest(): void
{
if (!$this->enabled) return;
$this->suites++;
}
/**
* A test suite ended.
*/
public function executeAfterLastTest(): 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->renderFooter();
}
}
/**
* 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.
*
* @param int $time Test execution time that was considered slow, in milliseconds
*/
protected function addSlowTest(string $test, int $time): void
{
$label = $this->makeLabel($test);
$this->slow[$label] = $time;
}
/**
* 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\\Extension\\Tests\\SomeSlowTest::testWithDataProvider with data set "Rock"'
*/
protected function makeLabel(string $test): string
{
list($class, $testName) = explode('::', $test);
// Remove argument list from end of string that is appended
// by default \PHPUnit\Framework\TestCase->toString() so slowness report
// output compatible with phpunit --filter flag
$testName = preg_replace('/\s\(.*\)$/', '', $testName);
return sprintf('%s::%s', addslashes($class), $testName);
}
/**
* 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(): void
{
echo sprintf("\n\nThe following tests were detected as slow (>%sms)\n", $this->slowThreshold);
}
/**
* Renders slowness report body.
*/
protected function renderBody(): void
{
$slowTests = $this->slow;
$length = $this->getReportLength();
for ($i = 1; $i <= $length; ++$i) {
$label = key($slowTests);
$time = array_shift($slowTests);
$seconds = $time / 1000;
echo sprintf("%2s) %6.3fs to run %s\n", $i, $seconds, $label);
}
}
/**
* Renders slowness report footer.
*/
protected function renderFooter(): void
{
if ($hidden = $this->getHiddenCount()) {
printf("and %s more slow tests hidden from view\n", $hidden);
}
}
/**
* Populate options into class internals.
*/
protected function loadOptions(array $options): void
{
$this->slowThreshold = $options['slowThreshold'] ?? 500;
$this->reportLength = $options['reportLength'] ?? 10;
}
/**
* 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(string $test): int
{
list($class, $testName) = explode('::', $test);
$ann = TestUtil::parseTestMethodAnnotations($class, $testName);
return isset($ann['method']['slowThreshold'][0]) ? (int) $ann['method']['slowThreshold'][0] : $this->slowThreshold;
}
}