Skip to content

Instantly share code, notes, and snippets.

@xphere
Created May 21, 2020 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xphere/6a49100515bd060bc0fff973c242af58 to your computer and use it in GitHub Desktop.
Save xphere/6a49100515bd060bc0fff973c242af58 to your computer and use it in GitHub Desktop.
Simplest PhpUnit extension reporting slow tests
<?php
declare(strict_types=1);
namespace Test\SpeedTrapListener;
use PHPUnit\Runner\AfterLastTestHook;
use PHPUnit\Runner\AfterTestHook;
use PHPUnit\Runner\BeforeTestHook;
final class SpeedTrapListener implements BeforeTestHook, AfterTestHook, AfterLastTestHook {
private float $timeLimit;
private float $startedAt;
private array $slowTests = [];
public function __construct(float $timeLimit = 500.0)
{
$this->timeLimit = $timeLimit;
}
public function executeBeforeTest(string $test): void
{
$this->startedAt = microtime(true);
}
public function executeAfterTest(string $test, float $time): void
{
$current = microtime(true);
$elapsed = ($current * 1000) - ($this->startedAt * 1000);
if ($elapsed > $this->timeLimit) {
$this->slowTests[$test] = $elapsed;
}
}
public function executeAfterLastTest(): void
{
if (empty($this->slowTests)) {
return;
}
asort($this->slowTests);
$this->slowTests = array_reverse($this->slowTests);
echo PHP_EOL, PHP_EOL;
echo 'Slow tests detected:', PHP_EOL;
foreach ($this->slowTests as $testName => $elapsed) {
printf(' (%6dms) %s%s', $elapsed, $testName, PHP_EOL);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment