Last active
July 17, 2023 22:42
-
-
Save alexander-schranz/d2b30177c1043099c44ef50b33db8412 to your computer and use it in GitHub Desktop.
Debug Memory Usage of PHPUnit TestCase
This file contains hidden or 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 App\Tests; | |
use PHPUnit\Framework\TestListener; | |
use PHPUnit\Framework\TestListenerDefaultImplementation; | |
use PHPUnit\Framework\TestSuite; | |
class DebugMemoryUsageTestListener implements TestListener | |
{ | |
use TestListenerDefaultImplementation; | |
/** | |
* The "endTestSuite" is called for every TestCase file, so we can make usage of that to clean up properties. | |
*/ | |
public function endTestSuite(TestSuite $suite): void | |
{ | |
if (!\class_exists($suite->getName())) { | |
return; | |
} | |
echo \PHP_EOL; | |
echo $suite->getName(); | |
echo ' (' . $this->human_filesize(\memory_get_usage(true)) . ')'; | |
} | |
public function human_filesize(int $bytes, int $dec = 2): string | |
{ | |
$size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; | |
$factor = \floor((\strlen((string) $bytes) - 1) / 3); | |
if (0.0 === $factor) { | |
$dec = 0; | |
} | |
return \sprintf("%.{$dec}f %s", $bytes / (1024 ** $factor), $size[$factor]); | |
} | |
} |
This file contains hidden or 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
<!-- add following to the phpunit.xml.dist --> | |
<listeners> | |
<listener class="App\Tests\DebugMemoryUsageTestListener" /> | |
</listeners> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment