diff --git a/CHANGELOG.md b/CHANGELOG.md index 210213f..967bca0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +### Fixed + +- **A whole-repository mutation run says which source files are never mutated.** A file PHP includes before Pest serves mutants (an `autoload.files` entry and what it loads, `tests/Pest.php` and what it loads), or before a bootstrap that loads the mutant itself does, is never replaced: its mutants survive whatever the tests assert, and nothing said so. The run, and `check --mutation-canary`, now list those a test covers. The score is unchanged: it still counts them. A run limited to some files already refused such a file, blaming Patchwork; it now says why. +- **No score is given when a bootstrap loads the mutant of a file PHP has already included.** Its processes die of the redeclaration and every mutant counts as caught: a file whose test asserts nothing read 100 %. Only the first source file was tried as an unchanged mutant; each file included early now is, with the canary test alone. **The bootstrap the README gave did this**: it now skips an original that `get_included_files()` lists. + ## [0.1.41] - 2026-11-27 ### Fixed diff --git a/README.md b/README.md index 791ff43..f30d9f3 100644 --- a/README.md +++ b/README.md @@ -235,7 +235,7 @@ The run is parallel. A suite that fails that way (a global function a helper dec Pest hands a mutant to its process through `PEST_MUTATION_TESTING` and `PEST_MUTATION_FILE` and serves it through a stream wrapper on `file`. If something else serves the original (Patchwork, which Brain Monkey loads, or a bootstrap), mutants survive unseen or their processes die and count as killed. After every run that has a score, in every scope, the harness therefore starts Pest as one of those processes with a "mutant" that only records that it was executed, and stops it. No record, no score: the gate fails, saying why (on the base of `changed-relative`, `base unmeasured`). A real 100 % passes, because what is judged is the record, not the value. - **With files** (`changed`, `added`, `changed-relative`), each file is probed with the real suite. A file included without its mutant refuses the score. A file no test includes has no covered line, hence no mutant, and says nothing; but at least one file of the set must have run its mutant (the suite is tried once more with `--parallel` before concluding that none did). -- **Whole repository**, there is no single file: the harness writes `src/PolloraCanary.php` and a test next to the others that loads Patchwork (when installed) and requires it, runs that test and removes both. +- **Whole repository**, there is no single file: the harness writes `src/PolloraCanary.php` and a test next to the others that loads Patchwork (when installed) and requires it, runs that test and removes both. The order of the files that process included tells which source files were there before a mutant could replace them; they are listed after the score, and the same test is run once as an unchanged mutant of each: a bootstrap that loads the mutant of an included file anyway dies of the redeclaration, which would count all its mutants as caught, so that refuses the score. **The tests must also pass on code that did not change.** A mutant's process that fails is a caught mutant for Pest, one that loops is a timeout, counted as caught too: a suite that breaks there whatever the file contains scores mutants nothing tested. So, before Pest runs: 1. **The suite runs alone** (`pest`, then `pest --parallel` if that fails, with coverage first, then without). It gives the duration and, with a coverage driver (pcov, Xdebug), which tests cover which file. When it does not pass, there is nothing to compare with. @@ -261,7 +261,9 @@ if ($mutating) { // Patchwork, Composer's autoloader and the helpers of the tests are loaded here -if ($mutating) { +// An original PHP has already included cannot be replaced: loading its mutant would die of the redeclaration, +// which Pest counts as a caught mutant +if ($mutating && ! in_array(realpath((string) getenv('PEST_MUTATION_TESTING')), get_included_files(), true)) { require (string) getenv('PEST_MUTATION_FILE'); } ``` @@ -282,7 +284,7 @@ It exits 1 when no score could be believed, whatever the mode of the repository, **Two traps of Pest's mutation runner.** - Pest builds its `--filter` as regex alternatives, one per test that covers the mutated line. Past the PCRE compilation limit (about 64 KB) the filter is invalid, no test runs and the mutant is counted as surviving. The lines covered by almost the whole suite are the ones concerned, and adding tests can lower the score there: fewer, broader tests (datasets folded into loops) beat more of them. -- A class Composer loads from `files` (a `register.php`, a helper) is loaded before Pest mutates anything, so its mutants always survive. `--class=` does not narrow the run, and a test file edited during a run makes it die silently. +- A file PHP includes before Pest serves mutants (a class Composer loads from `files`, what that file or `tests/Pest.php` loads) is never replaced, so its mutants always survive. A whole-repository run lists those some test covers after its score (`Never mutated`), as `check --mutation-canary` does. The score is Pest's and still counts them: it is lower than what the tests deserve, never higher. A limited run refuses such a file. `--class=` does not narrow the run, and a test file edited during a run makes it die silently. ### Mutation score of the changed files diff --git a/src/Check/MutationCanary.php b/src/Check/MutationCanary.php index 060160f..46a9914 100644 --- a/src/Check/MutationCanary.php +++ b/src/Check/MutationCanary.php @@ -26,6 +26,13 @@ * * A legitimate score of 100 % passes: it differs from a false one by the canary being executed, not by its value. * + * A source file PHP has included before Pest puts its wrapper on `file` (an `autoload.files` entry and what it loads, + * `tests/Pest.php` and what it loads), or before a bootstrap that loads the mutant itself does so, is never replaced: + * its mutants survive whatever the tests assert. For the whole repository, `inspect()` lists those files, read from + * the order of `get_included_files()` in a mutant's process. They stay in Pest's score, which is not corrected. It + * also runs the canary test as an unchanged mutant of each: a bootstrap that loads the mutant of an included file + * anyway dies of the redeclaration, which counts every mutant of the file as caught, and refuses the score. + * * A mutant that loads is not enough. Pest reads a mutant's process that fails as a caught mutant, and one that does not * end as a timeout, which counts as caught too. A test that fails or loops in that process whatever the file contains * (Patchwork stacked on Pest's stream wrapper breaks directory reading; that wrapper itself takes every `flock()` as @@ -55,6 +62,9 @@ final class MutationCanary /** and never before this many seconds, so that a short suite on a busy machine is not refused. */ public const float TIME_FLOOR = 120.0; + /** The file whose inclusion is Pest putting its wrapper on `file` (`Mutate::boot()` calls `StreamWrapper::start()`). */ + private const string WRAPPER = '/pest-plugin-mutate/src/Support/StreamWrapper.php'; + private const string LOADED = 'loaded'; private const string IGNORED = 'ignored'; @@ -76,9 +86,79 @@ final class MutationCanary */ public static function refusal(string $cwd, array $paths, float $floor = self::TIME_FLOOR): ?string { - $unchanged = self::unchanged($cwd, $paths, $floor); + return self::check($cwd, $paths, $floor)['refusal']; + } + + /** + * `refusal()`, with the files `inspect()` lists for the whole repository. + * + * @param list $paths Source files relative to $cwd; empty for the whole repository + * @param float $floor The shortest limit of a run, in seconds + * @return array{refusal: string|null, preloaded: list} + */ + public static function check(string $cwd, array $paths, float $floor = self::TIME_FLOOR): array + { + return self::verdict($cwd, $paths, self::unchanged($cwd, $paths, $floor)); + } + + /** + * What is left to check once `unchanged()` has answered: its refusal, else whether mutants are executed. + * + * @param list $paths Source files relative to $cwd; empty for the whole repository + * @param array{refusal: string|null, parallel: bool, controlled: bool, limit: float, covered: list|null} $unchanged + * @return array{refusal: string|null, preloaded: list} + */ + public static function verdict(string $cwd, array $paths, array $unchanged): array + { + if ($unchanged['refusal'] === null && $paths === []) { + return self::inspect($cwd, $unchanged['covered'], $unchanged['limit']); + } - return $unchanged['refusal'] ?? self::loaded($cwd, $paths, $unchanged['limit']); + // A limited run refuses a file that is never replaced rather than list it + return ['refusal' => $unchanged['refusal'] ?? self::loaded($cwd, $paths, $unchanged['limit']), 'preloaded' => []]; + } + + /** + * `loaded()` for the whole repository, with the source files whose mutants can never be run. + * + * @param list|null $covered The real paths of the files some test covers, the only ones Pest mutates; null + * without coverage data: every source file then + * @return array{refusal: string|null, preloaded: list} Why no score can be believed; the files, relative to + * $cwd, already included when a mutant would replace them + */ + public static function inspect(string $cwd, ?array $covered = null, float $limit = self::TIME_FLOOR): array + { + $root = realpath($cwd); + + if ($root === false) { + return ['refusal' => self::message('the repository cannot be read'), 'preloaded' => []]; + } + + return self::probeBootstrap($root, $covered, $limit); + } + + /** + * What a gate says beside a score about the files `inspect()` found, empty when there is none. + * + * @param list $preloaded + */ + public static function preloadedNotice(array $preloaded): string + { + if ($preloaded === []) { + return ''; + } + + $shown = array_slice($preloaded, 0, 20); + $more = count($preloaded) - count($shown); + + return implode("\n", [ + sprintf( + ' Never mutated (%d): source files already included when a mutant would replace them (loaded by `autoload.files`, tests/Pest.php or the test bootstrap, directly or not). Unless a test includes such a file again, its mutants survive whatever the tests assert. A mutation score counts them and is not corrected.', + count($preloaded), + ), + ...array_map(static fn (string $file): string => ' '.$file, $shown), + ...($more > 0 ? [sprintf(' and %d more', $more)] : []), + ]); } /** @@ -90,12 +170,13 @@ public static function refusal(string $cwd, array $paths, float $floor = self::T * * @param list $paths Source files relative to $cwd; empty for the whole repository * @param float $floor The shortest limit of a run, in seconds - * @return array{refusal: string|null, parallel: bool, controlled: bool, limit: float} Why no score can be believed; - * whether mutants can run in parallel; whether the suite passes on its own; the limit of a run, in seconds + * @return array{refusal: string|null, parallel: bool, controlled: bool, limit: float, covered: list|null} Why no + * score can be believed; whether mutants can run in parallel; whether the suite passes on its own; the limit of a run, in + * seconds; the real paths of the files some test covers, null without coverage data */ public static function unchanged(string $cwd, array $paths, float $floor = self::TIME_FLOOR): array { - $result = ['refusal' => null, 'parallel' => true, 'controlled' => true, 'limit' => $floor]; + $result = ['refusal' => null, 'parallel' => true, 'controlled' => true, 'limit' => $floor, 'covered' => null]; $root = realpath($cwd); if ($root === false) { @@ -118,6 +199,7 @@ public static function unchanged(string $cwd, array $paths, float $floor = self: [$seconds, $coverage] = $control; $result['limit'] = max($floor, self::TIME_FACTOR * $seconds); + $result['covered'] = $coverage === null ? null : array_keys(array_filter($coverage)); $covering = $coverage !== null && self::mutantsCollectCoverage($root); @@ -169,7 +251,7 @@ public static function loaded(string $cwd, array $paths, float $limit = self::TI } if ($paths === []) { - return self::probeBootstrap($root, $limit); + return self::probeBootstrap($root, [], $limit)['refusal']; } $originals = self::originals($root, $paths); @@ -177,7 +259,15 @@ public static function loaded(string $cwd, array $paths, float $limit = self::TI $output = ''; foreach ($originals as $path => $original) { - [$state, $output] = self::probe($root, $original, [], $limit); + [$state, $output, $included] = self::probe($root, $original, [], $limit); + + if ($state === self::IGNORED && in_array($original, self::beforeWrapper($included), true)) { + return self::message( + sprintf('%s is already included when Pest starts to serve mutants', $path), + $output, + 'PHP never reads it again, so every mutant of it survives whatever the tests assert. Something loads it at startup: an `autoload.files` entry, tests/Pest.php, or a file one of those includes.', + ); + } if ($state === self::IGNORED) { return self::message(sprintf('%s was included by the tests, but not its mutated version', $path), $output); @@ -384,9 +474,7 @@ private static function workerVariables(): array */ private static function unchangedRefusal(string $root, string $path, string $original, array $variables, ?string $filter, float $limit, bool $wholeRepository, bool $covering): ?string { - // Where Pest writes its mutants, so that a bootstrap which reads the mutant finds it where it would - $directory = $root.'/vendor/pestphp/pest-plugin-mutate/.temp/mutations'; - $copy = (MutationRun::temporaryDirectoryWritable($root) ? $directory : sys_get_temp_dir()).'/pollora-unchanged-'.bin2hex(random_bytes(8)); + $copy = self::copyPath($root); if (! @copy($original, $copy)) { return self::message(sprintf('the harness could not copy %s', $path)); @@ -438,10 +526,23 @@ private static function unchangedRefusal(string $root, string $path, string $ori ); } + /** + * Where Pest writes its mutants, so that a bootstrap which reads the mutant finds it where it would. + */ + private static function copyPath(string $root): string + { + $directory = $root.'/vendor/pestphp/pest-plugin-mutate/.temp/mutations'; + + return (MutationRun::temporaryDirectoryWritable($root) ? $directory : sys_get_temp_dir()).'/pollora-unchanged-'.bin2hex(random_bytes(8)); + } + /** * Probes a source file the harness writes, required by a test it writes. + * + * @param list|null $covered See `inspect()`; empty looks for no preloaded file + * @return array{refusal: string|null, preloaded: list} */ - private static function probeBootstrap(string $root, float $limit): ?string + private static function probeBootstrap(string $root, ?array $covered, float $limit): array { $name = 'PolloraCanary'.bin2hex(random_bytes(6)); $original = (is_dir($root.'/src') ? $root.'/src/' : $root.'/').$name.'.php'; @@ -455,12 +556,20 @@ private static function probeBootstrap(string $root, float $limit): ?string try { if (@file_put_contents($original, " self::message('the harness could not write its canary files in the repository'), 'preloaded' => []]; + } + + [$state, $output, $included] = self::probe($root, $original, [$test], $limit); + + if ($state !== self::LOADED) { + return ['refusal' => self::message('a mutated source file required by a test was not executed', $output), 'preloaded' => []]; } - [$state, $output] = self::probe($root, $original, [$test], $limit); + // Served by the wrapper of Pest, the canary is included under the name of the original: only what precedes + // that wrapper is beyond it. Included by a bootstrap, under another name, what it loaded before is too. + $preloaded = self::sourcesAmong($root, end($included) === $original ? self::beforeWrapper($included) : $included, $covered); - return $state === self::LOADED ? null : self::message('a mutated source file required by a test was not executed', $output); + return ['refusal' => self::redeclarationRefusal($root, $original, $test, $preloaded, $limit), 'preloaded' => array_keys($preloaded)]; } finally { foreach ([$original, $test] as $file) { if (is_file($file)) { @@ -470,19 +579,111 @@ private static function probeBootstrap(string $root, float $limit): ?string } } + /** + * The files included before Pest put its wrapper on `file`, from a list in the order of inclusion. + * + * @param list $included + * @return list Empty when the list does not show the wrapper + */ + private static function beforeWrapper(array $included): array + { + foreach ($included as $position => $file) { + if (str_ends_with(str_replace('\\', '/', $file), self::WRAPPER)) { + return array_slice($included, 0, $position); + } + } + + return []; + } + + /** + * The source files Pest may mutate among included files. + * + * @param list $included Real paths + * @param list|null $covered See `inspect()` + * @return array The real path of each, by its path relative to the repository + */ + private static function sourcesAmong(string $root, array $included, ?array $covered): array + { + $candidates = $covered ?? array_values(self::originals($root, [...ChangedSources::all($root), ...ChangedSources::autoloadFiles($root)])); + $sources = []; + + foreach (array_intersect($candidates, $included) as $file) { + if (str_starts_with($file, $root.'/') && ! str_starts_with($file, $root.'/vendor/')) { + $sources[substr($file, strlen($root) + 1)] = $file; + } + } + + ksort($sources); + + return $sources; + } + + /** + * Runs the canary test alone as a mutant of each preloaded file that changes nothing. It runs none of their tests: + * what fails it is a bootstrap that loads the mutant of a file PHP has already included, and dies of it. + * + * @param array $preloaded + */ + private static function redeclarationRefusal(string $root, string $canary, string $test, array $preloaded, float $limit): ?string + { + $run = static function (string $original) use ($root, $test, $limit): array { + $copy = self::copyPath($root); + + if (! @copy($original, $copy)) { + return [-1, 'the harness could not copy '.$original]; + } + + try { + [$code, $output] = self::execute($root, [$test], [...self::environment(), 'PEST_MUTATION_TESTING' => $original, 'PEST_MUTATION_FILE' => $copy], $limit); + + return [$code, $output]; + } finally { + if (is_file($copy)) { + unlink($copy); + } + } + }; + + // The canary test must pass as a mutant of its own source, or its failure for another file says nothing + if ($preloaded === [] || $run($canary)[0] !== 0) { + return null; + } + + foreach ($preloaded as $path => $original) { + // Twice: one flaky failure is no verdict + if ($run($original)[0] === 0) { + continue; + } + + [$code, $output] = $run($original); + + if ($code !== 0) { + return self::message( + sprintf('%s is already included when a mutant would replace it, and the process of a mutant of it that changes nothing dies', $path), + $output, + 'Pest counts each of its mutants as caught. A test bootstrap that loads PEST_MUTATION_FILE itself must leave alone an original that get_included_files() already lists (the README shows how).', + ); + } + } + + return null; + } + /** * Runs Pest as the process of one mutant of `$original`. * * @param list $arguments Arguments of Pest; none runs the whole suite, until the canary stops it - * @return array{string, string} Whether the canary ran (`loaded`), the original was included without it - * (`ignored`) or was not included (`absent`), and what Pest printed + * @return array{string, string, list} Whether the canary ran (`loaded`), the original was included without + * it (`ignored`) or was not included (`absent`); what Pest printed; the files included, in order, when the canary ran + * or, if it did not, at the end of a process that included the original */ private static function probe(string $root, string $original, array $arguments, float $limit): array { $directory = sys_get_temp_dir().'/pollora-canary-'.bin2hex(random_bytes(8)); if (! @mkdir($directory, 0o700)) { - return [self::ABSENT, 'cannot create '.$directory]; + return [self::ABSENT, 'cannot create '.$directory, []]; } [$mutant, $prepend, $loaded, $included] = array_map( @@ -491,9 +692,9 @@ private static function probe(string $root, string $original, array $arguments, ); try { - file_put_contents($mutant, sprintf(" self::ABSENT, }; - return [$state, $output]; + $list = match ($state) { + self::LOADED => $loaded, + self::IGNORED => $included, + default => null, + }; + $files = $list === null ? null : json_decode((string) file_get_contents($list), true); + + return [$state, $output, is_array($files) ? array_values(array_filter($files, is_string(...))) : []]; } finally { foreach ([$mutant, $prepend, $loaded, $included] as $file) { if (is_file($file)) { diff --git a/src/Check/MutationRun.php b/src/Check/MutationRun.php index 4021616..a248952 100644 --- a/src/Check/MutationRun.php +++ b/src/Check/MutationRun.php @@ -36,7 +36,9 @@ * before Pest runs, which is not started when they do not) and a mutated source being executed: otherwise (the suite * fails or loops in a mutant's process whatever the file contains, or something else serves the original file) the * result has a null score and says why in `unloaded`. When the tests only fail with the variables of a parallel run, the - * mutants are run in a single process. + * mutants are run in a single process. A run of the whole repository lists in `preloaded` the source files PHP had + * included before a mutant could replace them: their mutants survive whatever the tests assert, and the score, which + * counts them, is not corrected. */ final class MutationRun { @@ -44,7 +46,7 @@ final class MutationRun /** * @param list $paths Source files (relative to $cwd) to mutate; empty mutates everything the tests cover - * @return array{score: float|null, summary: string, output: string, empty: bool, unwritable: bool, unloaded?: string} + * @return array{score: float|null, summary: string, output: string, empty: bool, unwritable: bool, unloaded?: string, preloaded?: list} */ public static function run(string $cwd, array $paths = []): array { @@ -75,9 +77,17 @@ public static function run(string $cwd, array $paths = []): array return [...$result, 'score' => null, 'empty' => false, 'unwritable' => true]; } - $refusal = $result['score'] === null ? null : ($unchanged['refusal'] ?? MutationCanary::loaded($cwd, $paths, $unchanged['limit'])); + if ($result['score'] === null) { + return $result; + } + + ['refusal' => $refusal, 'preloaded' => $preloaded] = MutationCanary::verdict($cwd, $paths, $unchanged); + + if ($refusal !== null) { + return [...$result, 'score' => null, 'unloaded' => $refusal]; + } - return $refusal === null ? $result : [...$result, 'score' => null, 'unloaded' => $refusal]; + return $preloaded === [] ? $result : [...$result, 'preloaded' => $preloaded]; } /** diff --git a/src/Check/Plan.php b/src/Check/Plan.php index ffa27af..de0f8b2 100644 --- a/src/Check/Plan.php +++ b/src/Check/Plan.php @@ -523,7 +523,7 @@ static function () use ($cwd, $score): StepResult { return $run['score'] === null ? StepResult::failed(($run['empty'] ? 'Pest created no mutation: the tests cover no code it can mutate.' : 'Pest printed no mutation score: the tests must pass first.')."\n".trim(substr($run['output'], -600))) - : StepResult::passed(sprintf(' Mutation score %s %% (%s)', $run['score'], $run['summary'])); + : StepResult::passed(rtrim(sprintf(" Mutation score %s %% (%s)\n%s", $run['score'], $run['summary'], MutationCanary::preloadedNotice($run['preloaded'] ?? [])))); }, requires: ['vendor/pestphp/pest-plugin-mutate'], ); diff --git a/src/Console/Commands/CheckCommand.php b/src/Console/Commands/CheckCommand.php index ffa49e4..72f3731 100644 --- a/src/Console/Commands/CheckCommand.php +++ b/src/Console/Commands/CheckCommand.php @@ -120,7 +120,7 @@ private function mutationCanary(Io $io): int } } - $refusal = MutationCanary::refusal($io->cwd, $paths); + ['refusal' => $refusal, 'preloaded' => $preloaded] = MutationCanary::check($io->cwd, $paths); if ($refusal !== null) { $io->error($refusal); @@ -130,6 +130,10 @@ private function mutationCanary(Io $io): int $io->line('Mutation canary passed: mutants load, and the tests pass on unchanged code run as a mutant. No score was measured.'); + if ($preloaded !== []) { + $io->line(MutationCanary::preloadedNotice($preloaded)); + } + return self::SUCCESS; } diff --git a/tests/Unit/MutationPreloadedTest.php b/tests/Unit/MutationPreloadedTest.php new file mode 100644 index 0000000..04197c8 --- /dev/null +++ b/tests/Unit/MutationPreloadedTest.php @@ -0,0 +1,185 @@ + $files Further files of the project + * @param string $option The `check` option to run + * @return array{int, string} The exit code of `check --mutation-canary` and everything it printed + */ +function preloadingProject(string $autoload = '', string $bootstrap = '', array $files = [], string $option = '--mutation-canary'): array +{ + $harness = dirname(__DIR__, 2); + // Under /tmp for the reason `contractProject()` does + $root = '/tmp/pollora-harness-preload-'.bin2hex(random_bytes(5)); + + $files += [ + 'composer.json' => '{"autoload":{"psr-4":{"App\\\\":"src/"}}}', + 'vendor/bin/pest' => " " " " " "toBe(PreloadedEarly::answer());\n});\n", + 'phpunit.xml' => 'testssrc', + ]; + + foreach (['vendor/pestphp/pest/bin', 'vendor/pestphp/pest-plugin-mutate'] as $directory) { + mkdir("{$root}/{$directory}", 0o755, true); + } + + copy($harness.'/vendor/pestphp/pest/bin/pest', $root.'/vendor/pestphp/pest/bin/pest'); + copy($harness.'/vendor/pest-plugins.json', $root.'/vendor/pest-plugins.json'); + + foreach ($files as $path => $contents) { + if (! is_dir(dirname("{$root}/{$path}"))) { + mkdir(dirname("{$root}/{$path}"), 0o755, true); + } + + file_put_contents("{$root}/{$path}", $contents); + } + + try { + return canaryCommand($root, $option); + } finally { + $entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); + + foreach ($entries as $entry) { + $entry->isDir() && ! $entry->isLink() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + + rmdir($root); + } +} + +/** @return array{int, string} */ +function canaryCommand(string $root, string $option = '--mutation-canary'): array +{ + [$out, $err] = [fopen('php://memory', 'w+'), fopen('php://memory', 'w+')]; + $code = (new CheckCommand)->run(Io::fromArgv($root, [$option], $out, $err)); + rewind($out); + rewind($err); + + return [$code, stream_get_contents($out).stream_get_contents($err)]; +} + +/** What an `autoload.files` entry that loads a class does. */ +const LOADS_EARLY = "require_once __DIR__.'/../src/Early.php';"; + +/** A bootstrap that gives `file` back and loads the mutant itself, whatever PHP has already included. */ +const UNGUARDED_BOOTSTRAP = "if (is_string(getenv('PEST_MUTATION_TESTING'))) {\n \\Pest\\Mutate\\Support\\StreamWrapper::disable();\n require (string) getenv('PEST_MUTATION_FILE');\n}"; + +/** The same, leaving alone an original PHP has already included, as the README shows. */ +const GUARDED_BOOTSTRAP = "if (is_string(getenv('PEST_MUTATION_TESTING'))) {\n \\Pest\\Mutate\\Support\\StreamWrapper::disable();\n if (! in_array(realpath((string) getenv('PEST_MUTATION_TESTING')), get_included_files(), true)) {\n require (string) getenv('PEST_MUTATION_FILE');\n }\n}"; + +describe('a source file included before Pest serves mutants', function (): void { + it('is listed for the whole repository, without failing', function (string $autoload, array $files): void { + [$code, $output] = preloadingProject($autoload, files: $files); + + expect($code)->toBe(0)->and($output)->toContain('Never mutated (1)')->toContain("\n src/Early.php"); + })->with([ + 'loaded at startup by Composer' => [LOADS_EARLY, []], + 'loaded by tests/Pest.php' => ['', ['tests/Pest.php' => "toBe(0)->and($output)->toContain('No score was measured')->not->toContain('Never mutated'); + }); + + it('fails a run limited to it, saying that it is loaded at startup', function (): void { + [$code, $output] = preloadingProject(LOADS_EARLY, option: '--mutation-canary=src/Early.php'); + + expect($code)->toBe(1) + ->and($output)->toContain('src/Early.php is already included when Pest starts to serve mutants') + ->not->toContain('Patchwork'); + }); +}); + +describe('a bootstrap that loads the mutant itself', function (): void { + it('refuses the score when it loads the mutant of a file already included, whose processes all die', function (): void { + [$code, $output] = preloadingProject(LOADS_EARLY, UNGUARDED_BOOTSTRAP); + + expect($code)->toBe(1) + ->and($output)->toContain('src/Early.php is already included when a mutant would replace it') + ->toContain('counts each of its mutants as caught'); + }); + + it('is accepted when it leaves that file alone, which is listed', function (): void { + [$code, $output] = preloadingProject(LOADS_EARLY, GUARDED_BOOTSTRAP); + + expect($code)->toBe(0)->and($output)->toContain("\n src/Early.php"); + }); + + it('has what it includes before the mutant listed too', function (): void { + [$code, $output] = preloadingProject('', "require_once __DIR__.'/../src/Early.php';\n".GUARDED_BOOTSTRAP); + + expect($code)->toBe(0)->and($output)->toContain("\n src/Early.php"); + }); +}); + +/** A fake Pest whose mutant's process includes src/Early.php before its mutant. */ +function fakePreloadingProject(): string +{ + $root = harnessTempDir(); + mkdir($root.'/src'); + mkdir($root.'/vendor/bin', 0o777, true); + mkdir($root.'/vendor/pestphp/pest-plugin-mutate', 0o777, true); + file_put_contents($root.'/src/Answer.php', " 'core']), fakePreloadingProject()))->full(null, null, true); + $result = (array_values(array_filter($steps, static fn (Step $step): bool => $step->name === Plan::MUTATION))[0]->action)(); + + expect($result->status)->toBe(StepResult::PASSED) + ->and($result->detail)->toContain('Mutation score 66.67 %') + ->and($result->detail)->toContain('Never mutated (1)') + ->and($result->detail)->toContain("\n src/Early.php"); + }); + + it('is printed by check --mutation-canary', function (): void { + [$code, $output] = canaryCommand(fakePreloadingProject()); + + expect($code)->toBe(0)->and($output)->toContain('Never mutated (1)')->toContain('src/Early.php'); + }); + + it('names only files a test covers, the ones Pest mutates', function (): void { + $root = fakePreloadingProject(); + + expect(MutationCanary::inspect($root, [])['preloaded'])->toBe([]) + ->and(MutationCanary::inspect($root, [(string) realpath($root.'/src/Early.php')])['preloaded'])->toBe(['src/Early.php']); + }); + + it('is nothing without such a file, and counts those a long list leaves out', function (): void { + $many = array_map(static fn (int $number): string => "src/F{$number}.php", range(1, 25)); + + expect(MutationCanary::preloadedNotice([]))->toBe('') + ->and(MutationCanary::preloadedNotice($many))->toContain('Never mutated (25)')->toContain('and 5 more')->not->toContain('src/F21.php'); + }); +});