Compare commits

...

23 Commits

Author SHA1 Message Date
Mohannad Elemary 66e585081a fix(tia): stop ReadCapture from keeping a wrapper per filesystem call (#2057)
* fix(tia): free the ReadCapture wrapper each time it steps aside

stream_wrapper_restore() takes a user wrapper out of the wrapper table
but does not free it, so every filesystem call made while a test records
kept one until the process ended. Unregistering it first frees it.

* fix(tia): skip the unregister when file:// is already gone

A test can unregister file:// itself. stream_wrapper_unregister() then
warns, where stream_wrapper_restore() alone did not, so check first.

Also run the per-test memory check over 5,000 tests and update the
snapshot and parallel totals for the new tests.

* Use fopen() in the memory regression test

---------

Co-authored-by: Mohannad Elemary <20709195+MohannadElemary@users.noreply.github.com>
2026-11-22 02:11:09 +05:30
Maks Oleksyuk 9a6ceb0699 feat: let a shard unit bundle several test classes (#1829)
* feat: let a shard unit bundle several test classes

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: own unknown shard units in every shard and clean up worker timings

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix: drop removed test classes from shard units and consume coverage option values

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix: preserve empty shard units and consume more option values in discovery

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-21 01:03:33 +05:30
Jeremy Braband 996b5ee8f5 [5.x] TIA: stat once in ReadCapture::url_stat() (#2038)
* Stat once in ReadCapture url_stat

* Keep quiet url_stat probes away from error handlers

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-21 00:33:18 +05:30
Florian 776a44a391 Add an observer for the exit code after output plugins (#1905)
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-21 00:12:46 +05:30
nuno maduro 89999bdaed chore: updates sponsors 2026-11-20 17:07:24 +00:00
Adam Goulding f5c3687a68 fix: beforeEach/afterEach leaking into sibling describe blocks with same nested name (#1850)
* fix: beforeEach/afterEach leaking into sibling describe blocks with same nested name

* fix: resolve afterEach test ordering issue

* chore: update snapshots and parallel memory limit after rebase onto upstream/5.x

* chore: update snapshots and parallel memory limit after rebase onto upstream/5.x

---------

Co-authored-by: Adam Goulding <adam.goulding@ethixbase360.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 19:14:17 +05:30
Syl 41af35a3f2 feat(tia): let a project leave paths out of read capture (#2030)
* feat(tia): let a project leave paths out of read capture

* Verify TIA watch fallbacks and refresh snapshots

---------

Co-authored-by: Sylvain Valienne <2300259+sylouuu@users.noreply.github.com>
Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
2026-11-20 18:41:03 +05:30
Florian Raith fdc57f77b7 feat: convert namespace-style arguments to file paths in pest binary (#1705)
* feat: convert namespace-style arguments to file paths in pest binary

* test: allow running a single test using its namespace

* fix: preserve namespace filters when converting arguments

* test: update success snapshot for namespace filters

* fix: convert namespace after retry flag

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 15:29:37 +05:30
Ikki Nishihara 67d3733eb2 Allow help and version before the test suite is initialized (#2051)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 15:20:17 +05:30
Ikki Nishihara f80b3a89a0 Reject the parallel short flag during retry (#2043)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 15:12:02 +05:30
Ikki Nishihara fabc818ba9 Support nested Composer vendor directories (#2053)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 02:40:22 +05:30
Ikki Nishihara a865244b92 Keep focused tests local to each Pest run (#2049)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 02:38:12 +05:30
Ikki Nishihara d65b04a389 Preserve existing PHPUnit configuration files (#2044)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 02:35:43 +05:30
Ikki Nishihara a07f68bc54 Select dirty tests with quoted Git paths (#2042)
* Select dirty tests with quoted Git paths

* Skip missing files when selecting dirty tests

---------

Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 02:33:19 +05:30
Ikki Nishihara 989c08008f Skip execution for empty test shards (#2041)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 02:30:56 +05:30
Ikki Nishihara a1a902dbc7 Shorten overlong snapshot filenames (#2047)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 02:25:23 +05:30
Ikki Nishihara 4a66e6888d Match deleted paths against TIA watch patterns (#2050)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
2026-11-20 02:02:20 +05:30
Ikki Nishihara 9990d0ee36 Fail when a snapshot cannot be written (#2048)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-20 01:59:51 +05:30
Ikki Nishihara bb91916d0d Run the generated Pest suite without a Tests autoload mapping (#2054)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
2026-11-20 01:13:13 +05:30
Ikki Nishihara fcd408b895 Match the exact TeamCity output flag (#2052)
Co-authored-by: haranishi <223786623+haranishi@users.noreply.github.com>
2026-11-19 15:51:16 +05:30
Lazizbek Ergashev b4fcb2091e fix(tia): apply the prefix and suffix of source exclude directories (#2032) 2026-11-18 20:59:39 +05:30
Aleksandr Štšepelin 9dc8c1d5cb fix: honor all stop-on-* flags in parallel mode (#1684)
* fix: honor all stop-on-* flags in parallel mode

Previously --stop-on-failure was the only flag honored in parallel
mode, and it only cleared pending tests when the exit code was
non-zero. The rest (--stop-on-defect, --stop-on-error, --stop-on-risky,
--stop-on-incomplete, --stop-on-warning, --stop-on-notice,
--stop-on-deprecation, --stop-on-skipped) were silently ignored.

WrapperRunner now precomputes the set of progress-file characters that
should trigger a stop (F, E, R, I, W, N, D, S) based on the configured
flags, and scans each worker's progress file for them after every
cycle. Once any matching outcome is seen, the pending queue is cleared.

Up to N-1 in-flight tests (where N is --processes) can still complete
after the first stop-worthy outcome — stopping them mid-run would risk
corrupting shared state.

Closes #1463.

* fix: preserve parallel stop conditions on Pest 5

* test: expand parallel stop-on regression coverage
2026-11-17 01:49:46 +05:30
cyppe fbaa7fe8e9 fix(tia): fingerprint the configuration file the run uses (#1924)
* fix(tia): fingerprint the configuration file the run uses

* fix(tia): tell --no-configuration and identical copies of the configuration apart

* test(tia): cover the gitignore check with composer.lock, as the active configuration is fingerprinted tracked or not
2026-11-17 01:20:47 +05:30
95 changed files with 3179 additions and 257 deletions
+2 -4
View File
@@ -32,16 +32,14 @@ We cannot thank our sponsors enough for their incredible support in funding Pest
- **[PhpStorm](https://jb.gg/nuno)**
- **[CodeRabbit](https://coderabbit.link/nunomaduro)**
- **[SerpApi](https://serpapi.com/?ref=nunomaduro)**
- **[Bento](https://bentonow.com/?ref=nunomaduro)**
- **[CMS Max](https://cmsmax.com/?ref=nunomaduro)**
- **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)**
- **[Typesense](https://typesense.org/?ref=nunomaduro)**
- **[Pixel](https://wearepixel.com.au/?ref=nunomaduro)**
- **[NativePHP](https://nativephp.com/?ref=nunomaduro)**
- [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest)
- [Zapiet](https://zapiet.com/?ref=nunomaduro)
- [LoadForge](https://loadforge.com/?ref=nunomaduro)
- [Route4Me](https://route4me.com/?ref=nunomaduro)
- [Nerdify](https://getnerdify.com/?ref=nunomaduro)
- [Pushery](https://www.pushery.com/?ref=nunomaduro)
- [LFCarry](https://lfcarry.com/?ref=nunomaduro)
Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
+63 -13
View File
@@ -6,6 +6,7 @@ declare(strict_types=1);
use Pest\Contracts\Restarter;
use Pest\Kernel;
use Pest\Panic;
use Pest\Support\ComposerProject;
use Pest\Support\Container;
use Pest\TestCaseFilters\GitDirtyTestCaseFilter;
use Pest\TestCaseMethodFilters\AssigneeTestCaseFilter;
@@ -121,29 +122,78 @@ use Symfony\Component\Console\Output\ConsoleOutput;
}
}
if (str_contains($value, '--teamcity')) {
if ($value === '--teamcity') {
unset($arguments[$key]);
$arguments[] = '--no-output';
unset($_SERVER['COLLISION_PRINTER']);
}
}
// Used when Pest is required using composer.
$vendorPath = dirname(__DIR__, 4).'/vendor/autoload.php';
$optionsWithSeparateValue = [
'-c', '-d', '--atleast-version', '--bootstrap', '--cache-directory', '--columns', '--configuration',
'--coverage-filter', '--coverage-clover', '--coverage-cobertura', '--coverage-crap4j', '--coverage-html',
'--coverage-jsonl', '--coverage-openclover', '--coverage-php', '--coverage-xml', '--default-time-limit',
'--diff-context', '--exclude-group', '--filter', '--exclude-filter', '--generate-baseline', '--use-baseline',
'--group', '--covers', '--uses', '--requires-php-extension', '--include-path', '--list-tests-xml',
'--log-junit', '--log-otr', '--log-teamcity', '--order-by', '--random-order-seed', '--repeat',
'--timeout', '--testdox-html', '--testdox-text', '--test-suffix', '--testsuite', '--exclude-testsuite',
'--test-files-file', '--test-id-filter-file', '--run-test-id', '--log-events-text',
'--log-events-verbose-text', '--extension',
];
// Used when Pest maintainers are running Pest tests.
$localPath = dirname(__DIR__).'/vendor/autoload.php';
$isOptionValue = false;
if (file_exists($vendorPath)) {
include_once $vendorPath;
$autoloadPath = $vendorPath;
} else {
include_once $localPath;
$autoloadPath = $localPath;
// Convert namespace-style arguments (e.g. Tests\Unit\TestName) to file paths.
foreach ($arguments as $key => $value) {
if ($isOptionValue) {
$isOptionValue = false;
continue;
}
if (str_starts_with($value, '-')) {
$isOptionValue = in_array($value, $optionsWithSeparateValue, true);
continue;
}
if (! str_contains($value, '\\')) {
continue;
}
$path = str_replace('\\', DIRECTORY_SEPARATOR, $value);
if (! str_ends_with($path, '.php')) {
$path .= '.php';
}
if (file_exists($path)) {
$arguments[$key] = $path;
continue;
}
// Try lowercasing the first directory segment (e.g. Tests -> tests).
$segments = explode(DIRECTORY_SEPARATOR, $path);
$segments[0] = lcfirst($segments[0]);
$lowercasedPath = implode(DIRECTORY_SEPARATOR, $segments);
if (file_exists($lowercasedPath)) {
$arguments[$key] = $lowercasedPath;
}
}
// Get $rootPath based on $autoloadPath
$rootPath = dirname($autoloadPath, 2);
// Used when Pest is required using composer.
$autoloadPath = $GLOBALS['_composer_autoload_path'] ?? dirname(__DIR__, 3).'/autoload.php';
if (! is_file($autoloadPath)) {
$autoloadPath = dirname(__DIR__).'/vendor/autoload.php';
}
include_once $autoloadPath;
$GLOBALS['_composer_bin_dir'] ??= dirname($autoloadPath).'/bin';
$rootPath = ComposerProject::rootPath($autoloadPath);
$input = new ArgvInput;
+12 -4
View File
@@ -6,16 +6,18 @@ use ParaTest\WrapperRunner\ApplicationForWrapperWorker;
use ParaTest\WrapperRunner\WrapperWorker;
use Pest\Kernel;
use Pest\Plugins\Actions\CallsHandleArguments;
use Pest\Plugins\Parallel\Paratest\StopConditions;
use Pest\Support\ComposerProject;
use Pest\Support\Container;
use Pest\TestSuite;
use PHPUnit\TextUI\Configuration\Registry as ConfigurationRegistry;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
$bootPest = (static function (): void {
$bootPest = (static function (string $rootPath): void {
$workerArgv = new ArgvInput;
$rootPath = dirname(PHPUNIT_COMPOSER_INSTALL, 2);
$testSuite = TestSuite::getInstance($rootPath, $workerArgv->getParameterOption(
'--test-directory',
'tests'
@@ -54,13 +56,14 @@ $bootPest = (static function (): void {
if (file_exists($file)) {
require_once $file;
define('PHPUNIT_COMPOSER_INSTALL', $file);
$GLOBALS['_composer_bin_dir'] ??= dirname($file).'/bin';
break;
}
}
$container = Container::getInstance();
$rootPath = dirname(PHPUNIT_COMPOSER_INSTALL, 2);
$rootPath = ComposerProject::rootPath(PHPUNIT_COMPOSER_INSTALL);
foreach (Kernel::RESTARTERS as $restarterClass) {
$restarter = $container->get($restarterClass);
@@ -83,7 +86,7 @@ $bootPest = (static function (): void {
$phpunitArgv = unserialize($getopt['phpunit-argv'], ['allowed_classes' => false]);
assert(is_array($phpunitArgv));
$bootPest();
$bootPest($rootPath);
$phpunitArgv = CallsHandleArguments::execute($phpunitArgv);
@@ -99,6 +102,8 @@ $bootPest = (static function (): void {
(int) ($getopt['testdox-columns'] ?? null),
);
$stopConditions = null;
while (true) {
if (feof(STDIN)) {
$application->end();
@@ -113,6 +118,9 @@ $bootPest = (static function (): void {
$exitCode = $application->runTest(realpath(trim($testPath)));
$stopConditions ??= new StopConditions(ConfigurationRegistry::get());
$stopConditions->write($getopt['test-result-file'].'.stop');
fwrite($statusFile, (string) $exitCode);
fflush($statusFile);
}
+7 -3
View File
@@ -36,7 +36,7 @@ final class BootFiles implements Bootstrapper
public function boot(): void
{
if ($this->runningInit()) {
if ($this->hasCliOption('--init')) {
return;
}
@@ -44,6 +44,10 @@ final class BootFiles implements Bootstrapper
$testsPath = $rootPath.DIRECTORY_SEPARATOR.testDirectory();
if (! is_dir($testsPath)) {
if ($this->hasCliOption('--help', '--version')) {
return;
}
throw new FatalException(sprintf('The test directory [%s] does not exist.', $testsPath));
}
@@ -69,7 +73,7 @@ final class BootFiles implements Bootstrapper
$this->bootDatasets($testsPath);
}
private function runningInit(): bool
private function hasCliOption(string ...$options): bool
{
$arguments = $_SERVER['argv'] ?? null;
@@ -78,7 +82,7 @@ final class BootFiles implements Bootstrapper
}
/** @var array<int, string> $arguments */
return $this->hasArgument('--init', $arguments);
return array_any($options, fn (string $option): bool => $this->hasArgument($option, $arguments));
}
private function load(string $filename): void
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Pest\Contracts\Plugins;
interface ObservesExitCode
{
public function observeExitCode(int $exitCode): void;
}
+1 -2
View File
@@ -6,7 +6,6 @@ namespace Pest\PendingCalls;
use Closure;
use Pest\PendingCalls\Concerns\Describable;
use Pest\Support\Arr;
use Pest\Support\Backtrace;
use Pest\Support\ChainableClosure;
use Pest\Support\HigherOrderMessageCollection;
@@ -43,7 +42,7 @@ final class AfterEachCall
$proxies = $this->proxies;
$afterEachTestCase = ChainableClosure::boundWhen(
fn (): bool => $describing === [] || in_array(Arr::last($describing), $this->__describing, true),
fn (): bool => $describing === [] || (count($describing) <= count($this->__describing) && array_slice($this->__describing, 0, count($describing)) === $describing),
ChainableClosure::bound(fn () => $proxies->chain($this), $this->closure)->bindTo($this, self::class),
)->bindTo($this, self::class);
+4 -7
View File
@@ -7,7 +7,6 @@ namespace Pest\PendingCalls;
use Closure;
use Pest\Exceptions\AfterBeforeTestFunction;
use Pest\PendingCalls\Concerns\Describable;
use Pest\Support\Arr;
use Pest\Support\Backtrace;
use Pest\Support\ChainableClosure;
use Pest\Support\HigherOrderMessageCollection;
@@ -50,11 +49,9 @@ final class BeforeEachCall
$beforeEachTestCall = function (TestCall $testCall) use ($describing): void {
if ($this->describing !== []) {
if (Arr::last($describing) !== Arr::last($this->describing)) {
return;
}
if (! in_array(Arr::last($describing), $testCall->describing, true)) {
$testCallDescribing = $testCall->describing;
if (count($describing) > count($testCallDescribing) ||
array_slice($testCallDescribing, 0, count($describing)) !== $describing) {
return;
}
}
@@ -63,7 +60,7 @@ final class BeforeEachCall
};
$beforeEachTestCase = ChainableClosure::boundWhen(
fn (): bool => $describing === [] || in_array(Arr::last($describing), $this->__describing, true),
fn (): bool => $describing === [] || (count($describing) <= count($this->__describing) && array_slice($this->__describing, 0, count($describing)) === $describing),
ChainableClosure::bound(fn () => $testCaseProxies->chain($this), $this->closure)->bindTo($this, self::class),
)->bindTo($this, self::class);
+8 -4
View File
@@ -7,20 +7,24 @@ namespace Pest\Plugins\Actions;
use Pest\Contracts\Plugins;
use Pest\Plugin\Loader;
/**
* @internal
*/
final class CallsAddsOutput
{
public static function execute(int $exitCode): int
{
$plugins = Loader::getPlugins(Plugins\AddsOutput::class);
/** @var Plugins\AddsOutput $plugin */
foreach ($plugins as $plugin) {
assert($plugin instanceof Plugins\AddsOutput);
$exitCode = $plugin->addOutput($exitCode);
}
foreach (Loader::getPlugins(Plugins\ObservesExitCode::class) as $plugin) {
assert($plugin instanceof Plugins\ObservesExitCode);
$plugin->observeExitCode($exitCode);
}
return $exitCode;
}
}
+51 -13
View File
@@ -11,6 +11,7 @@ use Pest\Plugins\Concerns\HandleArguments;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\TextUI\CliArguments\Builder as CliConfigurationBuilder;
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
use RuntimeException;
/**
* @internal
@@ -27,6 +28,9 @@ final class Configuration implements HandlesArguments, Terminable
.DIRECTORY_SEPARATOR
.'resources/base-phpunit.xml';
/** @var array{path: string, dev: int, ino: int}|null */
private ?array $generatedConfiguration = null;
public function handleArguments(array $arguments): array
{
if ($this->hasArgument('--configuration', $arguments) || $this->hasArgument('-c', $arguments) || $this->hasCustomConfigurationFile()) {
@@ -40,19 +44,50 @@ final class Configuration implements HandlesArguments, Terminable
private function fromGeneratedConfigurationFile(): string
{
$path = $this->getTempPhpunitXmlPath();
if (file_exists($path)) {
unlink($path);
$directory = getcwd();
if ($directory === false) {
throw new RuntimeException('Unable to determine the working directory.');
}
$doc = new DOMDocument;
$doc->load(self::BASE_PHPUNIT_FILE);
$contents = $doc->saveXML();
assert(is_string($contents));
assert(is_int(file_put_contents($path, $contents)));
foreach (['.pest.xml', '.pest-fallback.xml', null] as $filename) {
$filename ??= '.pest-'.bin2hex(random_bytes(8)).'.xml';
$path = $directory.DIRECTORY_SEPARATOR.$filename;
$file = @fopen($path, 'xb');
return $path;
if ($file === false) {
continue;
}
try {
$stat = @fstat($file);
if ($stat === false) {
throw new RuntimeException('Unable to identify the temporary PHPUnit configuration file.');
}
$this->generatedConfiguration = ['path' => $path, 'dev' => $stat['dev'], 'ino' => $stat['ino']];
$written = @fwrite($file, $contents);
} finally {
fclose($file);
}
if ($written !== strlen($contents)) {
$this->terminate();
throw new RuntimeException('Unable to write the temporary PHPUnit configuration file.');
}
return $path;
}
throw new RuntimeException('Unable to create a temporary PHPUnit configuration file.');
}
private function hasCustomConfigurationFile(): bool
@@ -63,17 +98,20 @@ final class Configuration implements HandlesArguments, Terminable
return is_string($configurationFile);
}
private function getTempPhpunitXmlPath(): string
{
return getcwd().'/.pest.xml';
}
public function terminate(): void
{
$path = $this->getTempPhpunitXmlPath();
$configuration = $this->generatedConfiguration;
$this->generatedConfiguration = null;
if (file_exists($path)) {
unlink($path);
if ($configuration === null) {
return;
}
clearstatcache();
$stat = @lstat($configuration['path']);
if ($stat !== false && $stat['dev'] === $configuration['dev'] && $stat['ino'] === $configuration['ino']) {
unlink($configuration['path']);
}
}
}
+1 -1
View File
@@ -146,7 +146,7 @@ final readonly class Help implements HandlesArguments
],
[
'arg' => '--update-shards',
'desc' => 'Update shards.json with test timing data for time-balanced sharding',
'desc' => 'Update the shards file with timing data for time-balanced sharding',
],
], ...$content['Execution']];
+38 -39
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Plugins;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Contracts\Plugins\Terminable;
use Pest\Factories\Attribute;
use Pest\Factories\TestCaseMethodFactory;
@@ -13,17 +14,24 @@ use PHPUnit\Framework\Attributes\Group;
/**
* @internal
*/
final class Only implements Terminable
final class Only implements HandlesArguments, Terminable
{
private const string TEMPORARY_FOLDER = __DIR__
.DIRECTORY_SEPARATOR
.'..'
.DIRECTORY_SEPARATOR
.'..'
.DIRECTORY_SEPARATOR
.'.temp';
private const string DEFAULT_GROUP = '__pest_only';
public static function enable(TestCall|TestCaseMethodFactory $testCall, string $group = '__pest_only'): void
private const string WORKER_GROUP = 'ONLY_GROUP';
private static ?string $group = null;
public function handleArguments(array $arguments): array
{
if (! Parallel::isWorker()) {
self::shareGroupWithWorkers();
}
return $arguments;
}
public static function enable(TestCall|TestCaseMethodFactory $testCall, string $group = self::DEFAULT_GROUP): void
{
if ($testCall instanceof TestCall) {
$testCall->group($group);
@@ -38,52 +46,43 @@ final class Only implements Terminable
return;
}
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock';
if (file_exists($lockFile) && $group === '__pest_only') {
file_put_contents($lockFile, $group);
return;
}
if (! file_exists($lockFile)) {
touch($lockFile);
file_put_contents($lockFile, $group);
if (self::$group === null || $group === self::DEFAULT_GROUP) {
self::$group = $group;
self::shareGroupWithWorkers();
}
}
public static function isEnabled(): bool
{
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock';
return file_exists($lockFile);
return self::selectedGroup() !== null;
}
public static function group(): string
{
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock';
if (! file_exists($lockFile)) {
return '__pest_only';
}
return file_get_contents($lockFile) ?: '__pest_only'; // @phpstan-ignore-line
return self::selectedGroup() ?: self::DEFAULT_GROUP;
}
/**
* {@inheritDoc}
*/
public function terminate(): void
{
if (Parallel::isWorker()) {
return;
self::$group = null;
self::shareGroupWithWorkers();
}
private static function selectedGroup(): ?string
{
if (! Parallel::isWorker()) {
return self::$group;
}
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock';
$group = Parallel::getGlobal(self::WORKER_GROUP);
if (file_exists($lockFile)) {
unlink($lockFile);
return is_string($group) ? base64_decode($group) : null;
}
private static function shareGroupWithWorkers(): void
{
if (Parallel::isEnabled()) {
Parallel::setGlobal(self::WORKER_GROUP, self::$group === null ? false : base64_encode(self::$group));
}
}
}
+3
View File
@@ -29,6 +29,7 @@ final class Parallel implements HandlesArguments
Parallel\Handlers\Parallel::class,
Parallel\Handlers\Pest::class,
Parallel\Handlers\Laravel::class,
Parallel\Handlers\StopOn::class,
];
/**
@@ -148,6 +149,8 @@ final class Parallel implements HandlesArguments
$command->setName('Pest');
$command->setVersion(version());
Parallel\Handlers\StopOn::configureOptions($command->find('paratest')->getDefinition());
return $command;
}
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Parallel\Handlers;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugins\Parallel\Contracts\HandlersWorkerArguments;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
final class StopOn implements HandlersWorkerArguments, HandlesArguments
{
private const array OPTIONS = [
'--stop-on-defect',
'--stop-on-error',
'--stop-on-failure',
'--stop-on-warning',
'--stop-on-risky',
'--stop-on-deprecation',
'--stop-on-notice',
'--stop-on-skipped',
'--stop-on-incomplete',
];
public function handleArguments(array $arguments): array
{
foreach ($arguments as $index => $argument) {
[$option, $value] = array_pad(explode('=', $argument, 2), 2, '');
if (in_array($option, self::OPTIONS, true)
&& in_array($value, ['', '0'], true)) {
$arguments[$index] = $option.'=1';
}
}
return $arguments;
}
public function handleWorkerArguments(array $arguments): array
{
$arguments = array_values($arguments);
foreach ($arguments as $index => $argument) {
if (! in_array($argument, self::OPTIONS, true)
|| ! isset($arguments[$index + 1])
|| str_starts_with($arguments[$index + 1], '--')) {
continue;
}
$arguments[$index] .= '='.$arguments[$index + 1];
unset($arguments[$index + 1]);
}
return array_values($arguments);
}
public static function configureOptions(InputDefinition $definition): void
{
$options = $definition->getOptions();
foreach (self::OPTIONS as $argument) {
$name = substr($argument, 2);
$option = $options[$name];
$options[$name] = new InputOption(
$name,
$option->getShortcut(),
InputOption::VALUE_OPTIONAL,
$option->getDescription(),
false,
);
}
$definition->setOptions($options);
}
}
@@ -0,0 +1,216 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Parallel\Paratest;
use PHPUnit\Runner\DeprecationCollector\Facade as DeprecationCollector;
use PHPUnit\TestRunner\TestResult\Facade as TestResultFacade;
use PHPUnit\TestRunner\TestResult\Issues\Issue;
use PHPUnit\TestRunner\TestResult\TestResult;
use PHPUnit\TextUI\Configuration\Configuration;
use RuntimeException;
final class StopConditions
{
/**
* @var array<string, positive-int>
*/
private readonly array $thresholds;
/**
* @var array<string, array<string, non-negative-int>>
*/
private array $workerCounts = [];
/**
* @var array<string, non-negative-int>
*/
private array $totals = [];
/**
* @var array<string, array<string, true>>
*/
private array $issueIds = [];
public function __construct(private readonly Configuration $configuration)
{
$this->thresholds = array_filter([
'defect' => $configuration->stopOnDefectThreshold(),
'error' => $configuration->stopOnErrorThreshold(),
'failure' => $configuration->stopOnFailureThreshold(),
'warning' => $configuration->stopOnWarningThreshold(),
'risky' => $configuration->stopOnRiskyThreshold(),
'deprecation' => $configuration->stopOnDeprecationThreshold(),
'notice' => $configuration->stopOnNoticeThreshold(),
'incomplete' => $configuration->stopOnIncompleteThreshold(),
'skipped' => $configuration->stopOnSkippedThreshold(),
], static fn (int $threshold): bool => $threshold > 0);
}
public function write(string $filename): void
{
if ($this->thresholds === []) {
return;
}
$result = TestResultFacade::result();
$state = json_encode([
'counts' => $this->counts($result),
'issues' => $this->issues($result),
], JSON_THROW_ON_ERROR);
if (file_put_contents($filename.'.tmp', $state) === false
|| ! rename($filename.'.tmp', $filename)) {
throw new RuntimeException(sprintf('Unable to write the parallel stop counts to [%s].', $filename));
}
}
public function read(string $filename): void
{
if ($this->thresholds === []) {
return;
}
$contents = file_get_contents($filename);
if ($contents === false) {
throw new RuntimeException(sprintf('Unable to read the parallel stop counts from [%s].', $filename));
}
$state = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
if (! is_array($state)
|| ! isset($state['counts'], $state['issues'])
|| ! is_array($state['counts'])
|| ! is_array($state['issues'])) {
throw new RuntimeException(sprintf('Invalid parallel stop counts in [%s].', $filename));
}
$this->addCounts($filename, $state['counts']);
$this->addIssues($filename, $state['issues']);
}
public function shouldStop(): bool
{
return array_any($this->thresholds, function (int $threshold, string $outcome): bool {
$issueType = $outcome === 'defect' ? 'warning' : $outcome;
$count = ($this->totals[$outcome] ?? 0) + count($this->issueIds[$issueType] ?? []);
return $count >= $threshold;
});
}
/**
* @return array<string, int>
*/
private function counts(TestResult $result): array
{
$counts = [
'error' => $result->numberOfTestErroredEvents(),
'failure' => $result->numberOfTestFailedEvents(),
'warning' => $result->numberOfPhpunitWarnings(),
'risky' => $result->numberOfTestsWithTestConsideredRiskyEvents(),
'deprecation' => $this->numberOfDeprecations(),
'notice' => 0,
'incomplete' => $result->numberOfTestMarkedIncompleteEvents(),
'skipped' => $result->numberOfTestSkippedEvents(),
];
$counts['defect'] = $counts['error'] + $counts['failure'] + $counts['warning'] + $counts['risky'];
return $counts;
}
/**
* @return array<'warning'|'notice', list<non-empty-string>>
*/
private function issues(TestResult $result): array
{
$issues = [];
if (isset($this->thresholds['warning']) || isset($this->thresholds['defect'])) {
$issues['warning'] = array_merge(
$this->issueKeys($result->warnings(), 'user'),
$this->issueKeys($result->phpWarnings(), 'php'),
);
}
if (isset($this->thresholds['notice'])) {
$issues['notice'] = array_merge(
$this->issueKeys($result->notices(), 'user'),
$this->issueKeys($result->phpNotices(), 'php'),
);
}
return $issues;
}
/**
* @return non-negative-int
*/
private function numberOfDeprecations(): int
{
$deprecations = DeprecationCollector::filteredDeprecations();
if ($this->configuration->hasSpecificDeprecationToStopOn()) {
$message = $this->configuration->specificDeprecationToStopOn();
$deprecations = array_filter($deprecations, static fn (string $deprecation): bool => str_contains($deprecation, $message));
}
return count($deprecations);
}
/**
* @param array<array-key, mixed> $counts
*/
private function addCounts(string $filename, array $counts): void
{
foreach (array_keys($this->thresholds) as $outcome) {
if (! isset($counts[$outcome]) || ! is_int($counts[$outcome]) || $counts[$outcome] < 0) {
throw new RuntimeException(sprintf('Invalid parallel stop counts in [%s].', $filename));
}
$previous = $this->workerCounts[$filename][$outcome] ?? 0;
$increase = $counts[$outcome] - $previous;
if ($increase < 0) {
throw new RuntimeException(sprintf('Parallel stop counts decreased in [%s].', $filename));
}
$this->totals[$outcome] = ($this->totals[$outcome] ?? 0) + $increase;
$this->workerCounts[$filename][$outcome] = $counts[$outcome];
}
}
/**
* @param array<array-key, mixed> $issues
*/
private function addIssues(string $filename, array $issues): void
{
foreach ($issues as $outcome => $ids) {
if (! in_array($outcome, ['warning', 'notice'], true) || ! is_array($ids)) {
throw new RuntimeException(sprintf('Invalid parallel stop issues in [%s].', $filename));
}
foreach ($ids as $id) {
if (! is_string($id)) {
throw new RuntimeException(sprintf('Invalid parallel stop issue in [%s].', $filename));
}
$this->issueIds[$outcome][$id] = true;
}
}
}
/**
* @param list<Issue> $issues
* @return list<non-empty-string>
*/
private function issueKeys(array $issues, string $origin): array
{
return array_map(
static fn (Issue $issue): string => hash('sha256', implode(':', [$origin, $issue->file(), $issue->line(), $issue->description()])),
$issues,
);
}
}
+16 -10
View File
@@ -78,8 +78,6 @@ final class WrapperRunner implements RunnerInterface
/** @var list<non-empty-list<non-empty-string>> */
private array $pending = [];
private int $exitcode = -1;
/** @var array<positive-int,WrapperWorker> */
private array $workers = [];
@@ -122,6 +120,8 @@ final class WrapperRunner implements RunnerInterface
/** @var non-empty-string[] */
private readonly array $parameters;
private readonly StopConditions $stopConditions;
private CodeCoverageFilterRegistry $codeCoverageFilterRegistry;
/** @var non-empty-string */
@@ -133,6 +133,7 @@ final class WrapperRunner implements RunnerInterface
) {
$this->printer = new ResultPrinter($output, $options);
$this->timer = new Timer;
$this->stopConditions = new StopConditions($options->configuration);
$wrapper = realpath(
dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'worker.php',
@@ -248,17 +249,18 @@ final class WrapperRunner implements RunnerInterface
$this->flushWorker($worker);
if ($this->stopConditions->shouldStop()) {
$this->pending = [];
break;
}
if ($batchSize !== 0 && $this->batches[$token] >= $batchSize) {
$this->destroyWorker($token);
$worker = $this->startWorker($token);
}
if (
$this->exitcode > 0
&& $this->options->configuration->stopOnFailureThreshold() > 0
) {
$this->pending = [];
} elseif (($pending = array_shift($this->pending)) !== null) {
if (($pending = array_shift($this->pending)) !== null) {
$worker->assign($pending);
$this->batches[$token] += count($pending);
}
@@ -275,6 +277,7 @@ final class WrapperRunner implements RunnerInterface
if ($testResultFile !== '') {
$this->requiredTestResultFiles[$testResultFile] = true;
$this->stopConditions->read($testResultFile.'.stop');
}
if (isset($worker->coverageFile) && $worker->coverageFile->getPathname() !== '') {
@@ -282,7 +285,6 @@ final class WrapperRunner implements RunnerInterface
}
}
$this->exitcode = max($this->exitcode, $worker->getExitCode());
$this->printer->printFeedback(
$worker->progressFile,
$worker->unexpectedOutputFile,
@@ -501,7 +503,11 @@ final class WrapperRunner implements RunnerInterface
$this->clearFiles($this->statusFiles);
$this->clearFiles($this->progressFiles);
$this->clearFiles($this->unexpectedOutputFiles);
$this->clearFiles($this->testResultFiles);
foreach ($this->testResultFiles as $file) {
$this->clearFiles([$file, new SplFileInfo($file->getPathname().'.stop')]);
}
$this->clearFiles($this->resultCacheFiles);
$this->clearFiles($this->coverageFiles);
$this->clearFiles($this->junitFiles);
+1 -1
View File
@@ -23,7 +23,7 @@ final class Retry implements HandlesArguments
return $arguments;
}
if ($this->hasArgument('--parallel', $arguments)) {
if ($this->hasArgument('--parallel', $arguments) || in_array('-p', $arguments, true)) {
throw new InvalidOption('The [--retry] option is not supported when running in parallel.');
}
+262 -63
View File
@@ -43,6 +43,23 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private static bool $updateShards = false;
private static ?string $timingsFilename = null;
/**
* @var array<string, float|array{time: float, tests: list<string>}>|null
*/
private static ?array $externalTimings = null;
/**
* @var array<string, bool>|null
*/
private static ?array $ownership = null;
/**
* @var array<string, scalar>
*/
private static array $metadata = [];
private static bool $timeBalanced = false;
private static bool $shardsOutdated = false;
@@ -50,7 +67,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private static bool $passed = false;
/**
* @var array<string, float>|null
* @var array<string, float|array{time: float, tests: list<string>}>|null
*/
private static ?array $collectedTimings = null;
@@ -65,6 +82,48 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
//
}
public static function useTimingsFile(string $filename): void
{
self::$timingsFilename = $filename;
}
/**
* @param array<string, float|array{time: float, tests: list<string>}> $units
* @param array<string, scalar> $metadata Stored alongside the units, and read back
* by {@see self::metadata()} on sharded runs.
*/
public static function useTimings(array $units, array $metadata = []): void
{
self::$externalTimings = $units;
if ($metadata !== []) {
self::$metadata = $metadata;
}
}
/**
* @return array<string, scalar>
*/
public static function metadata(): array
{
return self::$metadata;
}
public static function owns(string $unit): bool
{
if (self::$ownership === null) {
return true;
}
if (! isset(self::$ownership[$unit])) {
self::$shardsOutdated = true;
return true;
}
return self::$ownership[$unit];
}
/**
* {@inheritDoc}
*/
@@ -98,20 +157,33 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
$tests = $this->allTests($arguments);
$timings = $this->loadShardsFile();
if ($timings !== null) {
$knownTests = array_values(array_filter($tests, fn (string $test): bool => isset($timings[$test])));
$newTests = array_values(array_diff($tests, $knownTests));
$units = $this->loadShardsFile();
if ($units !== null) {
$hasRemovedTests = array_diff($this->testsOf($units), $tests) !== [];
$partitions = $this->partitionByTime($knownTests, $timings, $total);
$units = $this->withoutRemovedTests($units, $tests);
$newTests = array_values(array_diff($tests, $this->testsOf($units)));
$partitions = $this->partitionByTime($units, $total);
$median = $this->medianTime($units);
foreach ($newTests as $i => $test) {
$partitions[$i % $total][] = $test;
$partitions[$i % $total][$test] = ['time' => $median, 'tests' => [$test]];
}
$testsToRun = $partitions[$index - 1] ?? [];
$selected = $partitions[$index - 1] ?? [];
self::$ownership = [];
foreach ($partitions as $i => $partition) {
self::$ownership += array_fill_keys(array_keys($partition), $i === $index - 1);
}
self::$timeBalanced = true;
self::$shardsOutdated = $newTests !== [];
self::$shardsOutdated = $newTests !== [] || $hasRemovedTests;
$testsToRun = array_values(array_intersect($tests, $this->testsOf($selected)));
} else {
$isInCurrentShard = fn (int $key): bool => $key % $total === ($index - 1);
$testsToRun = array_values(array_filter($tests, $isInCurrentShard, ARRAY_FILTER_USE_KEY));
@@ -124,10 +196,6 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
'testsCount' => count($tests),
];
if ($testsToRun === []) {
return $arguments;
}
$filter = $this->buildFilterArgument($testsToRun);
$this->ensureFilterLengthIsSafe($filter);
@@ -175,7 +243,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private function allTests(array $arguments): array
{
$command = $this->buildListTestsCommand(
$arguments,
$this->popArgument('--list-tests', $arguments),
TestSuite::getInstance()->testPath,
);
@@ -202,7 +270,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
}
}
if ($argument === '--runner') {
if (in_array($argument, ['--runner', '--processes'], strict: true)) {
$skipNext = true;
continue;
@@ -226,7 +294,28 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
*/
private function buildListTestsCommand(array $arguments, string $testPath): array
{
$filtered = $this->removeParallelArguments($arguments);
$filtered = [];
$skipNext = false;
foreach ($this->removeParallelArguments($arguments) as $argument) {
if ($skipNext) {
$skipNext = false;
if (! str_starts_with($argument, '-')) {
continue;
}
}
if (preg_match('/^--(?:coverage-(?:php|html|clover|xml|cobertura|crap4j|openclover|jsonl|filter)|min|exactly)$/', $argument) === 1) {
$skipNext = true;
continue;
}
if (! str_starts_with($argument, '--coverage')) {
$filtered[] = $argument;
}
}
return [PHP_BINARY, ...$filtered, '--test-directory='.$testPath, '--list-tests'];
}
@@ -247,7 +336,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private function buildFilterArgument(array $testsToRun): string
{
if ($testsToRun === []) {
return '';
return '(?!)';
}
/** @var array<string, mixed> $tree */
@@ -318,15 +407,16 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
{
self::$passed = $exitCode === 0;
if (self::$updateShards && self::$passed && ! Parallel::isWorker()) {
if (self::$updateShards && (self::$passed || self::$externalTimings !== null) && ! Parallel::isWorker()) {
self::$collectedTimings = $this->collectTimings();
}
$count = self::$knownTests !== null
? count(array_intersect_key(self::$collectedTimings, array_flip(self::$knownTests)))
: count(self::$collectedTimings);
if (self::$collectedTimings !== null && self::$collectedTimings !== []) {
$count = count($this->unitsToWrite(self::$collectedTimings));
$this->output->writeln(sprintf(
' <fg=gray>Shards:</> <fg=default>shards.json updated with timings for %d test class%s.</>',
' <fg=gray>Shards:</> <fg=default>%s updated with timings for %d test class%s.</>',
$this->timingsFilename(),
$count,
$count === 1 ? '' : 'es',
));
@@ -354,7 +444,10 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
));
if (self::$shardsOutdated) {
$this->output->writeln(' <fg=yellow;options=bold>WARN</> <fg=default>The [tests/.pest/shards.json] file is out of date. Run [--update-shards] to update it.</>');
$this->output->writeln(sprintf(
' <fg=yellow;options=bold>WARN</> <fg=default>The [%s] file is out of date. Run [--update-shards] to update it.</>',
$this->relativeTimingsPath(),
));
}
return $exitCode;
@@ -372,7 +465,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
return;
}
if (! self::$passed) {
if (! self::$passed && self::$externalTimings === null) {
return;
}
@@ -386,17 +479,17 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
}
/**
* @return array<string, float>
* @return array<string, float|array{time: float, tests: list<string>}>
*/
private function collectTimings(): array
{
$runId = Parallel::getGlobal('SHARD_RUN_ID');
if (is_string($runId)) {
return $this->readWorkerTimings($runId);
}
$collected = is_string($runId)
? $this->readWorkerTimings($runId)
: EnsureShardTimingsAreCollected::timings();
return EnsureShardTimingsAreCollected::timings();
return self::$externalTimings ?? $collected;
}
private function writeWorkerTimings(): void
@@ -451,15 +544,46 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
return $merged;
}
private function timingsFilename(): string
{
return self::$timingsFilename ?? 'shards.json';
}
private function relativeTimingsPath(): string
{
return implode(DIRECTORY_SEPARATOR, [TestSuite::getInstance()->testPath, '.pest', $this->timingsFilename()]);
}
private function shardsPath(): string
{
$testSuite = TestSuite::getInstance();
return implode(DIRECTORY_SEPARATOR, [$testSuite->rootPath, $testSuite->testPath, '.pest', 'shards.json']);
return TestSuite::getInstance()->rootPath.DIRECTORY_SEPARATOR.$this->relativeTimingsPath();
}
/**
* @return array<string, float>|null
* @param array<string, mixed> $units
* @return array<string, array{time: float, tests: list<string>}>
*/
private function normaliseUnits(array $units): array
{
$normalised = [];
foreach ($units as $key => $unit) {
if (is_array($unit) && isset($unit['time']) && isset($unit['tests']) && is_array($unit['tests'])) {
$normalised[$key] = ['time' => (float) $unit['time'], 'tests' => array_values(array_map(strval(...), $unit['tests']))];
continue;
}
if (is_float($unit) || is_int($unit)) {
$normalised[$key] = ['time' => (float) $unit, 'tests' => [$key]];
}
}
return $normalised;
}
/**
* @return array<string, array{time: float, tests: list<string>}>|null
*/
private function loadShardsFile(): ?array
{
@@ -472,50 +596,95 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
$contents = file_get_contents($path);
if ($contents === false) {
throw new InvalidOption('The [tests/.pest/shards.json] file could not be read. Delete it or run [--update-shards] to regenerate.');
throw new InvalidOption(sprintf('The [%s] file could not be read. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
}
$data = json_decode($contents, true);
if (! is_array($data) || ! isset($data['timings']) || ! is_array($data['timings'])) {
throw new InvalidOption('The [tests/.pest/shards.json] file is corrupted. Delete it or run [--update-shards] to regenerate.');
$units = null;
if (is_array($data)) {
$units = $data['units'] ?? $data['timings'] ?? null;
}
return $data['timings'];
if (! is_array($units)) {
throw new InvalidOption(sprintf('The [%s] file is corrupted. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
}
if (isset($data['metadata']) && is_array($data['metadata'])) {
self::$metadata = array_filter($data['metadata'], is_scalar(...));
}
return $this->normaliseUnits($units);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
* @param list<string> $tests
* @param array<string, float> $timings
* @return list<list<string>>
* @return array<string, array{time: float, tests: list<string>}>
*/
private function partitionByTime(array $tests, array $timings, int $total): array
private function withoutRemovedTests(array $units, array $tests): array
{
$knownTimings = array_filter(
array_map(fn (string $test): ?float => $timings[$test] ?? null, $tests),
fn (?float $t): bool => $t !== null,
);
$live = [];
$median = $knownTimings !== [] ? $this->median(array_values($knownTimings)) : 1.0;
foreach ($units as $key => $unit) {
$declared = $unit['tests'];
$unit['tests'] = array_values(array_intersect($declared, $tests));
$testsWithTimings = array_map(
fn (string $test): array => ['test' => $test, 'time' => $timings[$test] ?? $median],
$tests,
);
if ($declared === [] || $unit['tests'] !== []) {
$live[$key] = $unit;
}
}
usort($testsWithTimings, fn (array $a, array $b): int => $b['time'] <=> $a['time']);
return $live;
}
/** @var list<list<string>> */
/**
* @param array<string, array{time: float, tests: list<string>}> $units
* @return list<string>
*/
private function testsOf(array $units): array
{
$tests = [];
foreach ($units as $unit) {
foreach ($unit['tests'] as $test) {
$tests[$test] = true;
}
}
return array_keys($tests);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
*/
private function medianTime(array $units): float
{
$times = array_column($units, 'time');
return $times === [] ? 1.0 : $this->median($times);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
* @return list<array<string, array{time: float, tests: list<string>}>>
*/
private function partitionByTime(array $units, int $total): array
{
uasort($units, fn (array $a, array $b): int => $b['time'] <=> $a['time']);
/** @var list<array<string, array{time: float, tests: list<string>}>> */
$bins = array_fill(0, $total, []);
/** @var non-empty-list<float> */
$binTimes = array_fill(0, $total, 0.0);
foreach ($testsWithTimings as $item) {
foreach ($units as $key => $unit) {
$minIndex = array_search(min($binTimes), $binTimes, strict: true);
assert(is_int($minIndex));
$bins[$minIndex][] = $item['test'];
$binTimes[$minIndex] += $item['time'];
$bins[$minIndex][$key] = $unit;
$binTimes[$minIndex] += $unit['time'];
}
return $bins;
@@ -539,9 +708,32 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
}
/**
* @param array<string, float> $timings
* @param array<string, float|array{time: float, tests: list<string>}> $units
* @return array<string, array{time: float, tests: list<string>}>
*/
private function writeTimings(array $timings): void
private function unitsToWrite(array $units): array
{
$units = $this->normaliseUnits($units);
if (self::$knownTests === null) {
return $units;
}
$known = self::$knownTests;
$units = array_filter($units, fn (array $unit): bool => $unit['tests'] === [] || array_intersect($unit['tests'], $known) !== []);
foreach (array_diff($known, $this->testsOf($units)) as $test) {
$units[$test] = ['time' => 0.0, 'tests' => [$test]];
}
return $units;
}
/**
* @param array<string, float|array{time: float, tests: list<string>}> $units
*/
private function writeTimings(array $units): void
{
$path = $this->shardsPath();
@@ -550,18 +742,25 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
mkdir($directory, 0755, true);
}
if (self::$knownTests !== null) {
$knownSet = array_flip(self::$knownTests);
$timings = array_intersect_key($timings, $knownSet);
}
$bundled = self::$externalTimings !== null && array_filter($units, is_array(...)) !== [];
ksort($timings);
$units = $this->unitsToWrite($units);
$canonical = self::$knownTests ?? array_keys($timings);
ksort($units);
$canonical = self::$knownTests ?? $this->testsOf($units);
sort($canonical);
$payload = $bundled
? ['units' => $units]
: ['timings' => array_map(fn (array $unit): float => $unit['time'], $units)];
if (self::$metadata !== []) {
$payload['metadata'] = self::$metadata;
}
file_put_contents($path, json_encode([
'timings' => $timings,
...$payload,
'checksum' => md5(implode("\n", $canonical)),
'updated_at' => date('c'),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
+8 -3
View File
@@ -23,6 +23,7 @@ use Pest\Plugins\Concerns\HandleArguments;
use Pest\Plugins\Tia\BaselineSync;
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\CiBranch;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\Contracts\State;
use Pest\Plugins\Tia\CoverageCollector;
use Pest\Plugins\Tia\Fingerprint;
@@ -214,6 +215,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
/** @var array<int, string> */
private array $originalArguments = [];
private ?ConfigurationFile $configuration = null;
private ?string $driftLabel = null;
private ?string $driftDetails = null;
@@ -481,6 +484,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
exit(0);
}
$this->configuration = ConfigurationFile::fromArguments($arguments);
$isWorker = Parallel::isWorker();
$recordingGlobal = $isWorker && (string) Parallel::getGlobal(self::RECORDING_GLOBAL) === '1';
$replayingGlobal = $isWorker && (string) Parallel::getGlobal(self::REPLAYING_GLOBAL) === '1';
@@ -639,7 +644,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$changedFiles = new ChangedFiles($projectRoot);
$currentSha = $changedFiles->currentSha();
$currentFingerprint = Fingerprint::compute($projectRoot);
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
if ($this->structuralFingerprintShifted($currentFingerprint)) {
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
@@ -733,7 +738,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$changedFiles = new ChangedFiles($projectRoot);
$currentSha = $changedFiles->currentSha();
$currentFingerprint = Fingerprint::compute($projectRoot);
$currentFingerprint = Fingerprint::compute($projectRoot, $this->configuration);
if ($this->structuralFingerprintShifted($currentFingerprint)) {
$this->renderBadge('WARN', 'Project files changed during the run — discarding recorded edges.');
@@ -884,7 +889,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
: new TiaRequiresRemote);
}
$fingerprint = Fingerprint::compute($projectRoot);
$fingerprint = Fingerprint::compute($projectRoot, $this->configuration);
$this->startFingerprint = $fingerprint;
$this->startSha = new ChangedFiles($projectRoot)->currentSha();
+13
View File
@@ -115,4 +115,17 @@ final class Configuration
return $this;
}
/**
* @param list<string>|null $patterns Project-relative globs to exclude, or null to disable read capture. Use watch() for excluded files that an existing watch pattern does not cover.
* @return $this
*/
public function withoutReadCapture(?array $patterns = null): self
{
/** @var WatchPatterns $watchPatterns */
$watchPatterns = Container::getInstance()->get(WatchPatterns::class);
$watchPatterns->excludeReads($patterns);
return $this;
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Tia;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\TextUI\CliArguments\Builder;
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
use Throwable;
/**
* @internal
*/
final readonly class ConfigurationFile
{
private const string SUPPRESSED = 'none';
private const array DEFAULT_NAMES = ['phpunit.xml', 'phpunit.dist.xml', 'phpunit.xml.dist'];
private function __construct(
private ?string $path,
private bool $suppressed,
) {}
/**
* @param array<int, string> $arguments
*/
public static function fromArguments(array $arguments): self
{
try {
$configuration = new Builder(EventFacade::emitter())->fromParameters(self::configurationParameters($arguments));
} catch (Throwable) {
return self::projectDefault();
}
if (! $configuration->hasConfigurationFile() && ! $configuration->useDefaultConfiguration()) {
return new self(null, true);
}
$file = new XmlConfigurationFileFinder()->find($configuration);
$path = $file === false ? false : realpath($file);
return new self($path === false ? null : $path, false);
}
public static function at(string $path): self
{
return new self($path, false);
}
public static function projectDefault(): self
{
return new self(null, false);
}
public function fingerprint(string $projectRoot): ?string
{
if ($this->suppressed) {
return self::SUPPRESSED;
}
$path = $this->path ?? $this->defaultIn($projectRoot);
if ($path === null || ! is_file($path)) {
return null;
}
$hash = @hash_file('xxh128', $path);
return $hash === false ? null : $this->relativeTo($projectRoot, $path).':'.$hash;
}
private function defaultIn(string $projectRoot): ?string
{
foreach (self::DEFAULT_NAMES as $name) {
if (is_file($projectRoot.DIRECTORY_SEPARATOR.$name)) {
return $projectRoot.DIRECTORY_SEPARATOR.$name;
}
}
return null;
}
private function relativeTo(string $projectRoot, string $path): string
{
$root = rtrim(str_replace('\\', '/', realpath($projectRoot) ?: $projectRoot), '/').'/';
$file = str_replace('\\', '/', realpath($path) ?: $path);
return str_starts_with($file, $root) ? substr($file, strlen($root)) : $file;
}
/**
* @param array<int, string> $arguments
* @return list<string>
*/
private static function configurationParameters(array $arguments): array
{
$arguments = array_values($arguments);
$parameters = [];
foreach ($arguments as $index => $argument) {
if ($argument === '--no-configuration') {
$parameters[] = $argument;
} elseif ($argument === '--configuration' || $argument === '-c') {
if (isset($arguments[$index + 1])) {
$parameters[] = '--configuration';
$parameters[] = $arguments[$index + 1];
}
} elseif (str_starts_with($argument, '--configuration=')) {
$parameters[] = '--configuration';
$parameters[] = substr($argument, strlen('--configuration='));
} elseif (str_starts_with($argument, '-c') && ! str_starts_with($argument, '--')) {
$parameters[] = '--configuration';
$parameters[] = substr($argument, 2);
}
}
return $parameters;
}
}
+3 -4
View File
@@ -13,7 +13,7 @@ use Symfony\Component\Process\Process;
*/
final readonly class Fingerprint
{
private const int SCHEMA_VERSION = 18;
private const int SCHEMA_VERSION = 19;
/**
* @var array<int, class-string<Lockfile>>
@@ -28,14 +28,13 @@ final readonly class Fingerprint
* environmental: array<string, int|string|null>,
* }
*/
public static function compute(string $projectRoot): array
public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null): array
{
return [
'structural' => [
'schema' => self::SCHEMA_VERSION,
'composer_lock' => self::composerLockHash($projectRoot),
'phpunit_xml' => self::trackedHash($projectRoot, 'phpunit.xml'),
'phpunit_xml_dist' => self::trackedHash($projectRoot, 'phpunit.xml.dist'),
'phpunit_configuration' => ($configuration ?? ConfigurationFile::projectDefault())->fingerprint($projectRoot),
'vite_config' => self::viteConfigHash($projectRoot),
'package_lock' => self::packageLockHash($projectRoot),
'js_config' => self::jsConfigHash($projectRoot),
+1 -7
View File
@@ -655,13 +655,7 @@ final class Graph
if (isset($handledBlade[$rel])) {
continue;
}
if (! isset($this->fileIds[$rel])) {
if (! is_file($this->projectRoot.'/'.$rel)) {
continue;
}
$watchedPaths[] = $rel;
} elseif ($this->isFrameworkBootPath($rel)) {
if (! isset($this->fileIds[$rel]) || $this->isFrameworkBootPath($rel)) {
$watchedPaths[] = $rel;
}
}
+9 -14
View File
@@ -89,13 +89,16 @@ final class ReadCapture
private static function disable(): void
{
if (in_array(self::PROTOCOL, stream_get_wrappers(), true)) {
stream_wrapper_unregister(self::PROTOCOL);
}
if (self::$previousWrapper === null) {
stream_wrapper_restore(self::PROTOCOL);
return;
}
stream_wrapper_unregister(self::PROTOCOL);
stream_wrapper_register(self::PROTOCOL, self::$previousWrapper);
}
@@ -286,21 +289,13 @@ final class ReadCapture
public function url_stat(string $path, int $flags): array|false
{
return $this->withOriginalWrapper(function () use ($path, $flags): array|false {
$isQuiet = ($flags & STREAM_URL_STAT_QUIET) !== 0;
set_error_handler(static fn (): bool => true);
if (($flags & STREAM_URL_STAT_LINK) !== 0) {
if ($isQuiet && ! is_link($path) && ! file_exists($path)) {
return false;
}
return @lstat($path);
try {
return ($flags & STREAM_URL_STAT_LINK) !== 0 ? lstat($path) : stat($path);
} finally {
restore_error_handler();
}
if ($isQuiet && ! file_exists($path)) {
return false;
}
return @stat($path);
});
}
+29 -1
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia;
use Pest\Support\Container;
use Pest\TestSuite;
use ReflectionClass;
@@ -103,7 +104,9 @@ final class Recorder
$this->currentTestFile = $file;
ReadCapture::start($this);
if ($this->watchPatterns()->isReadCaptureEnabled()) {
ReadCapture::start($this);
}
if ($this->classUsesDatabase($className)) {
$this->perTestUsesDatabase[$file] = true;
@@ -201,9 +204,34 @@ final class Recorder
return;
}
$relative = $this->projectRelative($real);
if ($relative !== null && $this->watchPatterns()->excludesRead($relative)) {
return;
}
$this->linkSource($real);
}
private function projectRelative(string $realPath): ?string
{
$root = rtrim(TestSuite::getInstance()->rootPath, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
if (! str_starts_with($realPath, $root)) {
return null;
}
return str_replace(DIRECTORY_SEPARATOR, '/', substr($realPath, strlen($root)));
}
private function watchPatterns(): WatchPatterns
{
$watchPatterns = Container::getInstance()->get(WatchPatterns::class);
assert($watchPatterns instanceof WatchPatterns);
return $watchPatterns;
}
private function classUsesDatabase(string $className): bool
{
if (array_key_exists($className, $this->classUsesDatabaseCache)) {
+13 -7
View File
@@ -35,7 +35,7 @@ final class SourceScope
/**
* @param list<string> $includes Absolute, normalised directory paths.
* @param list<string> $excludes Absolute, normalised directory paths.
* @param list<array{path: string, prefix: string, suffix: string}> $excludes Absolute, normalised directory paths with the file name prefix and suffix they apply to.
*/
public function __construct(
private readonly array $includes,
@@ -55,7 +55,11 @@ final class SourceScope
}
foreach ($source->excludeDirectories() as $dir) {
$phpunitExcludes[] = self::normalise($dir->path());
$phpunitExcludes[] = [
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
'prefix' => $dir->prefix(),
'suffix' => $dir->suffix(),
];
}
} catch (Throwable) {
//
@@ -64,10 +68,10 @@ final class SourceScope
$rootIncludes = self::topLevelProjectDirs($projectRoot);
$includes = array_values(array_unique([...$phpunitIncludes, ...$rootIncludes]));
$excludes = array_values(array_unique([
$excludes = [
...$phpunitExcludes,
...self::nestedNoiseDirs($projectRoot),
]));
];
if ($includes === []) {
$includes = [self::normalise($projectRoot)];
@@ -111,7 +115,9 @@ final class SourceScope
$candidate = self::normalise($candidate);
foreach ($this->excludes as $excluded) {
if ($this->startsWithDir($candidate, $excluded)) {
if ($this->startsWithDir($candidate, $excluded['path'])
&& str_starts_with(basename($candidate), $excluded['prefix'])
&& str_ends_with(basename($candidate), $excluded['suffix'])) {
return $this->containsCache[$absoluteFile] = false;
}
}
@@ -166,7 +172,7 @@ final class SourceScope
}
/**
* @return list<string>
* @return list<array{path: string, prefix: string, suffix: string}>
*/
private static function nestedNoiseDirs(string $projectRoot): array
{
@@ -174,7 +180,7 @@ final class SourceScope
foreach (self::NESTED_NOISE as $relative) {
$abs = $projectRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
$out[] = self::normalise(@realpath($abs) ?: $abs);
$out[] = ['path' => self::normalise(@realpath($abs) ?: $abs), 'prefix' => '', 'suffix' => ''];
}
return $out;
+42
View File
@@ -43,6 +43,13 @@ final class WatchPatterns
private bool $defaultsEnabled = true;
/**
* @var list<string>
*/
private array $excludedReadPatterns = [];
private bool $readCaptureEnabled = true;
/**
* @var array<string, array{include: string, excludes: array<int, string>, allowDotfiles: bool}>
*/
@@ -110,6 +117,39 @@ final class WatchPatterns
]));
}
/**
* @param list<string>|null $patterns
*/
public function excludeReads(?array $patterns = null): void
{
if ($patterns === null) {
$this->readCaptureEnabled = false;
return;
}
$this->excludedReadPatterns = array_values(array_unique([
...$this->excludedReadPatterns,
...$patterns,
]));
}
public function isReadCaptureEnabled(): bool
{
return $this->readCaptureEnabled;
}
/**
* @param string $file Project-relative path.
*/
public function excludesRead(string $file): bool
{
return array_any(
$this->excludedReadPatterns,
fn (string $pattern): bool => $this->keyMatches($pattern, $file),
);
}
/**
* @param string $projectRoot Absolute path.
* @param array<int, string> $changedFiles Project-relative paths.
@@ -279,6 +319,8 @@ final class WatchPatterns
$this->defaultPatterns = [];
$this->excludedDefaultPatterns = [];
$this->defaultsEnabled = true;
$this->excludedReadPatterns = [];
$this->readCaptureEnabled = true;
$this->parsed = [];
$this->enabled = false;
$this->locally = false;
+4 -1
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Repositories;
use Pest\Exceptions\ShouldNotHappen;
use RuntimeException;
/**
* @internal
@@ -48,7 +49,9 @@ final readonly class Snapshot
@mkdir($directory, 0755, true);
}
file_put_contents($this->filename, $contents);
if (@file_put_contents($this->filename, $contents) !== strlen($contents)) {
throw new RuntimeException(sprintf('Unable to write snapshot at [%s].', $this->path()));
}
return $this;
}
+14 -9
View File
@@ -13,6 +13,8 @@ use Pest\TestSuite;
*/
final class SnapshotRepository
{
private const int MAX_FILENAME_BYTES = 255;
private static ?string $key = null;
private static int $ordinal = 0;
@@ -95,15 +97,18 @@ final class SnapshotRepository
$relativePath = substr($testFile, strlen($startPath));
$relativePath = substr($relativePath, 0, (int) strrpos($relativePath, '.'));
return new Snapshot(
sprintf(
'%s/%s%s.snap',
$this->testsPath.'/'.$this->snapshotsPath.$relativePath,
TestSuite::getInstance()->getDescription(),
$suffix,
),
dirname($this->testsPath).'/',
);
$directory = $this->testsPath.'/'.$this->snapshotsPath.$relativePath;
$description = TestSuite::getInstance()->getDescription().$suffix;
$extension = '.snap';
$filename = $description.$extension;
if (strlen($filename) > self::MAX_FILENAME_BYTES && ! is_file($directory.'/'.$filename)) {
$digest = '__'.hash('xxh128', $description);
$prefix = mb_strcut($description, 0, self::MAX_FILENAME_BYTES - strlen($digest.$extension), 'UTF-8');
$filename = $prefix.$digest.$extension;
}
return new Snapshot($directory.'/'.$filename, dirname($this->testsPath).'/');
}
private function synchronize(): void
+7 -3
View File
@@ -7,6 +7,7 @@ namespace Pest\Restarters;
use Composer\XdebugHandler\XdebugHandler;
use Pest\Contracts\Restarter;
use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
use Pest\Plugins\Tia\Storage;
@@ -86,10 +87,13 @@ final class XdebugRestarter implements Restarter
return false;
}
return $this->tiaWillReplay($projectRoot);
return $this->tiaWillReplay($projectRoot, $arguments);
}
private function tiaWillReplay(string $projectRoot): bool
/**
* @param array<int, string> $arguments
*/
private function tiaWillReplay(string $projectRoot, array $arguments): bool
{
$path = Storage::tempDir($projectRoot).DIRECTORY_SEPARATOR.Tia::KEY_GRAPH;
@@ -111,7 +115,7 @@ final class XdebugRestarter implements Restarter
return Fingerprint::structuralMatches(
$graph->fingerprint(),
Fingerprint::compute($projectRoot),
Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments)),
);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
/**
* @internal
*/
final class ComposerProject
{
public static function rootPath(string $autoloadPath): string
{
$vendorPath = dirname($autoloadPath);
$vendorPath = realpath($vendorPath) ?: $vendorPath;
$rootPath = dirname($vendorPath);
$metadataPath = $vendorPath.'/composer/installed.php';
if (! is_file($metadataPath)) {
return $rootPath;
}
/** @var array{root: array{install_path: string}} $installed */
$installed = require $metadataPath;
return realpath($installed['root']['install_path']) ?: $rootPath;
}
}
+14 -16
View File
@@ -46,33 +46,31 @@ final class GitDirtyTestCaseFilter implements TestCaseFilter
private function loadChangedFiles(): void
{
$status = new Git(timeout: 60.0)->raw(['status', '--short', '--', '*.php']);
$git = new Git($this->projectRoot, timeout: 60.0);
$status = $git->raw(['status', '--porcelain=v1', '-z', '--no-renames', '--', '*.php']);
$prefix = $git->raw(['rev-parse', '--show-prefix']);
if ($status === null) {
if ($status === null || $prefix === null) {
throw new MissingDependency('Filter by dirty files', 'git');
}
$output = preg_split('/\R+/', $status, flags: PREG_SPLIT_NO_EMPTY);
assert(is_array($output));
$pathOffset = 3 + strlen(rtrim($prefix, "\r\n"));
$dirtyFiles = [];
foreach ($output as $dirtyFile) {
$dirtyFiles[substr($dirtyFile, 3)] = trim(substr($dirtyFile, 0, 3));
foreach (explode("\0", $status) as $entry) {
if ($entry === '' || trim(substr($entry, 0, 2)) === 'D') {
continue;
}
$dirtyFiles[] = substr($entry, $pathOffset);
}
$dirtyFiles = array_filter($dirtyFiles, fn (string $status): bool => $status !== 'D');
$dirtyFiles = array_map(
fn (string $file, string $status): string => in_array($status, ['R', 'RM'], true)
? explode(' -> ', $file)[1]
: $file, array_keys($dirtyFiles), $dirtyFiles,
);
$dirtyFiles = array_filter(
$dirtyFiles,
fn (string $file): bool => str_starts_with('.'.DIRECTORY_SEPARATOR.$file, TestSuite::getInstance()->testPath)
fn (string $file): bool => (
str_starts_with('.'.DIRECTORY_SEPARATOR.$file, TestSuite::getInstance()->testPath)
|| str_starts_with($file, TestSuite::getInstance()->testPath)
) && is_file($this->projectRoot.DIRECTORY_SEPARATOR.$file)
);
$dirtyFiles = array_values($dirtyFiles);
+4
View File
@@ -13,6 +13,10 @@ use Tests\TestCase;
|
*/
if (! class_exists(TestCase::class)) {
require_once __DIR__.'/TestCase.php';
}
pest()->extend(TestCase::class)->in('Feature');
/*
@@ -54,7 +54,7 @@
EXECUTION OPTIONS:
--parallel ........................................... Run tests in parallel
--update-snapshots Update snapshots for tests using the "toMatchSnapshot" expectation
--update-shards Update shards.json with test timing data for time-balanced sharding
--update-shards Update the shards file with timing data for time-balanced sharding
--globals-backup ................. Backup and restore $GLOBALS for each test
--static-backup ......... Backup and restore static properties for each test
--strict-coverage ................... Be strict about code coverage metadata
+188 -3
View File
@@ -33,6 +33,8 @@
✓ matching describe block names → outer → middle → it should not call afterEach functions for sibling describe blocks with the same name
✓ matching describe block names → outer → inner → it does not get executed before the test
✓ matching describe block names → outer → inner → it should not call afterEach functions for descendent of sibling describe blocks with the same name
✓ hierarchical test naming → block one → the same name → it does not call afterEach from sibling describe with same name
✓ hierarchical test naming → block two → the same name → it correctly calls afterEach from own describe hierarchy
PASS Tests\Features\Assignee
✓ it may be associated with an assignee [@nunomaduro, @taylorotwell]
@@ -56,6 +58,8 @@
✓ matching name → it should not call the before each on the describe block with the same name
✓ called on all tests → beforeEach should be called
✓ called on all tests → beforeEach should be called for all tests
✓ hierarchical test naming → block one → the same name → it does not call beforeEach from sibling describe with same name
✓ hierarchical test naming → block two → the same name → it correctly calls beforeEach from own describe hierarchy
PASS Tests\Features\BeforeEachProxiesToTestCallWithExpectations
✓ runs 1
@@ -73,6 +77,14 @@
↓ is marked as todo 3
↓ shouldBeMarkedAsTodo
PASS Tests\Features\Configuration
✓ preserves an existing .pest.xml file with dataset "explicit configuration"
✓ preserves an existing .pest.xml file with dataset "discovered configuration"
✓ preserves an existing .pest.xml file with dataset "generated configuration"
✓ removes the generated configuration when it finishes with dataset "sequential"
✓ removes the generated configuration when it finishes with dataset "parallel"
✓ preserves a replacement for the generated configuration
WARN Tests\Features\Coverage
✓ it has plugin
- it adds coverage if --coverage exist → Coverage is not available
@@ -327,6 +339,8 @@
✓ depends on describe using with → foo with (3)
✓ depends on describe using with → bar with (3)
✓ with test after describe → it should run the before each
✓ sibling describes may share the same it() description → block one → it can be created
✓ sibling describes may share the same it() description → block two → it can be created
PASS Tests\Features\DescriptionLess
✓ get 'foo'
@@ -401,6 +415,12 @@
✓ it works with nested properties
✓ it works with higher order tests
PASS Tests\Features\Expect\LongSnapshotNames
✓ creates and matches snapshots with long dataset labels
PASS Tests\Features\Expect\SnapshotWriteFailure
✓ reports a missing snapshot that cannot be written
PASS Tests\Features\Expect\each
✓ an exception is thrown if the the type is not iterable
✓ it expects on each item
@@ -1302,7 +1322,7 @@
… a "describe" group of tests → it is incompleted
PASS Tests\Features\Init
✓ init creates a suite when the tests directory is missing
✓ init creates a runnable suite when the tests directory is missing
✓ init creates a suite when --init is not the first argument
✓ init creates a suite when --init is passed with a value
✓ a missing tests directory does not crash while resolving tia state
@@ -1380,6 +1400,10 @@
! notice → This is a notice description // tests/Features/Notices.php:6
! a "describe" group of tests → notice → This is a notice description // tests/Features/Notices.php:13
PASS Tests\Features\Only
✓ limits focus to the invocation that discovers it with dataset "sequential"
✓ limits focus to the invocation that discovers it with dataset "parallel"
PASS Tests\Features\Pr
✓ it may be associated with an pr #1, #2
✓ nested → it may be associated with an pr #1, #4, #5, #6, #3
@@ -1836,6 +1860,15 @@
PASS Tests\Unit\Overrides\ThrowableBuilder
✓ collision editor can be added to the stack trace
PASS Tests\Unit\Plugins\Actions\CallsAddsOutput
✓ exit code observers run after every output plugin
✓ exit code observers receive unchanged codes when there are no output plugins with (0)
✓ exit code observers receive unchanged codes when there are no output plugins with (1)
✓ exit code observers receive unchanged codes when there are no output plugins with (2)
✓ exit code observers receive unchanged codes when there are no output plugins with (42)
✓ output plugins work without exit code observers
✓ exit code observers are not called when an output plugin throws
PASS Tests\Unit\Plugins\Concerns\HandleArguments
✓ method hasArgument with ('--long-argument', true)
✓ method hasArgument with ('-a', true)
@@ -1852,6 +1885,8 @@
PASS Tests\Unit\Plugins\Retry
✓ it orders by defects and stop on defects if when --retry is used
✓ it rejects retry with a parallel flag with ('--parallel')
✓ it rejects retry with a parallel flag with ('-p')
PASS Tests\Unit\Plugins\Shard
✓ getShard → it parses valid shard format with ('1/2', 1, 2)
@@ -1874,7 +1909,7 @@
✓ buildFilterArgument → it generates compact filter for single test
✓ buildFilterArgument → it generates compact filter for multiple tests with common prefix
✓ buildFilterArgument → it generates compact filter for tests with different namespaces
✓ buildFilterArgument → it returns empty string for empty test list
✓ buildFilterArgument → it generates a filter that selects no tests for an empty test list
✓ buildFilterArgument → it generates compact filter for deeply nested namespaces
✓ buildFilterArgument → it handles mix of nested and flat namespaces
✓ buildFilterArgument → it does not match a class outside of the shard when another class name is its prefix
@@ -1906,6 +1941,33 @@
✓ addOutput → it displays shard information after test execution
✓ addOutput → it uses singular form for single test file
✓ addOutput → it returns original exit code when shard is not set
✓ timings file → it reads and writes shards.json until a plugin overrides the filename
✓ timings file → it prefers timings supplied by a plugin over the ones collected from the test run
✓ timings file → it records known tests without supplied timings as zero
✓ timings file → it keeps timings supplied by a plugin even when the test suite did not pass
✓ timings file → it strips coverage arguments when building the list-tests command
✓ timings file → it strips the separate path of a coverage argument when building the list-tests command
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-jsonl')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-filter')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--min')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--exactly')
✓ timings file → it strips the separate value of the parallel processes option when building the list-tests command
✓ timings file → it keeps a unit saved with no test classes, but drops one emptied by removed classes
✓ timings file → it drops test classes that no longer exist from the stored units
✓ units → it treats a bare timing as a unit bundling only its own test class
✓ units → it keeps the test classes a unit bundles together in one shard
✓ units → it owns every unit when the run is not time-balanced
✓ units → it owns only the units allocated to the current shard
✓ units → it owns a unit the timings file does not know in every shard, and reports the file as out of date
✓ units → it keeps a unit that bundles no test class when writing
✓ units → it collects every test class the given units bundle
✓ units → it writes bundled units, and reads back both shapes
PASS Tests\Unit\Plugins\Tia\ConfigurationFile
✓ it fingerprints the path and the content of the configuration file
✓ it tells an identical copy under another name apart from the original
✓ it resolves a configuration directory the way PHPUnit does
✓ it gives a run with --no-configuration its own fingerprint
PASS Tests\Unit\Plugins\Tia\ContentHash
✓ of() → it returns false when file does not exist
@@ -2038,11 +2100,23 @@
✓ the file wrapper → it is restored when the recorder resets
✓ the file wrapper → it passes filesystem operations through while a test records
✓ the file wrapper → it writes with LOCK_EX while a test records
✓ the file wrapper → it reports a missing path to the error handler as plain PHP does while a test records
✓ the file wrapper → it keeps no memory for each filesystem call while a test records
✓ the file wrapper → it keeps no memory for each test it records
✓ the file wrapper → it is restored quietly when the test already restored it
✓ the file wrapper → it is restored quietly when the test unregistered it
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a link to an existing file"
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a dangling link"
✓ a wrapper already registered for file:// → it opens reads through it and still links them
✓ a wrapper already registered for file:// → it keeps the include flag for the files a test includes
✓ a wrapper already registered for file:// → it is registered again after the test
✓ withoutReadCapture() → it does not link a file matching an excluded glob
✓ withoutReadCapture() → it still links a file outside the excluded globs
✓ withoutReadCapture() → it keeps the file wrapper registered while globs are excluded
✓ withoutReadCapture() → it links every read when the list of globs is empty
✓ withoutReadCapture() → it registers no wrapper and links no read when called without globs
✓ withoutReadCapture() → it keeps the explicit links when called without globs
✓ withoutReadCapture() → it leaves a wrapper already registered for file:// untouched when called without globs
PASS Tests\Unit\Plugins\Tia\Recorder
✓ activateLinkTracking() → it tracks tables without a coverage driver
@@ -2055,6 +2129,11 @@
✓ it records assertions against the same per-dataset key
✓ it leaves a test without a dataset keyed by class and method
PASS Tests\Unit\Plugins\Tia\SourceScope
✓ contains() → it excludes only the files matching the suffix of an excluded directory
✓ contains() → it excludes only the files matching the prefix of an excluded directory
✓ contains() → it excludes every file of an excluded directory without a prefix or suffix
WARN Tests\Unit\Plugins\Tia\StaleCoverageLines
- a remeasured file drops line numbers that the current file no longer has → Coverage is not available
@@ -2228,6 +2307,16 @@
✓ it retains recorded Inertia dependencies when default watches are disabled
✓ it retains recorded migration tables when default watches are disabled
✓ it uses custom mappings for an unknown Vue page with defaults disabled
✓ it captures every read by default
✓ it excludes reads of files matching a glob
✓ it matches read globs like watch patterns
✓ it does not exclude a dotfile unless the glob names it
✓ it accumulates read exclusions from repeated calls
✓ it does not turn read capture off for an empty exclusion list
✓ it turns read capture off without a list of globs
✓ it keeps read capture off when globs are added afterwards
✓ it captures reads again on reset
✓ it does not change the default watch fallbacks of an excluded read
PASS Tests\Unit\Plugins\Tia\WorkerToken
✓ prefers the per-process UNIQUE_TEST_TOKEN over the per-slot TEST_TOKEN, so two workers recycled into the same slot get different tokens
@@ -2384,6 +2473,14 @@
PASS Tests\Visual\Collision
✓ collision with ([''])
PASS Tests\Visual\Dirty
✓ dirty selects paths with spaces and Unicode with dataset "repository root"
✓ dirty selects paths with spaces and Unicode with dataset "project subdirectory"
✓ dirty selects paths with spaces and Unicode with dataset "subdirectory with leading space"
✓ dirty ignores a test removed after staging a modification with dataset "sequential"
✓ dirty ignores a test removed after staging a modification with dataset "parallel"
✓ dirty selects an unresolved test only while its file exists
PASS Tests\Visual\FailingBoot
✓ a failure in the boot files renders only that failure
@@ -2394,6 +2491,11 @@
✓ junit output
✓ junit with parallel
PASS Tests\Visual\NestedVendorDirectory
✓ runs with a nested Composer vendor directory with dataset "Composer proxy"
✓ runs with a nested Composer vendor directory with dataset "Composer proxy with workers"
✓ runs with a nested Composer vendor directory with dataset "direct execution with workers"
PASS Tests\Visual\Parallel
✓ parallel
✓ a parallel test can extend another test with same name
@@ -2413,9 +2515,88 @@
PASS Tests\Visual\ParallelNestedDatasets
✓ parallel loads nested datasets from nested directories
PASS Tests\Visual\ParallelStopOn
✓ parallel stop-on fixtures run completely without a stop flag with dataset "failure"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "error"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "risky"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "incomplete"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "warning"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "notice"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "deprecation"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "skipped"
✓ parallel honors stop-on flags with worker recycling with dataset "failure" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "failure" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "defect" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "defect" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "error" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "error" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "risky" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "risky" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "incomplete" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "incomplete" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "warning" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "warning" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "notice" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "notice" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "deprecation" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "deprecation" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "skipped" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "skipped" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "failure" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "failure" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "defect" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "defect" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "error" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "error" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "risky" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "risky" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "incomplete" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "incomplete" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "warning" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "warning" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "notice" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "notice" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "deprecation" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "deprecation" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "skipped" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "skipped" / (1)
✓ parallel stop-on-defect includes errors warnings and risky tests with ('errors', 'failed', 2)
✓ parallel stop-on-defect includes errors warnings and risky tests with ('warns', 'warning', 0)
✓ parallel stop-on-defect includes errors warnings and risky tests with ('is risky', 'risky', 1)
✓ parallel stop-on-defect allows incomplete and skipped tests with ('is incomplete', 'incomplete')
✓ parallel stop-on-defect allows incomplete and skipped tests with ('is skipped', 'skipped')
✓ parallel does not count the same failure twice with (0)
✓ parallel does not count the same failure twice with (1)
✓ parallel counts issues hidden by the progress output with ('--stop-on-warning', 'has combined issues', 'failed', …)
✓ parallel counts issues hidden by the progress output with ('--stop-on-defect=2', 'has combined issues', 'failed', …)
✓ parallel counts issues hidden by the progress output with ('--stop-on-warning=2', 'has repeated warnings', 'warning', …)
✓ parallel counts issues hidden by the progress output with ('--stop-on-notice=2', 'has repeated notifications', 'notice', …)
✓ parallel stops only on the requested deprecation message with ('user deprecation', 1)
✓ parallel stops only on the requested deprecation message with ('another deprecation', 2)
✓ parallel honors stop-on flags from XML
✓ parallel CLI thresholds override XML stop-on flags
✓ parallel clamps empty and non-positive thresholds like PHPUnit with ('')
✓ parallel clamps empty and non-positive thresholds like PHPUnit with ('0')
✓ parallel clamps empty and non-positive thresholds like PHPUnit with ('-2')
✓ parallel counts a shared issue only once across recycled workers with ('warning', 'shares warning', 'warning')
✓ parallel counts a shared issue only once across recycled workers with ('defect', 'shares warning', 'warning')
✓ parallel counts a shared issue only once across recycled workers with ('notice', 'shares notice', 'notice')
✓ parallel combines stop-on counts from different workers and cleans up their files
PASS Tests\Visual\Shard
✓ an empty shard runs no tests with dataset "sequential"
✓ an empty shard runs no tests with dataset "parallel"
✓ an empty shard runs no tests with dataset "sequential with fail-on-empty-test-suite"
✓ an empty shard runs no tests with dataset "parallel with fail-on-empty-test-suite"
✓ an empty shard lists no tests
✓ a non-empty shard runs its assigned test
PASS Tests\Visual\SingleTestOrDirectory
✓ allows to run a single test
✓ allows to run a directory
✓ allows to run a single test using its namespace
✓ keeps namespace filters unchanged
✓ converts a namespace after the retry flag
✓ it disable decorating printer when colors is set to never
WARN Tests\Visual\Success
@@ -2424,6 +2605,8 @@
WARN Tests\Visual\TeamCity
- visual snapshot of team city with ('Failure.php')
- visual snapshot of team city with ('SuccessOnly.php')
✓ preserves TeamCity text in a test filter with dataset "attached value"
✓ preserves TeamCity text in a test filter with dataset "separate value"
WARN Tests\Visual\Todo
- todos
@@ -2437,9 +2620,11 @@
WARN Tests\Visual\Version
- visual snapshot of help command output
✓ prints information when the tests directory is missing with dataset "help"
✓ prints information when the tests directory is missing with dataset "version"
PASS Testsexternal\Features\Expect\toMatchSnapshot
✓ pass with dataset with ('my-datas-set-value')
✓ within describe → pass with dataset with ('my-datas-set-value')
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1756 passed (3817 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1919 passed (4374 assertions)
+26
View File
@@ -100,3 +100,29 @@ describe('matching describe block names', function (): void {
});
});
});
describe('hierarchical test naming', function (): void {
describe('block one', function (): void {
describe('the same name', function (): void {
it('does not call afterEach from sibling describe with same name', function (): void {
expect($this)->not->toHaveProperty('example');
});
});
});
describe('block two', function (): void {
describe('the same name', function (): void {
beforeEach(function (): void {
$this->example = false;
});
afterEach(function (): void {
expect($this->example)->toBeFalse();
});
it('correctly calls afterEach from own describe hierarchy', function (): void {
expect($this->example)->toBeFalse();
});
});
});
});
+26
View File
@@ -126,3 +126,29 @@ describe('called on all tests', function (): void {
expect($this->baz)->toBe(2);
});
});
describe('hierarchical test naming', function (): void {
describe('block one', function (): void {
describe('the same name', function (): void {
it('does not call beforeEach from sibling describe with same name', function (): void {
expect($this)->not->toHaveProperty('example');
});
});
});
describe('block two', function (): void {
beforeEach(function (): void {
$this->example = false;
});
describe('the same name', function (): void {
beforeEach(function (): void {
$this->result = $this->example;
});
it('correctly calls beforeEach from own describe hierarchy', function (): void {
expect($this->result)->toBeFalse();
});
});
});
});
+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('preserves an existing .pest.xml file', function (array $arguments, bool $hasDefaultConfiguration): void {
$project = Project::withoutGit();
$configuration = $project->path('.pest.xml');
$contents = $arguments === [] ? 'An existing project file.' : (string) file_get_contents($project->path('phpunit.xml'));
$project->write('.pest.xml', $contents);
if (! $hasDefaultConfiguration) {
unlink($project->path('phpunit.xml'));
}
$result = $project->pest('tests/Unit/GreeterTest.php', '--cache-directory', $project->path('.phpunit.cache'), ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain('2 passed')
->and(glob($project->path('.pest*.xml')))->toHaveCount(1)
->and($configuration)->toBeFile()
->and(file_get_contents($configuration))->toBe($contents);
})->with([
'explicit configuration' => [['--configuration=.pest.xml'], false],
'discovered configuration' => [[], true],
'generated configuration' => [[], false],
])->group('integration');
test('removes the generated configuration when it finishes', function (array $arguments): void {
$project = Project::withoutGit();
unlink($project->path('phpunit.xml'));
$result = $project->pest('tests/Unit/GreeterTest.php', '--cache-directory', $project->path('.phpunit.cache'), ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain('2 passed')
->and(glob($project->path('.pest*.xml')))->toBe([]);
})->with(Project::SEQUENTIAL_AND_PARALLEL)->group('integration');
test('preserves a replacement for the generated configuration', function (): void {
$project = Project::withoutGit();
unlink($project->path('phpunit.xml'));
$project->write('replacement.xml', 'A replacement project file.');
$project->write('tests/Unit/ReplaceConfigurationTest.php', <<<'PHP'
<?php
test('replaces the configuration', function (): void {
expect(rename('replacement.xml', '.pest.xml'))->toBeTrue();
});
PHP);
$result = $project->pest('tests/Unit/ReplaceConfigurationTest.php', '--cache-directory', $project->path('.phpunit.cache'));
expect($result->exitCode)->toBe(0, $result->describe())
->and($project->path('.pest.xml'))->toBeFile()
->and(file_get_contents($project->path('.pest.xml')))->toBe('A replacement project file.');
})->group('integration');
+14
View File
@@ -108,3 +108,17 @@ describe('with test after describe', function (): void {
expect($this->count)->toBe(2);
});
});
describe('sibling describes may share the same it() description', function (): void {
describe('block one', function (): void {
it('can be created', function (): void {
expect(true)->toBeTrue();
});
});
describe('block two', function (): void {
it('can be created', function (): void {
expect(true)->toBeTrue();
});
});
});
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('creates and matches snapshots with long dataset labels', function (): void {
$project = Project::withoutGit();
$testFile = 'tests/Unit/SnapshotNamesTest.php';
$snapshotDirectory = $project->path('tests/.pest/snapshots/Unit/SnapshotNamesTest');
$project->write($testFile, <<<'FIXTURE'
<?php
$prefix = str_repeat('日本', 135);
test('stores a snapshot', function (string $value): void {
expect($value)->toMatchSnapshot()
->and(strtoupper($value))->toMatchSnapshot(as: 'upper');
})->with([
'short' => ['short'],
$prefix.' one' => ['one'],
$prefix.' two' => ['two'],
]);
FIXTURE);
$first = $project->pest($testFile, '--update-snapshots');
$snapshots = glob($snapshotDirectory.'/*.snap');
expect($first->exitCode)->toBe(0, $first->describe())
->and($snapshots)->toHaveCount(6)
->and(array_map(file_get_contents(...), $snapshots))->toEqualCanonicalizing(['short', 'SHORT', 'one', 'ONE', 'two', 'TWO'])
->and($snapshotDirectory.'/stores_a_snapshot_with_data_set__dataset__short__.snap')->toBeFile()
->and($snapshotDirectory.'/stores_a_snapshot_with_data_set__dataset__short____upper.snap')->toBeFile();
foreach ($snapshots as $snapshot) {
$filename = basename($snapshot);
expect(strlen($filename))->toBeLessThanOrEqual(255)
->and(mb_check_encoding($filename, 'UTF-8'))->toBeTrue();
}
$second = $project->pestWithEnvironment($project->path(), ['CI' => 'true'], $testFile);
expect($second->exitCode)->toBe(0, $second->describe())
->and($second->tally())->toContain('3 passed');
})->group('integration');
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('reports a missing snapshot that cannot be written', function (): void {
$project = Project::withoutGit();
$testFile = 'tests/Unit/BlockedSnapshotTest.php';
$directory = 'tests/.pest/snapshots/Unit/BlockedSnapshotTest';
$project->write($directory, 'An existing file.');
$project->write($testFile, <<<'PHP'
<?php
test('stores a snapshot', function (): void {
expect('content')->toMatchSnapshot();
});
PHP);
$run = $project->pest($testFile, '--update-snapshots');
expect($run->exitCode)->toBe(2, $run->describe())
->and(str_replace('\\', '/', $run->output))->toContain("Unable to write snapshot at [$directory/stores_a_snapshot.snap].")
->not->toContain('Snapshot created at')
->and(file_get_contents($project->path($directory)))->toBe('An existing file.');
})->group('integration');
+12 -6
View File
@@ -4,7 +4,7 @@ declare(strict_types=1);
use Symfony\Component\Process\Process;
test('init creates a suite when the tests directory is missing', function (): void {
test('init creates a runnable suite when the tests directory is missing', function (): void {
$root = makeInitProject();
try {
@@ -17,6 +17,11 @@ test('init creates a suite when the tests directory is missing', function (): vo
->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Pest.php')->toBeFile()
->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'TestCase.php')->toBeFile()
->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Unit'.DIRECTORY_SEPARATOR.'ExampleTest.php')->toBeFile();
$suite = runInitProject($root, '--colors=never');
expect($suite->getExitCode())->toBe(0)
->and($suite->getOutput())->toContain('2 passed (2 assertions)');
} finally {
removeInitProject($root);
}
@@ -58,7 +63,7 @@ test('a missing tests directory does not crash while resolving tia state', funct
$root = makeInitProject();
try {
$process = runInitProject($root, '--version');
$process = runInitProject($root);
expect($process->getExitCode())->not->toBe(0)
->and($process->getOutput())->toContain('does not exist')
@@ -85,6 +90,11 @@ function makeInitProject(): string
true,
);
file_put_contents(
$root.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
"<?php\n\nreturn require_once {$autoload};\n",
);
file_put_contents($root.DIRECTORY_SEPARATOR.'run.php', <<<PHP
<?php
@@ -100,10 +110,6 @@ require {$autoload};
\$arguments = array_slice(\$argv, 1);
if (\$arguments === []) {
\$arguments = ['--version'];
}
\$GLOBALS['_composer_bin_dir'] = getcwd().'/vendor/bin';
\$_SERVER['argv'] = ['pest', ...\$arguments];
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('limits focus to the invocation that discovers it', function (array $arguments): void {
$project = Project::withoutGit();
$testFile = 'tests/Unit/FocusTest.php';
$project->write('vendor/pestphp/pest/.temp/.gitkeep', '');
$project->write($testFile, <<<'FIXTURE'
<?php
use Symfony\Component\Process\Process;
test('runs with a named focus group in CI', function (): void {
expect(true)->toBeTrue();
})->only('named-focus');
test('runs an independent Pest invocation', function (): void {
foreach ([[], ['--parallel', '--processes=2']] as $arguments) {
$process = new Process(
[PHP_BINARY, 'vendor/pestphp/pest/bin/pest', 'tests/Unit/GreeterTest.php', '--cache-directory', '.home/nested', ...$arguments],
env: ['PARATEST' => '0'],
);
$process->mustRun();
expect($process->getOutput())->toContain('2 passed');
}
})->only();
test('runs without focus in CI', function (): void {
expect(true)->toBeTrue();
});
FIXTURE);
$focused = $project->pest($testFile, '--cache-directory', $project->path('.home/focused'), ...$arguments);
expect($focused->exitCode)->toBe(0, $focused->describe())
->and($focused->tally())->toContain('1 passed (2 assertions)');
$ci = $project->pest($testFile, '--ci', '--cache-directory', $project->path('.home/ci'), ...$arguments);
expect($ci->exitCode)->toBe(0, $ci->describe())
->and($ci->tally())->toContain('3 passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->group('integration');
+4 -2
View File
@@ -2,6 +2,7 @@
use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\FileState;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
@@ -13,6 +14,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
$projectRoot = dirname(__DIR__, 2);
$home = sys_get_temp_dir().'/pest-tia-'.bin2hex(random_bytes(8));
$fixture = 'tests/Fixtures/Suites/TiaReplayHooks.php';
$configuration = 'tests/Fixtures/Suites/TiaReplayHooks.xml';
mkdir($home, 0755, true);
@@ -24,7 +26,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
$id = fn (string $description): string => 'P\Tests\Fixtures\Suites\TiaReplayHooks::'.Str::evaluable($description);
$graph = new Graph($projectRoot);
$graph->setFingerprint(Fingerprint::compute($projectRoot));
$graph->setFingerprint(Fingerprint::compute($projectRoot, ConfigurationFile::at($projectRoot.DIRECTORY_SEPARATOR.$configuration)));
$graph->setRecordedAtSha($branch, $sha);
$graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? []));
$graph->markKnownTestFiles([$fixture]);
@@ -48,7 +50,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
expect($storage->write(Tia::KEY_GRAPH, (string) $json))->toBeTrue();
$process = new Process(
['php', 'bin/pest', '--configuration', 'tests/Fixtures/Suites/TiaReplayHooks.xml', '--tia'],
['php', 'bin/pest', '--configuration', $configuration, '--tia'],
$projectRoot,
[
'COLLISION_PRINTER' => 'DefaultPrinter',
+102
View File
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function writeAlternateConfiguration(Project $project, string $failOnRisky = 'false'): void
{
$project->write('phpunit.alternate.xml', str_replace(
'failOnRisky="true"',
sprintf('failOnRisky="%s"', $failOnRisky),
(string) file_get_contents($project->path('phpunit.xml')),
));
}
test('naming the default configuration file or its directory still replays the graph', function (array $arguments): void {
$project = Project::make('master');
$project->seed('master');
$result = $project->pest('--tia', ...$arguments);
expect($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe());
})->with([
'file' => [['--configuration', 'phpunit.xml']],
'short option' => [['-c', 'phpunit.xml']],
'equals form' => [['--configuration=phpunit.xml']],
'directory' => [['--configuration', '.']],
])->skipOnWindows();
test('a graph recorded under one configuration file is not replayed under another', function (array $arguments): void {
$project = Project::make('master');
writeAlternateConfiguration($project);
$project->git()->commit('add an alternate configuration');
$project->seed('master');
$result = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('editing the configuration file in use stops the replay', function (array $arguments): void {
$project = Project::make('master');
writeAlternateConfiguration($project);
$project->git()->commit('add an alternate configuration');
$project->seed('master', configuration: 'phpunit.alternate.xml');
$unchanged = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($unchanged->replayed())->toBe(Project::TOTAL_TESTS, $unchanged->describe());
writeAlternateConfiguration($project, failOnRisky: 'true');
$project->git()->commit('change the alternate configuration');
$edited = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($edited->exitCode)->toBe(0, $edited->describe())
->and($edited->replayed())->toBe(0, $edited->describe())
->and($edited->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('editing a configuration file that git ignores stops the replay', function (): void {
$project = Project::make('master');
$project->write('.gitignore', "phpunit.xml\n");
$project->git()->run(['rm', '--cached', '--quiet', 'phpunit.xml']);
$project->git()->commit('stop tracking phpunit.xml');
$project->seed('master');
$unchanged = $project->pest('--tia');
expect($unchanged->replayed())->toBe(Project::TOTAL_TESTS, $unchanged->describe());
$project->write('phpunit.xml', str_replace(
'failOnRisky="true"',
'failOnRisky="false"',
(string) file_get_contents($project->path('phpunit.xml')),
));
$edited = $project->pest('--tia');
expect($edited->exitCode)->toBe(0, $edited->describe())
->and($edited->replayed())->toBe(0, $edited->describe())
->and($edited->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->skipOnWindows();
test('an identical copy of the configuration file under another name does not replay the graph', function (array $arguments): void {
$project = Project::make('master');
$project->write('phpunit.copy.xml', (string) file_get_contents($project->path('phpunit.xml')));
$project->git()->commit('add an identical copy of the configuration');
$project->seed('master');
$result = $project->pest('--tia', '--configuration', 'phpunit.copy.xml', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+78
View File
@@ -25,6 +25,19 @@ function tiaRecordWithSourceReadingTest(Project $project, string ...$arguments):
$project->pest('--tia', ...$arguments);
}
/**
* @return array<int, string>
*/
function tiaEdgeFiles(Project $project, string $testFile): array
{
$graph = $project->graph() ?? [];
return array_map(
fn (int $id): string => $graph['files'][$id],
$graph['edges'][$testFile] ?? [],
);
}
test('a test that reads a file records an edge to it', function (array $arguments): void {
$project = Project::make('master');
@@ -108,3 +121,68 @@ test('a file a test reads does not select it when another file changes', functio
expect($result->affected())->toBe(4, $result->describe())
->and($result->replayed())->toBe(3, $result->describe());
})->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a test that reads an excluded file records no edge to it', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutReadCapture(['app/Greeter.php']);\n");
tiaRecordWithSourceReadingTest($project, ...$arguments);
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php')
->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a test that reads a file outside the excluded globs still records an edge to it', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutReadCapture(['lang/*.json']);\n");
tiaRecordWithSourceReadingTest($project, ...$arguments);
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->toContain('app/Greeter.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('no read records an edge when read capture is off', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutReadCapture();\n");
tiaRecordWithSourceReadingTest($project, ...$arguments);
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php')
->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a watch pattern reruns tests after an excluded file changes', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).<<<'PHP'
pest()->tia()
->withoutReadCapture(['data/*.json'])
->watch(['data/*.json' => 'tests/Unit/GreeterTest.php']);
PHP);
$project->write('data/status.json', '"ready"');
$testFile = 'tests/Unit/GreeterTest.php';
$project->write($testFile, str_replace(
' expect((new Greeter)->greet(\'Nuno\'))->toBe(\'Hello, Nuno!\');',
' expect(file_get_contents(__DIR__.\'/../../data/status.json\'))->toBe(\'"ready"\');',
file_get_contents($project->path($testFile)),
));
$project->git()->commit('add a watched JSON fixture');
$project->seed('master');
$project->write('data/status.json', '"broken"');
$project->git()->commit('change the watched fixture');
$result = $project->pest('--tia', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->affected())->toBe(2, $result->describe())
->and($result->replayed())->toBe(4, $result->describe())
->and($result->output)->toContain('greets a person', 'broken');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+28
View File
@@ -63,3 +63,31 @@ test('still runs every test without a baseline when defaults are disabled', func
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('runs dependent tests when a watched path is removed', function (array $gitArguments, array $arguments): void {
$project = Project::make('master');
$project->write('schema/api.graphql', "type Query { status: String }\n");
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutDefaultWatchPatterns()->watch(['schema/*.graphql' => 'tests/Unit/GreeterTest.php']);\n");
$test = 'tests/Unit/GreeterTest.php';
$project->write($test, str_replace(
"test('greets a person', function (): void {",
"test('greets a person', function (): void {\n expect('schema/api.graphql')->toBeFile();",
file_get_contents($project->path($test)),
));
$project->git()->commit('add a watched schema and its test');
$project->seed('master');
$project->git()->run($gitArguments);
$project->git()->commit('remove the watched path');
$result = $project->pest('--tia', '--filtered', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->affected())->toBe(2, $result->describe())
->and($result->output)->toContain('greets a person', 'schema/api.graphql');
})->with([
'deleted' => [['rm', '--', 'schema/api.graphql']],
'renamed' => [['mv', '--', 'schema/api.graphql', 'moved.graphql']],
])->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="../../../vendor/autoload.php" stopOnFailure="true">
<testsuites>
<testsuite name="parallel-stop-on">
<directory suffix="Test.php">ParallelStopOn</directory>
</testsuite>
</testsuites>
</phpunit>
@@ -0,0 +1,7 @@
<?php
it('deprecates', function () {
trigger_error('user deprecation', E_USER_DEPRECATED);
expect(true)->toBeTrue();
});
@@ -0,0 +1,5 @@
<?php
it('errors', function () {
throw new RuntimeException('boom');
});
@@ -0,0 +1,3 @@
<?php
it('fails', require __DIR__.'/../ParallelStopOnFailure.php');
@@ -0,0 +1,5 @@
<?php
it('is incomplete', function () {
$this->markTestIncomplete('work in progress');
});
@@ -0,0 +1,7 @@
<?php
it('notices', function () {
trigger_error('user notice', E_USER_NOTICE);
expect(true)->toBeTrue();
});
@@ -0,0 +1,5 @@
<?php
it('is risky', function () {
//
});
@@ -0,0 +1,7 @@
<?php
$issue = require __DIR__.'/../ParallelStopOnSharedIssue.php';
it('shares warning', $issue(E_USER_WARNING));
it('shares notice', $issue(E_USER_NOTICE));
@@ -0,0 +1,3 @@
<?php
it('is skipped')->skip('skipping');
@@ -0,0 +1,7 @@
<?php
it('warns', function () {
trigger_error('user warning', E_USER_WARNING);
expect(true)->toBeTrue();
});
@@ -0,0 +1,21 @@
<?php
it('has combined issues', function (): void {
trigger_error('combined warning', E_USER_WARNING);
expect(false)->toBeTrue();
});
it('has repeated warnings', function (): void {
trigger_error('first warning', E_USER_WARNING);
trigger_error('second warning', E_USER_WARNING);
expect(true)->toBeTrue();
});
it('has repeated notifications', function (): void {
trigger_error('first notice', E_USER_NOTICE);
trigger_error('second notice', E_USER_NOTICE);
expect(true)->toBeTrue();
});
@@ -0,0 +1,7 @@
<?php
it('deprecates', function () {
trigger_error('user deprecation', E_USER_DEPRECATED);
expect(true)->toBeTrue();
});
@@ -0,0 +1,5 @@
<?php
it('errors', function () {
throw new RuntimeException('boom');
});
@@ -0,0 +1,3 @@
<?php
it('fails', require __DIR__.'/../../ParallelStopOnFailure.php');
@@ -0,0 +1,5 @@
<?php
it('is incomplete', function () {
$this->markTestIncomplete('work in progress');
});
@@ -0,0 +1,7 @@
<?php
it('notices', function () {
trigger_error('user notice', E_USER_NOTICE);
expect(true)->toBeTrue();
});
@@ -0,0 +1,5 @@
<?php
it('is risky', function () {
//
});
@@ -0,0 +1,7 @@
<?php
$issue = require __DIR__.'/../../ParallelStopOnSharedIssue.php';
it('shares warning', $issue(E_USER_WARNING));
it('shares notice', $issue(E_USER_NOTICE));
@@ -0,0 +1,3 @@
<?php
it('is skipped')->skip('skipping');
@@ -0,0 +1,7 @@
<?php
it('warns', function () {
trigger_error('user warning', E_USER_WARNING);
expect(true)->toBeTrue();
});
@@ -0,0 +1,3 @@
<?php
it('passes 01')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 02')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 03')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 04')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 05')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 06')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 07')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 08')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 09')->assertTrue(true);
@@ -0,0 +1,3 @@
<?php
it('passes 10')->assertTrue(true);
@@ -0,0 +1,20 @@
<?php
return function (): void {
$barrier = getenv('PEST_TEST_STOP_BARRIER');
if ($barrier !== false) {
touch($barrier.'/worker-'.getenv('TEST_TOKEN'));
$deadline = microtime(true) + 10;
while (count(glob($barrier.'/worker-*')) < 2) {
if (microtime(true) >= $deadline) {
throw new RuntimeException('The second parallel worker did not reach the barrier.');
}
usleep(1000);
}
}
expect(false)->toBeTrue();
};
@@ -0,0 +1,7 @@
<?php
return static fn (int $severity): Closure => function () use ($severity): void {
trigger_error('shared issue', $severity);
expect(true)->toBeTrue();
};
+5 -4
View File
@@ -7,6 +7,7 @@ namespace Tests\Fixtures\Tia;
use FilesystemIterator;
use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\FileState;
use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph;
@@ -197,15 +198,15 @@ final class Project
/**
* @param array<int, string> $failing
*/
public function seed(string $branch, bool $sentinel = true, array $failing = []): void
public function seed(string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
{
$this->seedFor($this->path, $branch, $sentinel, $failing);
$this->seedFor($this->path, $branch, $sentinel, $failing, $configuration);
}
/**
* @param array<int, string> $failing
*/
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = []): void
public function seedFor(string $root, string $branch, bool $sentinel = true, array $failing = [], ?string $configuration = null): void
{
$this->graphRoot = $root;
@@ -213,7 +214,7 @@ final class Project
$sha = new GitRepo($root)->sha();
$graph = new Graph($root);
$graph->setFingerprint(Fingerprint::compute($root));
$graph->setFingerprint(Fingerprint::compute($root, $configuration === null ? null : ConfigurationFile::at($root.DIRECTORY_SEPARATOR.$configuration)));
$graph->setRecordedAtSha($branch, $sha);
$graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? []));
@@ -0,0 +1,114 @@
<?php
use Pest\Contracts\Plugins\AddsOutput;
use Pest\Contracts\Plugins\ObservesExitCode;
use Pest\Plugin\Loader;
use Pest\Plugins\Actions\CallsAddsOutput;
function withExitCodePlugins(array $plugins, Closure $test): void
{
$loader = new ReflectionClass(Loader::class);
$instances = $loader->getProperty('instances');
$loaded = $loader->getProperty('loaded');
$previousInstances = $instances->getValue();
$previousLoaded = $loaded->getValue();
try {
$instances->setValue(null, $plugins);
$loaded->setValue(null, true);
$test();
} finally {
$instances->setValue(null, $previousInstances);
$loaded->setValue(null, $previousLoaded);
}
}
test('exit code observers run after every output plugin', function (): void {
$events = new ArrayObject;
$observer = new readonly class($events) implements ObservesExitCode
{
public function __construct(private ArrayObject $events) {}
public function observeExitCode(int $exitCode): void
{
$this->events[] = ['observed', $exitCode];
}
};
$output = new readonly class($events) implements AddsOutput
{
public function __construct(private ArrayObject $events) {}
public function addOutput(int $exitCode): int
{
$this->events[] = ['output', $exitCode];
return $exitCode + 1;
}
};
withExitCodePlugins([$observer, $output, clone $observer, clone $output], function () use ($events): void {
expect(CallsAddsOutput::execute(0))->toBe(2)
->and($events->getArrayCopy())->toBe([
['output', 0],
['output', 1],
['observed', 2],
['observed', 2],
]);
});
});
test('exit code observers receive unchanged codes when there are no output plugins', function (int $exitCode): void {
$observer = new class implements ObservesExitCode
{
public ?int $exitCode = null;
public function observeExitCode(int $exitCode): void
{
$this->exitCode = $exitCode;
}
};
withExitCodePlugins([$observer], function () use ($observer, $exitCode): void {
expect(CallsAddsOutput::execute($exitCode))->toBe($exitCode)
->and($observer->exitCode)->toBe($exitCode);
});
})->with([0, 1, 2, 42]);
test('output plugins work without exit code observers', function (): void {
$output = new class implements AddsOutput
{
public function addOutput(int $exitCode): int
{
return 42;
}
};
withExitCodePlugins([$output], function (): void {
expect(CallsAddsOutput::execute(0))->toBe(42);
});
});
test('exit code observers are not called when an output plugin throws', function (): void {
$observer = new class implements ObservesExitCode
{
public bool $called = false;
public function observeExitCode(int $exitCode): void
{
$this->called = true;
}
};
$output = new class implements AddsOutput
{
public function addOutput(int $exitCode): int
{
throw new RuntimeException('Output failed');
}
};
withExitCodePlugins([$observer, $output], function () use ($observer): void {
expect(fn (): int => CallsAddsOutput::execute(0))->toThrow(RuntimeException::class, 'Output failed')
->and($observer->called)->toBeFalse();
});
});
+8
View File
@@ -1,5 +1,6 @@
<?php
use Pest\Exceptions\InvalidOption;
use Pest\Plugins\Retry;
it('orders by defects and stop on defects if when --retry is used ', function (): void {
@@ -12,3 +13,10 @@ it('orders by defects and stop on defects if when --retry is used ', function ()
'--stop-on-failure',
]);
});
it('rejects retry with a parallel flag', function (string $parallelFlag): void {
(new Retry)->handleArguments(['--retry', $parallelFlag]);
})->with(['--parallel', '-p'])->throws(
InvalidOption::class,
'The [--retry] option is not supported when running in parallel.',
);
+309 -2
View File
@@ -2,6 +2,8 @@
use Pest\Exceptions\InvalidOption;
use Pest\Plugins\Shard;
use Pest\Subscribers\EnsureShardTimingsAreCollected;
use Pest\Support\Arr;
use SebastianBergmann\CliParser\Parser;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\BufferedOutput;
@@ -94,7 +96,7 @@ describe('buildFilterArgument', function (): void {
expect($filter)->toBe('Tests\\\\(Unit\\\\FooTest::|Feature\\\\BarTest::)');
});
it('returns empty string for empty test list', function (): void {
it('generates a filter that selects no tests for an empty test list', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
@@ -103,7 +105,7 @@ describe('buildFilterArgument', function (): void {
$filter = $method->invoke($shard, []);
expect($filter)->toBeEmpty();
expect('Tests\\Unit\\ExampleTest::testExample')->not->toMatch('/'.$filter.'/');
});
it('generates compact filter for deeply nested namespaces', function (): void {
@@ -624,3 +626,308 @@ describe('addOutput', function (): void {
->and($outputText)->not->toContain('Shard:');
});
});
describe('timings file', function (): void {
afterEach(function (): void {
$reflection = new ReflectionClass(Shard::class);
$reflection->getProperty('timingsFilename')->setValue(null, null);
$reflection->getProperty('externalTimings')->setValue(null, null);
$reflection->getProperty('collectedTimings')->setValue(null, null);
$reflection->getProperty('knownTests')->setValue(null, null);
$reflection->getProperty('updateShards')->setValue(null, false);
$reflection->getProperty('shard')->setValue(null, null);
new ReflectionClass(EnsureShardTimingsAreCollected::class)
->getProperty('timings')
->setValue(null, []);
});
it('reads and writes shards.json until a plugin overrides the filename', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('shardsPath');
expect($method->invoke($shard))->toEndWith('.pest'.DIRECTORY_SEPARATOR.'shards.json');
Shard::useTimingsFile('mutation-shards.json');
expect($method->invoke($shard))->toEndWith('.pest'.DIRECTORY_SEPARATOR.'mutation-shards.json');
});
it('prefers timings supplied by a plugin over the ones collected from the test run', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
new ReflectionClass(EnsureShardTimingsAreCollected::class)
->getProperty('timings')
->setValue(null, ['Tests\\Unit\\CollectedTest' => 9.0]);
Shard::useTimings(['Tests\\Unit\\SuppliedTest' => 1.5]);
$method = new ReflectionClass($shard)->getMethod('collectTimings');
expect($method->invoke($shard))->toBe(['Tests\\Unit\\SuppliedTest' => 1.5]);
});
it('records known tests without supplied timings as zero', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$reflection = new ReflectionClass($shard);
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\MutatedTest', 'Tests\\Unit\\PlainTest']);
Shard::useTimingsFile('shards-fixture.json');
Shard::useTimings($timings = ['Tests\\Unit\\MutatedTest' => 4.5]);
$path = $reflection->getMethod('shardsPath')->invoke($shard);
try {
$reflection->getMethod('writeTimings')->invoke($shard, $timings);
expect(json_decode((string) file_get_contents($path), true)['timings'])->toEqual([
'Tests\\Unit\\MutatedTest' => 4.5,
'Tests\\Unit\\PlainTest' => 0.0,
]);
} finally {
@unlink($path);
}
});
it('keeps timings supplied by a plugin even when the test suite did not pass', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
new ReflectionClass($shard)->getProperty('updateShards')->setValue(null, true);
Shard::useTimingsFile('mutation-shards.json');
Shard::useTimings(['Tests\\Unit\\SuppliedTest' => 1.5]);
$paratest = Arr::get($_SERVER, 'PARATEST');
unset($_SERVER['PARATEST']);
try {
expect($shard->addOutput(1))->toBe(1)
->and($output->fetch())->toContain('mutation-shards.json updated with timings for 1 test class.');
} finally {
if ($paratest !== null) {
$_SERVER['PARATEST'] = $paratest;
}
}
});
it('strips coverage arguments when building the list-tests command', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', '--coverage-php=/tmp/coverage.php', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
});
it('strips the separate path of a coverage argument when building the list-tests command', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', '--coverage-php', '/tmp/coverage.php', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
});
it('strips the separate value of a coverage option when building the list-tests command', function (string $option): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', $option, '/tmp/value', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
})->with(['--coverage-jsonl', '--coverage-filter', '--min', '--exactly']);
it('strips the separate value of the parallel processes option when building the list-tests command', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('buildListTestsCommand');
$command = $method->invoke($shard, ['bin/pest', '--parallel', '--processes', '4', '--update-shards'], 'tests');
expect($command)->toBe([
PHP_BINARY,
'bin/pest',
'--update-shards',
'--test-directory=tests',
'--list-tests',
]);
});
it('keeps a unit saved with no test classes, but drops one emptied by removed classes', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('withoutRemovedTests');
$units = [
'src/Explicit.php' => ['time' => 1.0, 'tests' => []],
'src/Emptied.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\RemovedTest']],
];
expect($method->invoke($shard, $units, ['Tests\\Unit\\AliveTest']))->toBe([
'src/Explicit.php' => ['time' => 1.0, 'tests' => []],
]);
});
it('drops test classes that no longer exist from the stored units', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('withoutRemovedTests');
$units = [
'Tests\\Unit\\AliveTest' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\AliveTest']],
'Tests\\Unit\\RemovedTest' => ['time' => 100.0, 'tests' => ['Tests\\Unit\\RemovedTest']],
'src/Bundle.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\AliveTest', 'Tests\\Unit\\RemovedTest']],
];
expect($method->invoke($shard, $units, ['Tests\\Unit\\AliveTest']))->toBe([
'Tests\\Unit\\AliveTest' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\AliveTest']],
'src/Bundle.php' => ['time' => 2.0, 'tests' => ['Tests\\Unit\\AliveTest']],
]);
});
});
describe('units', function (): void {
afterEach(function (): void {
$reflection = new ReflectionClass(Shard::class);
$reflection->getProperty('timingsFilename')->setValue(null, null);
$reflection->getProperty('externalTimings')->setValue(null, null);
$reflection->getProperty('collectedTimings')->setValue(null, null);
$reflection->getProperty('knownTests')->setValue(null, null);
$reflection->getProperty('ownership')->setValue(null, null);
$reflection->getProperty('shardsOutdated')->setValue(null, false);
});
it('treats a bare timing as a unit bundling only its own test class', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('normaliseUnits');
expect($method->invoke($shard, ['Tests\\Unit\\FooTest' => 1.5]))->toBe([
'Tests\\Unit\\FooTest' => ['time' => 1.5, 'tests' => ['Tests\\Unit\\FooTest']],
]);
});
it('keeps the test classes a unit bundles together in one shard', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('partitionByTime');
$partitions = $method->invoke($shard, [
'app/Heavy.php' => ['time' => 10.0, 'tests' => ['Tests\\Unit\\OneTest', 'Tests\\Unit\\TwoTest']],
'app/Light.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\ThreeTest']],
'app/Medium.php' => ['time' => 4.0, 'tests' => ['Tests\\Unit\\FourTest']],
], 2);
expect(array_keys($partitions[0]))->toBe(['app/Heavy.php'])
->and(array_keys($partitions[1]))->toBe(['app/Medium.php', 'app/Light.php']);
});
it('owns every unit when the run is not time-balanced', function (): void {
expect(Shard::owns('app/Anything.php'))->toBeTrue();
});
it('owns only the units allocated to the current shard', function (): void {
new ReflectionClass(Shard::class)->getProperty('ownership')->setValue(null, [
'app/Mine.php' => true,
'app/Theirs.php' => false,
]);
expect(Shard::owns('app/Mine.php'))->toBeTrue()
->and(Shard::owns('app/Theirs.php'))->toBeFalse()
->and(new ReflectionClass(Shard::class)->getProperty('shardsOutdated')->getValue())->toBeFalse();
});
it('owns a unit the timings file does not know in every shard, and reports the file as out of date', function (): void {
$reflection = new ReflectionClass(Shard::class);
$reflection->getProperty('ownership')->setValue(null, ['app/Theirs.php' => false]);
expect(Shard::owns('app/New.php'))->toBeTrue()
->and($reflection->getProperty('shardsOutdated')->getValue())->toBeTrue();
});
it('keeps a unit that bundles no test class when writing', function (): void {
$shard = new Shard(new BufferedOutput);
$reflection = new ReflectionClass($shard);
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\FooTest']);
expect(array_keys($reflection->getMethod('unitsToWrite')->invoke($shard, [
'app/Uncovered.php' => ['time' => 0.0, 'tests' => []],
'app/Gone.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\GoneTest']],
])))->toBe(['app/Uncovered.php', 'Tests\\Unit\\FooTest']);
});
it('collects every test class the given units bundle', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$method = new ReflectionClass($shard)->getMethod('testsOf');
expect($method->invoke($shard, [
'app/One.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']],
'app/Two.php' => ['time' => 1.0, 'tests' => ['Tests\\Unit\\BarTest']],
]))->toBe(['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']);
});
it('writes bundled units, and reads back both shapes', function (): void {
$output = new BufferedOutput;
$shard = new Shard($output);
$reflection = new ReflectionClass($shard);
$reflection->getProperty('knownTests')->setValue(null, ['Tests\\Unit\\FooTest', 'Tests\\Unit\\BarTest']);
Shard::useTimingsFile('units-fixture.json');
Shard::useTimings($units = [
'app/One.php' => ['time' => 4.5, 'tests' => ['Tests\\Unit\\FooTest']],
]);
$path = $reflection->getMethod('shardsPath')->invoke($shard);
try {
$reflection->getMethod('writeTimings')->invoke($shard, $units);
expect(json_decode((string) file_get_contents($path), true))->toHaveKey('units')
->and($reflection->getMethod('loadShardsFile')->invoke($shard))->toEqual([
'app/One.php' => ['time' => 4.5, 'tests' => ['Tests\\Unit\\FooTest']],
'Tests\\Unit\\BarTest' => ['time' => 0.0, 'tests' => ['Tests\\Unit\\BarTest']],
]);
} finally {
@unlink($path);
}
});
});
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
use Pest\Plugins\Tia\ConfigurationFile;
beforeEach(function (): void {
$this->projectRoot = sys_get_temp_dir().'/pest-tia-configuration-'.bin2hex(random_bytes(4));
mkdir($this->projectRoot, 0755, true);
$contents = "<?xml version=\"1.0\"?>\n<phpunit/>\n";
file_put_contents($this->projectRoot.'/phpunit.xml', $contents);
file_put_contents($this->projectRoot.'/phpunit.copy.xml', $contents);
});
afterEach(function (): void {
@unlink($this->projectRoot.'/phpunit.xml');
@unlink($this->projectRoot.'/phpunit.copy.xml');
@rmdir($this->projectRoot);
});
it('fingerprints the path and the content of the configuration file', function (): void {
$fingerprint = ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->fingerprint($this->projectRoot);
expect($fingerprint)->toBe('phpunit.xml:'.hash_file('xxh128', $this->projectRoot.'/phpunit.xml'));
});
it('tells an identical copy under another name apart from the original', function (): void {
expect(ConfigurationFile::at($this->projectRoot.'/phpunit.copy.xml')->fingerprint($this->projectRoot))
->not->toBe(ConfigurationFile::at($this->projectRoot.'/phpunit.xml')->fingerprint($this->projectRoot));
});
it('resolves a configuration directory the way PHPUnit does', function (): void {
expect(ConfigurationFile::fromArguments(['--configuration', $this->projectRoot])->fingerprint($this->projectRoot))
->toBe(ConfigurationFile::projectDefault()->fingerprint($this->projectRoot));
});
it('gives a run with --no-configuration its own fingerprint', function (): void {
expect(ConfigurationFile::fromArguments(['--no-configuration'])->fingerprint($this->projectRoot))
->toBe('none')
->not->toBe(ConfigurationFile::projectDefault()->fingerprint($this->projectRoot));
});
+8 -8
View File
@@ -56,7 +56,7 @@ describe('compute()', function (): void {
$fingerprint = Fingerprint::compute($clone);
expect($fingerprint['structural']['composer_lock'])->not->toBeNull()
->and($fingerprint['structural']['phpunit_xml'])->not->toBeNull();
->and($fingerprint['structural']['phpunit_configuration'])->not->toBeNull();
} finally {
fingerprintRemoveDirectory($clone);
}
@@ -79,9 +79,9 @@ describe('compute()', function (): void {
$worktreeFingerprint = Fingerprint::compute($worktree);
expect($worktreeFingerprint['structural']['composer_lock'])->not->toBeNull()
->and($worktreeFingerprint['structural']['phpunit_xml'])->not->toBeNull()
->and($worktreeFingerprint['structural']['phpunit_configuration'])->not->toBeNull()
->and($worktreeFingerprint['structural']['composer_lock'])->toBe($cloneFingerprint['structural']['composer_lock'])
->and($worktreeFingerprint['structural']['phpunit_xml'])->toBe($cloneFingerprint['structural']['phpunit_xml']);
->and($worktreeFingerprint['structural']['phpunit_configuration'])->toBe($cloneFingerprint['structural']['phpunit_configuration']);
} finally {
fingerprintRemoveDirectory($clone);
}
@@ -91,17 +91,17 @@ describe('compute()', function (): void {
$clone = fingerprintRepository();
try {
file_put_contents($clone.'/composer.lock', '{"packages": []}');
file_put_contents($clone.'/.gitignore', "phpunit.xml\n");
file_put_contents($clone.'/phpunit.xml', '<phpunit/>');
file_put_contents($clone.'/.gitignore', "composer.lock\n");
fingerprintGit($clone, 'add', '-A');
fingerprintGit($clone, 'commit', '-q', '-m', 'init');
file_put_contents($clone.'/phpunit.xml', '<phpunit/>');
file_put_contents($clone.'/composer.lock', '{"packages": []}');
$fingerprint = Fingerprint::compute($clone);
expect($fingerprint['structural']['phpunit_xml'])->toBeNull()
->and($fingerprint['structural']['composer_lock'])->not->toBeNull();
expect($fingerprint['structural']['composer_lock'])->toBeNull()
->and($fingerprint['structural']['phpunit_configuration'])->not->toBeNull();
} finally {
fingerprintRemoveDirectory($clone);
}
+205
View File
@@ -2,8 +2,11 @@
declare(strict_types=1);
use Pest\Plugins\Tia\Configuration;
use Pest\Plugins\Tia\ReadCapture;
use Pest\Plugins\Tia\Recorder;
use Pest\Plugins\Tia\WatchPatterns;
use Pest\Support\Container;
use Tests\Fixtures\Tia\LoggingFileWrapper;
/**
@@ -202,6 +205,111 @@ describe('the file wrapper', function (): void {
}
});
it('reports a missing path to the error handler as plain PHP does while a test records', function (): void {
$missing = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-missing-'.bin2hex(random_bytes(8));
$warnings = [];
$results = [];
set_error_handler(function (int $level, string $message) use (&$warnings): bool {
$warnings[] = $message;
return true;
});
try {
tiaReadCaptureLinks(function () use ($missing, &$warnings, &$results): void {
clearstatcache();
$results['quiet'] = [file_exists($missing), is_file($missing), is_dir($missing), is_link($missing)];
$results['warnings after quiet probes'] = count($warnings);
$results['stat'] = stat($missing);
$results['warnings after stat'] = count($warnings);
});
} finally {
restore_error_handler();
}
expect($results)->toBe([
'quiet' => [false, false, false, false],
'warnings after quiet probes' => 0,
'stat' => false,
'warnings after stat' => 1,
]);
});
it('keeps no memory for each filesystem call while a test records', function (): void {
$growth = 0;
tiaReadCaptureLinks(function () use (&$growth): void {
fclose(fopen(__FILE__, 'rb'));
$before = memory_get_usage();
for ($i = 0; $i < 10_000; $i++) {
fclose(fopen(__FILE__, 'rb'));
}
$growth = memory_get_usage() - $before;
});
expect($growth)->toBeLessThan(100_000);
});
it('keeps no memory for each test it records', function (): void {
tiaReadCaptureLinks(fn (): bool => true);
$before = memory_get_usage();
for ($i = 0; $i < 5_000; $i++) {
tiaReadCaptureLinks(fn (): bool => true);
}
expect(memory_get_usage() - $before)->toBeLessThan(100_000);
});
it('is restored quietly when the test already restored it', function (): void {
$errors = [];
set_error_handler(function (int $level, string $message) use (&$errors): bool {
$errors[] = $message;
return true;
});
try {
tiaReadCaptureLinks(fn (): bool => stream_wrapper_restore('file'));
} finally {
restore_error_handler();
}
expect($errors)->toBeEmpty()
->and(tiaReadCaptureWrapperType())->toBe('plainfile');
});
it('is restored quietly when the test unregistered it', function (): void {
$errors = [];
set_error_handler(function (int $level, string $message) use (&$errors): bool {
$errors[] = $message;
return true;
});
try {
tiaReadCaptureLinks(fn (): bool => stream_wrapper_unregister('file'));
} finally {
restore_error_handler();
if (! in_array('file', stream_get_wrappers(), true)) {
stream_wrapper_restore('file');
}
}
expect($errors)->toBeEmpty()
->and(tiaReadCaptureWrapperType())->toBe('plainfile');
});
it('reports symlinks as links while a test records', function (bool $targetExists, bool $expectedExists): void {
$directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-read-capture-'.bin2hex(random_bytes(8));
mkdir($directory);
@@ -294,3 +402,100 @@ describe('a wrapper already registered for file://', function (): void {
->and(tiaReadCaptureWrapperClass())->toBe(LoggingFileWrapper::class);
});
});
describe('withoutReadCapture()', function (): void {
beforeEach(function (): void {
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
$this->excluded = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/ReadCapture.php');
$this->kept = (string) realpath(dirname(__DIR__, 4).'/src/Plugins/Tia/Recorder.php');
});
afterEach(function (): void {
Container::getInstance()->add(WatchPatterns::class, new WatchPatterns);
});
it('does not link a file matching an excluded glob', function (): void {
(new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']);
expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($this->excluded)))->toBeEmpty();
});
it('still links a file outside the excluded globs', function (): void {
(new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']);
$links = tiaReadCaptureLinks(function (): void {
file_get_contents($this->excluded);
file_get_contents($this->kept);
});
expect($links)->toBe([$this->kept]);
});
it('keeps the file wrapper registered while globs are excluded', function (): void {
(new Configuration)->withoutReadCapture(['src/Plugins/Tia/Read*.php']);
$during = '';
tiaReadCaptureLinks(function () use (&$during): void {
$during = tiaReadCaptureWrapperType();
});
expect($during)->toBe('user-space');
});
it('links every read when the list of globs is empty', function (): void {
(new Configuration)->withoutReadCapture([]);
expect(tiaReadCaptureLinks(fn (): string|false => file_get_contents($this->excluded)))->toBe([$this->excluded]);
});
it('registers no wrapper and links no read when called without globs', function (): void {
(new Configuration)->withoutReadCapture();
$during = '';
$links = tiaReadCaptureLinks(function () use (&$during): void {
$during = tiaReadCaptureWrapperType();
file_get_contents($this->kept);
});
expect($during)->toBe('plainfile')
->and($links)->toBeEmpty()
->and(tiaReadCaptureWrapperType())->toBe('plainfile');
});
it('keeps the explicit links when called without globs', function (): void {
(new Configuration)->withoutReadCapture();
$recorder = new Recorder;
$recorder->activateLinkTracking();
$recorder->beginTest('Some\Missing\TestClass', 'it links', '/project/tests/Feature/LinksTest.php');
$recorder->linkSource('/project/resources/views/welcome.blade.php');
$recorder->endTest();
expect($recorder->perTestFiles())
->toBe(['/project/tests/Feature/LinksTest.php' => ['/project/resources/views/welcome.blade.php']]);
});
it('leaves a wrapper already registered for file:// untouched when called without globs', function (): void {
(new Configuration)->withoutReadCapture();
LoggingFileWrapper::enable();
try {
$during = null;
$links = tiaReadCaptureLinks(function () use (&$during): void {
$during = tiaReadCaptureWrapperClass();
file_get_contents($this->kept);
});
} finally {
LoggingFileWrapper::disable();
}
expect($during)->toBe(LoggingFileWrapper::class)
->and($links)->toBeEmpty();
});
});
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
use Pest\Plugins\Tia\SourceScope;
describe('contains()', function (): void {
it('excludes only the files matching the suffix of an excluded directory', function (): void {
$scope = new SourceScope(
['/project/src'],
[['path' => '/project/src', 'prefix' => '', 'suffix' => 'Test.php']],
);
expect($scope->contains('/project/src/Calculator.php'))->toBeTrue()
->and($scope->contains('/project/src/CalculatorTest.php'))->toBeFalse();
});
it('excludes only the files matching the prefix of an excluded directory', function (): void {
$scope = new SourceScope(
['/project/src'],
[['path' => '/project/src', 'prefix' => 'Legacy', 'suffix' => '.php']],
);
expect($scope->contains('/project/src/Calculator.php'))->toBeTrue()
->and($scope->contains('/project/src/LegacyCalculator.php'))->toBeFalse();
});
it('excludes every file of an excluded directory without a prefix or suffix', function (): void {
$scope = new SourceScope(
['/project'],
[['path' => '/project/storage/framework', 'prefix' => '', 'suffix' => '']],
);
expect($scope->contains('/project/app/Calculator.php'))->toBeTrue()
->and($scope->contains('/project/storage/framework/views/compiled.php'))->toBeFalse();
});
});
+85
View File
@@ -181,3 +181,88 @@ it('uses custom mappings for an unknown Vue page with defaults disabled', functi
expect($graph->affected(['resources/js/Pages/Enroll.vue']))->toBe(['tests/Unit/CalculatorTest.php']);
});
it('captures every read by default', function (): void {
expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse();
});
it('excludes reads of files matching a glob', function (): void {
$configuration = new Configuration;
expect($configuration->withoutReadCapture(['lang/*.json']))->toBe($configuration)
->and($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue()
->and($this->watchPatterns->excludesRead('lang/vendor/package/fr.json'))->toBeFalse()
->and($this->watchPatterns->excludesRead('resources/lang/fr.json'))->toBeFalse()
->and($this->watchPatterns->excludesRead('lang/fr.php'))->toBeFalse();
});
it('matches read globs like watch patterns', function (): void {
(new Configuration)->withoutReadCapture([
'lang/**/*.json !lang/vendor/keep/**',
'tests/Fixtures/*.csv',
'.env.testing',
]);
expect($this->watchPatterns->excludesRead('lang/vendor/package/fr.json'))->toBeTrue()
->and($this->watchPatterns->excludesRead('lang/vendor/keep/fr.json'))->toBeFalse()
->and($this->watchPatterns->excludesRead('tests/Fixtures/orders.csv'))->toBeTrue()
->and($this->watchPatterns->excludesRead('tests/Fixtures/nested/orders.csv'))->toBeFalse()
->and($this->watchPatterns->excludesRead('.env.testing'))->toBeTrue()
->and($this->watchPatterns->excludesRead('.env.local'))->toBeFalse();
});
it('does not exclude a dotfile unless the glob names it', function (): void {
(new Configuration)->withoutReadCapture(['**']);
expect($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue()
->and($this->watchPatterns->excludesRead('.env.testing'))->toBeFalse();
});
it('accumulates read exclusions from repeated calls', function (): void {
(new Configuration)
->withoutReadCapture(['lang/*.json'])
->withoutReadCapture(['resources/lang/*.json']);
expect($this->watchPatterns->excludesRead('lang/fr.json'))->toBeTrue()
->and($this->watchPatterns->excludesRead('resources/lang/fr.json'))->toBeTrue();
});
it('does not turn read capture off for an empty exclusion list', function (): void {
(new Configuration)->withoutReadCapture([]);
expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse();
});
it('turns read capture off without a list of globs', function (): void {
(new Configuration)->withoutReadCapture();
expect($this->watchPatterns->isReadCaptureEnabled())->toBeFalse();
});
it('keeps read capture off when globs are added afterwards', function (): void {
(new Configuration)
->withoutReadCapture()
->withoutReadCapture(['lang/*.json']);
expect($this->watchPatterns->isReadCaptureEnabled())->toBeFalse();
});
it('captures reads again on reset', function (): void {
(new Configuration)
->withoutReadCapture()
->withoutReadCapture(['lang/*.json']);
$this->watchPatterns->reset();
expect($this->watchPatterns->isReadCaptureEnabled())->toBeTrue()
->and($this->watchPatterns->excludesRead('lang/fr.json'))->toBeFalse();
});
it('does not change the default watch fallbacks of an excluded read', function (): void {
(new Configuration)->withoutReadCapture(['.env.testing']);
expect($this->watchPatterns->matchedDirectories(getcwd(), ['.env.testing']))->toBe(['tests']);
});
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
use Tests\Fixtures\Tia\GitRepo;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('dirty selects paths with spaces and Unicode', function (string $directory): void {
$project = Project::make();
$root = $directory === '' ? $project->path() : $project->nested($directory);
$testDirectory = $directory === '' ? 'tests/Unit' : $directory.'/tests/Unit';
$project->git()->run(['config', 'core.quotePath', 'true']);
foreach (['RegularTest', 'Before Rename Test', 'UnchangedTest', 'DeletedTest'] as $file) {
$project->write($testDirectory.'/'.$file.'.php', "<?php\n\nit('runs $file')->assertTrue(true);\n");
}
$project->git()->commit('add dirty test fixtures');
$project->git()->run(['mv', $testDirectory.'/Before Rename Test.php', $testDirectory.'/After Rename Test.php']);
$project->write($testDirectory.'/RegularTest.php', "<?php\n\nit('runs modified test')->assertTrue(true);\n");
$project->write($testDirectory.'/Café Test.php', "<?php\n\nit('runs new test')->assertTrue(true);\n");
unlink($project->path($testDirectory.'/DeletedTest.php'));
$result = $project->pestIn($root, '--dirty');
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->toContain('3 passed (3 assertions)', 'runs modified test', 'runs Before Rename Test', 'runs new test')
->not->toContain('runs UnchangedTest', 'runs DeletedTest');
})->with([
'repository root' => [''],
'project subdirectory' => ['backend'],
'subdirectory with leading space' => [' backend'],
])->skipOnWindows();
test('dirty ignores a test removed after staging a modification', function (array $arguments): void {
$project = Project::make();
$testFile = 'tests/Unit/GreeterTest.php';
$project->write($testFile, "<?php\n\nit('runs staged test')->assertTrue(true);\n");
$project->git()->run(['add', '--', $testFile]);
unlink($project->path($testFile));
$result = $project->pest('--dirty', '--fail-on-empty-test-suite', '--cache-directory', $project->path('.home/cache'), ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->toContain('No "dirty" tests found.');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('dirty selects an unresolved test only while its file exists', function (): void {
$project = Project::make();
$testFile = 'tests/Unit/GreeterTest.php';
$project->git()->switchTo('modified', true);
$project->write($testFile, "<?php\n\nit('runs the unresolved test')->assertTrue(true);\n");
$project->git()->commit('modify the test');
$project->git()->switchTo('master');
unlink($project->path($testFile));
$project->git()->commit('remove the test');
$merge = new Process(['git', 'merge', '--no-edit', 'modified'], $project->path(), GitRepo::ENV);
expect($merge->run())->toBe(1);
$present = $project->pest('--dirty', '--fail-on-empty-test-suite');
expect($present->exitCode)->toBe(0, $present->describe())
->and($present->output)->toContain('1 passed (1 assertions)', 'runs the unresolved test');
unlink($project->path($testFile));
$missing = $project->pest('--dirty', '--fail-on-empty-test-suite');
expect($missing->exitCode)->toBe(0, $missing->describe())
->and($missing->output)->toContain('No "dirty" tests found.');
})->skipOnWindows();
+65
View File
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
use Tests\Fixtures\Tia\Project;
test('runs with a nested Composer vendor directory', function (string $binary, array $arguments, int $assertions): void {
$project = Project::withoutGit();
try {
$vendor = 'build/dependencies';
mkdir($project->path('build'));
rename($project->path('vendor'), $project->path($vendor));
$project->write($vendor.'/composer/installed.php', <<<'METADATA'
<?php
return ['root' => ['install_path' => __DIR__.'/../../..']];
METADATA);
$project->write($vendor.'/bin/pest', <<<'PROXY'
<?php
$GLOBALS['_composer_bin_dir'] = __DIR__;
$GLOBALS['_composer_autoload_path'] = __DIR__.'/../autoload.php';
return include __DIR__.'/../pestphp/pest/bin/pest';
PROXY);
$project->write($vendor.'/pestphp/pest/.temp/.gitkeep', '');
$project->write('phpunit.xml', <<<'CONFIGURATION'
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="build/dependencies/autoload.php" cacheDirectory=".phpunit.cache"/>
CONFIGURATION);
$test = 'tests/NestedVendorTest.php';
$project->write($test, <<<'FIXTURE'
<?php
test('uses the project root', function (): void {
expect(Pest\TestSuite::getInstance()->rootPath)->toBe(realpath(__DIR__.'/..'));
if (($_SERVER['PARATEST'] ?? null) === '1') {
expect($_SERVER['PEST_PARALLEL'] ?? null)->toBe('1');
}
});
FIXTURE);
$process = new Process(
[PHP_BINARY, $project->path($vendor.'/'.$binary), '--configuration='.$project->path('phpunit.xml'), '--colors=never', $project->path($test), ...$arguments],
dirname($project->path),
['PARATEST' => '0', 'PAO_DISABLE' => '1'],
);
expect($process->run())->toBe(0)
->and($process->getOutput())->toContain("1 passed ($assertions assertions)");
} finally {
Project::destroyAll();
}
})->with([
'Composer proxy' => ['bin/pest', [], 1],
'Composer proxy with workers' => ['bin/pest', ['--parallel', '--processes=2'], 2],
'direct execution with workers' => ['pestphp/pest/bin/pest', ['--parallel', '--processes=2'], 2],
]);
+2 -2
View File
@@ -4,7 +4,7 @@ use Symfony\Component\Process\Process;
$run = function (): ?string {
$process = new Process(
array_merge(['php', 'bin/pest', '--parallel', '--processes=3'], func_get_args()),
array_merge(['php', '-d', 'memory_limit=512M', 'bin/pest', '--parallel', '--processes=3', '--passthru-php=-d memory_limit=512M'], func_get_args()),
dirname(__DIR__, 2),
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
);
@@ -21,7 +21,7 @@ test('parallel', function () use ($run): void {
$output = implode("\n", array_slice(explode("\n", (string) $output), -10));
$profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile');
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1727 passed (3739 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 30 skipped, 1792 passed (3849 assertions)';
expect($output)
->toContain("Tests: {$expected}")
+164
View File
@@ -0,0 +1,164 @@
<?php
use Symfony\Component\Process\Process;
$run = function (int $exitCode, array $arguments, array $environment = []): string {
$process = new Process(
['php', 'bin/pest', '--parallel', '--processes=1', '--order-by=default', '--fail-on-deprecation', ...$arguments, 'tests/Fixtures/Suites/ParallelStopOn'],
dirname(__DIR__, 2),
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1', ...$environment],
);
$process->run();
$output = (string) removeAnsiEscapeSequences($process->getOutput());
expect($process->getExitCode())->toBe($exitCode, $process->getErrorOutput().$output)
->and($process->getErrorOutput())->toBeEmpty()
->and($output)->toMatch('/Tests:\s+\d+ [^\r\n]+\(\d+ assertions\)/');
return $output;
};
$outcomes = [
'failure' => ['failure', 'fails', 'failed', 1],
'defect' => ['defect', 'fails', 'failed', 1],
'error' => ['error', 'errors', 'failed', 2],
'risky' => ['risky', 'is risky', 'risky', 1],
'incomplete' => ['incomplete', 'is incomplete', 'incomplete', 0],
'warning' => ['warning', 'warns', 'warning', 0],
'notice' => ['notice', 'notices', 'notice', 0],
'deprecation' => ['deprecation', 'deprecates', 'deprecated', 1],
'skipped' => ['skipped', 'is skipped', 'skipped', 0],
];
test('parallel stop-on fixtures run completely without a stop flag', function (string $flag, string $name, string $outcome, int $exitCode) use ($run): void {
$output = $run($exitCode, ['--filter', "($name|passes)"]);
$plural = in_array($outcome, ['warning', 'notice'], true) ? $outcome.'s' : $outcome;
expect($output)->toContain("Tests: 2 $plural, 10 passed");
})->with(array_diff_key($outcomes, ['defect' => true]))->skipOnWindows();
test('parallel honors stop-on flags with worker recycling', function (string $flag, string $name, string $outcome, int $exitCode, int $batchSize) use ($run): void {
$output = $run($exitCode, ['--filter', "($name|passes)", "--stop-on-$flag", "--max-batch-size=$batchSize"]);
expect($output)->toContain("Tests: 1 $outcome (")
->not->toMatch('/\d+ passed/');
})->with($outcomes)->with([0, 1])->skipOnWindows();
test('parallel honors numeric stop-on thresholds', function (string $flag, string $name, string $outcome, int $exitCode, int $batchSize) use ($run): void {
$output = $run($exitCode, ['--filter', "($name|passes)", "--stop-on-$flag=2", "--max-batch-size=$batchSize"]);
$plural = in_array($outcome, ['warning', 'notice'], true) ? $outcome.'s' : $outcome;
expect($output)->toContain("Tests: 2 $plural (")
->not->toMatch('/\d+ passed/');
})->with($outcomes)->with([0, 1])->skipOnWindows();
test('parallel stop-on-defect includes errors warnings and risky tests', function (string $name, string $outcome, int $exitCode) use ($run): void {
$output = $run($exitCode, ['--filter', "($name|passes)", '--stop-on-defect', '--max-batch-size=1']);
expect($output)->toContain("Tests: 1 $outcome (")
->not->toMatch('/\d+ passed/');
})->with([
['errors', 'failed', 2],
['warns', 'warning', 0],
['is risky', 'risky', 1],
])->skipOnWindows();
test('parallel stop-on-defect allows incomplete and skipped tests', function (string $name, string $outcome) use ($run): void {
$output = $run(0, ['--filter', "($name|passes)", '--stop-on-defect']);
expect($output)->toContain("Tests: 2 $outcome, 10 passed");
})->with([
['is incomplete', 'incomplete'],
['is skipped', 'skipped'],
])->skipOnWindows();
test('parallel does not count the same failure twice', function (int $batchSize) use ($run): void {
$output = $run(1, ['--filter', '(fails|passes)', '--stop-on-failure=3', "--max-batch-size=$batchSize"]);
expect($output)->toContain('Tests: 2 failed, 10 passed');
})->with([0, 1])->skipOnWindows();
test('parallel counts issues hidden by the progress output', function (string $flag, string $name, string $outcome, int $exitCode) use ($run): void {
$output = $run($exitCode, ['--filter', "($name|passes)", $flag, '--max-batch-size=1']);
expect($output)->toContain("Tests: 1 $outcome (")
->not->toMatch('/\d+ passed/');
})->with([
['--stop-on-warning', 'has combined issues', 'failed', 1],
['--stop-on-defect=2', 'has combined issues', 'failed', 1],
['--stop-on-warning=2', 'has repeated warnings', 'warning', 0],
['--stop-on-notice=2', 'has repeated notifications', 'notice', 0],
])->skipOnWindows();
test('parallel stops only on the requested deprecation message', function (string $message, int $count) use ($run): void {
$output = $run(1, ['--filter', '(deprecates|passes)', "--stop-on-deprecation=$message", '--max-batch-size=1']);
expect($output)->toContain("Tests: $count deprecated");
if ($count === 1) {
expect($output)->not->toMatch('/\d+ passed/');
} else {
expect($output)->toContain('10 passed');
}
})->with([
['user deprecation', 1],
['another deprecation', 2],
])->skipOnWindows();
test('parallel honors stop-on flags from XML', function () use ($run): void {
$output = $run(1, ['--configuration=tests/Fixtures/Suites/ParallelStopOn.xml', '--filter', '(fails|passes)', '--max-batch-size=1']);
expect($output)->toContain('Tests: 1 failed (')
->not->toMatch('/\d+ passed/');
})->skipOnWindows();
test('parallel CLI thresholds override XML stop-on flags', function () use ($run): void {
$output = $run(1, ['--configuration=tests/Fixtures/Suites/ParallelStopOn.xml', '--filter', '(fails|passes)', '--stop-on-failure=2']);
expect($output)->toContain('Tests: 2 failed (')
->not->toMatch('/\d+ passed/');
})->skipOnWindows();
test('parallel clamps empty and non-positive thresholds like PHPUnit', function (string $threshold) use ($run): void {
$output = $run(1, ['--filter', '(fails|passes)', "--stop-on-failure=$threshold"]);
expect($output)->toContain('Tests: 1 failed (')
->not->toMatch('/\d+ passed/');
})->with(['', '0', '-2'])->skipOnWindows();
test('parallel counts a shared issue only once across recycled workers', function (string $flag, string $name, string $outcome) use ($run): void {
$output = $run(0, ['--filter', "($name|passes)", "--stop-on-$flag=2", '--max-batch-size=1']);
expect($output)->toMatch('/Tests:\s+\d+ '.$outcome.'s?, 10 passed/');
})->with([
['warning', 'shares warning', 'warning'],
['defect', 'shares warning', 'warning'],
['notice', 'shares notice', 'notice'],
])->skipOnWindows();
test('parallel combines stop-on counts from different workers and cleans up their files', function () use ($run): void {
$directory = sys_get_temp_dir().'/pest-stop-on-'.bin2hex(random_bytes(8));
mkdir($directory);
try {
$output = $run(
1,
['--processes=2', '--stop-on-failure=2', '--filter', '(fails|passes)', '--tmp-dir='.$directory],
['PEST_TEST_STOP_BARRIER' => $directory],
);
expect($output)->toContain('Tests: 2 failed')
->not->toContain('10 passed')
->not->toContain('did not reach the barrier')
->and(glob($directory.'/worker-*'))->toHaveCount(2)
->and(glob($directory.'/paratest_*'))->toBeEmpty();
} finally {
foreach (glob($directory.'/worker-*') as $file) {
unlink($file);
}
rmdir($directory);
}
})->skipOnWindows();
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\Process;
test('an empty shard runs no tests', function (int $exitCode, string ...$arguments): void {
$process = new Process([
PHP_BINARY, 'bin/pest', 'tests/Fixtures/DirectoryWithTests/ExampleTest.php',
'--colors=never', '--shard=2/2', ...$arguments,
], dirname(__DIR__, 2));
$process->run();
expect($process->getExitCode())->toBe($exitCode)
->and(removeAnsiEscapeSequences($process->getOutput()))
->toContain('No tests found.', '2 of 2 — 0 files ran, out of 1.')
->not->toContain('example 1');
})->with([
'sequential' => [0],
'parallel' => [0, '--parallel', '--processes=2'],
'sequential with fail-on-empty-test-suite' => [1, '--fail-on-empty-test-suite'],
'parallel with fail-on-empty-test-suite' => [1, '--parallel', '--processes=2', '--fail-on-empty-test-suite'],
]);
test('an empty shard lists no tests', function (): void {
$process = new Process([
PHP_BINARY, 'bin/pest', 'tests/Fixtures/DirectoryWithTests/ExampleTest.php',
'--colors=never', '--shard=2/2', '--list-tests',
], dirname(__DIR__, 2));
$process->run();
expect($process->getExitCode())->toBe(0)
->and($process->getOutput())->toContain('Available test')
->not->toContain('__pest_evaluable_it_example_1', 'example 1');
});
test('a non-empty shard runs its assigned test', function (): void {
$process = new Process([
PHP_BINARY, 'bin/pest', 'tests/Fixtures/DirectoryWithTests/ExampleTest.php',
'--colors=never', '--shard=1/2',
], dirname(__DIR__, 2));
$process->run();
expect($process->getExitCode())->toBe(0)
->and($process->getOutput())->toContain('1 passed', '1 of 2 — 1 file ran, out of 1.');
});
+38
View File
@@ -30,6 +30,44 @@ test('allows to run a directory', function () use ($run, $snapshot): void {
expect($run('tests/Fixtures/DirectoryWithTests'))->toContain($snapshot('allows-to-run-a-directory'));
})->skipOnWindows();
test('allows to run a single test using its namespace', function () use ($run, $snapshot): void {
expect($run('Tests\\Fixtures\\DirectoryWithTests\\ExampleTest'))->toContain($snapshot('allows-to-run-a-single-test'));
})->skipOnWindows();
test('keeps namespace filters unchanged', function () use ($snapshot): void {
$process = new Process([
'php',
'bin/pest',
'tests/Fixtures/DirectoryWithTests',
'--filter',
'Tests\\\\Fixtures\\\\DirectoryWithTests\\\\ExampleTest',
'--colors=never',
], dirname(__DIR__, 2),
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
);
$process->run();
expect(removeAnsiEscapeSequences($process->getOutput()))->toContain($snapshot('allows-to-run-a-single-test'));
})->skipOnWindows();
test('converts a namespace after the retry flag', function () use ($snapshot): void {
$process = new Process([
'php',
'bin/pest',
'--retry',
'Tests\\Fixtures\\DirectoryWithTests\\ExampleTest',
'--colors=never',
], dirname(__DIR__, 2),
['COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_IGNORE_DURATION' => 'true', 'PAO_DISABLE' => '1'],
);
$process->run();
expect($process->getExitCode())->toBe(0)
->and(removeAnsiEscapeSequences($process->getOutput()))->toContain($snapshot('allows-to-run-a-single-test'));
})->skipOnWindows();
it('disable decorating printer when colors is set to never', function () use ($snapshot): void {
$process = new Process([
'php',
+14
View File
@@ -46,3 +46,17 @@ test('visual snapshot of team city', function (string $testFile): void {
'Failure.php',
'SuccessOnly.php',
])->skip(! getenv('REBUILD_SNAPSHOTS') && getenv('EXCLUDE'));
test('preserves TeamCity text in a test filter', function (array $filterArguments): void {
$process = new Process(
[PHP_BINARY, 'bin/pest', '--colors=never', 'tests/Fixtures/Suites/SuccessOnly.php', ...$filterArguments],
dirname(__DIR__, 2),
['PARATEST' => '0', 'PAO_DISABLE' => '1'],
);
expect($process->run())->toBe(0)
->and($process->getOutput())->toContain('1 passed (1 assertions)');
})->with([
'attached value' => [['--filter=can pass with comparison|--teamcity']],
'separate value' => [['--filter', 'can pass with comparison|--teamcity']],
]);
+20
View File
@@ -1,6 +1,7 @@
<?php
use Symfony\Component\Process\Process;
use Tests\Fixtures\Tia\Project;
test('visual snapshot of help command output', function (): void {
$output = function (): ?string {
@@ -13,3 +14,22 @@ test('visual snapshot of help command output', function (): void {
expect($output())->toMatchSnapshot();
})->skipOnWindows()->skip(! getenv('REBUILD_SNAPSHOTS') && getenv('EXCLUDE'));
test('prints information when the tests directory is missing', function (string $option, string $expected): void {
$project = Project::withoutGit();
try {
rename($project->path('tests'), $project->path('fixtures'));
unlink($project->path('phpunit.xml'));
$result = $project->pest($option);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->toContain($expected);
} finally {
Project::destroyAll();
}
})->with([
'help' => ['--help', '--init'],
'version' => ['--version', 'Pest Testing Framework'],
]);