|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Codeception\Module\Symfony; |
| 6 | + |
| 7 | +use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector; |
| 8 | +use function round; |
| 9 | +use function sprintf; |
| 10 | + |
| 11 | +trait TimeAssertionsTrait |
| 12 | +{ |
| 13 | + /** |
| 14 | + * Asserts that the time a request lasted is less than expected. |
| 15 | + * |
| 16 | + * If the page performed a HTTP redirect, only the time of the last request will be taken into account. |
| 17 | + * You can modify this behavior using [stopFollowingRedirects()](https://codeception.com/docs/modules/Symfony#stopFollowingRedirects) first. |
| 18 | + * |
| 19 | + * Also, note that using code coverage can significantly increase the time it takes to resolve a request, |
| 20 | + * which could lead to unreliable results when used together. |
| 21 | + * |
| 22 | + * It is recommended to set [`rebootable_client`](https://codeception.com/docs/modules/Symfony#Config) to `true` (=default), |
| 23 | + * cause otherwise this assertion gives false results if you access multiple pages in a row, or if your app performs a redirect. |
| 24 | + * |
| 25 | + * @param int|float $expectedMilliseconds The expected time in milliseconds |
| 26 | + */ |
| 27 | + public function seeRequestTimeIsLessThan($expectedMilliseconds): void |
| 28 | + { |
| 29 | + $expectedMilliseconds = round($expectedMilliseconds, 2); |
| 30 | + |
| 31 | + $timeCollector = $this->grabTimeCollector(__FUNCTION__); |
| 32 | + |
| 33 | + $actualMilliseconds = round($timeCollector->getDuration(), 2); |
| 34 | + |
| 35 | + $this->assertLessThan( |
| 36 | + $expectedMilliseconds, |
| 37 | + $actualMilliseconds, |
| 38 | + sprintf( |
| 39 | + 'The request was expected to last less than %d ms, but it actually lasted %d ms.', |
| 40 | + $expectedMilliseconds, |
| 41 | + $actualMilliseconds |
| 42 | + ) |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + protected function grabTimeCollector(string $function): TimeDataCollector |
| 47 | + { |
| 48 | + return $this->grabCollector('time', $function); |
| 49 | + } |
| 50 | +} |
0 commit comments