Created
May 21, 2020 13:20
-
-
Save xphere/6a49100515bd060bc0fff973c242af58 to your computer and use it in GitHub Desktop.
Simplest PhpUnit extension reporting slow tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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