diff --git a/CHANGELOG.md b/CHANGELOG.md index 76f5d8f..3e021e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## [Unreleased] +### Fixed + +- **No mutation score is given when the tests do not pass on unchanged code run as a mutant.** Pest counts a mutant's process that fails as a caught mutant, and one that loops as a timeout, caught too, so a suite that breaks in that process whatever the file contains scored mutants nothing had tested (on `pollora/media`, one file read 100 % with Patchwork 2.2.5 and 77.92 % with its unreleased fix). Before Pest runs, the harness now runs the suite alone, then the tests covering the code with `PEST_MUTATION_TESTING` set to the source file and `PEST_MUTATION_FILE` to an exact copy of it; selected by name as Pest selects them, never passing `--parallel`; if they fail (twice: one flaky failure is not a verdict), or are still running after five times the duration of the suite (never less than 120 s), Pest is not started and the gate fails with the failing tests. When they only fail with the variables of a parallel run, the mutants are run in a single process. **A repository whose score the gate accepted may now be refused**: Patchwork (loaded by Brain Monkey) under tests that read a directory, and Pest's own stream wrapper, which takes every `flock()` as shared and reports an unreadable file as absent, are two causes. The README says what to do. + +- A run of the canary that ran out of memory says so: a `php -d memory_limit=...` on the command does not reach the processes of the tests, as it does not reach those of Pest's mutants. +- The advice to give `file` back to a bootstrap now carries its condition, only when Pest's wrapper is on it: unconditionally, `StreamWrapper::disable()` fails every test PHPUnit isolates in a process of its own. The README has the code. + +### Added + +- `check --mutation-canary[=FILES]` asks only whether a mutation score could be believed, without a mutation pass or any other gate, and exits with a failure when it could not, in any mode. + ### Documentation - The README gives the security patterns a template runs (SEC-01 to SEC-07 and CONV-10) and says `mutation.min` has no default for `changed-relative`; the headers of the reusable workflows call a current tag. diff --git a/README.md b/README.md index 106d8d0..93793c0 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,7 @@ The **Dependency analysis** gate uses the repository's `composer-dependency-anal | `pollora-qa check --strict` | Also fails when a gate could not run because a tool is missing (Semgrep, a `vendor/bin/` tool) | | `pollora-qa check --coverage[=FILE]` | Runs the tests with coverage and compares the Clover report with the ratchet (default `.harness/coverage.xml`) | | `pollora-qa check --mutation` | Also runs Pest's mutation testing (`pest --mutate --everything --covered-only`) and compares its score with the ratchet's `msi`; reported, never blocking by itself | +| `pollora-qa check --mutation-canary[=FILES]` | Runs no gate: only checks that a mutation score could be believed (mutants load, tests pass on unchanged code run as a mutant) | | `pollora-qa check --mutation --mutation-base=REF` | With a limited `mutation.scope` in `.harness.json`, the commit the changed files are counted from (and, for `changed-relative`, the base each file is measured on) (default `HEAD^1`) | | `pollora-qa promote-report [--json] [... \| --root= [--only=a,b]]` | For each observed rule, what would block here if it became enforced (read only, see [Promoting a rule](#promoting-a-rule)); with paths or `--root`, one rule x repository matrix | | `pollora-qa check --mutation --mutation-scope=all\|changed\|added\|changed-relative` | What `--mutation` mutates in this run, over the `mutation.scope` of `.harness.json`. A limited scope is held to `mutation.min`, or to 50 % when the file sets none; an unknown value fails before any gate runs | @@ -229,14 +230,55 @@ The run is parallel. A suite that fails that way (a global function a helper dec **No cache.** Pest keeps the mutants it generated in `.temp/pest-mutate-cache` and does not check that their files exist: after a run that could not write them, the next one reads 100 % with no warning. Every run of the harness passes `--no-cache`, so mutants are generated again each time and the cache of a developer is neither read nor written. A `pest --mutate` typed by hand still uses it: `--clear-cache` empties it. -#### A score needs proof that mutants load +#### A score needs proof that mutants load, and that the tests pass on unchanged code 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. -- **Cost.** Nothing more when a bootstrap loads the mutant at once (the framework: 0.1 s) or when a test includes the file early; otherwise as long as the suite takes to reach the file. A refusal costs a whole run of the suite. -- **What it cannot see.** That the processes of the mutants fail for a reason of their own (a test that only fails under `--filter`, a flaky one): they count as killed. A wrapper replaced only by some tests, which the probe does not run before the file is read. For the whole repository, a bootstrap that loads some files and not others. A `pest --mutate` run outside `pollora-qa`. +**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. +2. **The tests run as a mutant of an unchanged file**: `PEST_MUTATION_TESTING` is the source file, `PEST_MUTATION_FILE` an exact copy of it. As Pest does, only the tests that cover the file are selected, by name (`--filter`, in several runs when too long for PCRE; for the whole repository, the first source file stands for the others, with every test that covers a source file), and `--parallel` is never passed: the variables of a ParaTest worker are set instead. With pest-plugin-mutate 3, whose mutants collect coverage, so does this run. Without coverage data every test runs, which can refuse a score for a test no mutant of the file would run. +3. **They must exit 0** (a run that fails is tried once more) within five times the duration of step 1, and never less than 120 seconds. Otherwise Pest is not started and the gate fails, listing the failing tests. If they only fail with the worker variables, the mutants are run in a single process instead. + +Each of these runs has a temporary directory of its own (`TMPDIR`), removed afterwards, so that what a failing run leaves behind does not fail the next one. A test that starts further processes in a mutant's process (PHPUnit's `RunTestsInSeparateProcesses`) has them inherit `PEST_MUTATION_TESTING` without Pest's wrapper: a bootstrap must not assume the wrapper is there (`StreamWrapper::disable()` then raises a notice, `file:// was never changed`, which fails the test). + +Two causes have been seen. **Patchwork** (Brain Monkey loads it) stacked on Pest's stream wrapper breaks directory reading ([antecedent/patchwork#235](https://github.com/antecedent/patchwork/pull/235)). **Pest's wrapper itself** takes every `flock()` as a shared lock and reports a file nobody may read as absent, so a test of locking or permissions fails whatever Patchwork does. Both go away when the test bootstrap, if `PEST_MUTATION_TESTING` is set, gives `file` back and loads `PEST_MUTATION_FILE` itself. It gives it back **only when Pest's wrapper is on it**: a process PHPUnit isolates a test in has the variables but not the wrapper. At the top of the bootstrap, before Patchwork is loaded (it puts its own wrapper on `file`): + +```php +$mutating = is_string(getenv('PEST_MUTATION_TESTING')) && class_exists(\Pest\Mutate\Support\StreamWrapper::class); + +if ($mutating) { + $handle = fopen(__FILE__, 'r'); + $wrapped = (stream_get_meta_data($handle)['wrapper_data'] ?? null) instanceof \Pest\Mutate\Support\StreamWrapper; + fclose($handle); + + if ($wrapped) { + \Pest\Mutate\Support\StreamWrapper::disable(); + } +} + +// Patchwork, Composer's autoloader and the helpers of the tests are loaded here + +if ($mutating) { + require (string) getenv('PEST_MUTATION_FILE'); +} +``` + +That `require` is enough for a file that can be included on its own. For `__DIR__` and `__FILE__` in the mutated file, see the framework's `tests/bootstrap.php`. + +**To check a repository without a mutation pass** (a few runs of the suite, no gate, no report): + +```bash +vendor/bin/pollora-qa check --mutation-canary # the whole repository +vendor/bin/pollora-qa check --mutation-canary=src/A.php,src/B.php # some files, as the limited scopes do +``` + +It exits 1 when no score could be believed, whatever the mode of the repository, and when `pest-plugin-mutate` is not installed. Give it a coverage driver, as the mutation run has. + +- **Cost.** Two runs of the suite or of the covering tests (the control, then one per file; more when a run fails, which is tried again, and without the worker variables), then the canary: nothing more when a bootstrap loads the mutant at once (the framework: 0.1 s) or when a test includes the file early; otherwise as long as the suite takes to reach the file. A refusal costs a whole run of the suite. +- **What it cannot see.** Pest selects tests line by line: a test that only fails in the smaller selection of one line is not seen, nor a flaky one: they count as killed. A test that fails only now and then as a mutant: a failing run is tried once more, Pest tries each mutant once. A test that is slower as a mutant than Pest's own limit (the duration of its first run, plus 5 s or 20 %) yet within the limit above. A wrapper replaced only by some tests, which the probe does not run before the file is read. For the whole repository, a bootstrap that loads some files and not others. A `pest --mutate` run outside `pollora-qa`. **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. @@ -280,7 +322,7 @@ Only `scope` is needed; the other keys are optional and shown with their default - **New files** (absent from the base) are held to `min`, as `added` does; a renamed file is compared with its old path. A file with no mutant on the change (an interface) is listed, not failed; with no mutant on the base, it is held to `min`. - **Base unmeasured.** When the base cannot be measured (its tests fail there, a guard below refuses its score, its suite needs a file git ignores), a regression cannot be proved: the file is held to `min`, and the line says `base unmeasured` with the reason. The change must reach the fixed floor, so that a broken base never makes a file pass for free. - **Nothing is measured twice for nothing.** The change is measured first. A file at or above `100 - tolerance` cannot have dropped beyond the tolerance, so its base is not measured (the line says so). -- **A score is refused rather than believed**, on the change and on the base, in the cases that already gave a false figure: Pest could not write its temporary files (every mutant process fails and counts as killed: 100 %; the gate fails and names the directory); the test bootstrap loads **Patchwork** (Brain Monkey does) and Patchwork's stream wrapper replaced Pest's, so the mutants never load (every one survives) or the process dies (every one counts as killed, 100 % that no test earned). Pest's compact report shows neither, and the line `\Patchwork\CodeManipulation\Stream::reinstateWrapper();` also appears in the output of a healthy run (the framework's), so the gate does not read the output for it. It refuses on what it can see: a repository that has `antecedent/patchwork` and no test bootstrap (`tests/*.php`, `tests/*/*.php`, `phpunit.xml*`) that reads `PEST_MUTATION_TESTING` fails before any run, naming the fix (the framework's `tests/bootstrap.php` gives the wrapper back to Pest); and a run in which **at least 5 mutants all survive** (`859 untested, 0 tested`, the first failure above) is `unmeasured`. The check on the repository only proves the bootstrap *mentions* the variable: whether it works is checked by running it (see [A score needs proof that mutants load](#a-score-needs-proof-that-mutants-load)). A genuine 0 % on 4 mutants is judged like any other score; a genuine 100 % is believed. +- **A score is refused rather than believed**, on the change and on the base, in the cases that already gave a false figure: the tests fail on unchanged code run as a mutant (above); Pest could not write its temporary files (every mutant process fails and counts as killed: 100 %; the gate fails and names the directory); the test bootstrap loads **Patchwork** (Brain Monkey does) and Patchwork's stream wrapper replaced Pest's, so the mutants never load (every one survives) or the process dies (every one counts as killed, 100 % that no test earned). Pest's compact report shows neither, and the line `\Patchwork\CodeManipulation\Stream::reinstateWrapper();` also appears in the output of a healthy run (the framework's), so the gate does not read the output for it. It refuses on what it can see: a repository that has `antecedent/patchwork` and no test bootstrap (`tests/*.php`, `tests/*/*.php`, `phpunit.xml*`) that reads `PEST_MUTATION_TESTING` fails before any run, naming the fix (the framework's `tests/bootstrap.php` gives the wrapper back to Pest); and a run in which **at least 5 mutants all survive** (`859 untested, 0 tested`, the first failure above) is `unmeasured`. The check on the repository only proves the bootstrap *mentions* the variable: whether it works is checked by running it (see [A score needs proof that mutants load](#a-score-needs-proof-that-mutants-load)). A genuine 0 % on 4 mutants is judged like any other score; a genuine 100 % is believed. - **The cost is capped, and the cap fails.** Two passes per file: measured on the framework, a small file of 49 mutants takes about three minutes a pass (see the CHANGELOG), so the defaults are `max_files: 3` and `max_minutes: 15`. A change that touches more files than `max_files` fails **before anything runs**, naming the files and what to do (raise the key, split the change, measure by hand): measuring only some would let the others through. A release pull request does not reach this limit in the reusable workflow, which does not run the gate there (above); run by hand, `check` applies it as to any other change. During the run, a pass that the passes so far say would run past `max_minutes` is not started; the gate then fails and lists each file it did not reach (`not measured: the time budget ran out`), never green. A pass already started is not interrupted, so the job can overrun by one pass; the `timeout-minutes: 30` of the quality job stays the hard limit. - **What it does not see.** A change that only edits tests touches no source file and measures nothing (as with the other scopes). A regression spread over files the change does not touch is invisible. A renamed file is found by git's similarity detection (`-M`); a copied file counts as new. A suite whose result depends on files git ignores, or on a classmap-authoritative autoloader of the change, may read `base unmeasured`. The parallel and the single-process runs do not give exactly the same counts (above), and the gate does not know which of the two measured each side: that is what the tolerance is for. diff --git a/src/Check/MutationCanary.php b/src/Check/MutationCanary.php index d8ca115..060160f 100644 --- a/src/Check/MutationCanary.php +++ b/src/Check/MutationCanary.php @@ -4,10 +4,12 @@ namespace Pollora\Harness\Check; +use Pollora\Harness\Support\ChangedSources; use Pollora\Harness\Support\InterpreterFlags; /** - * Checks that the mutated source is the code PHP runs, before a mutation score is believed. + * Checks, before a mutation score is believed, that the process of a mutant says something about the mutant: the mutated + * source is the code PHP runs, and the tests pass when that source is not changed at all. * * Pest hands a mutant to its process through `PEST_MUTATION_TESTING` (the source file) and `PEST_MUTATION_FILE` (the * mutated copy), and serves the copy through a stream wrapper on `file`. Another wrapper (Patchwork, which Brain @@ -23,20 +25,142 @@ * repository's bootstrap leaves mutant loading working, not that every one of its files is loaded that way. * * A legitimate score of 100 % passes: it differs from a false one by the canary being executed, not by its value. + * + * 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 + * shared and reports an unreadable file as absent) therefore scores mutants nothing tested. So tests are also run as + * Pest runs a mutant, with `PEST_MUTATION_FILE` an exact copy of the source: + * + * - First the suite runs alone: the control, which times it and, with a coverage driver, says which tests cover which + * file. A single process is tried first, then `--parallel` (for a suite that only holds that way, or one flaky run), + * both with coverage before either without; when none passes there is nothing to compare with. + * - Then, with the environment of a mutant, the tests Pest would select: those that cover the file (`--filter`, the + * union of what it selects for each line, in several runs when too long for one). Never their whole class: a test + * that covers nothing is run for no mutant. Without coverage data, the whole suite, which can refuse a score for a + * test that no mutant of the file would run. + * - Pest never gives a mutant `--parallel`: in a parallel mutation run it sets the variables of a ParaTest worker, and + * so does this. When the tests only fail with those, mutants are not run in parallel. + * - pest-plugin-mutate 3 leaves `--coverage-php` among the arguments of a mutant (4 removes it), so with coverage data + * those runs collect coverage too when the installed version does. + * - A run that fails is tried once more: one flaky failure must not refuse the score. + * - Without `--bail`, so that every failing test is listed; the verdict is the same. + * - The limit of these runs is `TIME_FACTOR` times the control, and never below `TIME_FLOOR` seconds. */ final class MutationCanary { + /** A run as a mutant is stopped after this many times the duration of the suite alone, */ + public const float TIME_FACTOR = 5.0; + + /** 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; + private const string LOADED = 'loaded'; private const string IGNORED = 'ignored'; private const string ABSENT = 'absent'; + /** Past this length a `--filter` is split over several runs: PCRE refuses a longer one, which then selects nothing. */ + private const int FILTER_LIMIT = 20_000; + + /** What Pest and ParaTest set in the processes of a run: none of it may leak into the control. */ + private const array PEST_VARIABLES = ['PEST_MUTATION_TESTING', 'PEST_MUTATION_FILE', 'PARATEST', 'TEST_TOKEN', 'UNIQUE_TEST_TOKEN', 'LARAVEL_PARALLEL_TESTING']; + /** + * Both checks at once, for a use without a mutation run (`check --mutation-canary`). + * + * @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 string|null Why no score could be believed, null when it could + */ + public static function refusal(string $cwd, array $paths, float $floor = self::TIME_FLOOR): ?string + { + $unchanged = self::unchanged($cwd, $paths, $floor); + + return $unchanged['refusal'] ?? self::loaded($cwd, $paths, $unchanged['limit']); + } + + /** + * Whether the tests pass as the process of a mutant that changes nothing. To be asked before Pest runs its + * mutants: they may leave files behind that make the suite fail afterwards. + * + * For the whole repository, the first source file stands for the others (Pest puts its wrapper on `file` whatever + * the file is), with the tests that cover any of them. Each file of a limited run is tried with its own tests. + * + * @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 + */ + public static function unchanged(string $cwd, array $paths, float $floor = self::TIME_FLOOR): array + { + $result = ['refusal' => null, 'parallel' => true, 'controlled' => true, 'limit' => $floor]; + $root = realpath($cwd); + + if ($root === false) { + return $result; + } + + $sources = $paths === [] ? ChangedSources::all($root) : $paths; + $originals = self::originals($root, $paths === [] ? array_slice($sources, 0, 1) : $paths); + + // Without a source file to copy there is no mutant either + if ($originals === []) { + return $result; + } + + $control = self::control($root); + + if (is_string($control)) { + return [...$result, 'refusal' => $control, 'controlled' => false]; + } + + [$seconds, $coverage] = $control; + $result['limit'] = max($floor, self::TIME_FACTOR * $seconds); + + $covering = $coverage !== null && self::mutantsCollectCoverage($root); + + foreach ($originals as $path => $original) { + $filters = null; + + if ($coverage !== null) { + $tests = self::testsCovering($coverage, $paths === [] ? array_values(self::originals($root, $sources)) : [$original]); + + // No test covers the file: Pest runs no mutant of it + if ($tests === [] && $paths !== []) { + continue; + } + + $filters = $tests === [] ? null : self::filters($tests); + } + + foreach ($filters ?? [null] as $filter) { + $variables = $result['parallel'] ? self::workerVariables() : []; + $refusal = self::unchangedRefusal($root, $path, $original, $variables, $filter, $result['limit'], $paths === [], $covering); + + if ($refusal !== null && $variables !== []) { + $result['parallel'] = false; + $refusal = self::unchangedRefusal($root, $path, $original, [], $filter, $result['limit'], $paths === [], $covering); + } + + if ($refusal !== null) { + return [...$result, 'refusal' => $refusal]; + } + } + } + + return $result; + } + + /** + * Whether the mutated version of a source file is the code the tests run. + * * @param list $paths The source files the run mutated, relative to $cwd; empty for the whole repository + * @param float $limit The longest a run may take, in seconds * @return string|null Why no score can be believed, null when mutated sources are executed */ - public static function refusal(string $cwd, array $paths): ?string + public static function loaded(string $cwd, array $paths, float $limit = self::TIME_FLOOR): ?string { $root = realpath($cwd); @@ -45,20 +169,15 @@ public static function refusal(string $cwd, array $paths): ?string } if ($paths === []) { - return self::probeBootstrap($root); + return self::probeBootstrap($root, $limit); } + $originals = self::originals($root, $paths); $loaded = false; $output = ''; - foreach ($paths as $path) { - $original = realpath($root.'/'.$path); - - if ($original === false) { - continue; - } - - [$state, $output] = self::probe($root, $original); + foreach ($originals as $path => $original) { + [$state, $output] = self::probe($root, $original, [], $limit); if ($state === self::IGNORED) { return self::message(sprintf('%s was included by the tests, but not its mutated version', $path), $output); @@ -72,21 +191,257 @@ public static function refusal(string $cwd, array $paths): ?string } // A suite that only holds in parallel may stop, in a single process, before it reaches the file + foreach ($originals as $original) { + if (self::probe($root, $original, ['--parallel'], $limit)[0] === self::LOADED) { + return null; + } + } + + return self::message(sprintf('no mutated version of %s was executed by the tests', implode(', ', $paths)), $output); + } + + /** + * @param list $paths + * @return array The real path of each file that exists + */ + private static function originals(string $root, array $paths): array + { + $originals = []; + foreach ($paths as $path) { $original = realpath($root.'/'.$path); - if ($original !== false && self::probe($root, $original, ['--parallel'])[0] === self::LOADED) { + if ($original !== false) { + $originals[$path] = $original; + } + } + + return $originals; + } + + /** + * Runs the suite alone, with nothing of a mutant. + * + * @return array{float, array>|null}|string Its duration and the tests covering each file (null + * without coverage data), or why nothing can be compared + */ + private static function control(string $root): array|string + { + $report = sys_get_temp_dir().'/pollora-coverage-'.bin2hex(random_bytes(8)).'.php'; + + // In parallel too: without coverage data, every test would be run as a mutant, those of no mutant included + foreach ([[], ['--parallel']] as $arguments) { + try { + [$code, , $seconds] = self::execute($root, [...$arguments, '--coverage-php='.$report], [...self::environment(), 'XDEBUG_MODE' => 'coverage'], flags: InterpreterFlags::coverageScope($root)); + + if ($code === 0) { + return [$seconds, self::coverage($root, $report)]; + } + } finally { + if (is_file($report)) { + unlink($report); + } + } + } + + $output = ''; + + // Coverage can be what fails (no driver, in a repository that fails on warnings) + foreach ([[], ['--parallel']] as $arguments) { + [$code, $output, $seconds] = self::execute($root, $arguments, self::environment()); + + if ($code === 0) { + return [$seconds, null]; + } + } + + return self::message('the tests do not pass on their own, outside any mutation', $output, 'Run `vendor/bin/pest`: it must pass first.'); + } + + /** + * The tests that cover each file, read from a `--coverage-php` report with the classes of the repository. + * + * @return array>|null null when the report cannot be read or names no test + */ + private static function coverage(string $root, string $report): ?array + { + if (! is_file($report)) { + return null; + } + + $code = <<<'PHP' + if (is_file($argv[1])) { require $argv[1]; } + $coverage = require $argv[2]; + $files = []; + foreach ($coverage->getData()->lineCoverage() as $file => $lines) { + $tests = []; + foreach ($lines as $names) { foreach ((array) $names as $name) { $tests[$name] = true; } } + if ($tests !== []) { $files[realpath($file) ?: $file] = array_keys($tests); } + } + echo "\n", json_encode($files); + PHP; + // A report weighs tens of megabytes before it is unserialized + $process = proc_open([PHP_BINARY, '-d', 'memory_limit=-1', '-r', $code, '--', $root.'/vendor/autoload.php', $report], [1 => ['pipe', 'w'], 2 => ['file', '/dev/null', 'w']], $pipes, $root); + + if (! is_resource($process)) { + return null; + } + + $lines = explode("\n", (string) stream_get_contents($pipes[1])); + fclose($pipes[1]); + proc_close($process); + $files = json_decode((string) end($lines), true); + + if (! is_array($files) || $files === []) { + return null; + } + + $coverage = []; + + foreach ($files as $file => $tests) { + $coverage[(string) $file] = is_array($tests) ? array_values(array_filter($tests, is_string(...))) : []; + } + + return $coverage; + } + + /** + * @param array> $coverage + * @param list $files + * @return list + */ + private static function testsCovering(array $coverage, array $files): array + { + $tests = []; + + foreach ($files as $file) { + array_push($tests, ...($coverage[$file] ?? [])); + } + + return array_values(array_unique($tests)); + } + + /** + * The `--filter` Pest gives the process of a mutant (`MutationTest::start()`), for these tests, in as many parts as + * their length needs. + * + * @param list $tests As the coverage names them + * @return list|null null when a test has a name Pest's own pattern does not read + */ + private static function filters(array $tests): ?array + { + $names = []; + + foreach ($tests as $test) { + if (preg_match('/\\\\([a-zA-Z0-9]*)::(__pest_evaluable_)?([^#]*)"?/', $test, $matches) !== 1) { return null; } + + $names[$matches[1].'::(.*)'.($matches[2] === '__pest_evaluable_' ? str_replace(['__', '_'], ['.{1,2}', '.'], $matches[3]) : $matches[3])] = true; } - return self::message(sprintf('no mutated version of %s was executed by the tests', implode(', ', $paths)), $output); + $filters = []; + $part = ''; + + foreach (array_keys($names) as $name) { + if ($part !== '' && strlen($part) + strlen($name) >= self::FILTER_LIMIT) { + $filters[] = $part; + $part = ''; + } + + $part .= ($part === '' ? '' : '|').$name; + } + + return $part === '' ? $filters : [...$filters, $part]; + } + + /** + * Whether the installed pest-plugin-mutate gives a mutant the `--coverage-php` of its own run: it does unless + * `MutationTest` removes it. + */ + private static function mutantsCollectCoverage(string $root): bool + { + $source = $root.'/vendor/pestphp/pest-plugin-mutate/src/MutationTest.php'; + + return is_file($source) && ! str_contains((string) file_get_contents($source), "'--coverage'"); + } + + /** + * What Pest sets in the process of a mutant of a parallel run. + * + * @return array + */ + private static function workerVariables(): array + { + return ['PARATEST' => '1', 'TEST_TOKEN' => '1', 'UNIQUE_TEST_TOKEN' => '1_'.bin2hex(random_bytes(6)), 'LARAVEL_PARALLEL_TESTING' => '1']; + } + + /** + * Runs the tests as the process of a mutant that changes nothing. + * + * @param array $variables Those of a parallel run, or none + * @param string|null $filter The tests to run; null runs them all + */ + 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)); + + if (! @copy($original, $copy)) { + return self::message(sprintf('the harness could not copy %s', $path)); + } + + $environment = [...self::environment(), 'PEST_MUTATION_TESTING' => $original, 'PEST_MUTATION_FILE' => $copy, ...$variables]; + $report = $covering ? sys_get_temp_dir().'/pollora-coverage-'.bin2hex(random_bytes(8)).'.php' : null; + $coverageArguments = $report === null ? [] : ['--coverage-php='.$report]; + + try { + // Never --parallel, which Pest gives no mutant + $arguments = [...$coverageArguments, ...($filter === null ? [] : ['--filter='.$filter])]; + [$code, $output] = self::execute($root, $arguments, $environment, $limit); + + // A filter that selects nothing proves nothing: the whole suite then + if ($filter !== null && preg_match('/No tests (?:found|executed)/i', $output) === 1) { + $filter = null; + $arguments = $coverageArguments; + [$code, $output] = self::execute($root, $arguments, $environment, $limit); + } + + // One flaky failure is no verdict; a run past the limit is not tried again + if ($code !== 0 && $code !== null) { + [$code, $output] = self::execute($root, $arguments, $environment, $limit); + } + } finally { + foreach ([$copy, $report] as $file) { + if ($file !== null && is_file($file)) { + unlink($file); + } + } + } + + if ($code === 0) { + return null; + } + + return self::message( + sprintf( + 'the suite passes on its own but %s %s when Pest runs them as a mutant of %s that changes nothing%s%s', + $filter === null ? 'its tests (all of them: no coverage data to select by)' : 'the tests covering the code', + $code === null ? sprintf('are still running after %d s', (int) ceil($limit)) : sprintf('fail (exit code %d)', $code), + $path, + $variables === [] ? '' : ', in a parallel run', + $wholeRepository ? ' (the first source file, standing for every one: the failure does not have to be about it)' : '', + ), + $output, + 'Pest counts such a failure as a caught mutant, and a loop as a timeout, which counts as caught too. Known causes: the stream wrapper Pest puts on `file` (it takes every flock() as shared and reports a file nobody may read as absent), Patchwork, which Brain Monkey loads, stacked on it (reading a directory then fails: antecedent/patchwork#235), and tests that only pass after others that Pest does not run with them. When PEST_MUTATION_TESTING is set, the test bootstrap can give `file` back, only if the wrapper of Pest is on it (a process PHPUnit isolates a test in has the variables but not the wrapper), and load PEST_MUTATION_FILE itself (the README shows how).', + ); } /** * Probes a source file the harness writes, required by a test it writes. */ - private static function probeBootstrap(string $root): ?string + private static function probeBootstrap(string $root, float $limit): ?string { $name = 'PolloraCanary'.bin2hex(random_bytes(6)); $original = (is_dir($root.'/src') ? $root.'/src/' : $root.'/').$name.'.php'; @@ -103,7 +458,7 @@ private static function probeBootstrap(string $root): ?string return self::message('the harness could not write its canary files in the repository'); } - [$state, $output] = self::probe($root, $original, [$test]); + [$state, $output] = self::probe($root, $original, [$test], $limit); return $state === self::LOADED ? null : self::message('a mutated source file required by a test was not executed', $output); } finally { @@ -122,7 +477,7 @@ private static function probeBootstrap(string $root): ?string * @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 */ - private static function probe(string $root, string $original, array $arguments = []): array + private static function probe(string $root, string $original, array $arguments, float $limit): array { $directory = sys_get_temp_dir().'/pollora-canary-'.bin2hex(random_bytes(8)); @@ -130,9 +485,9 @@ private static function probe(string $root, string $original, array $arguments = return [self::ABSENT, 'cannot create '.$directory]; } - [$mutant, $prepend, $loaded, $included, $log] = array_map( + [$mutant, $prepend, $loaded, $included] = array_map( static fn (string $name): string => $directory.'/'.$name, - ['mutant.php', 'prepend.php', 'loaded', 'included', 'output'], + ['mutant.php', 'prepend.php', 'loaded', 'included'], ); try { @@ -143,18 +498,14 @@ private static function probe(string $root, string $original, array $arguments = var_export($included, true), )); - $process = proc_open( - [PHP_BINARY, ...InterpreterFlags::inherited(), '-d', 'auto_prepend_file='.$prepend, 'vendor/bin/pest', ...$arguments], - [1 => ['file', $log, 'w'], 2 => ['file', '/dev/null', 'w']], - $pipes, + [, $output] = self::execute( $root, - [...getenv(), 'PEST_MUTATION_TESTING' => $original, 'PEST_MUTATION_FILE' => $mutant], + $arguments, + [...self::environment(), 'PEST_MUTATION_TESTING' => $original, 'PEST_MUTATION_FILE' => $mutant], + $limit, + ['-d', 'auto_prepend_file='.$prepend], ); - if (is_resource($process)) { - proc_close($process); - } - clearstatcache(); $state = match (true) { @@ -163,9 +514,9 @@ private static function probe(string $root, string $original, array $arguments = default => self::ABSENT, }; - return [$state, is_file($log) ? (string) file_get_contents($log) : '']; + return [$state, $output]; } finally { - foreach ([$mutant, $prepend, $loaded, $included, $log] as $file) { + foreach ([$mutant, $prepend, $loaded, $included] as $file) { if (is_file($file)) { unlink($file); } @@ -175,14 +526,162 @@ private static function probe(string $root, string $original, array $arguments = } } - private static function message(string $what, string $output = ''): string + /** + * Runs Pest, and kills it and its processes once past the limit. + * + * @param list $arguments + * @param array $environment + * @param list $flags Flags of the interpreter + * @return array{int|null, string, float} The exit code (null when killed), the output and the seconds it took + */ + private static function execute(string $root, array $arguments, array $environment, ?float $limit = null, array $flags = []): array { - $tail = trim(substr($output, -600)); + $log = (string) tempnam(sys_get_temp_dir(), 'pollora-pest-'); + // A run of its own: what a killed or failing run leaves behind must not fail the next one + $temporary = sys_get_temp_dir().'/pollora-run-'.bin2hex(random_bytes(6)); - return sprintf( - 'No mutation score can be believed: %s, so Pest\'s score is not about its mutants (they survive unseen, or their processes die and count as killed). Something else serves the source files, usually Patchwork replacing the stream wrapper: the test bootstrap must give it back to Pest when PEST_MUTATION_TESTING is set and load PEST_MUTATION_FILE.%s', - $what, - $tail === '' ? '' : "\n".$tail, - ); + if (@mkdir($temporary, 0o700)) { + $environment = [...$environment, 'TMPDIR' => $temporary, 'TMP' => $temporary, 'TEMP' => $temporary]; + } + + $started = microtime(true); + + try { + $process = proc_open( + [PHP_BINARY, ...InterpreterFlags::inherited(), '-d', 'display_errors=1', ...$flags, 'vendor/bin/pest', ...$arguments], + [1 => ['file', $log, 'a'], 2 => ['file', $log, 'a']], + $pipes, + $root, + $environment, + ); + + if (! is_resource($process)) { + return [-1, 'Pest could not be started', 0.0]; + } + + $code = null; + + while (true) { + $status = proc_get_status($process); + + if (! $status['running']) { + $code = $status['exitcode']; + + break; + } + + if ($limit !== null && microtime(true) - $started > $limit) { + self::kill($process, $status['pid']); + + break; + } + + usleep(20_000); + } + + proc_close($process); + + return [$code, (string) file_get_contents($log), microtime(true) - $started]; + } finally { + unlink($log); + self::remove($temporary); + } + } + + /** + * Removes a directory and what is in it, without following links. + */ + private static function remove(string $directory): void + { + if (! is_dir($directory) || is_link($directory)) { + return; + } + + // A test may leave a directory nobody can list + @chmod($directory, 0o700); + + foreach (array_diff((array) @scandir($directory), ['.', '..', false]) as $name) { + $path = $directory.'/'.$name; + + if (is_dir($path) && ! is_link($path)) { + self::remove($path); + } else { + @unlink($path); + } + } + + @rmdir($directory); + } + + /** + * Kills a process and the processes it started (the workers of ParaTest, a server a test left running). + * + * @param resource $process + */ + private static function kill($process, int $pid): void + { + $list = proc_open(['ps', '-A', '-o', 'pid=,ppid='], [1 => ['pipe', 'w'], 2 => ['file', '/dev/null', 'w']], $pipes); + $table = ''; + + if (is_resource($list)) { + $table = (string) stream_get_contents($pipes[1]); + fclose($pipes[1]); + proc_close($list); + } + + preg_match_all('/^\s*(\d+)\s+(\d+)\s*$/m', $table, $rows, PREG_SET_ORDER); + $doomed = [$pid]; + + for ($index = 0; $index < count($doomed); $index++) { + foreach ($rows as [, $child, $parent]) { + if ((int) $parent === $doomed[$index]) { + $doomed[] = (int) $child; + } + } + } + + proc_terminate($process, 9); + + // The command rather than posix_kill(), which would make ext-posix a requirement + if (count($doomed) > 1) { + $killing = proc_open(['kill', '-9', ...array_map(strval(...), array_slice($doomed, 1))], [2 => ['file', '/dev/null', 'w']], $ignored); + + if (is_resource($killing)) { + proc_close($killing); + } + } + } + + /** + * The environment of the harness without what Pest sets for the processes of a run. + * + * @return array + */ + private static function environment(): array + { + return array_diff_key(getenv(), array_flip(self::PEST_VARIABLES)); + } + + private static function message(string $what, string $output = '', ?string $advice = null): string + { + $clean = (string) preg_replace('/\x1b\[[0-9;]*m/', '', $output); + preg_match_all('/^\s*FAILED\s+\S.*$/m', $clean, $failures); + $failed = array_slice(array_map(static fn (string $line): string => ' '.trim((string) preg_replace('/\s{2,}/', ' ', $line)), $failures[0]), 0, 15); + $tail = trim(substr($clean, -600)); + // Said first: an exhausted memory looks like any other failure, and a flag of the command does not help + $memory = preg_match('/Allowed memory size of (\d+) bytes exhausted/', $clean, $exhausted) === 1 + ? [sprintf('A process ran out of memory (memory_limit of %d MB). A `php -d memory_limit=...` on this command does not reach the processes of the tests, as it does not reach those Pest starts for its mutants: set it in php.ini (or a PHP_INI_SCAN_DIR file), or in phpunit.xml with .', intdiv((int) $exhausted[1], 1024 * 1024))] + : []; + + return implode("\n", [ + sprintf( + 'No mutation score can be believed: %s, so Pest\'s score is not about its mutants (they survive unseen, or their processes die and count as killed). %s', + $what, + $advice ?? 'Something else serves the source files, usually Patchwork replacing the stream wrapper: when PEST_MUTATION_TESTING is set, the test bootstrap must give it back to Pest, only if the wrapper of Pest is on it, and load PEST_MUTATION_FILE (the README shows how).', + ), + ...$memory, + ...$failed, + ...($tail === '' ? [] : [$tail]), + ]); } } diff --git a/src/Check/MutationMeasure.php b/src/Check/MutationMeasure.php index dea3b12..13d07a5 100644 --- a/src/Check/MutationMeasure.php +++ b/src/Check/MutationMeasure.php @@ -20,7 +20,8 @@ * survives (`859 untested, 0 tested`, `unmeasured`); the second, a score of 100 % that no test earned, is refused * by `RelativeMutation::patchworkGuard()` before any run, from the repository. * - Pest created no mutation: `Score: 0.00%` measures nothing (`empty`). - * - `MutationCanary` saw no mutated source being executed: the score is about something else (`unmeasured`). + * - `MutationCanary` saw no mutated source being executed, or the tests fail in the process of a mutant that changes + * nothing: the score is about something else (`unmeasured`). * * `RelativeMutation` adds the one check that needs the repository, not the output: a suite that loads Patchwork * without handing the stream wrapper back to Pest. diff --git a/src/Check/MutationRun.php b/src/Check/MutationRun.php index ab41b91..4021616 100644 --- a/src/Check/MutationRun.php +++ b/src/Check/MutationRun.php @@ -32,9 +32,11 @@ * Pest keeps the mutants it generated in a cache that names files it does not check again: after a run that could not * write them, the next one reads 100 % with no warning. The run therefore passes `--no-cache`. * - * Last, a score is only returned once `MutationCanary` has seen a mutated source being executed: when something else - * serves the original file (Patchwork replacing Pest's stream wrapper), the result has a null score and says why in - * `unloaded`. + * Last, a score is only returned when `MutationCanary` has seen the tests pass as a mutant that changes nothing (asked + * 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. */ final class MutationRun { @@ -50,11 +52,22 @@ public static function run(string $cwd, array $paths = []): array return ['score' => null, 'summary' => '', 'output' => '', 'empty' => false, 'unwritable' => true]; } + // Before Pest runs: its mutants may leave files behind that make the suite fail afterwards + $unchanged = MutationCanary::unchanged($cwd, $paths); + + // No pass of Pest could give a score to believe: not worth its time + if ($unchanged['controlled'] && $unchanged['refusal'] !== null) { + return ['score' => null, 'summary' => '', 'output' => '', 'empty' => false, 'unwritable' => false, 'unloaded' => $unchanged['refusal']]; + } + $started = time(); - $result = self::execute($cwd, true, $paths); + // Not in parallel when the tests fail with the variables of a worker, which would count mutants as caught + $parallel = $unchanged['parallel']; + $result = self::execute($cwd, $parallel, $paths); - if ($result['score'] === null && ! $result['empty'] && ! $result['unwritable']) { - $result = self::execute($cwd, false, $paths); + if ($parallel && $result['score'] === null && ! $result['empty'] && ! $result['unwritable']) { + $parallel = false; + $result = self::execute($cwd, $parallel, $paths); } // A directory that stopped being writable, or a mutant left empty (a full disk), while Pest was running @@ -62,7 +75,7 @@ public static function run(string $cwd, array $paths = []): array return [...$result, 'score' => null, 'empty' => false, 'unwritable' => true]; } - $refusal = $result['score'] === null ? null : MutationCanary::refusal($cwd, $paths); + $refusal = $result['score'] === null ? null : ($unchanged['refusal'] ?? MutationCanary::loaded($cwd, $paths, $unchanged['limit'])); return $refusal === null ? $result : [...$result, 'score' => null, 'unloaded' => $refusal]; } diff --git a/src/Check/RelativeMutation.php b/src/Check/RelativeMutation.php index 7d4c3b6..7824e92 100644 --- a/src/Check/RelativeMutation.php +++ b/src/Check/RelativeMutation.php @@ -30,7 +30,8 @@ * - **Base unmeasured** (its tests fail, a measuring guard trips): the file is held to `min` and says so; a * regression cannot be proved, so it is the fixed floor or nothing. * - **Change unmeasured**: the gate fails. A score is refused rather than believed when Pest could not write its - * files, when no mutated source was seen being executed (`MutationCanary`: Patchwork or another stream wrapper + * files, when the tests fail on unchanged code run as a mutant or no mutated source was seen being executed + * (`MutationCanary`: Patchwork or another stream wrapper * serving the original), when every mutant survived, or when the tests fail. * - **Nothing is measured twice for nothing.** The change is measured first; a file at or above `100 - tolerance` * cannot have dropped beyond the tolerance, so its base is not measured. @@ -203,7 +204,7 @@ public static function patchworkGuard(string $cwd): ?string } } - return "The mutation score cannot be measured here: antecedent/patchwork is installed (Brain Monkey loads it) and no test bootstrap reads PEST_MUTATION_TESTING.\nPatchwork and Pest both rewrite what PHP loads through a stream wrapper on `file`: the mutant is never loaded and every mutant survives, or the process dies and counts as killed, so the score would be wrong in a way Pest does not report. Give the wrapper back to Pest in the tests' bootstrap when PEST_MUTATION_TESTING is set (see the framework's tests/bootstrap.php)."; + return "The mutation score cannot be measured here: antecedent/patchwork is installed (Brain Monkey loads it) and no test bootstrap reads PEST_MUTATION_TESTING.\nPatchwork and Pest both rewrite what PHP loads through a stream wrapper on `file`: the mutant is never loaded and every mutant survives, or the process dies and counts as killed, so the score would be wrong in a way Pest does not report. When PEST_MUTATION_TESTING is set, the tests' bootstrap must give the wrapper back, only if Pest's wrapper is on `file`, and load PEST_MUTATION_FILE (the harness README shows how)."; } /** diff --git a/src/Console/Commands/CheckCommand.php b/src/Console/Commands/CheckCommand.php index 909a885..ffa49e4 100644 --- a/src/Console/Commands/CheckCommand.php +++ b/src/Console/Commands/CheckCommand.php @@ -4,6 +4,7 @@ namespace Pollora\Harness\Console\Commands; +use Pollora\Harness\Check\MutationCanary; use Pollora\Harness\Check\Plan; use Pollora\Harness\Check\Report; use Pollora\Harness\Check\Runner; @@ -34,6 +35,7 @@ public function usage(): string --coverage[=FILE] Run the tests with coverage and compare the Clover report with the ratchet (default file .harness/coverage.xml) --infection=FILE Infection JSON log to compare with the ratchet --mutation Run Pest's mutation testing (pest --mutate) and compare its score with the ratchet's msi + --mutation-canary[=FILES] Run no gate: only check that a mutation score could be believed here (mutants load, and the tests pass on unchanged code run as a mutant), of the whole repository or of the files given (comma separated); fails whatever the mode --mutation-base=REF With a limited mutation.scope, the commit the changed files are counted from (default HEAD^1: a pull request's merge commit needs fetch-depth 2) --budgets-base=REF The commit the query budgets (PERF-01) are compared with, to refuse a budget that went up (default HEAD^1; "not compared" when it is not in the checkout) --mutation-scope=S all, changed, added or changed-relative: what --mutation mutates in this run, over .harness.json (a limited scope is held to mutation.min, 50 % without one) @@ -52,6 +54,10 @@ public function run(Io $io): int return $this->template($io); } + if ($io->flag('mutation-canary')) { + return $this->mutationCanary($io); + } + $config = HarnessConfig::load($io->cwd); $mode = match (true) { $io->flag('enforce') => Mode::Enforce, @@ -92,6 +98,41 @@ public function run(Io $io): int return $report->hasBlockingFailures() ? self::FAILURE : self::SUCCESS; } + /** + * `check --mutation-canary`: what a mutation run checks about its score, without the run itself, in the time of + * a few passes of the suite and without a coverage driver. + */ + private function mutationCanary(Io $io): int + { + if (! is_dir($io->cwd.'/vendor/pestphp/pest-plugin-mutate')) { + $io->error('vendor/pestphp/pest-plugin-mutate is not installed: nothing was checked.'); + + return self::FAILURE; + } + + $paths = array_values(array_filter(explode(',', $io->option('mutation-canary') ?? ''), static fn (string $path): bool => $path !== '')); + + foreach ($paths as $path) { + if (! is_file($io->cwd.'/'.$path)) { + $io->error(sprintf('--mutation-canary: %s is not a file of the repository.', $path)); + + return self::FAILURE; + } + } + + $refusal = MutationCanary::refusal($io->cwd, $paths); + + if ($refusal !== null) { + $io->error($refusal); + + return self::FAILURE; + } + + $io->line('Mutation canary passed: mutants load, and the tests pass on unchanged code run as a mutant. No score was measured.'); + + return self::SUCCESS; + } + /** * `check --template`: the gates `template.yml` cannot run as separate jobs, read from the optional file of * the template. Without a file it does nothing and succeeds, so that a template that never adopted one diff --git a/src/Support/ChangedSources.php b/src/Support/ChangedSources.php index 06bcaba..c8fce33 100644 --- a/src/Support/ChangedSources.php +++ b/src/Support/ChangedSources.php @@ -4,6 +4,10 @@ namespace Pollora\Harness\Support; +use FilesystemIterator; +use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; + /** * The source files a change touches, for the mutation run limited to them (`mutation.scope: "changed"`). * @@ -26,6 +30,43 @@ final class ChangedSources /** The name Pest's mutation bootstrap gives the copy of a file it mutates; never a source file. */ private const string MUTANT_PREFIX = '.mutant-'; + /** + * Every source file of the repository, by the same rules as `since()`, sorted, relative to `$cwd`. + * + * @return list + */ + public static function all(string $cwd): array + { + $root = rtrim($cwd, '/'); + $loaded = self::autoloadFiles($cwd); + $files = []; + + foreach (self::sourceDirectories($cwd) as $directory) { + $path = rtrim($root.'/'.$directory, '/'); + + // The root itself as a source directory would walk vendor/ + if (! is_dir($path) || realpath($path) === realpath($root)) { + continue; + } + + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::CURRENT_AS_PATHNAME | FilesystemIterator::SKIP_DOTS)) as $file) { + if (! is_string($file)) { + continue; + } + + $name = substr($file, strlen($root) + 1); + + if (str_ends_with($name, '.php') && ! str_starts_with(basename($name), self::MUTANT_PREFIX) && ! in_array($name, $loaded, true)) { + $files[] = $name; + } + } + } + + sort($files); + + return $files; + } + /** * The PHP source files added, copied, modified or renamed between `$base` and `HEAD`, relative to `$cwd`. * diff --git a/tests/Unit/MutationTrustTest.php b/tests/Unit/MutationTrustTest.php index 91937c0..df724ce 100644 --- a/tests/Unit/MutationTrustTest.php +++ b/tests/Unit/MutationTrustTest.php @@ -9,6 +9,9 @@ use Pollora\Harness\Check\Step; use Pollora\Harness\Check\StepResult; use Pollora\Harness\Config\HarnessConfig; +use Pollora\Harness\Console\Commands\CheckCommand; +use Pollora\Harness\Console\Io; +use Pollora\Harness\Support\ChangedSources; require_once __DIR__.'/../Support/RelativeMutationFixture.php'; @@ -204,8 +207,9 @@ function trustPrints(string $report): string * @param string $bootstrap PHP run by the test bootstrap, after the autoloader * @param list $paths */ -function realPestRefusal(string $bootstrap, array $paths): ?string +function realPestRefusal(string $bootstrap, array $paths, ?string $test = null): ?string { + $test ??= "expect(require __DIR__.'/../src/Answer.php')->toBeInt();"; $harness = dirname(__DIR__, 2); $root = '/tmp/pollora-harness-canary-'.bin2hex(random_bytes(5)); @@ -219,7 +223,8 @@ function realPestRefusal(string $bootstrap, array $paths): ?string file_put_contents($root.'/vendor/autoload.php', "toBeInt();\n});\n"); + // A whole test file, or the body of one test + file_put_contents($root.'/tests/AnswerTest.php', str_starts_with($test, 'tests'); try { @@ -251,3 +256,347 @@ function realPestRefusal(string $bootstrap, array $paths): ?string expect(realPestRefusal($bootstrap, $paths))->toBeNull(); })->with(['a file' => [['src/Answer.php']], 'the whole repository' => [[]]]); }); + +/** A mutant's process that loads its mutant and then fails: what Patchwork on top of Pest's wrapper does to a suite. */ +const FAILS_AFTER_LOADING = "require getenv('PEST_MUTATION_FILE'); echo \" FAILED Tests\\\\ATest > it lists a directory\\n\"; exit(2);"; + +describe('the tests on unchanged code run as a mutant', function (): void { + it('give no score when they fail, though the mutant loads and Pest reads 100 %', function (array $paths): void { + $root = trustProject(trustPrints(TRUST_REPORT), FAILS_AFTER_LOADING); + + $measure = MutationMeasure::fromRun(MutationRun::run($root, $paths)); + + expect($measure->state)->toBe(MutationMeasure::UNMEASURED) + ->and($measure->why)->toContain('No mutation score can be believed') + ->and($measure->why)->toContain('fail (exit code 2) when Pest runs them as a mutant of src/A.php that changes nothing') + ->and($measure->why)->toContain('FAILED Tests\ATest > it lists a directory'); + })->with(['a file' => [['src/A.php']], 'the whole repository' => [[]]]); + + it('do not start Pest, whose mutants would all be read as caught', function (): void { + $root = trustProject("if (in_array('--mutate', \$argv, true)) {\n touch('ran');\n}", FAILS_AFTER_LOADING); + + expect(MutationRun::run($root)['score'])->toBeNull() + ->and($root.'/ran')->not->toBeFile(); + }); + + it('are given an exact copy where Pest writes its mutants, neither --bail nor --parallel, and the copy is removed', function (): void { + $record = <<<'PHP' + $copy = (string) getenv('PEST_MUTATION_FILE'); + $original = (string) getenv('PEST_MUTATION_TESTING'); + if (str_contains($copy, 'pollora-unchanged-')) { + file_put_contents('seen', json_encode([$original, $copy, md5_file($copy) === md5_file($original), array_slice($argv, 1), getenv('PARATEST'), getenv('TEST_TOKEN')])); + } + require $copy; + PHP; + $root = trustProject('', $record); + + expect(MutationCanary::refusal($root, ['src/A.php']))->toBeNull(); + + [$original, $copy, $same, $arguments, $paratest, $token] = json_decode((string) file_get_contents($root.'/seen'), true); + + expect($original)->toBe(realpath($root.'/src/A.php')) + ->and($copy)->toStartWith(realpath($root).'/vendor/pestphp/pest-plugin-mutate/.temp/mutations/') + ->and($copy)->not->toBeFile() + ->and($same)->toBeTrue() + ->and($arguments)->toBe([]) + // As the processes of the parallel pass, which the harness runs first + ->and([$paratest, $token])->toBe(['1', '1']); + }); + + it('are not run in parallel, rather than refused, when only the variables of a worker fail them', function (): void { + $mutant = "require getenv('PEST_MUTATION_FILE'); if (getenv('PARATEST') === '1' && getenv('TEST_TOKEN') !== false) { exit(1); }"; + // The parallel pass would read 100 %, a single process reads the real score + $mutate = "echo in_array('--parallel', \$argv, true) ? ".var_export(TRUST_REPORT, true).' : '.var_export(TRUST_HONEST, true).';'; + + expect(MutationRun::run(trustProject($mutate, $mutant))['score'])->toBe(66.67); + }); + + /** + * A project whose control writes the coverage of src/A.php (by ATest) and whose mutant processes fail unless the + * `--filter` leaves out BTest, as a test that only fails under Pest's wrapper and does not cover A.php. + */ + $covered = static function (string $coveredBy): string { + $root = trustProject('', "require getenv('PEST_MUTATION_FILE'); if (str_contains((string) getenv('PEST_MUTATION_FILE'), 'pollora-unchanged-')) { \$filter = implode(' ', preg_grep('/^--filter=/', \$argv)); file_put_contents('filter', \$filter); exit(\$filter !== '' && ! str_contains(\$filter, 'BTest') ? 0 : 1); }"); + $report = sprintf(' [3 => [%s]]]; } };', var_export(realpath($root.'/src/A.php'), true), var_export($coveredBy, true)); + $pest = (string) file_get_contents($root.'/vendor/bin/pest'); + file_put_contents($root.'/vendor/bin/pest', str_replace("toBeNull() + // Never the whole class, even for the whole repository: its other tests may be run for no mutant + ->and(file_get_contents($root.'/filter'))->toBe('--filter=ATest::(.*)it.reads.{1,2}the.answer'); + })->with(['a file' => [['src/A.php']], 'the whole repository' => [[]]]); + + it('refuse the score when a test that covers the file fails', function () use ($covered): void { + $root = $covered('P\\Tests\\BTest::__pest_evaluable_it_locks'); + + expect(MutationCanary::unchanged($root, ['src/A.php'])['refusal'])->toContain('the tests covering the code fail'); + }); + + it('say nothing about a file no test covers, which has no mutant', function () use ($covered): void { + $root = $covered('P\\Tests\\BTest::__pest_evaluable_it_locks'); + file_put_contents($root.'/src/Unused.php', "toBeNull(); + }); + + it('give each run its own temporary directory, removed with what the run left there', function (): void { + $root = trustProject('', "require getenv('PEST_MUTATION_FILE');"); + file_put_contents($root.'/vendor/bin/pest', "toBeNull(); + + $runs = file($root.'/runs', FILE_IGNORE_NEW_LINES); + + expect($runs)->toHaveCount(count(array_unique($runs))) + ->and(array_filter($runs, is_dir(...)))->toBe([]); + }); + + it('stop a loop at the limit, with the processes it started', function (): void { + $loop = <<<'PHP' + require getenv('PEST_MUTATION_FILE'); + if (str_contains((string) getenv('PEST_MUTATION_FILE'), 'pollora-unchanged-')) { + $child = proc_open([PHP_BINARY, '-r', 'sleep(60);'], [], $pipes); + file_put_contents('child', (string) proc_get_status($child)['pid']); + sleep(60); + } + PHP; + $root = trustProject('', $loop); + $started = microtime(true); + + $refusal = MutationCanary::refusal($root, ['src/A.php'], 1.0); + + expect($refusal)->toContain('are still running after 1 s') + ->and(microtime(true) - $started)->toBeLessThan(30.0); + + usleep(200_000); + $state = trim((string) shell_exec('ps -o stat= -p '.(int) file_get_contents($root.'/child'))); + + // Gone, or a zombie nobody reaped yet + expect($state === '' || str_starts_with($state, 'Z'))->toBeTrue(); + }); + + it('accept a slow run within a few times the duration of the suite alone', function (): void { + $slow = "usleep(1_500_000); require getenv('PEST_MUTATION_FILE');"; + // The suite alone takes 0.6 s: the limit is 3 s, well over the floor of this test + $root = trustProject('usleep(600_000);', $slow); + + expect(MutationCanary::unchanged($root, ['src/A.php'], 0.1))->toMatchArray(['refusal' => null, 'parallel' => true]); + }); + + it('never allow less than two minutes, and five times the suite beyond', function (): void { + expect(MutationCanary::TIME_FLOOR)->toBe(120.0) + ->and(MutationCanary::TIME_FACTOR)->toBe(5.0) + ->and(MutationCanary::unchanged(trustProject(''), ['src/A.php'])['limit'])->toBe(120.0); + }); + + it('say that the tests fail on their own when they do, and leave Pest to report it', function (): void { + $root = trustProject('exit(1);'); + + expect(MutationCanary::refusal($root, ['src/A.php']))->toContain('the tests do not pass on their own'); + + $run = MutationRun::run($root); + + expect($run['score'])->toBeNull() + ->and($run)->not->toHaveKey('unloaded'); + }); + + /** A fake Pest whose suite only passes with --parallel on its own; `$mutant` is what a run as a mutant exits with. */ + $parallelOnly = static function (string $mutant): string { + $root = trustProject(''); + file_put_contents($root.'/vendor/bin/pest', "toContain('fail (exit code 1)'); + }); + + it('accept a suite that needs --parallel on its own when its tests pass as a mutant', function () use ($parallelOnly): void { + expect(MutationCanary::unchanged($parallelOnly('exit(0);'), ['src/A.php'])['refusal'])->toBeNull(); + }); + + it('try the coverage of the control again, in parallel, before running every test as a mutant', function () use ($covered): void { + $root = $covered('P\\Tests\\ATest::__pest_evaluable_it_reads'); + $pest = (string) file_get_contents($root.'/vendor/bin/pest'); + // The single process fails, as one flaky test would make it + file_put_contents($root.'/vendor/bin/pest', str_replace("toBeNull() + ->and(file_get_contents($root.'/filter'))->toBe('--filter=ATest::(.*)it.reads'); + }); + + it('do not refuse a score for one flaky failure', function (): void { + $root = trustProject('', "require getenv('PEST_MUTATION_FILE'); if (str_contains((string) getenv('PEST_MUTATION_FILE'), 'pollora-unchanged-') && ! is_file('flaked')) { touch('flaked'); exit(1); }"); + + expect(MutationCanary::unchanged($root, ['src/A.php']))->toMatchArray(['refusal' => null, 'parallel' => true]) + ->and($root.'/flaked')->toBeFile(); + }); + + it('collect coverage in a run as a mutant when the installed pest-plugin-mutate does', function (string $source, bool $collects) use ($covered): void { + $root = $covered('P\\Tests\\ATest::__pest_evaluable_it_reads'); + mkdir($root.'/vendor/pestphp/pest-plugin-mutate/src'); + file_put_contents($root.'/vendor/pestphp/pest-plugin-mutate/src/MutationTest.php', $source); + $pest = (string) file_get_contents($root.'/vendor/bin/pest'); + file_put_contents($root.'/vendor/bin/pest', str_replace("toBeNull() + ->and(str_contains((string) file_get_contents($root.'/arguments'), '--coverage-php='))->toBe($collects); + })->with([ + 'version 3, which passes the arguments as they are' => [' [" ! str_starts_with(\$a, '--coverage'));", false], + ]); + + it('split a filter too long for PCRE over several runs, naming every test', function (): void { + $tests = array_map(static fn (int $i): string => 'P\\Tests\\ATest::__pest_evaluable_it_'.str_repeat('x', 100).$i, range(1, 500)); + $root = trustProject('', "require getenv('PEST_MUTATION_FILE'); if (str_contains((string) getenv('PEST_MUTATION_FILE'), 'pollora-unchanged-')) { file_put_contents('filters', implode('', preg_grep('/^--filter=/', \$argv)).\"\\n\", FILE_APPEND); }"); + $report = sprintf(' [3 => %s]]; } };', var_export(realpath($root.'/src/A.php'), true), var_export($tests, true)); + file_put_contents($root.'/report', $report); + $pest = (string) file_get_contents($root.'/vendor/bin/pest'); + file_put_contents($root.'/vendor/bin/pest', str_replace("toBeNull(); + + $filters = file($root.'/filters', FILE_IGNORE_NEW_LINES); + $names = array_merge(...array_map(static fn (string $filter): array => explode('|', substr($filter, 9)), $filters)); + + expect(count($filters))->toBeGreaterThan(1) + ->and(max(array_map(strlen(...), $filters)))->toBeLessThan(20_100) + ->and(array_unique($names))->toHaveCount(500); + }); + + it('run the first source file for the whole repository, never one Composer loads at startup', function (): void { + $root = trustProject(''); + mkdir($root.'/src/Deep'); + file_put_contents($root.'/src/0-helpers.php', "toBe(['src/A.php', 'src/Deep/B.php']); + }); +}); + +describe('check --mutation-canary', function (): void { + $check = static function (string $root, array $argv = ['--mutation-canary']): array { + [$out, $err] = [fopen('php://memory', 'w+'), fopen('php://memory', 'w+')]; + $code = (new CheckCommand)->run(Io::fromArgv($root, $argv, $out, $err)); + rewind($out); + rewind($err); + + return [$code, stream_get_contents($out).stream_get_contents($err)]; + }; + + it('passes without running a mutation pass or a gate', function () use ($check): void { + $root = trustProject("if (in_array('--mutate', \$argv, true)) {\n touch('ran');\n}"); + + [$code, $output] = $check($root); + + expect($code)->toBe(0) + ->and($output)->toContain('No score was measured') + ->and($root.'/ran')->not->toBeFile() + ->and($root.'/.harness')->not->toBeDirectory(); + }); + + it('fails when no score could be believed, even in observe mode', function (string $argument) use ($check): void { + [$code, $output] = $check(trustProject('', FAILS_AFTER_LOADING), [$argument, '--observe']); + + expect($code)->toBe(1)->and($output)->toContain('that changes nothing'); + })->with(['--mutation-canary', '--mutation-canary=src/A.php']); + + it('fails rather than pass when there was nothing to check', function () use ($check): void { + expect($check(harnessTempDir())[1])->toContain('nothing was checked') + ->and($check(harnessTempDir())[0])->toBe(1) + ->and($check(trustProject(''), ['--mutation-canary=src/Missing.php'])[0])->toBe(1); + }); +}); + +describe('unchanged code, with a real Pest', function (): void { + /** An exclusive lock keeps a second one out, except behind the wrapper of Pest, which takes every lock as shared. */ + $locks = <<<'PHP' + require __DIR__.'/../src/Answer.php'; + $file = sys_get_temp_dir().'/pollora-lock-'.getmypid(); + $first = fopen($file, 'c'); + $second = fopen($file, 'c'); + flock($first, LOCK_EX); + $taken = flock($second, LOCK_EX | LOCK_NB); + unlink($file); + expect($taken)->toBeFalse(); + PHP; + + it('gives no score when a test fails only behind the wrapper of Pest', function (array $paths) use ($locks): void { + expect(realPestRefusal('', $paths, $locks)) + ->toContain('fail (exit code') + ->toContain('src/Answer.php that changes nothing'); + })->with(['a file' => [['src/Answer.php']], 'the whole repository' => [[]]]); + + it('accepts the same suite once the bootstrap gives the wrapper back and loads the mutant itself', function (array $paths) use ($locks): void { + $bootstrap = "if (is_string(\$mutated)) {\n \Pest\Mutate\Support\StreamWrapper::disable();\n require (string) getenv('PEST_MUTATION_FILE');\n}"; + // The file is already loaded by the bootstrap: the test reads nothing from it + $test = str_replace("require __DIR__.'/../src/Answer.php';", '', $locks); + + expect(realPestRefusal($bootstrap, $paths, $paths === [] ? $test : $locks))->toBeNull(); + })->with(['a file' => [['src/Answer.php']], 'the whole repository' => [[]]]); +}); + +describe('the bootstrap the README advises', function (): void { + preg_match('/only when Pest\'s wrapper is on it.*?```php\n(.*?)```/s', (string) file_get_contents(dirname(__DIR__, 2).'/README.md'), $advised); + + /** A test PHPUnit runs in a process of its own, which has the variables of a mutant and not the wrapper of Pest. */ + $isolated = <<<'PHP' + assertIsInt(require __DIR__.'/../src/Answer.php'); + } + } + PHP; + + it('works in a process PHPUnit isolates a test in', function () use ($advised, $isolated): void { + expect(realPestRefusal($advised[1] ?? '', ['src/Answer.php'], $isolated))->toBeNull(); + }); + + it('gives the wrapper back in the process Pest starts', function () use ($advised): void { + // A second exclusive lock is only refused without the wrapper of Pest + $locks = <<<'PHP' + $file = sys_get_temp_dir().'/pollora-lock-'.getmypid(); + [$first, $second] = [fopen($file, 'c'), fopen($file, 'c')]; + flock($first, LOCK_EX); + $taken = flock($second, LOCK_EX | LOCK_NB); + unlink($file); + expect($taken)->toBeFalse(); + PHP; + + expect(realPestRefusal($advised[1] ?? '', [], $locks))->toBeNull(); + }); + + it('would not without its condition', function () use ($isolated): void { + $unconditional = "if (is_string(\$mutated)) {\n \\Pest\\Mutate\\Support\\StreamWrapper::disable();\n}"; + + expect(realPestRefusal($unconditional, ['src/Answer.php'], $isolated))->toContain('file:// was never changed'); + }); +}); + +describe('a run out of memory', function (): void { + it('is said to be, and where the limit has to be raised', function (): void { + $root = trustProject("echo 'PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20 bytes) in x.php'; echo str_repeat(\"\\ntrace\", 200); exit(255);"); + + expect(MutationCanary::refusal($root, ['src/A.php'])) + ->toContain('ran out of memory (memory_limit of 128 MB)') + ->toContain('PHP_INI_SCAN_DIR'); + }); +});