Compare commits

...

55 Commits

Author SHA1 Message Date
Jhon Farias 0481044270 fix(tia): read the baseline of the changed files in one git process (#2090)
* fix(tia): read the baseline of the changed files in one git process

* fix(tia): read the baseline blobs in size-bounded groups

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-12-04 18:31:59 +05:30
Jhon Farias d2c1b99236 fix: keep the options that Pest adds before -- (#2087)
* fix: keep added options before the `--` separator

Pest added its own options (`--runner`, `--cache-directory`, `--teamcity`, `--no-coverage`, ...) after the `--` that the user gave. PHPUnit and ParaTest then read them as paths, thus `pest -- <path>` and `pest --parallel -- <path>` failed.

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

* fix: keep every option that Pest adds before `--`

pushArgument renumbers the list before it searches `--`, because bin/pest unsets options without array_values. Coverage, Shard and the `--teamcity` handling of bin/pest now place their options before `--` too. The changed files lose their comments, as AGENTS.md section 4 asks.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-12-04 14:41:42 +05:30
Jhon Farias 59c1cb78f8 feat(tia): replay unaffected tests in a partial run (#2092)
* feat(tia): replay unaffected tests in a partial run

* fix(tia): run a partial selection directly where a complete run is refused

* fix(tia): leave a graph from another environment alone in a partial run
2026-12-04 14:23:50 +05:30
Jhon Farias cd5bae7e91 fix(tia): restrict Xdebug coverage to the source scope before tracing (#2091)
* fix(tia): restrict Xdebug coverage to the source scope before tracing

* fix(tia): set the Xdebug exclude filter before the bootstrap and keep case twins traced

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-12-04 14:13:25 +05:30
Jhon Farias 586add8ff2 fix(tia): keep the run going when git is slow at boot (#2088)
* fix(tia): keep the run going when git is slow at boot

* fix(tia): catch GitTimedOut in the boot git calls

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 14:01:13 +05:30
Mr PHP 13fc0a7890 fix: toThrow() and throws() with an interface (#2098)
* fix: toThrow() and throws() with an interface

* test: cover not->toThrow() with an interface

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-12-04 13:48:23 +05:30
Jhon Farias 2b2a1dab31 fix(tia): record test files the graph does not know during a replay (#2093)
* fix(tia): record test files the graph does not know during a replay

* fix(tia): keep coverage-scoped edges off test files the graph does not know

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-12-04 12:42:52 +05:30
Jhon Farias 12bddc0137 fix(parallel): support --include-path (#2075)
* fix(parallel): support --include-path

* fix(parallel): keep an include path with an equals sign in the parent process

* fix(parallel): apply the include path before the bootstrap file

* chore(rector): skip the parallel include path fixture

* fix(parallel): apply the command line include path before the XML one in the bootstrap file

Register `--include-path` on the ParaTest command, so ParaTest passes it to
the PHPUnit configuration of the parent process. PHPUnit then puts the
command line paths before the XML `<includePath>` before it includes the
`--bootstrap` file.

Read the value and the arguments the option consumes through PHPUnit's
`Builder`, and write the value back in a form that PHPUnit reads unchanged,
for the parent process and for each worker. Run the include path handler
first, so it reads only the arguments of the user.

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

* test(parallel): declare strict types and refresh the success snapshot

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-12-04 01:48:02 +05:30
Punyapal Shah f5874c12ca Refresh 5.x test snapshots (#2097) 2026-12-03 20:59:12 +05:30
Youssef Mansour 557aca75a0 fix: accept space separated values for --min and --exactly (#1921)
`--min` and `--exactly` only accepted the `--min=50` notation. When the
space separated notation was used, the plugin kept the `--min` token but
left the `50` token behind, so `ArgvInput` received an option without a
value and threw:

    $ pest --coverage --min 50

    Symfony\Component\Console\Exception\RuntimeException
    The "--min" option requires a value.

The run aborted with an unhandled exception and a stack trace, even
though every other valued option Pest forwards to PHPUnit accepts both
notations (`pest --filter add` works). The orphaned value token was also
forwarded to PHPUnit as a positional argument.

`handleArguments()` now walks the arguments positionally instead of
filtering them, so an option that takes a value also claims the token
that follows it. Value-less options (`--coverage`, `--only-covered`) keep
their current behaviour and never consume the next token, and a bare
`--min` with no value still produces the regular "requires a value"
error rather than swallowing the option that follows it.
2026-12-03 14:00:33 +00:00
Punyapal Shah 5b534641e4 Split macOS integration tests into separate jobs (#2096)
* Split macOS integration tests into separate jobs

* Keep visual tests in the main macOS jobs
2026-12-03 14:00:12 +00:00
Mr PHP edb56ae412 fix: not->toHaveKeys() with nested keys (#2094) 2026-12-03 14:00:01 +00:00
Jhon Farias 8c635c5ba0 fix(tia): report a git timeout like any other git failure (#2069)
* fix(tia): report a git timeout like any other git failure

* fix(tia): raise a git timeout so no git helper reads it as an answer

* test(tia): cover a slow git check-ignore and stop probing git after a timeout

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-30 18:38:29 +05:30
Jhon Farias b5851d67ff fix(tia): run the full suite when code the project loads from outside its root changes (#1915)
* fix(tia): run the full suite when code the project loads from outside its root changes

* test(tia): cover the configuration fingerprint of a nested project

* fix(tia): run the full suite when a declared external root holds files git ignores

* fix(tia): track ignored inputs under external roots by content hash

* fix(tia): harden external source tracking from the review loop

* test: update the suite totals for the external source tests

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:09:05 +05:30
Jhon Farias d314fc0540 fix(tia): keep numeric file, branch and page names as strings (#2066)
Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-27 18:30:39 +05:30
Razvan Aurariu 093ca57693 fix Laravel parallel process hooks (#2084)
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-27 17:34:00 +05:30
Chris Mellor cf21b7cd64 fix(tia): report why an include failed as plain PHP does (#2082)
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-27 17:15:37 +05:30
Jhon Farias a6a919c32c fix(tia): keep the graph writable when a path is not valid UTF-8 (#2079)
* fix(tia): keep the graph writable when a path is not valid UTF-8

* test: update the suite totals for the byte-safe JSON tests

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-27 12:18:19 +05:30
Bartłomiej Gajda fa6e96486e fix(sharding): strip every paratest-only option from the --list-tests sub-process (#2076)
* fix(sharding): strip every paratest-only option from the `--list-tests` sub-process

`--update-shards` (and `--shard` without a shards.json) discovers the test classes by
re-running Pest with `--list-tests`. That sub-process is a plain PHPUnit run, but only
`--parallel`, `-p`, `--processes` and `--runner` were removed from its arguments, so any
other ParaTest option killed the run before a single test:

    pest --parallel --update-shards --max-batch-size=100
    Unknown option "--max-batch-size".

Strip every option ParaTest defines that PHPUnit does not (`--max-batch-size`/`-m`,
`--max-processes`, `--passthru-php`, `--tmp-dir`, `--functional`, `--no-test-tokens`,
plus the existing `--processes` and `--runner`), in both `--option=value` and
`--option value` form.

* fix(sharding): strip ParaTest's `-m` with its value attached (`-m100`)

ParaTest reads `-m100` as `--max-batch-size=100`, but the option check split
arguments on `=` only, so the attached form reached PHPUnit's `--list-tests`
sub-process, which rejects `-m`. `-p` is left alone: Pest reads it as
`--parallel`.

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-27 11:54:04 +05:30
Lazizbek Ergashev 249a120d89 fix: allow dynamic properties on TestCall (#2085) 2026-11-27 11:21:01 +05:30
Jhon Farias 8d004b80d7 fix(parallel): load the autoloader of the parent process in workers (#2058)
* fix(parallel): load the autoloader of the parent process in workers

* test(parallel): cover the worker autoloader handoff end to end

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-26 20:32:39 +05:30
Jhon Farias 12f3cd80de fix(tia): run git in the C locale so Pest reads its messages in any language (#2074)
Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
2026-11-26 19:39:28 +05:30
Jhon Farias dc73ec009e fix: ignore packages bundled in a PHAR when detecting installed packages (#2059)
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-26 19:34:03 +05:30
Lazizbek Ergashev 5bb349dcf2 fix(tia): forward ReadCapture calls to wrappers that use __call (#2078)
* fix(tia): forward ReadCapture calls to wrappers that use __call

* fix(tia): open through a __call wrapper too

---------

Co-authored-by: Punyapal Shah <53343069+MrPunyapal@users.noreply.github.com>
2026-11-26 18:40:43 +05:30
Punyapal Shah 1f60dc8f9a Fix Rector style checks on 5.x (#2083) 2026-11-26 17:31:40 +05:30
nuno maduro b75cf904b7 chore: bump deps 2026-11-26 07:49:40 +00:00
Jhon Farias 0fe7c2440c fix(tia): fingerprint the bootstrap and include path the command line sets (#2068)
* fix(tia): fingerprint the bootstrap and include path the command line sets

* fix(tia): keep the bootstrap and include path in their own fingerprint fields

* fix(tia): keep a literal backslash in a Unix path in the fingerprint

* fix(tia): keep the include path entries apart in the fingerprint

* Refresh output snapshots for TIA configuration tests

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-24 00:48:55 +05:30
Jhon Farias 4c886b16d1 fix(tia): fingerprint the generated configuration like the restarter does (#2065)
* fix(tia): fingerprint the generated configuration like the restarter does

* test(tia): pass one configuration option per call

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-23 15:27:13 +05:30
Ben Dailey 8c87eefebf fix(tia): load rolldown from vite/rolldown under Vite+ (#2061)
* fix(tia): load rolldown from vite/rolldown under Vite+

* refactor(tia): call loadRolldown() with its default root

---------

Co-authored-by: Ben Dailey <ben@dev-deb12>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-22 22:09:09 +05:30
Ben Dailey 4cfeb458fe fix(tia): end the SFC script tag after quoted attributes that hold > (#2063)
Co-authored-by: Ben Dailey <ben@dev-deb12>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-22 21:32:28 +05:30
Jhon Farias 5cb7a1c043 fix(tia): keep the results of a parallel full-suite fallback (#2067) 2026-11-22 21:02:01 +05:30
Jhon Farias a2d3e6badd fix(tia): support a Pest project nested in a git repository (#1914)
* fix(tia): support a Pest project nested in a git repository

Tia refused to run whenever the Pest project was not the git repository
root, because git prints and addresses paths relative to the repository
root while the dependency graph is keyed on project-relative paths.

Translate at every git boundary instead of guarding against the mismatch.
`Git::pathPrefix()` resolves the directory of the project inside the
repository, and `ChangedFiles` strips that prefix off the paths git prints,
drops the paths of sibling packages, and prepends it to `git show`. Both
diffs read `-z` records, because `core.quotePath` C-quotes a path outside
ASCII, and `--no-relative` holds the frame when a user sets `diff.relative`.

Three places read `<projectRoot>/.git` directly, which is absent in a
nested project and in a worktree, and now ask git: `BaseRemote`, `Storage`
and `Fingerprint::isTrackedByGit()`. `Storage` folds the prefix into the
state key so two projects in one repository do not share a graph, and the
fingerprint carries the prefix so a baseline published by a sibling project
is rejected. A project at the repository root keeps the key and the
fingerprint it had.

`git check-ignore` runs without `--no-index`, so a tracked file that an
ignore rule matches counts as part of the project on both sides of the
boundary.

Changes outside the project are dropped and reported by count in the run
summary, so a nested project does not look idle when the repository around
it moved.

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

* fix(tia): keep whitespace at the edge of the paths git returns

* fix(tia): run the full suite when a PHP file outside a nested project changes

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
2026-11-22 20:41:58 +05:30
Mohannad Elemary 66e585081a fix(tia): stop ReadCapture from keeping a wrapper per filesystem call (#2057)
* fix(tia): free the ReadCapture wrapper each time it steps aside

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

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

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

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

* Use fopen() in the memory regression test

---------

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

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

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

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

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

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

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

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

---------

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

* Keep quiet url_stat probes away from error handlers

---------

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

* fix: resolve afterEach test ordering issue

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

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

---------

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

* Verify TIA watch fallbacks and refresh snapshots

---------

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

* test: allow running a single test using its namespace

* fix: preserve namespace filters when converting arguments

* test: update success snapshot for namespace filters

* fix: convert namespace after retry flag

---------

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

* Skip missing files when selecting dirty tests

---------

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

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

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

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

Closes #1463.

* fix: preserve parallel stop conditions on Pest 5

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

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

* test(tia): cover the gitignore check with composer.lock, as the active configuration is fingerprinted tracked or not
2026-11-17 01:20:47 +05:30
175 changed files with 12455 additions and 737 deletions
+16 -1
View File
@@ -27,8 +27,12 @@ jobs:
symfony: ['8.0'] symfony: ['8.0']
php: ['8.4', '8.5', '8.6'] php: ['8.4', '8.5', '8.6']
dependency_version: [prefer-stable] dependency_version: [prefer-stable]
suite: [default, tia]
exclude:
- os: ubuntu-latest
suite: tia
name: PHP ${{ matrix.php }} - Symfony ^${{ matrix.symfony }} - ${{ matrix.os }} - ${{ matrix.dependency_version }} name: PHP ${{ matrix.php }} - Symfony ^${{ matrix.symfony }} - ${{ matrix.os }} - ${{ matrix.dependency_version }}${{ matrix.suite != 'default' && format(' - {0}', matrix.suite) || '' }}
steps: steps:
- name: Checkout - name: Checkout
@@ -68,10 +72,21 @@ jobs:
run: composer update --${{ matrix.dependency_version }} --no-interaction --no-progress --ansi --with="symfony/console:^${{ matrix.symfony }}" run: composer update --${{ matrix.dependency_version }} --no-interaction --no-progress --ansi --with="symfony/console:^${{ matrix.symfony }}"
- name: Unit Tests - name: Unit Tests
if: matrix.suite == 'default'
run: composer test:unit run: composer test:unit
- name: Parallel Tests - name: Parallel Tests
if: matrix.suite == 'default'
run: composer test:parallel run: composer test:parallel
- name: Integration Tests - name: Integration Tests
if: runner.os != 'macOS'
run: composer test:integration run: composer test:integration
- name: TIA Integration Tests
if: matrix.suite == 'tia'
run: XDEBUG_MODE=off composer test:tia
- name: Visual Integration Tests
if: runner.os == 'macOS' && matrix.suite == 'default'
run: composer test:integration -- --exclude-group=tia
+2 -4
View File
@@ -32,16 +32,14 @@ We cannot thank our sponsors enough for their incredible support in funding Pest
- **[PhpStorm](https://jb.gg/nuno)** - **[PhpStorm](https://jb.gg/nuno)**
- **[CodeRabbit](https://coderabbit.link/nunomaduro)** - **[CodeRabbit](https://coderabbit.link/nunomaduro)**
- **[SerpApi](https://serpapi.com/?ref=nunomaduro)** - **[SerpApi](https://serpapi.com/?ref=nunomaduro)**
- **[Bento](https://bentonow.com/?ref=nunomaduro)**
- **[CMS Max](https://cmsmax.com/?ref=nunomaduro)**
- **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)** - **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)**
- **[Typesense](https://typesense.org/?ref=nunomaduro)** - **[Typesense](https://typesense.org/?ref=nunomaduro)**
- **[Pixel](https://wearepixel.com.au/?ref=nunomaduro)** - **[Pixel](https://wearepixel.com.au/?ref=nunomaduro)**
- **[NativePHP](https://nativephp.com/?ref=nunomaduro)** - **[NativePHP](https://nativephp.com/?ref=nunomaduro)**
- [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest) - [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest)
- [Zapiet](https://zapiet.com/?ref=nunomaduro) - [Zapiet](https://zapiet.com/?ref=nunomaduro)
- [LoadForge](https://loadforge.com/?ref=nunomaduro)
- [Route4Me](https://route4me.com/?ref=nunomaduro) - [Route4Me](https://route4me.com/?ref=nunomaduro)
- [Nerdify](https://getnerdify.com/?ref=nunomaduro) - [Pushery](https://www.pushery.com/?ref=nunomaduro)
- [LFCarry](https://lfcarry.com/?ref=nunomaduro)
Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**. Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
+62 -16
View File
@@ -6,6 +6,7 @@ declare(strict_types=1);
use Pest\Contracts\Restarter; use Pest\Contracts\Restarter;
use Pest\Kernel; use Pest\Kernel;
use Pest\Panic; use Pest\Panic;
use Pest\Support\ComposerProject;
use Pest\Support\Container; use Pest\Support\Container;
use Pest\TestCaseFilters\GitDirtyTestCaseFilter; use Pest\TestCaseFilters\GitDirtyTestCaseFilter;
use Pest\TestCaseMethodFilters\AssigneeTestCaseFilter; use Pest\TestCaseMethodFilters\AssigneeTestCaseFilter;
@@ -19,7 +20,6 @@ use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\ConsoleOutput;
(static function () { (static function () {
// Ensures Collision's Printer is registered.
$_SERVER['COLLISION_PRINTER'] = 'DefaultPrinter'; $_SERVER['COLLISION_PRINTER'] = 'DefaultPrinter';
$arguments = $originalArguments = $_SERVER['argv']; $arguments = $originalArguments = $_SERVER['argv'];
@@ -121,29 +121,75 @@ use Symfony\Component\Console\Output\ConsoleOutput;
} }
} }
if (str_contains($value, '--teamcity')) { if ($value === '--teamcity') {
unset($arguments[$key]); $arguments[$key] = '--no-output';
$arguments[] = '--no-output';
unset($_SERVER['COLLISION_PRINTER']); unset($_SERVER['COLLISION_PRINTER']);
} }
} }
// Used when Pest is required using composer. $optionsWithSeparateValue = [
$vendorPath = dirname(__DIR__, 4).'/vendor/autoload.php'; '-c', '-d', '--atleast-version', '--bootstrap', '--cache-directory', '--columns', '--configuration',
'--coverage-filter', '--coverage-clover', '--coverage-cobertura', '--coverage-crap4j', '--coverage-html',
'--coverage-jsonl', '--coverage-openclover', '--coverage-php', '--coverage-xml', '--default-time-limit',
'--diff-context', '--exclude-group', '--filter', '--exclude-filter', '--generate-baseline', '--use-baseline',
'--group', '--covers', '--uses', '--requires-php-extension', '--include-path', '--list-tests-xml',
'--log-junit', '--log-otr', '--log-teamcity', '--order-by', '--random-order-seed', '--repeat',
'--timeout', '--testdox-html', '--testdox-text', '--test-suffix', '--testsuite', '--exclude-testsuite',
'--test-files-file', '--test-id-filter-file', '--run-test-id', '--log-events-text',
'--log-events-verbose-text', '--extension',
];
// Used when Pest maintainers are running Pest tests. $isOptionValue = false;
$localPath = dirname(__DIR__).'/vendor/autoload.php';
if (file_exists($vendorPath)) { foreach ($arguments as $key => $value) {
include_once $vendorPath; if ($isOptionValue) {
$autoloadPath = $vendorPath; $isOptionValue = false;
} else {
include_once $localPath; continue;
$autoloadPath = $localPath; }
if (str_starts_with($value, '-')) {
$isOptionValue = in_array($value, $optionsWithSeparateValue, true);
continue;
}
if (! str_contains($value, '\\')) {
continue;
}
$path = str_replace('\\', DIRECTORY_SEPARATOR, $value);
if (! str_ends_with($path, '.php')) {
$path .= '.php';
}
if (file_exists($path)) {
$arguments[$key] = $path;
continue;
}
$segments = explode(DIRECTORY_SEPARATOR, $path);
$segments[0] = lcfirst($segments[0]);
$lowercasedPath = implode(DIRECTORY_SEPARATOR, $segments);
if (file_exists($lowercasedPath)) {
$arguments[$key] = $lowercasedPath;
}
} }
// Get $rootPath based on $autoloadPath $autoloadPath = $GLOBALS['_composer_autoload_path'] ?? dirname(__DIR__, 3).'/autoload.php';
$rootPath = dirname($autoloadPath, 2);
if (! is_file($autoloadPath)) {
$autoloadPath = dirname(__DIR__).'/vendor/autoload.php';
}
include_once $autoloadPath;
$GLOBALS['_composer_autoload_path'] = $autoloadPath;
$GLOBALS['_composer_bin_dir'] ??= dirname($autoloadPath).'/bin';
$rootPath = ComposerProject::rootPath($autoloadPath);
$input = new ArgvInput; $input = new ArgvInput;
+7 -3
View File
@@ -13,7 +13,7 @@ const PAGE_EXTENSIONS = new Set([
'.mts', '.cts', '.mjs', '.cjs', '.mts', '.cts', '.mjs', '.cjs',
]) ])
const SFC_RE = /\.(vue|svelte)$/i const SFC_RE = /\.(vue|svelte)$/i
const SCRIPT_BLOCK_RE = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi const SCRIPT_BLOCK_RE = /<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script>/gi
const ASSET_EXT_RE = /\.(css|scss|sass|less|styl|stylus|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|eot|otf|md|mdx|txt|html|mp4|webm|mp3|wav|ogg|m4a|pdf|wasm|glsl|frag|vert)$/i const ASSET_EXT_RE = /\.(css|scss|sass|less|styl|stylus|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|eot|otf|md|mdx|txt|html|mp4|webm|mp3|wav|ogg|m4a|pdf|wasm|glsl|frag|vert)$/i
const PROJECT_ROOT = resolve(process.argv[2] ?? process.cwd()) const PROJECT_ROOT = resolve(process.argv[2] ?? process.cwd())
const PAGE_DIR_CANDIDATES = [ const PAGE_DIR_CANDIDATES = [
@@ -25,8 +25,8 @@ const PAGE_DIR_CANDIDATES = [
'assets/pages', 'assets/pages',
] ]
async function loadRolldown() { export async function loadRolldown(projectRoot = PROJECT_ROOT) {
const projectRequire = createRequire(join(PROJECT_ROOT, 'package.json')) const projectRequire = createRequire(join(projectRoot, 'package.json'))
let path = null let path = null
try { path = projectRequire.resolve('rolldown') } catch {} try { path = projectRequire.resolve('rolldown') } catch {}
@@ -40,6 +40,10 @@ async function loadRolldown() {
} catch {} } catch {}
} }
if (path === null) {
try { path = projectRequire.resolve('vite/rolldown') } catch {}
}
if (path === null) return null if (path === null) return null
return await import(pathToFileURL(path).href) return await import(pathToFileURL(path).href)
+14 -4
View File
@@ -6,16 +6,18 @@ use ParaTest\WrapperRunner\ApplicationForWrapperWorker;
use ParaTest\WrapperRunner\WrapperWorker; use ParaTest\WrapperRunner\WrapperWorker;
use Pest\Kernel; use Pest\Kernel;
use Pest\Plugins\Actions\CallsHandleArguments; use Pest\Plugins\Actions\CallsHandleArguments;
use Pest\Plugins\Parallel\Paratest\StopConditions;
use Pest\Support\ComposerProject;
use Pest\Support\Container; use Pest\Support\Container;
use Pest\TestSuite; use Pest\TestSuite;
use PHPUnit\TextUI\Configuration\Registry as ConfigurationRegistry;
use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
$bootPest = (static function (): void { $bootPest = (static function (string $rootPath): void {
$workerArgv = new ArgvInput; $workerArgv = new ArgvInput;
$rootPath = dirname(PHPUNIT_COMPOSER_INSTALL, 2);
$testSuite = TestSuite::getInstance($rootPath, $workerArgv->getParameterOption( $testSuite = TestSuite::getInstance($rootPath, $workerArgv->getParameterOption(
'--test-directory', '--test-directory',
'tests' 'tests'
@@ -41,9 +43,11 @@ $bootPest = (static function (): void {
'testdox-columns:', 'testdox-columns:',
'testdox-summary', 'testdox-summary',
'phpunit-argv:', 'phpunit-argv:',
'composer-autoload:',
]); ]);
$composerAutoloadFiles = [ $composerAutoloadFiles = [
...(isset($getopt['composer-autoload']) && is_string($getopt['composer-autoload']) ? [$getopt['composer-autoload']] : []),
dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'autoload.php', dirname(__DIR__, 3).DIRECTORY_SEPARATOR.'autoload.php',
dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php', dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
dirname(__DIR__).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php', dirname(__DIR__).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
@@ -54,13 +58,14 @@ $bootPest = (static function (): void {
if (file_exists($file)) { if (file_exists($file)) {
require_once $file; require_once $file;
define('PHPUNIT_COMPOSER_INSTALL', $file); define('PHPUNIT_COMPOSER_INSTALL', $file);
$GLOBALS['_composer_bin_dir'] ??= dirname($file).'/bin';
break; break;
} }
} }
$container = Container::getInstance(); $container = Container::getInstance();
$rootPath = dirname(PHPUNIT_COMPOSER_INSTALL, 2); $rootPath = ComposerProject::rootPath(PHPUNIT_COMPOSER_INSTALL);
foreach (Kernel::RESTARTERS as $restarterClass) { foreach (Kernel::RESTARTERS as $restarterClass) {
$restarter = $container->get($restarterClass); $restarter = $container->get($restarterClass);
@@ -83,7 +88,7 @@ $bootPest = (static function (): void {
$phpunitArgv = unserialize($getopt['phpunit-argv'], ['allowed_classes' => false]); $phpunitArgv = unserialize($getopt['phpunit-argv'], ['allowed_classes' => false]);
assert(is_array($phpunitArgv)); assert(is_array($phpunitArgv));
$bootPest(); $bootPest($rootPath);
$phpunitArgv = CallsHandleArguments::execute($phpunitArgv); $phpunitArgv = CallsHandleArguments::execute($phpunitArgv);
@@ -99,6 +104,8 @@ $bootPest = (static function (): void {
(int) ($getopt['testdox-columns'] ?? null), (int) ($getopt['testdox-columns'] ?? null),
); );
$stopConditions = null;
while (true) { while (true) {
if (feof(STDIN)) { if (feof(STDIN)) {
$application->end(); $application->end();
@@ -113,6 +120,9 @@ $bootPest = (static function (): void {
$exitCode = $application->runTest(realpath(trim($testPath))); $exitCode = $application->runTest(realpath(trim($testPath)));
$stopConditions ??= new StopConditions(ConfigurationRegistry::get());
$stopConditions->write($getopt['test-result-file'].'.stop');
fwrite($statusFile, (string) $exitCode); fwrite($statusFile, (string) $exitCode);
fflush($statusFile); fflush($statusFile);
} }
+3 -3
View File
@@ -26,7 +26,7 @@
"pestphp/pest-plugin-mutate": "^5.0.2", "pestphp/pest-plugin-mutate": "^5.0.2",
"pestphp/pest-plugin-profanity": "^5.0.1", "pestphp/pest-plugin-profanity": "^5.0.1",
"phpunit/phpunit": "^13.4.7", "phpunit/phpunit": "^13.4.7",
"symfony/process": "^8.1.10" "symfony/process": "^8.1.12"
}, },
"conflict": { "conflict": {
"filp/whoops": "<2.18.3", "filp/whoops": "<2.18.3",
@@ -63,8 +63,8 @@
"pestphp/pest-dev-tools": "^5.0.0", "pestphp/pest-dev-tools": "^5.0.0",
"pestphp/pest-plugin-browser": "^5.2.0", "pestphp/pest-plugin-browser": "^5.2.0",
"pestphp/pest-plugin-phpstan": "^5.3.1", "pestphp/pest-plugin-phpstan": "^5.3.1",
"pestphp/pest-plugin-rector": "^5.0.6", "pestphp/pest-plugin-rector": "^5.0.7",
"pestphp/pest-plugin-type-coverage": "^5.1.0", "pestphp/pest-plugin-type-coverage": "^5.1.1",
"phpstan/phpstan": "^2.3.5 <2.3.6", "phpstan/phpstan": "^2.3.5 <2.3.6",
"psy/psysh": "^0.12.24" "psy/psysh": "^0.12.24"
}, },
+1
View File
@@ -19,6 +19,7 @@
<directory suffix=".php">./tests-external</directory> <directory suffix=".php">./tests-external</directory>
<exclude>./tests/.snapshots</exclude> <exclude>./tests/.snapshots</exclude>
<exclude>./tests/Fixtures/Inheritance</exclude> <exclude>./tests/Fixtures/Inheritance</exclude>
<exclude>./tests/Fixtures/ParallelIncludePath</exclude>
<exclude>./tests/Fixtures/Suites</exclude> <exclude>./tests/Fixtures/Suites</exclude>
<exclude>./tests/Fixtures/Tia</exclude> <exclude>./tests/Fixtures/Tia</exclude>
</testsuite> </testsuite>
+1 -4
View File
@@ -7,9 +7,7 @@ use Pest\Rector\Set\PestSetList;
use Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector; use Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector;
use Rector\CodingStyle\Rector\ArrowFunction\ArrowFunctionDelegatingCallToFirstClassCallableRector; use Rector\CodingStyle\Rector\ArrowFunction\ArrowFunctionDelegatingCallToFirstClassCallableRector;
use Rector\Config\RectorConfig; use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\ClassMethod\RemoveDuplicatedReturnSelfDocblockRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector; use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveReturnTagIncompatibleWithNativeTypeRector; use Rector\DeadCode\Rector\ClassMethod\RemoveReturnTagIncompatibleWithNativeTypeRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedConstructorParamRector; use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedConstructorParamRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessUnionReturnDocblockRector; use Rector\DeadCode\Rector\ClassMethod\RemoveUselessUnionReturnDocblockRector;
@@ -30,11 +28,10 @@ return RectorConfig::configure()
__DIR__.'/src/Plugins/Parallel/Paratest/WrapperRunner.php', __DIR__.'/src/Plugins/Parallel/Paratest/WrapperRunner.php',
__DIR__.'/tests/Fixtures/Arch', __DIR__.'/tests/Fixtures/Arch',
__DIR__.'/tests/Fixtures/Suites', __DIR__.'/tests/Fixtures/Suites',
__DIR__.'/tests/Fixtures/ParallelIncludePath',
ReturnNeverTypeRector::class, ReturnNeverTypeRector::class,
ArrowFunctionDelegatingCallToFirstClassCallableRector::class, ArrowFunctionDelegatingCallToFirstClassCallableRector::class,
NarrowObjectReturnTypeRector::class, NarrowObjectReturnTypeRector::class,
RemoveParentDelegatingConstructorRector::class,
RemoveDuplicatedReturnSelfDocblockRector::class,
RemoveUselessUnionReturnDocblockRector::class, RemoveUselessUnionReturnDocblockRector::class,
RemoveReturnTagIncompatibleWithNativeTypeRector::class => [ RemoveReturnTagIncompatibleWithNativeTypeRector::class => [
__DIR__.'/src/Expectations/HigherOrderExpectation.php', __DIR__.'/src/Expectations/HigherOrderExpectation.php',
+7 -3
View File
@@ -36,7 +36,7 @@ final class BootFiles implements Bootstrapper
public function boot(): void public function boot(): void
{ {
if ($this->runningInit()) { if ($this->hasCliOption('--init')) {
return; return;
} }
@@ -44,6 +44,10 @@ final class BootFiles implements Bootstrapper
$testsPath = $rootPath.DIRECTORY_SEPARATOR.testDirectory(); $testsPath = $rootPath.DIRECTORY_SEPARATOR.testDirectory();
if (! is_dir($testsPath)) { if (! is_dir($testsPath)) {
if ($this->hasCliOption('--help', '--version')) {
return;
}
throw new FatalException(sprintf('The test directory [%s] does not exist.', $testsPath)); throw new FatalException(sprintf('The test directory [%s] does not exist.', $testsPath));
} }
@@ -69,7 +73,7 @@ final class BootFiles implements Bootstrapper
$this->bootDatasets($testsPath); $this->bootDatasets($testsPath);
} }
private function runningInit(): bool private function hasCliOption(string ...$options): bool
{ {
$arguments = $_SERVER['argv'] ?? null; $arguments = $_SERVER['argv'] ?? null;
@@ -78,7 +82,7 @@ final class BootFiles implements Bootstrapper
} }
/** @var array<int, string> $arguments */ /** @var array<int, string> $arguments */
return $this->hasArgument('--init', $arguments); return array_any($options, fn (string $option): bool => $this->hasArgument($option, $arguments));
} }
private function load(string $filename): void private function load(string $filename): void
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Pest\Contracts\Plugins;
interface ObservesExitCode
{
public function observeExitCode(int $exitCode): void;
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use RuntimeException;
use Symfony\Component\Console\Exception\ExceptionInterface;
/**
* @internal
*/
final class GitTimedOut extends RuntimeException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{
/**
* @param array<int, string> $arguments
*/
public function __construct(array $arguments, float $timeout)
{
parent::__construct(sprintf('Git did not answer within %s seconds: git %s', $timeout, implode(' ', $arguments)));
}
}
@@ -1,44 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Pest\Contracts\Panicable;
use RuntimeException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class TiaRequiresRepositoryRoot extends RuntimeException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
{
public function __construct(private readonly string $subdirectoryPrefix)
{
parent::__construct(sprintf(
'Tia mode requires the project root to be the git repository root, but this project sits in the subdirectory [%s] of a larger repository. Please give it its own repository to use Tia.',
$this->subdirectoryPrefix,
));
}
public function render(OutputInterface $output): void
{
$output->writeln([
'',
' <fg=white;options=bold;bg=red> ERROR </> Tia mode requires the git repository root.',
'',
sprintf(' This project sits in a subdirectory of a larger repo <fg=yellow>%s</>.', $this->subdirectoryPrefix),
'',
' Give the project its own git repository to use Tia.',
'',
]);
}
public function exitCode(): int
{
return 1;
}
}
+7 -5
View File
@@ -48,12 +48,14 @@ final readonly class OppositeExpectation
public function toHaveKeys(array $keys): Expectation public function toHaveKeys(array $keys): Expectation
{ {
foreach ($keys as $k => $key) { foreach ($keys as $k => $key) {
if (is_array($key)) {
$this->toHaveKeys(array_keys(Arr::dot($key, $k.'.')));
continue;
}
try { try {
if (is_array($key)) { $this->original->toHaveKey($key);
$this->toHaveKeys(array_keys(Arr::dot($key, $k.'.')));
} else {
$this->original->toHaveKey($key);
}
} catch (ExpectationFailedException) { } catch (ExpectationFailedException) {
continue; continue;
} }
+2 -2
View File
@@ -847,7 +847,7 @@ final class Expectation
return $this; return $this;
} }
if (! class_exists($exception)) { if (! class_exists($exception) && ! interface_exists($exception)) {
if ($e instanceof Error && "Class \"$exception\" not found" === $e->getMessage()) { if ($e instanceof Error && "Class \"$exception\" not found" === $e->getMessage()) {
Assert::assertTrue(true); Assert::assertTrue(true);
@@ -872,7 +872,7 @@ final class Expectation
Assert::assertTrue(true); Assert::assertTrue(true);
if (! $exception instanceof Throwable && ! class_exists($exception)) { if (! $exception instanceof Throwable && ! class_exists($exception) && ! interface_exists($exception)) {
throw new ExpectationFailedException("Exception with message [$exception] not thrown."); throw new ExpectationFailedException("Exception with message [$exception] not thrown.");
} }
+1 -2
View File
@@ -6,7 +6,6 @@ namespace Pest\PendingCalls;
use Closure; use Closure;
use Pest\PendingCalls\Concerns\Describable; use Pest\PendingCalls\Concerns\Describable;
use Pest\Support\Arr;
use Pest\Support\Backtrace; use Pest\Support\Backtrace;
use Pest\Support\ChainableClosure; use Pest\Support\ChainableClosure;
use Pest\Support\HigherOrderMessageCollection; use Pest\Support\HigherOrderMessageCollection;
@@ -43,7 +42,7 @@ final class AfterEachCall
$proxies = $this->proxies; $proxies = $this->proxies;
$afterEachTestCase = ChainableClosure::boundWhen( $afterEachTestCase = ChainableClosure::boundWhen(
fn (): bool => $describing === [] || in_array(Arr::last($describing), $this->__describing, true), fn (): bool => $describing === [] || (count($describing) <= count($this->__describing) && array_slice($this->__describing, 0, count($describing)) === $describing),
ChainableClosure::bound(fn () => $proxies->chain($this), $this->closure)->bindTo($this, self::class), ChainableClosure::bound(fn () => $proxies->chain($this), $this->closure)->bindTo($this, self::class),
)->bindTo($this, self::class); )->bindTo($this, self::class);
+4 -7
View File
@@ -7,7 +7,6 @@ namespace Pest\PendingCalls;
use Closure; use Closure;
use Pest\Exceptions\AfterBeforeTestFunction; use Pest\Exceptions\AfterBeforeTestFunction;
use Pest\PendingCalls\Concerns\Describable; use Pest\PendingCalls\Concerns\Describable;
use Pest\Support\Arr;
use Pest\Support\Backtrace; use Pest\Support\Backtrace;
use Pest\Support\ChainableClosure; use Pest\Support\ChainableClosure;
use Pest\Support\HigherOrderMessageCollection; use Pest\Support\HigherOrderMessageCollection;
@@ -50,11 +49,9 @@ final class BeforeEachCall
$beforeEachTestCall = function (TestCall $testCall) use ($describing): void { $beforeEachTestCall = function (TestCall $testCall) use ($describing): void {
if ($this->describing !== []) { if ($this->describing !== []) {
if (Arr::last($describing) !== Arr::last($this->describing)) { $testCallDescribing = $testCall->describing;
return; if (count($describing) > count($testCallDescribing) ||
} array_slice($testCallDescribing, 0, count($describing)) !== $describing) {
if (! in_array(Arr::last($describing), $testCall->describing, true)) {
return; return;
} }
} }
@@ -63,7 +60,7 @@ final class BeforeEachCall
}; };
$beforeEachTestCase = ChainableClosure::boundWhen( $beforeEachTestCase = ChainableClosure::boundWhen(
fn (): bool => $describing === [] || in_array(Arr::last($describing), $this->__describing, true), fn (): bool => $describing === [] || (count($describing) <= count($this->__describing) && array_slice($this->__describing, 0, count($describing)) === $describing),
ChainableClosure::bound(fn () => $testCaseProxies->chain($this), $this->closure)->bindTo($this, self::class), ChainableClosure::bound(fn () => $testCaseProxies->chain($this), $this->closure)->bindTo($this, self::class),
)->bindTo($this, self::class); )->bindTo($this, self::class);
+4 -2
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\PendingCalls; namespace Pest\PendingCalls;
use AllowDynamicProperties;
use Closure; use Closure;
use Pest\Concerns\Testable; use Pest\Concerns\Testable;
use Pest\Exceptions\InvalidArgumentException; use Pest\Exceptions\InvalidArgumentException;
@@ -34,7 +35,8 @@ use PHPUnit\Framework\TestCase;
* *
* @mixin HigherOrderCallables|TestCase|Testable * @mixin HigherOrderCallables|TestCase|Testable
*/ */
final class TestCall // @phpstan-ignore-line #[AllowDynamicProperties] // @phpstan-ignore-line
final class TestCall
{ {
use Describable; use Describable;
@@ -104,7 +106,7 @@ final class TestCall // @phpstan-ignore-line
{ {
if (is_int($exception)) { if (is_int($exception)) {
$exceptionCode = $exception; $exceptionCode = $exception;
} elseif (class_exists($exception)) { } elseif (class_exists($exception) || interface_exists($exception)) {
$this->testCaseMethod $this->testCaseMethod
->proxies ->proxies
->add(Backtrace::file(), Backtrace::line(), 'expectException', [$exception]); ->add(Backtrace::file(), Backtrace::line(), 'expectException', [$exception]);
+8 -4
View File
@@ -7,20 +7,24 @@ namespace Pest\Plugins\Actions;
use Pest\Contracts\Plugins; use Pest\Contracts\Plugins;
use Pest\Plugin\Loader; use Pest\Plugin\Loader;
/**
* @internal
*/
final class CallsAddsOutput final class CallsAddsOutput
{ {
public static function execute(int $exitCode): int public static function execute(int $exitCode): int
{ {
$plugins = Loader::getPlugins(Plugins\AddsOutput::class); $plugins = Loader::getPlugins(Plugins\AddsOutput::class);
/** @var Plugins\AddsOutput $plugin */
foreach ($plugins as $plugin) { foreach ($plugins as $plugin) {
assert($plugin instanceof Plugins\AddsOutput);
$exitCode = $plugin->addOutput($exitCode); $exitCode = $plugin->addOutput($exitCode);
} }
foreach (Loader::getPlugins(Plugins\ObservesExitCode::class) as $plugin) {
assert($plugin instanceof Plugins\ObservesExitCode);
$plugin->observeExitCode($exitCode);
}
return $exitCode; return $exitCode;
} }
} }
+10 -1
View File
@@ -33,7 +33,16 @@ trait HandleArguments
*/ */
public function pushArgument(string $argument, array $arguments): array public function pushArgument(string $argument, array $arguments): array
{ {
$arguments[] = $argument; $arguments = array_values($arguments);
$endOfOptionsPosition = array_search('--', $arguments, true);
if ($endOfOptionsPosition === false) {
$arguments[] = $argument;
return $arguments;
}
array_splice($arguments, $endOfOptionsPosition, 0, [$argument]);
return $arguments; return $arguments;
} }
+56 -13
View File
@@ -11,6 +11,7 @@ use Pest\Plugins\Concerns\HandleArguments;
use PHPUnit\Event\Facade as EventFacade; use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\TextUI\CliArguments\Builder as CliConfigurationBuilder; use PHPUnit\TextUI\CliArguments\Builder as CliConfigurationBuilder;
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder; use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
use RuntimeException;
/** /**
* @internal * @internal
@@ -27,6 +28,9 @@ final class Configuration implements HandlesArguments, Terminable
.DIRECTORY_SEPARATOR .DIRECTORY_SEPARATOR
.'resources/base-phpunit.xml'; .'resources/base-phpunit.xml';
/** @var array{path: string, dev: int, ino: int}|null */
private ?array $generatedConfiguration = null;
public function handleArguments(array $arguments): array public function handleArguments(array $arguments): array
{ {
if ($this->hasArgument('--configuration', $arguments) || $this->hasArgument('-c', $arguments) || $this->hasCustomConfigurationFile()) { if ($this->hasArgument('--configuration', $arguments) || $this->hasArgument('-c', $arguments) || $this->hasCustomConfigurationFile()) {
@@ -38,21 +42,57 @@ final class Configuration implements HandlesArguments, Terminable
return $this->pushArgument((string) realpath($this->fromGeneratedConfigurationFile()), $arguments); return $this->pushArgument((string) realpath($this->fromGeneratedConfigurationFile()), $arguments);
} }
public function generatedConfigurationPath(): ?string
{
return $this->generatedConfiguration['path'] ?? null;
}
private function fromGeneratedConfigurationFile(): string private function fromGeneratedConfigurationFile(): string
{ {
$path = $this->getTempPhpunitXmlPath(); $directory = getcwd();
if (file_exists($path)) {
unlink($path); if ($directory === false) {
throw new RuntimeException('Unable to determine the working directory.');
} }
$doc = new DOMDocument; $doc = new DOMDocument;
$doc->load(self::BASE_PHPUNIT_FILE); $doc->load(self::BASE_PHPUNIT_FILE);
$contents = $doc->saveXML(); $contents = $doc->saveXML();
assert(is_string($contents));
assert(is_int(file_put_contents($path, $contents))); foreach (['.pest.xml', '.pest-fallback.xml', null] as $filename) {
$filename ??= '.pest-'.bin2hex(random_bytes(8)).'.xml';
$path = $directory.DIRECTORY_SEPARATOR.$filename;
$file = @fopen($path, 'xb');
return $path; if ($file === false) {
continue;
}
try {
$stat = @fstat($file);
if ($stat === false) {
throw new RuntimeException('Unable to identify the temporary PHPUnit configuration file.');
}
$this->generatedConfiguration = ['path' => $path, 'dev' => $stat['dev'], 'ino' => $stat['ino']];
$written = @fwrite($file, $contents);
} finally {
fclose($file);
}
if ($written !== strlen($contents)) {
$this->terminate();
throw new RuntimeException('Unable to write the temporary PHPUnit configuration file.');
}
return $path;
}
throw new RuntimeException('Unable to create a temporary PHPUnit configuration file.');
} }
private function hasCustomConfigurationFile(): bool private function hasCustomConfigurationFile(): bool
@@ -63,17 +103,20 @@ final class Configuration implements HandlesArguments, Terminable
return is_string($configurationFile); return is_string($configurationFile);
} }
private function getTempPhpunitXmlPath(): string
{
return getcwd().'/.pest.xml';
}
public function terminate(): void public function terminate(): void
{ {
$path = $this->getTempPhpunitXmlPath(); $configuration = $this->generatedConfiguration;
$this->generatedConfiguration = null;
if (file_exists($path)) { if ($configuration === null) {
unlink($path); return;
}
clearstatcache();
$stat = @lstat($configuration['path']);
if ($stat !== false && $stat['dev'] === $configuration['dev'] && $stat['ino'] === $configuration['ino']) {
unlink($configuration['path']);
} }
} }
} }
+55 -27
View File
@@ -27,6 +27,16 @@ final class Coverage implements AddsOutput, HandlesArguments
private const string ONLY_COVERED_OPTION = 'only-covered'; private const string ONLY_COVERED_OPTION = 'only-covered';
/**
* @var array<string, bool>
*/
private const array OPTIONS = [
self::COVERAGE_OPTION => false,
self::MIN_OPTION => true,
self::EXACTLY_OPTION => true,
self::ONLY_COVERED_OPTION => false,
];
public bool $coverage = false; public bool $coverage = false;
public bool $compact = false; public bool $compact = false;
@@ -37,33 +47,11 @@ final class Coverage implements AddsOutput, HandlesArguments
public bool $showOnlyCovered = false; public bool $showOnlyCovered = false;
public function __construct(private readonly OutputInterface $output) public function __construct(private readonly OutputInterface $output) {}
{
//
}
/**
* {@inheritdoc}
*/
public function handleArguments(array $originals): array public function handleArguments(array $originals): array
{ {
$arguments = [...[''], ...array_values(array_filter($originals, function (string $original): bool { [$arguments, $originals] = $this->extractOwnArguments($originals);
foreach ([self::COVERAGE_OPTION, self::MIN_OPTION, self::EXACTLY_OPTION, self::ONLY_COVERED_OPTION] as $option) {
if ($original === sprintf('--%s', $option)) {
return true;
}
if (Str::startsWith($original, sprintf('--%s=', $option))) {
return true;
}
}
return false;
}))];
foreach ($arguments as $argument) {
$originals = $this->popArgument($argument, $originals);
}
$inputs = []; $inputs = [];
$inputs[] = new InputOption(self::COVERAGE_OPTION, null, InputOption::VALUE_NONE); $inputs[] = new InputOption(self::COVERAGE_OPTION, null, InputOption::VALUE_NONE);
@@ -74,8 +62,8 @@ final class Coverage implements AddsOutput, HandlesArguments
$input = new ArgvInput($arguments, new InputDefinition($inputs)); $input = new ArgvInput($arguments, new InputDefinition($inputs));
if ((bool) $input->getOption(self::COVERAGE_OPTION)) { if ((bool) $input->getOption(self::COVERAGE_OPTION)) {
$this->coverage = true; $this->coverage = true;
$originals[] = '--coverage-php'; $originals = $this->pushArgument('--coverage-php', $originals);
$originals[] = \Pest\Support\Coverage::getPath(); $originals = $this->pushArgument(\Pest\Support\Coverage::getPath(), $originals);
if (! \Pest\Support\Coverage::isAvailable()) { if (! \Pest\Support\Coverage::isAvailable()) {
if (\Pest\Support\Coverage::usingXdebug()) { if (\Pest\Support\Coverage::usingXdebug()) {
@@ -122,8 +110,48 @@ final class Coverage implements AddsOutput, HandlesArguments
} }
/** /**
* {@inheritdoc} * @param array<int, string> $originals
* @return array{0: list<string>, 1: list<string>}
*/ */
private function extractOwnArguments(array $originals): array
{
$originals = array_values($originals);
$owned = [];
$forwarded = [];
for ($index = 0, $total = count($originals); $index < $total; $index++) {
$original = $originals[$index];
foreach (self::OPTIONS as $option => $requiresValue) {
if (Str::startsWith($original, sprintf('--%s=', $option))) {
$owned[] = $original;
continue 2;
}
if ($original !== sprintf('--%s', $option)) {
continue;
}
$owned[] = $original;
$value = $originals[$index + 1] ?? null;
if ($requiresValue && $value !== null && ! Str::startsWith($value, '-')) {
$owned[] = $value;
$index++;
}
continue 2;
}
$forwarded[] = $original;
}
return [['', ...$owned], $forwarded];
}
public function addOutput(int $exitCode): int public function addOutput(int $exitCode): int
{ {
if (Parallel::isWorker()) { if (Parallel::isWorker()) {
+1 -1
View File
@@ -146,7 +146,7 @@ final readonly class Help implements HandlesArguments
], ],
[ [
'arg' => '--update-shards', 'arg' => '--update-shards',
'desc' => 'Update shards.json with test timing data for time-balanced sharding', 'desc' => 'Update the shards file with timing data for time-balanced sharding',
], ],
], ...$content['Execution']]; ], ...$content['Execution']];
+3 -3
View File
@@ -4,9 +4,9 @@ declare(strict_types=1);
namespace Pest\Plugins; namespace Pest\Plugins;
use Composer\InstalledVersions;
use Pest\Console\Thanks; use Pest\Console\Thanks;
use Pest\Contracts\Plugins\HandlesArguments; use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Support\InstalledPackages;
use Pest\Support\View; use Pest\Support\View;
use Pest\TestSuite; use Pest\TestSuite;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
@@ -96,11 +96,11 @@ final readonly class Init implements HandlesArguments
View::render('components.new-line'); View::render('components.new-line');
(new Thanks($this->input, $this->output))(); new Thanks($this->input, $this->output)();
} }
private function isLaravelInstalled(): bool private function isLaravelInstalled(): bool
{ {
return InstalledVersions::isInstalled('laravel/framework'); return InstalledPackages::has('laravel/framework');
} }
} }
+38 -39
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Plugins; namespace Pest\Plugins;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Contracts\Plugins\Terminable; use Pest\Contracts\Plugins\Terminable;
use Pest\Factories\Attribute; use Pest\Factories\Attribute;
use Pest\Factories\TestCaseMethodFactory; use Pest\Factories\TestCaseMethodFactory;
@@ -13,17 +14,24 @@ use PHPUnit\Framework\Attributes\Group;
/** /**
* @internal * @internal
*/ */
final class Only implements Terminable final class Only implements HandlesArguments, Terminable
{ {
private const string TEMPORARY_FOLDER = __DIR__ private const string DEFAULT_GROUP = '__pest_only';
.DIRECTORY_SEPARATOR
.'..'
.DIRECTORY_SEPARATOR
.'..'
.DIRECTORY_SEPARATOR
.'.temp';
public static function enable(TestCall|TestCaseMethodFactory $testCall, string $group = '__pest_only'): void private const string WORKER_GROUP = 'ONLY_GROUP';
private static ?string $group = null;
public function handleArguments(array $arguments): array
{
if (! Parallel::isWorker()) {
self::shareGroupWithWorkers();
}
return $arguments;
}
public static function enable(TestCall|TestCaseMethodFactory $testCall, string $group = self::DEFAULT_GROUP): void
{ {
if ($testCall instanceof TestCall) { if ($testCall instanceof TestCall) {
$testCall->group($group); $testCall->group($group);
@@ -38,52 +46,43 @@ final class Only implements Terminable
return; return;
} }
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock'; if (self::$group === null || $group === self::DEFAULT_GROUP) {
self::$group = $group;
if (file_exists($lockFile) && $group === '__pest_only') { self::shareGroupWithWorkers();
file_put_contents($lockFile, $group);
return;
}
if (! file_exists($lockFile)) {
touch($lockFile);
file_put_contents($lockFile, $group);
} }
} }
public static function isEnabled(): bool public static function isEnabled(): bool
{ {
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock'; return self::selectedGroup() !== null;
return file_exists($lockFile);
} }
public static function group(): string public static function group(): string
{ {
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock'; return self::selectedGroup() ?: self::DEFAULT_GROUP;
if (! file_exists($lockFile)) {
return '__pest_only';
}
return file_get_contents($lockFile) ?: '__pest_only'; // @phpstan-ignore-line
} }
/**
* {@inheritDoc}
*/
public function terminate(): void public function terminate(): void
{ {
if (Parallel::isWorker()) { self::$group = null;
return; self::shareGroupWithWorkers();
}
private static function selectedGroup(): ?string
{
if (! Parallel::isWorker()) {
return self::$group;
} }
$lockFile = self::TEMPORARY_FOLDER.DIRECTORY_SEPARATOR.'only.lock'; $group = Parallel::getGlobal(self::WORKER_GROUP);
if (file_exists($lockFile)) { return is_string($group) ? base64_decode($group) : null;
unlink($lockFile); }
private static function shareGroupWithWorkers(): void
{
if (Parallel::isEnabled()) {
Parallel::setGlobal(self::WORKER_GROUP, self::$group === null ? false : base64_encode(self::$group));
} }
} }
} }
+6 -4
View File
@@ -26,9 +26,11 @@ final class Parallel implements HandlesArguments
private const string GLOBAL_PREFIX = 'PEST_PARALLEL_GLOBAL_'; private const string GLOBAL_PREFIX = 'PEST_PARALLEL_GLOBAL_';
private const array HANDLERS = [ private const array HANDLERS = [
Parallel\Handlers\IncludePath::class,
Parallel\Handlers\Parallel::class, Parallel\Handlers\Parallel::class,
Parallel\Handlers\Pest::class, Parallel\Handlers\Pest::class,
Parallel\Handlers\Laravel::class, Parallel\Handlers\Laravel::class,
Parallel\Handlers\StopOn::class,
]; ];
/** /**
@@ -77,9 +79,6 @@ final class Parallel implements HandlesArguments
return null; return null;
} }
/**
* {@inheritdoc}
*/
public function handleArguments(array $arguments): array public function handleArguments(array $arguments): array
{ {
if ($this->hasArgumentsThatWouldBeFasterWithoutParallel()) { if ($this->hasArgumentsThatWouldBeFasterWithoutParallel()) {
@@ -148,6 +147,9 @@ final class Parallel implements HandlesArguments
$command->setName('Pest'); $command->setName('Pest');
$command->setVersion(version()); $command->setVersion(version());
Parallel\Handlers\StopOn::configureOptions($command->find('paratest')->getDefinition());
Parallel\Handlers\IncludePath::configureOptions($command->find('paratest')->getDefinition());
return $command; return $command;
} }
@@ -177,7 +179,7 @@ final class Parallel implements HandlesArguments
{ {
$argv = new ArgvInput; $argv = new ArgvInput;
if ($argv->hasParameterOption('--teamcity')) { if ($argv->hasParameterOption('--teamcity')) {
$arguments[] = '--teamcity'; $arguments = $this->pushArgument('--teamcity', $arguments);
} }
return $arguments; return $arguments;
@@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Parallel\Handlers;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugins\Parallel as ParallelPlugin;
use Pest\Plugins\Parallel\Contracts\HandlersWorkerArguments;
use Pest\Subscribers\EnsureCommandLineIncludePathComesFirst;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\TextUI\CliArguments\Builder;
use PHPUnit\TextUI\CliArguments\Configuration;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Throwable;
final class IncludePath implements HandlersWorkerArguments, HandlesArguments
{
private const string OPTION = '--include-path';
private const string GLOBAL_KEY = 'INCLUDE_PATH';
private const string PROGRAM = 'pest';
public function handleArguments(array $arguments): array
{
$arguments = array_values($arguments);
$includePath = null;
$argumentsForParatest = [];
$separatorAndArgumentsAfterIt = [];
for ($index = 0; $index < count($arguments); $index++) {
$argument = trim($arguments[$index]);
if ($argument === '--') {
$separatorAndArgumentsAfterIt = array_slice($arguments, $index);
break;
}
if ($argument === self::OPTION || str_starts_with($argument, self::OPTION.'=')) {
$optionArguments = $this->optionArgumentsPhpunitReads($arguments, $index);
$includePath = $this->includePathPhpunitReads($optionArguments);
$index += count($optionArguments) - 1;
continue;
}
$argumentsForParatest[] = $arguments[$index];
}
ParallelPlugin::setGlobal(self::GLOBAL_KEY, $includePath === null ? false : base64_encode($includePath));
if ($includePath !== null) {
$commandLineIncludePathComesFirst = new EnsureCommandLineIncludePathComesFirst($includePath);
$commandLineIncludePathComesFirst->apply();
EventFacade::instance()->registerSubscriber($commandLineIncludePathComesFirst);
}
if ($includePath !== null && $this->survivesThePhpunitParser($includePath)) {
array_push($argumentsForParatest, ...$this->argumentsPhpunitReadsAs($includePath));
}
return [...$argumentsForParatest, ...$separatorAndArgumentsAfterIt];
}
public static function configureOptions(InputDefinition $definition): void
{
$definition->addOption(new InputOption(substr(self::OPTION, 2), null, InputOption::VALUE_REQUIRED));
}
public function handleWorkerArguments(array $arguments): array
{
$encodedIncludePath = ParallelPlugin::getGlobal(self::GLOBAL_KEY);
$includePath = is_string($encodedIncludePath) ? base64_decode($encodedIncludePath, true) : false;
if (! is_string($includePath) || $includePath === '') {
return $arguments;
}
return [...$arguments, ...$this->argumentsPhpunitReadsAs($includePath)];
}
/**
* @param list<string> $arguments
* @return list<string>
*/
private function optionArgumentsPhpunitReads(array $arguments, int $index): array
{
if ($this->phpunitConfiguration([$arguments[$index]]) instanceof Configuration) {
return [$arguments[$index]];
}
return array_slice($arguments, $index, 2);
}
/**
* @param list<string> $optionArguments
*/
private function includePathPhpunitReads(array $optionArguments): ?string
{
$configuration = $this->phpunitConfiguration($optionArguments);
return $configuration instanceof Configuration && $configuration->hasIncludePath() ? $configuration->includePath() : null;
}
/**
* @param list<string> $parameters
*/
private function phpunitConfiguration(array $parameters): ?Configuration
{
try {
return new Builder(EventFacade::emitter())->fromParameters([self::PROGRAM, ...$parameters]);
} catch (Throwable) {
return null;
}
}
/**
* @return list<string>
*/
private function argumentsPhpunitReadsAs(string $includePath): array
{
if (! $this->survivesThePhpunitParser($includePath)) {
return [self::OPTION, $includePath];
}
return [self::OPTION.'='.$includePath.$this->closingEqualsSignThatStopsTheTrim($includePath)];
}
private function closingEqualsSignThatStopsTheTrim(string $includePath): string
{
return rtrim($includePath) === $includePath ? '' : '=';
}
private function survivesThePhpunitParser(string $includePath): bool
{
return $includePath !== '' && ! str_contains($includePath, '=');
}
}
+5 -5
View File
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Pest\Plugins\Parallel\Handlers; namespace Pest\Plugins\Parallel\Handlers;
use Closure; use Closure;
use Composer\InstalledVersions;
use Illuminate\Testing\ParallelRunner; use Illuminate\Testing\ParallelRunner;
use Orchestra\Testbench\TestCase; use Orchestra\Testbench\TestCase;
use ParaTest\Options; use ParaTest\Options;
@@ -13,6 +12,7 @@ use ParaTest\RunnerInterface;
use Pest\Contracts\Plugins\HandlesArguments; use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugins\Concerns\HandleArguments; use Pest\Plugins\Concerns\HandleArguments;
use Pest\Plugins\Parallel\Paratest\WrapperRunner; use Pest\Plugins\Parallel\Paratest\WrapperRunner;
use Pest\Support\InstalledPackages;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
/** /**
@@ -43,7 +43,7 @@ final class Laravel implements HandlesArguments
*/ */
private function whenUsingLaravel(array $arguments, Closure $closure): array private function whenUsingLaravel(array $arguments, Closure $closure): array
{ {
$isLaravelApplication = InstalledVersions::isInstalled('laravel/framework', false); $isLaravelApplication = InstalledPackages::has('laravel/framework', false);
$isLaravelPackage = class_exists(TestCase::class); $isLaravelPackage = class_exists(TestCase::class);
if ($isLaravelApplication && ! $isLaravelPackage) { if ($isLaravelApplication && ! $isLaravelPackage) {
@@ -66,14 +66,14 @@ final class Laravel implements HandlesArguments
*/ */
private function ensureEnvironmentVariables(array $arguments): array private function ensureEnvironmentVariables(array $arguments): array
{ {
$_ENV['LARAVEL_PARALLEL_TESTING'] = 1; $_SERVER['LARAVEL_PARALLEL_TESTING'] = $_ENV['LARAVEL_PARALLEL_TESTING'] = 1;
if ($this->hasArgument('--recreate-databases', $arguments)) { if ($this->hasArgument('--recreate-databases', $arguments)) {
$_ENV['LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES'] = 1; $_SERVER['LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES'] = $_ENV['LARAVEL_PARALLEL_TESTING_RECREATE_DATABASES'] = 1;
} }
if ($this->hasArgument('--drop-databases', $arguments)) { if ($this->hasArgument('--drop-databases', $arguments)) {
$_ENV['LARAVEL_PARALLEL_TESTING_DROP_DATABASES'] = 1; $_SERVER['LARAVEL_PARALLEL_TESTING_DROP_DATABASES'] = $_ENV['LARAVEL_PARALLEL_TESTING_DROP_DATABASES'] = 1;
} }
$arguments = $this->popArgument('--recreate-databases', $arguments); $arguments = $this->popArgument('--recreate-databases', $arguments);
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Parallel\Handlers;
use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Plugins\Parallel\Contracts\HandlersWorkerArguments;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
final class StopOn implements HandlersWorkerArguments, HandlesArguments
{
private const array OPTIONS = [
'--stop-on-defect',
'--stop-on-error',
'--stop-on-failure',
'--stop-on-warning',
'--stop-on-risky',
'--stop-on-deprecation',
'--stop-on-notice',
'--stop-on-skipped',
'--stop-on-incomplete',
];
public function handleArguments(array $arguments): array
{
foreach ($arguments as $index => $argument) {
[$option, $value] = array_pad(explode('=', $argument, 2), 2, '');
if (in_array($option, self::OPTIONS, true)
&& in_array($value, ['', '0'], true)) {
$arguments[$index] = $option.'=1';
}
}
return $arguments;
}
public function handleWorkerArguments(array $arguments): array
{
$arguments = array_values($arguments);
foreach ($arguments as $index => $argument) {
if (! in_array($argument, self::OPTIONS, true)
|| ! isset($arguments[$index + 1])
|| str_starts_with($arguments[$index + 1], '--')) {
continue;
}
$arguments[$index] .= '='.$arguments[$index + 1];
unset($arguments[$index + 1]);
}
return array_values($arguments);
}
public static function configureOptions(InputDefinition $definition): void
{
$options = $definition->getOptions();
foreach (self::OPTIONS as $argument) {
$name = substr($argument, 2);
$option = $options[$name];
$options[$name] = new InputOption(
$name,
$option->getShortcut(),
InputOption::VALUE_OPTIONAL,
$option->getDescription(),
false,
);
}
$definition->setOptions($options);
}
}
@@ -0,0 +1,216 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Parallel\Paratest;
use PHPUnit\Runner\DeprecationCollector\Facade as DeprecationCollector;
use PHPUnit\TestRunner\TestResult\Facade as TestResultFacade;
use PHPUnit\TestRunner\TestResult\Issues\Issue;
use PHPUnit\TestRunner\TestResult\TestResult;
use PHPUnit\TextUI\Configuration\Configuration;
use RuntimeException;
final class StopConditions
{
/**
* @var array<string, positive-int>
*/
private readonly array $thresholds;
/**
* @var array<string, array<string, non-negative-int>>
*/
private array $workerCounts = [];
/**
* @var array<string, non-negative-int>
*/
private array $totals = [];
/**
* @var array<string, array<string, true>>
*/
private array $issueIds = [];
public function __construct(private readonly Configuration $configuration)
{
$this->thresholds = array_filter([
'defect' => $configuration->stopOnDefectThreshold(),
'error' => $configuration->stopOnErrorThreshold(),
'failure' => $configuration->stopOnFailureThreshold(),
'warning' => $configuration->stopOnWarningThreshold(),
'risky' => $configuration->stopOnRiskyThreshold(),
'deprecation' => $configuration->stopOnDeprecationThreshold(),
'notice' => $configuration->stopOnNoticeThreshold(),
'incomplete' => $configuration->stopOnIncompleteThreshold(),
'skipped' => $configuration->stopOnSkippedThreshold(),
], static fn (int $threshold): bool => $threshold > 0);
}
public function write(string $filename): void
{
if ($this->thresholds === []) {
return;
}
$result = TestResultFacade::result();
$state = json_encode([
'counts' => $this->counts($result),
'issues' => $this->issues($result),
], JSON_THROW_ON_ERROR);
if (file_put_contents($filename.'.tmp', $state) === false
|| ! rename($filename.'.tmp', $filename)) {
throw new RuntimeException(sprintf('Unable to write the parallel stop counts to [%s].', $filename));
}
}
public function read(string $filename): void
{
if ($this->thresholds === []) {
return;
}
$contents = file_get_contents($filename);
if ($contents === false) {
throw new RuntimeException(sprintf('Unable to read the parallel stop counts from [%s].', $filename));
}
$state = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
if (! is_array($state)
|| ! isset($state['counts'], $state['issues'])
|| ! is_array($state['counts'])
|| ! is_array($state['issues'])) {
throw new RuntimeException(sprintf('Invalid parallel stop counts in [%s].', $filename));
}
$this->addCounts($filename, $state['counts']);
$this->addIssues($filename, $state['issues']);
}
public function shouldStop(): bool
{
return array_any($this->thresholds, function (int $threshold, string $outcome): bool {
$issueType = $outcome === 'defect' ? 'warning' : $outcome;
$count = ($this->totals[$outcome] ?? 0) + count($this->issueIds[$issueType] ?? []);
return $count >= $threshold;
});
}
/**
* @return array<string, int>
*/
private function counts(TestResult $result): array
{
$counts = [
'error' => $result->numberOfTestErroredEvents(),
'failure' => $result->numberOfTestFailedEvents(),
'warning' => $result->numberOfPhpunitWarnings(),
'risky' => $result->numberOfTestsWithTestConsideredRiskyEvents(),
'deprecation' => $this->numberOfDeprecations(),
'notice' => 0,
'incomplete' => $result->numberOfTestMarkedIncompleteEvents(),
'skipped' => $result->numberOfTestSkippedEvents(),
];
$counts['defect'] = $counts['error'] + $counts['failure'] + $counts['warning'] + $counts['risky'];
return $counts;
}
/**
* @return array<'warning'|'notice', list<non-empty-string>>
*/
private function issues(TestResult $result): array
{
$issues = [];
if (isset($this->thresholds['warning']) || isset($this->thresholds['defect'])) {
$issues['warning'] = array_merge(
$this->issueKeys($result->warnings(), 'user'),
$this->issueKeys($result->phpWarnings(), 'php'),
);
}
if (isset($this->thresholds['notice'])) {
$issues['notice'] = array_merge(
$this->issueKeys($result->notices(), 'user'),
$this->issueKeys($result->phpNotices(), 'php'),
);
}
return $issues;
}
/**
* @return non-negative-int
*/
private function numberOfDeprecations(): int
{
$deprecations = DeprecationCollector::filteredDeprecations();
if ($this->configuration->hasSpecificDeprecationToStopOn()) {
$message = $this->configuration->specificDeprecationToStopOn();
$deprecations = array_filter($deprecations, static fn (string $deprecation): bool => str_contains($deprecation, $message));
}
return count($deprecations);
}
/**
* @param array<array-key, mixed> $counts
*/
private function addCounts(string $filename, array $counts): void
{
foreach (array_keys($this->thresholds) as $outcome) {
if (! isset($counts[$outcome]) || ! is_int($counts[$outcome]) || $counts[$outcome] < 0) {
throw new RuntimeException(sprintf('Invalid parallel stop counts in [%s].', $filename));
}
$previous = $this->workerCounts[$filename][$outcome] ?? 0;
$increase = $counts[$outcome] - $previous;
if ($increase < 0) {
throw new RuntimeException(sprintf('Parallel stop counts decreased in [%s].', $filename));
}
$this->totals[$outcome] = ($this->totals[$outcome] ?? 0) + $increase;
$this->workerCounts[$filename][$outcome] = $counts[$outcome];
}
}
/**
* @param array<array-key, mixed> $issues
*/
private function addIssues(string $filename, array $issues): void
{
foreach ($issues as $outcome => $ids) {
if (! in_array($outcome, ['warning', 'notice'], true) || ! is_array($ids)) {
throw new RuntimeException(sprintf('Invalid parallel stop issues in [%s].', $filename));
}
foreach ($ids as $id) {
if (! is_string($id)) {
throw new RuntimeException(sprintf('Invalid parallel stop issue in [%s].', $filename));
}
$this->issueIds[$outcome][$id] = true;
}
}
}
/**
* @param list<Issue> $issues
* @return list<non-empty-string>
*/
private function issueKeys(array $issues, string $origin): array
{
return array_map(
static fn (Issue $issue): string => hash('sha256', implode(':', [$origin, $issue->file(), $issue->line(), $issue->description()])),
$issues,
);
}
}
+20 -10
View File
@@ -78,8 +78,6 @@ final class WrapperRunner implements RunnerInterface
/** @var list<non-empty-list<non-empty-string>> */ /** @var list<non-empty-list<non-empty-string>> */
private array $pending = []; private array $pending = [];
private int $exitcode = -1;
/** @var array<positive-int,WrapperWorker> */ /** @var array<positive-int,WrapperWorker> */
private array $workers = []; private array $workers = [];
@@ -122,6 +120,8 @@ final class WrapperRunner implements RunnerInterface
/** @var non-empty-string[] */ /** @var non-empty-string[] */
private readonly array $parameters; private readonly array $parameters;
private readonly StopConditions $stopConditions;
private CodeCoverageFilterRegistry $codeCoverageFilterRegistry; private CodeCoverageFilterRegistry $codeCoverageFilterRegistry;
/** @var non-empty-string */ /** @var non-empty-string */
@@ -133,6 +133,7 @@ final class WrapperRunner implements RunnerInterface
) { ) {
$this->printer = new ResultPrinter($output, $options); $this->printer = new ResultPrinter($output, $options);
$this->timer = new Timer; $this->timer = new Timer;
$this->stopConditions = new StopConditions($options->configuration);
$wrapper = realpath( $wrapper = realpath(
dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'worker.php', dirname(__DIR__, 4).DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'worker.php',
@@ -155,6 +156,10 @@ final class WrapperRunner implements RunnerInterface
$parameters[] = $wrapper; $parameters[] = $wrapper;
$parameters[] = '--test-directory='.TestSuite::getInstance()->testPath; $parameters[] = '--test-directory='.TestSuite::getInstance()->testPath;
if (is_string($GLOBALS['_composer_autoload_path'] ?? null)) {
$parameters[] = '--composer-autoload='.$GLOBALS['_composer_autoload_path'];
}
$this->parameters = $parameters; $this->parameters = $parameters;
$this->codeCoverageFilterRegistry = new CodeCoverageFilterRegistry; $this->codeCoverageFilterRegistry = new CodeCoverageFilterRegistry;
} }
@@ -248,17 +253,18 @@ final class WrapperRunner implements RunnerInterface
$this->flushWorker($worker); $this->flushWorker($worker);
if ($this->stopConditions->shouldStop()) {
$this->pending = [];
break;
}
if ($batchSize !== 0 && $this->batches[$token] >= $batchSize) { if ($batchSize !== 0 && $this->batches[$token] >= $batchSize) {
$this->destroyWorker($token); $this->destroyWorker($token);
$worker = $this->startWorker($token); $worker = $this->startWorker($token);
} }
if ( if (($pending = array_shift($this->pending)) !== null) {
$this->exitcode > 0
&& $this->options->configuration->stopOnFailureThreshold() > 0
) {
$this->pending = [];
} elseif (($pending = array_shift($this->pending)) !== null) {
$worker->assign($pending); $worker->assign($pending);
$this->batches[$token] += count($pending); $this->batches[$token] += count($pending);
} }
@@ -275,6 +281,7 @@ final class WrapperRunner implements RunnerInterface
if ($testResultFile !== '') { if ($testResultFile !== '') {
$this->requiredTestResultFiles[$testResultFile] = true; $this->requiredTestResultFiles[$testResultFile] = true;
$this->stopConditions->read($testResultFile.'.stop');
} }
if (isset($worker->coverageFile) && $worker->coverageFile->getPathname() !== '') { if (isset($worker->coverageFile) && $worker->coverageFile->getPathname() !== '') {
@@ -282,7 +289,6 @@ final class WrapperRunner implements RunnerInterface
} }
} }
$this->exitcode = max($this->exitcode, $worker->getExitCode());
$this->printer->printFeedback( $this->printer->printFeedback(
$worker->progressFile, $worker->progressFile,
$worker->unexpectedOutputFile, $worker->unexpectedOutputFile,
@@ -501,7 +507,11 @@ final class WrapperRunner implements RunnerInterface
$this->clearFiles($this->statusFiles); $this->clearFiles($this->statusFiles);
$this->clearFiles($this->progressFiles); $this->clearFiles($this->progressFiles);
$this->clearFiles($this->unexpectedOutputFiles); $this->clearFiles($this->unexpectedOutputFiles);
$this->clearFiles($this->testResultFiles);
foreach ($this->testResultFiles as $file) {
$this->clearFiles([$file, new SplFileInfo($file->getPathname().'.stop')]);
}
$this->clearFiles($this->resultCacheFiles); $this->clearFiles($this->resultCacheFiles);
$this->clearFiles($this->coverageFiles); $this->clearFiles($this->coverageFiles);
$this->clearFiles($this->junitFiles); $this->clearFiles($this->junitFiles);
+1 -1
View File
@@ -23,7 +23,7 @@ final class Retry implements HandlesArguments
return $arguments; return $arguments;
} }
if ($this->hasArgument('--parallel', $arguments)) { if ($this->hasArgument('--parallel', $arguments) || in_array('-p', $arguments, true)) {
throw new InvalidOption('The [--retry] option is not supported when running in parallel.'); throw new InvalidOption('The [--retry] option is not supported when running in parallel.');
} }
+304 -76
View File
@@ -31,6 +31,26 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private const string CLASS_END = "\0"; private const string CLASS_END = "\0";
/**
* @var array<string, bool>
*/
private const array PARATEST_ONLY_OPTIONS = [
'--processes' => true,
'--runner' => true,
'--max-batch-size' => true,
'-m' => true,
'--max-processes' => true,
'--passthru-php' => true,
'--tmp-dir' => true,
'--functional' => false,
'--no-test-tokens' => false,
];
/**
* @var list<string>
*/
private const array PARATEST_ONLY_SHORT_OPTIONS_WITH_VALUE = ['-m'];
/** /**
* @var array{ * @var array{
* index: int, * index: int,
@@ -43,6 +63,23 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private static bool $updateShards = false; private static bool $updateShards = false;
private static ?string $timingsFilename = null;
/**
* @var array<string, float|array{time: float, tests: list<string>}>|null
*/
private static ?array $externalTimings = null;
/**
* @var array<string, bool>|null
*/
private static ?array $ownership = null;
/**
* @var array<string, scalar>
*/
private static array $metadata = [];
private static bool $timeBalanced = false; private static bool $timeBalanced = false;
private static bool $shardsOutdated = false; private static bool $shardsOutdated = false;
@@ -50,7 +87,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private static bool $passed = false; private static bool $passed = false;
/** /**
* @var array<string, float>|null * @var array<string, float|array{time: float, tests: list<string>}>|null
*/ */
private static ?array $collectedTimings = null; private static ?array $collectedTimings = null;
@@ -61,13 +98,50 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
public function __construct( public function __construct(
private readonly OutputInterface $output, private readonly OutputInterface $output,
) { ) {}
//
public static function useTimingsFile(string $filename): void
{
self::$timingsFilename = $filename;
} }
/** /**
* {@inheritDoc} * @param array<string, float|array{time: float, tests: list<string>}> $units
* @param array<string, scalar> $metadata Stored alongside the units, and read back
* by {@see self::metadata()} on sharded runs.
*/ */
public static function useTimings(array $units, array $metadata = []): void
{
self::$externalTimings = $units;
if ($metadata !== []) {
self::$metadata = $metadata;
}
}
/**
* @return array<string, scalar>
*/
public static function metadata(): array
{
return self::$metadata;
}
public static function owns(string $unit): bool
{
if (self::$ownership === null) {
return true;
}
if (! isset(self::$ownership[$unit])) {
self::$shardsOutdated = true;
return true;
}
return self::$ownership[$unit];
}
public function handleArguments(array $arguments): array public function handleArguments(array $arguments): array
{ {
if ($this->hasArgument('--update-shards', $arguments)) { if ($this->hasArgument('--update-shards', $arguments)) {
@@ -98,20 +172,33 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
$tests = $this->allTests($arguments); $tests = $this->allTests($arguments);
$timings = $this->loadShardsFile(); $units = $this->loadShardsFile();
if ($timings !== null) { if ($units !== null) {
$knownTests = array_values(array_filter($tests, fn (string $test): bool => isset($timings[$test]))); $hasRemovedTests = array_diff($this->testsOf($units), $tests) !== [];
$newTests = array_values(array_diff($tests, $knownTests));
$partitions = $this->partitionByTime($knownTests, $timings, $total); $units = $this->withoutRemovedTests($units, $tests);
$newTests = array_values(array_diff($tests, $this->testsOf($units)));
$partitions = $this->partitionByTime($units, $total);
$median = $this->medianTime($units);
foreach ($newTests as $i => $test) { foreach ($newTests as $i => $test) {
$partitions[$i % $total][] = $test; $partitions[$i % $total][$test] = ['time' => $median, 'tests' => [$test]];
} }
$testsToRun = $partitions[$index - 1] ?? []; $selected = $partitions[$index - 1] ?? [];
self::$ownership = [];
foreach ($partitions as $i => $partition) {
self::$ownership += array_fill_keys(array_keys($partition), $i === $index - 1);
}
self::$timeBalanced = true; self::$timeBalanced = true;
self::$shardsOutdated = $newTests !== []; self::$shardsOutdated = $newTests !== [] || $hasRemovedTests;
$testsToRun = array_values(array_intersect($tests, $this->testsOf($selected)));
} else { } else {
$isInCurrentShard = fn (int $key): bool => $key % $total === ($index - 1); $isInCurrentShard = fn (int $key): bool => $key % $total === ($index - 1);
$testsToRun = array_values(array_filter($tests, $isInCurrentShard, ARRAY_FILTER_USE_KEY)); $testsToRun = array_values(array_filter($tests, $isInCurrentShard, ARRAY_FILTER_USE_KEY));
@@ -124,15 +211,12 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
'testsCount' => count($tests), 'testsCount' => count($tests),
]; ];
if ($testsToRun === []) {
return $arguments;
}
$filter = $this->buildFilterArgument($testsToRun); $filter = $this->buildFilterArgument($testsToRun);
$this->ensureFilterLengthIsSafe($filter); $this->ensureFilterLengthIsSafe($filter);
$arguments = [...$arguments, '--filter', $filter]; $arguments = $this->pushArgument('--filter', $arguments);
$arguments = $this->pushArgument($filter, $arguments);
if ($this->hasArgument('--do-not-fail-on-empty-test-suite', $arguments) || $this->hasArgument('--fail-on-empty-test-suite', $arguments)) { if ($this->hasArgument('--do-not-fail-on-empty-test-suite', $arguments) || $this->hasArgument('--fail-on-empty-test-suite', $arguments)) {
return $arguments; return $arguments;
@@ -175,7 +259,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private function allTests(array $arguments): array private function allTests(array $arguments): array
{ {
$command = $this->buildListTestsCommand( $command = $this->buildListTestsCommand(
$arguments, $this->popArgument('--list-tests', $arguments),
TestSuite::getInstance()->testPath, TestSuite::getInstance()->testPath,
); );
@@ -202,33 +286,67 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
} }
} }
if ($argument === '--runner') { if (in_array($argument, ['--parallel', '-p'], strict: true)) {
$skipNext = true; continue;
}
if ($this->isAttachedParatestShortOption($argument)) {
continue;
}
[$option] = explode('=', $argument, 2);
if (! array_key_exists($option, self::PARATEST_ONLY_OPTIONS)) {
$filtered[] = $argument;
continue; continue;
} }
if (in_array($argument, ['--parallel', '-p'], strict: true) $skipNext = self::PARATEST_ONLY_OPTIONS[$option] && ! str_contains($argument, '=');
|| str_starts_with($argument, '--processes')
|| str_starts_with($argument, '--runner=')) {
continue;
}
$filtered[] = $argument;
} }
return $filtered; return $filtered;
} }
private function isAttachedParatestShortOption(string $argument): bool
{
if (strlen($argument) <= 2 || str_starts_with($argument, '--')) {
return false;
}
return in_array(substr($argument, 0, 2), self::PARATEST_ONLY_SHORT_OPTIONS_WITH_VALUE, strict: true);
}
/** /**
* @param list<string> $arguments * @param list<string> $arguments
* @return list<string> * @return list<string>
*/ */
private function buildListTestsCommand(array $arguments, string $testPath): array private function buildListTestsCommand(array $arguments, string $testPath): array
{ {
$filtered = $this->removeParallelArguments($arguments); $filtered = [];
$skipNext = false;
return [PHP_BINARY, ...$filtered, '--test-directory='.$testPath, '--list-tests']; foreach ($this->removeParallelArguments($arguments) as $argument) {
if ($skipNext) {
$skipNext = false;
if (! str_starts_with($argument, '-')) {
continue;
}
}
if (preg_match('/^--(?:coverage-(?:php|html|clover|xml|cobertura|crap4j|openclover|jsonl|filter)|min|exactly)$/', $argument) === 1) {
$skipNext = true;
continue;
}
if (! str_starts_with($argument, '--coverage')) {
$filtered[] = $argument;
}
}
return [PHP_BINARY, ...$this->pushArgument('--list-tests', $this->pushArgument('--test-directory='.$testPath, $filtered))];
} }
/** /**
@@ -247,7 +365,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
private function buildFilterArgument(array $testsToRun): string private function buildFilterArgument(array $testsToRun): string
{ {
if ($testsToRun === []) { if ($testsToRun === []) {
return ''; return '(?!)';
} }
/** @var array<string, mixed> $tree */ /** @var array<string, mixed> $tree */
@@ -318,15 +436,16 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
{ {
self::$passed = $exitCode === 0; self::$passed = $exitCode === 0;
if (self::$updateShards && self::$passed && ! Parallel::isWorker()) { if (self::$updateShards && (self::$passed || self::$externalTimings !== null) && ! Parallel::isWorker()) {
self::$collectedTimings = $this->collectTimings(); self::$collectedTimings = $this->collectTimings();
}
$count = self::$knownTests !== null if (self::$collectedTimings !== null && self::$collectedTimings !== []) {
? count(array_intersect_key(self::$collectedTimings, array_flip(self::$knownTests))) $count = count($this->unitsToWrite(self::$collectedTimings));
: count(self::$collectedTimings);
$this->output->writeln(sprintf( $this->output->writeln(sprintf(
' <fg=gray>Shards:</> <fg=default>shards.json updated with timings for %d test class%s.</>', ' <fg=gray>Shards:</> <fg=default>%s updated with timings for %d test class%s.</>',
$this->timingsFilename(),
$count, $count,
$count === 1 ? '' : 'es', $count === 1 ? '' : 'es',
)); ));
@@ -354,7 +473,10 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
)); ));
if (self::$shardsOutdated) { if (self::$shardsOutdated) {
$this->output->writeln(' <fg=yellow;options=bold>WARN</> <fg=default>The [tests/.pest/shards.json] file is out of date. Run [--update-shards] to update it.</>'); $this->output->writeln(sprintf(
' <fg=yellow;options=bold>WARN</> <fg=default>The [%s] file is out of date. Run [--update-shards] to update it.</>',
$this->relativeTimingsPath(),
));
} }
return $exitCode; return $exitCode;
@@ -372,7 +494,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
return; return;
} }
if (! self::$passed) { if (! self::$passed && self::$externalTimings === null) {
return; return;
} }
@@ -386,17 +508,17 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
} }
/** /**
* @return array<string, float> * @return array<string, float|array{time: float, tests: list<string>}>
*/ */
private function collectTimings(): array private function collectTimings(): array
{ {
$runId = Parallel::getGlobal('SHARD_RUN_ID'); $runId = Parallel::getGlobal('SHARD_RUN_ID');
if (is_string($runId)) { $collected = is_string($runId)
return $this->readWorkerTimings($runId); ? $this->readWorkerTimings($runId)
} : EnsureShardTimingsAreCollected::timings();
return EnsureShardTimingsAreCollected::timings(); return self::$externalTimings ?? $collected;
} }
private function writeWorkerTimings(): void private function writeWorkerTimings(): void
@@ -451,15 +573,46 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
return $merged; return $merged;
} }
private function timingsFilename(): string
{
return self::$timingsFilename ?? 'shards.json';
}
private function relativeTimingsPath(): string
{
return implode(DIRECTORY_SEPARATOR, [TestSuite::getInstance()->testPath, '.pest', $this->timingsFilename()]);
}
private function shardsPath(): string private function shardsPath(): string
{ {
$testSuite = TestSuite::getInstance(); return TestSuite::getInstance()->rootPath.DIRECTORY_SEPARATOR.$this->relativeTimingsPath();
return implode(DIRECTORY_SEPARATOR, [$testSuite->rootPath, $testSuite->testPath, '.pest', 'shards.json']);
} }
/** /**
* @return array<string, float>|null * @param array<string, mixed> $units
* @return array<string, array{time: float, tests: list<string>}>
*/
private function normaliseUnits(array $units): array
{
$normalised = [];
foreach ($units as $key => $unit) {
if (is_array($unit) && isset($unit['time']) && isset($unit['tests']) && is_array($unit['tests'])) {
$normalised[$key] = ['time' => (float) $unit['time'], 'tests' => array_values(array_map(strval(...), $unit['tests']))];
continue;
}
if (is_float($unit) || is_int($unit)) {
$normalised[$key] = ['time' => (float) $unit, 'tests' => [$key]];
}
}
return $normalised;
}
/**
* @return array<string, array{time: float, tests: list<string>}>|null
*/ */
private function loadShardsFile(): ?array private function loadShardsFile(): ?array
{ {
@@ -472,50 +625,95 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
$contents = file_get_contents($path); $contents = file_get_contents($path);
if ($contents === false) { if ($contents === false) {
throw new InvalidOption('The [tests/.pest/shards.json] file could not be read. Delete it or run [--update-shards] to regenerate.'); throw new InvalidOption(sprintf('The [%s] file could not be read. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
} }
$data = json_decode($contents, true); $data = json_decode($contents, true);
if (! is_array($data) || ! isset($data['timings']) || ! is_array($data['timings'])) { $units = null;
throw new InvalidOption('The [tests/.pest/shards.json] file is corrupted. Delete it or run [--update-shards] to regenerate.');
if (is_array($data)) {
$units = $data['units'] ?? $data['timings'] ?? null;
} }
return $data['timings']; if (! is_array($units)) {
throw new InvalidOption(sprintf('The [%s] file is corrupted. Delete it or run [--update-shards] to regenerate.', $this->relativeTimingsPath()));
}
if (isset($data['metadata']) && is_array($data['metadata'])) {
self::$metadata = array_filter($data['metadata'], is_scalar(...));
}
return $this->normaliseUnits($units);
} }
/** /**
* @param array<string, array{time: float, tests: list<string>}> $units
* @param list<string> $tests * @param list<string> $tests
* @param array<string, float> $timings * @return array<string, array{time: float, tests: list<string>}>
* @return list<list<string>>
*/ */
private function partitionByTime(array $tests, array $timings, int $total): array private function withoutRemovedTests(array $units, array $tests): array
{ {
$knownTimings = array_filter( $live = [];
array_map(fn (string $test): ?float => $timings[$test] ?? null, $tests),
fn (?float $t): bool => $t !== null,
);
$median = $knownTimings !== [] ? $this->median(array_values($knownTimings)) : 1.0; foreach ($units as $key => $unit) {
$declared = $unit['tests'];
$unit['tests'] = array_values(array_intersect($declared, $tests));
$testsWithTimings = array_map( if ($declared === [] || $unit['tests'] !== []) {
fn (string $test): array => ['test' => $test, 'time' => $timings[$test] ?? $median], $live[$key] = $unit;
$tests, }
); }
usort($testsWithTimings, fn (array $a, array $b): int => $b['time'] <=> $a['time']); return $live;
}
/** @var list<list<string>> */ /**
* @param array<string, array{time: float, tests: list<string>}> $units
* @return list<string>
*/
private function testsOf(array $units): array
{
$tests = [];
foreach ($units as $unit) {
foreach ($unit['tests'] as $test) {
$tests[$test] = true;
}
}
return array_keys($tests);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
*/
private function medianTime(array $units): float
{
$times = array_column($units, 'time');
return $times === [] ? 1.0 : $this->median($times);
}
/**
* @param array<string, array{time: float, tests: list<string>}> $units
* @return list<array<string, array{time: float, tests: list<string>}>>
*/
private function partitionByTime(array $units, int $total): array
{
uasort($units, fn (array $a, array $b): int => $b['time'] <=> $a['time']);
/** @var list<array<string, array{time: float, tests: list<string>}>> */
$bins = array_fill(0, $total, []); $bins = array_fill(0, $total, []);
/** @var non-empty-list<float> */ /** @var non-empty-list<float> */
$binTimes = array_fill(0, $total, 0.0); $binTimes = array_fill(0, $total, 0.0);
foreach ($testsWithTimings as $item) { foreach ($units as $key => $unit) {
$minIndex = array_search(min($binTimes), $binTimes, strict: true); $minIndex = array_search(min($binTimes), $binTimes, strict: true);
assert(is_int($minIndex)); assert(is_int($minIndex));
$bins[$minIndex][] = $item['test']; $bins[$minIndex][$key] = $unit;
$binTimes[$minIndex] += $item['time']; $binTimes[$minIndex] += $unit['time'];
} }
return $bins; return $bins;
@@ -539,9 +737,32 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
} }
/** /**
* @param array<string, float> $timings * @param array<string, float|array{time: float, tests: list<string>}> $units
* @return array<string, array{time: float, tests: list<string>}>
*/ */
private function writeTimings(array $timings): void private function unitsToWrite(array $units): array
{
$units = $this->normaliseUnits($units);
if (self::$knownTests === null) {
return $units;
}
$known = self::$knownTests;
$units = array_filter($units, fn (array $unit): bool => $unit['tests'] === [] || array_intersect($unit['tests'], $known) !== []);
foreach (array_diff($known, $this->testsOf($units)) as $test) {
$units[$test] = ['time' => 0.0, 'tests' => [$test]];
}
return $units;
}
/**
* @param array<string, float|array{time: float, tests: list<string>}> $units
*/
private function writeTimings(array $units): void
{ {
$path = $this->shardsPath(); $path = $this->shardsPath();
@@ -550,18 +771,25 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
mkdir($directory, 0755, true); mkdir($directory, 0755, true);
} }
if (self::$knownTests !== null) { $bundled = self::$externalTimings !== null && array_filter($units, is_array(...)) !== [];
$knownSet = array_flip(self::$knownTests);
$timings = array_intersect_key($timings, $knownSet);
}
ksort($timings); $units = $this->unitsToWrite($units);
$canonical = self::$knownTests ?? array_keys($timings); ksort($units);
$canonical = self::$knownTests ?? $this->testsOf($units);
sort($canonical); sort($canonical);
$payload = $bundled
? ['units' => $units]
: ['timings' => array_map(fn (array $unit): float => $unit['time'], $units)];
if (self::$metadata !== []) {
$payload['metadata'] = self::$metadata;
}
file_put_contents($path, json_encode([ file_put_contents($path, json_encode([
'timings' => $timings, ...$payload,
'checksum' => md5(implode("\n", $canonical)), 'checksum' => md5(implode("\n", $canonical)),
'updated_at' => date('c'), 'updated_at' => date('c'),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n"); ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n");
+608 -103
View File
File diff suppressed because it is too large Load Diff
+4 -23
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia\Baselines; namespace Pest\Plugins\Tia\Baselines;
use Pest\Plugins\Tia\WatchPatterns; use Pest\Plugins\Tia\WatchPatterns;
use Pest\Support\Git;
use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
@@ -73,23 +74,7 @@ abstract readonly class BaseRemote // @pest-arch-ignore-line
protected function readOriginUrl(string $projectRoot): ?string // @pest-arch-ignore-line protected function readOriginUrl(string $projectRoot): ?string // @pest-arch-ignore-line
{ {
$gitConfig = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config'; return new Git($projectRoot)->originUrl();
if (! is_file($gitConfig)) {
return null;
}
$content = @file_get_contents($gitConfig);
if ($content === false) {
return null;
}
if (preg_match('/\[remote "origin"\][^\[]*?url\s*=\s*(\S+)/s', $content, $match) !== 1) {
return null;
}
return $match[1];
} }
/** /**
@@ -120,13 +105,9 @@ abstract readonly class BaseRemote // @pest-arch-ignore-line
return $configured; return $configured;
} }
$process = new Process(['git', 'symbolic-ref', 'refs/remotes/origin/HEAD']); $ref = new Git()->output(['symbolic-ref', 'refs/remotes/origin/HEAD']);
$process->setTimeout(5.0);
$process->run();
if ($process->isSuccessful()) {
$ref = trim($process->getOutput());
if ($ref !== null) {
$branch = str_replace('refs/remotes/origin/', '', $ref); $branch = str_replace('refs/remotes/origin/', '', $ref);
if ($branch !== '') { if ($branch !== '') {
+104
View File
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Tia;
use JsonException;
/**
* @internal
*/
final class ByteSafeJson
{
private const string ESCAPE_PREFIX = "\0base64:";
private const string ENCODED_ESCAPE_PREFIX = '\u0000base64:';
/**
* @throws JsonException
*/
public static function encode(mixed $value): string
{
$plain = json_encode($value, JSON_UNESCAPED_SLASHES);
if ($plain !== false && ! self::holdsEscapes($plain)) {
return $plain;
}
return json_encode(self::escape($value), JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
}
public static function decode(string $json): mixed
{
return self::restore(json_decode($json, true), $json);
}
public static function restore(mixed $decoded, string $json): mixed
{
return self::holdsEscapes($json) ? self::unescape($decoded) : $decoded;
}
private static function holdsEscapes(string $json): bool
{
return str_contains($json, self::ENCODED_ESCAPE_PREFIX);
}
private static function escape(mixed $value): mixed
{
if (is_string($value)) {
return self::escapeString($value);
}
if (! is_array($value)) {
return $value;
}
$escaped = [];
foreach ($value as $key => $item) {
$escaped[is_string($key) ? self::escapeString($key) : $key] = self::escape($item);
}
return $escaped;
}
private static function unescape(mixed $value): mixed
{
if (is_string($value)) {
return self::unescapeString($value);
}
if (! is_array($value)) {
return $value;
}
$unescaped = [];
foreach ($value as $key => $item) {
$unescaped[is_string($key) ? self::unescapeString($key) : $key] = self::unescape($item);
}
return $unescaped;
}
private static function escapeString(string $value): string
{
if (preg_match('//u', $value) === 1 && ! str_starts_with($value, self::ESCAPE_PREFIX)) {
return $value;
}
return self::ESCAPE_PREFIX.base64_encode($value);
}
private static function unescapeString(string $value): string
{
if (! str_starts_with($value, self::ESCAPE_PREFIX)) {
return $value;
}
$raw = base64_decode(substr($value, strlen(self::ESCAPE_PREFIX)), true);
return $raw === false ? $value : $raw;
}
}
+271 -50
View File
@@ -6,21 +6,90 @@ namespace Pest\Plugins\Tia;
use Pest\Exceptions\MissingDependency; use Pest\Exceptions\MissingDependency;
use Pest\Exceptions\TiaGitFailed; use Pest\Exceptions\TiaGitFailed;
use Pest\Support\Arr;
use Pest\Support\Git; use Pest\Support\Git;
use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\ExecutableFinder;
/** /**
* @internal * @internal
*/ */
final readonly class ChangedFiles final class ChangedFiles
{ {
private Git $git; private readonly Git $git;
public function __construct(private string $projectRoot) private ?string $gitPrefix = null;
/**
* @var array<string, true>
*/
private array $outsideProject = [];
/**
* @var array<string, true>
*/
private array $outsideProjectDirty = [];
public function __construct(private readonly string $projectRoot)
{ {
$this->git = new Git($projectRoot); $this->git = new Git($projectRoot);
} }
public function gitPrefix(): string
{
return $this->gitPrefix ??= $this->git->pathPrefix();
}
/**
* @param array<int, string> $files repository-relative paths, as printed by git.
* @return array<int, string> project-relative paths; paths outside the project are dropped.
*/
private function toProjectRelative(array $files, bool $fromWorkingTree = false): array
{
$prefix = $this->gitPrefix();
if ($prefix === '') {
return $files;
}
$projectFiles = [];
foreach ($files as $file) {
if (str_starts_with($file, $prefix)) {
$projectFiles[] = substr($file, strlen($prefix));
continue;
}
if ($file === '') {
continue;
}
$this->outsideProject[$file] = true;
if ($fromWorkingTree) {
$this->outsideProjectDirty[$file] = true;
}
}
return $projectFiles;
}
/**
* @return array<int, string>
*/
public function outsideProjectDirty(): array
{
return Arr::stringKeys($this->outsideProjectDirty);
}
/**
* @return array<int, string>
*/
public function outsideProject(): array
{
return Arr::stringKeys($this->outsideProject);
}
/** /**
* @param array<int, string> $files project-relative paths. * @param array<int, string> $files project-relative paths.
* @param array<string, string> $lastRunTree path → content hash from last run. * @param array<string, string> $lastRunTree path → content hash from last run.
@@ -34,13 +103,13 @@ final readonly class ChangedFiles
$candidates = array_fill_keys($files, true); $candidates = array_fill_keys($files, true);
foreach (array_keys($lastRunTree) as $snapshotted) { foreach (Arr::stringKeys($lastRunTree) as $snapshotted) {
$candidates[$snapshotted] = true; $candidates[$snapshotted] = true;
} }
$remaining = []; $remaining = [];
foreach (array_keys($candidates) as $file) { foreach (Arr::stringKeys($candidates) as $file) {
$snapshot = $lastRunTree[$file] ?? null; $snapshot = $lastRunTree[$file] ?? null;
$current = $this->currentHash($file); $current = $this->currentHash($file);
@@ -52,6 +121,100 @@ final readonly class ChangedFiles
return $remaining; return $remaining;
} }
/**
* @param array<int, string> $repositoryRelativeInputs
* @return array<string, string>
*/
public function baselineTree(?string $sha, array $repositoryRelativeInputs): array
{
return $this->snapshotTree([...($this->since($sha) ?? []), ...$this->externalKeys($repositoryRelativeInputs)]);
}
/**
* @param array<int, string> $repositoryRelativeInputs
* @param array<int, string> $repositoryRelativeRepositories
* @param array<int, string> $repositoryRelativeUnlisted
* @return array<string, string>
*/
public function externalInputHashes(array $repositoryRelativeInputs, array $repositoryRelativeRepositories = [], array $repositoryRelativeUnlisted = []): array
{
$hashes = $this->snapshotTree($this->externalKeys($repositoryRelativeInputs));
foreach ($this->externalKeys($repositoryRelativeRepositories) as $key) {
$hashes[$key] = 'repository';
}
foreach ($this->externalKeys($repositoryRelativeUnlisted) as $key) {
$hashes[$key] = 'unlisted';
}
return $hashes;
}
/**
* @param array<string, string> $before
* @param array<string, string> $after
* @return array<int, string>
*/
public function changedExternalInputs(array $before, array $after): array
{
$parent = $this->parentPath();
$changed = [];
foreach (Arr::stringKeys([...$before, ...$after]) as $key) {
if (($before[$key] ?? null) !== ($after[$key] ?? null)) {
$changed[] = $parent !== '' && str_starts_with($key, $parent) ? substr($key, strlen($parent)) : $key;
}
}
sort($changed);
return $changed;
}
/**
* @param array<int, string> $files
* @param array<int, string> $repositoryRelativeInputs
* @param array<string, string> $lastRunTree
* @return array{0: array<int, string>, 1: array<int, string>}
*/
public function changedSinceLastRun(array $files, array $repositoryRelativeInputs, array $lastRunTree): array
{
$parent = $this->parentPath();
$projectFiles = [];
$externalInputsChanged = [];
foreach ($this->filterUnchangedSinceLastRun([...$files, ...$this->externalKeys($repositoryRelativeInputs)], $lastRunTree) as $file) {
if ($parent !== '' && str_starts_with($file, $parent)) {
$externalInputsChanged[] = substr($file, strlen($parent));
} else {
$projectFiles[] = $file;
}
}
return [$projectFiles, $externalInputsChanged];
}
/**
* @param array<int, string> $repositoryRelativeInputs
* @return array<int, string>
*/
private function externalKeys(array $repositoryRelativeInputs): array
{
$parent = $this->parentPath();
if ($parent === '') {
return [];
}
return array_map(static fn (string $input): string => $parent.$input, $repositoryRelativeInputs);
}
private function parentPath(): string
{
return str_repeat('../', substr_count($this->gitPrefix(), '/'));
}
private function currentHash(string $relativePath): ?string private function currentHash(string $relativePath): ?string
{ {
$absolute = $this->projectRoot.DIRECTORY_SEPARATOR.$relativePath; $absolute = $this->projectRoot.DIRECTORY_SEPARATOR.$relativePath;
@@ -60,11 +223,22 @@ final readonly class ChangedFiles
return null; return null;
} }
$hash = ContentHash::of($absolute); $hash = $this->hashOf($relativePath, $absolute);
return $hash === false ? null : $hash; return $hash === false ? null : $hash;
} }
private function hashOf(string $relativePath, string $absolute): string|false
{
$parent = $this->parentPath();
if ($parent !== '' && str_starts_with($relativePath, $parent)) {
return @hash_file('xxh128', $absolute);
}
return ContentHash::of($absolute);
}
/** /**
* @param array<int, string> $files * @param array<int, string> $files
* @return array<string, string> path → xxh128 content hash * @return array<string, string> path → xxh128 content hash
@@ -82,7 +256,7 @@ final readonly class ChangedFiles
continue; continue;
} }
$hash = ContentHash::of($absolute); $hash = $this->hashOf($file, $absolute);
if ($hash !== false) { if ($hash !== false) {
$out[$file] = $hash; $out[$file] = $hash;
@@ -97,6 +271,9 @@ final readonly class ChangedFiles
*/ */
public function since(?string $sha): ?array public function since(?string $sha): ?array
{ {
$this->outsideProject = [];
$this->outsideProjectDirty = [];
$files = []; $files = [];
if ($sha !== null && $sha !== '') { if ($sha !== null && $sha !== '') {
@@ -118,7 +295,9 @@ final readonly class ChangedFiles
$unique[$file] = true; $unique[$file] = true;
} }
$candidates = array_keys($this->filterIgnored($unique)); $candidates = Arr::stringKeys($this->filterIgnored($unique));
$this->filterIgnoredOutsideProject();
if ($sha !== null && $sha !== '') { if ($sha !== null && $sha !== '') {
return $this->filterBehaviourallyUnchanged($candidates, $sha); return $this->filterBehaviourallyUnchanged($candidates, $sha);
@@ -133,36 +312,65 @@ final readonly class ChangedFiles
*/ */
private function filterBehaviourallyUnchanged(array $files, string $sha): array private function filterBehaviourallyUnchanged(array $files, string $sha): array
{ {
$remaining = []; $files = array_values($files);
$currentHashes = array_map($this->currentHash(...), $files);
$present = array_filter($currentHashes, static fn (?string $hash): bool => $hash !== null);
$indexes = array_keys($present);
$matches = $this->matchesAtSha($sha, array_map(static fn (int $index): string => $files[$index], $indexes), array_values($present));
$unchanged = [];
foreach ($files as $file) { foreach ($indexes as $position => $index) {
$currentHash = $this->currentHash($file); if ($matches[$position] ?? false) {
$unchanged[$index] = true;
if ($currentHash === null) {
$remaining[] = $file;
continue;
}
$baselineContent = $this->contentAtSha($sha, $file);
if ($baselineContent === null) {
$remaining[] = $file;
continue;
}
if ($currentHash !== ContentHash::ofContent($file, $baselineContent)) {
$remaining[] = $file;
} }
} }
return $remaining; return array_values(array_filter($files, static fn (int $index): bool => ! isset($unchanged[$index]), ARRAY_FILTER_USE_KEY));
} }
private function contentAtSha(string $sha, string $path): ?string /**
* @param list<string> $paths
* @param list<string> $hashes
* @return array<int, bool>
*/
private function matchesAtSha(string $sha, array $paths, array $hashes): array
{ {
return $this->git->show($sha, $path); if ($paths === []) {
return [];
}
$matches = [];
$compare = static function (int $position, ?string $content) use (&$matches, $paths, $hashes): void {
$matches[$position] = $content !== null && $hashes[$position] === ContentHash::ofContent($paths[$position], $content);
};
$repositoryPaths = array_map(fn (string $path): string => $this->gitPrefix().$path, $paths);
if (! $this->scan()->showEach($sha, $repositoryPaths, $compare)) {
foreach ($repositoryPaths as $position => $path) {
$compare($position, $this->git->show($sha, $path));
}
}
return $matches;
}
private function filterIgnoredOutsideProject(): void
{
if ($this->outsideProject === []) {
return;
}
$repositoryRoot = $this->git->repositoryRoot();
if ($repositoryRoot === null) {
return;
}
$git = new Git($repositoryRoot);
$this->outsideProject = $this->filterIgnoredWith($git, $this->outsideProject);
$this->outsideProjectDirty = array_intersect_key($this->outsideProjectDirty, $this->outsideProject);
} }
/** /**
@@ -170,30 +378,28 @@ final readonly class ChangedFiles
* @return array<string, true> * @return array<string, true>
*/ */
private function filterIgnored(array $candidates): array private function filterIgnored(array $candidates): array
{
return $this->filterIgnoredWith($this->git, $candidates);
}
/**
* @param array<string, true> $candidates
* @return array<string, true>
*/
private function filterIgnoredWith(Git $git, array $candidates): array
{ {
if ($candidates === []) { if ($candidates === []) {
return $candidates; return $candidates;
} }
$result = $this->git->result( $result = $git->checkIgnore(Arr::stringKeys($candidates));
['check-ignore', '--no-index', '-z', '--stdin'],
implode("\x00", array_keys($candidates)),
);
if ($result['exitCode'] !== 0 && $result['exitCode'] !== 1) { if ($result['exitCode'] !== 0 && $result['exitCode'] !== 1) {
throw $this->gitFailure($result); throw $this->gitFailure(['exitCode' => $result['exitCode'], 'output' => '', 'errorOutput' => $result['errorOutput']]);
} }
$output = $result['output']; foreach ($result['ignored'] as $ignored) {
unset($candidates[$ignored]);
if ($output === '') {
return $candidates;
}
foreach (explode("\x00", rtrim($output, "\x00")) as $ignored) {
if ($ignored !== '') {
unset($candidates[$ignored]);
}
} }
return $candidates; return $candidates;
@@ -274,7 +480,7 @@ final readonly class ChangedFiles
} }
} }
return array_keys($names); return Arr::stringKeys($names);
} }
public function hasRemote(): bool public function hasRemote(): bool
@@ -323,13 +529,13 @@ final readonly class ChangedFiles
*/ */
private function diffSinceSha(string $sha): array private function diffSinceSha(string $sha): array
{ {
$result = $this->scan()->result(['diff', '--name-only', '--no-renames', $sha.'..HEAD']); $result = $this->scan()->result(['diff', '--name-only', '--no-renames', '--no-relative', '-z', $sha.'..HEAD']);
if ($result['exitCode'] !== 0) { if ($result['exitCode'] !== 0) {
throw $this->gitFailure($result); throw $this->gitFailure($result);
} }
return $this->splitLines($result['output']); return $this->toProjectRelative($this->splitRecords($result['output']));
} }
/** /**
@@ -377,7 +583,7 @@ final readonly class ChangedFiles
$files[] = $path; $files[] = $path;
} }
return $files; return $this->toProjectRelative($files, fromWorkingTree: true);
} }
public function currentSha(): ?string public function currentSha(): ?string
@@ -407,6 +613,21 @@ final readonly class ChangedFiles
return new TiaGitFailed($error !== '' ? $error : sprintf('Git exited with code %d.', $result['exitCode'])); return new TiaGitFailed($error !== '' ? $error : sprintf('Git exited with code %d.', $result['exitCode']));
} }
/**
* @return array<int, string>
*/
private function splitRecords(string $output): array
{
if ($output === '') {
return [];
}
return array_values(array_filter(
explode("\x00", rtrim($output, "\x00")),
static fn (string $record): bool => $record !== '',
));
}
/** /**
* @return array<int, string> * @return array<int, string>
*/ */
+13
View File
@@ -115,4 +115,17 @@ final class Configuration
return $this; return $this;
} }
/**
* @param list<string>|null $patterns Project-relative globs to exclude, or null to disable read capture. Use watch() for excluded files that an existing watch pattern does not cover.
* @return $this
*/
public function withoutReadCapture(?array $patterns = null): self
{
/** @var WatchPatterns $watchPatterns */
$watchPatterns = Container::getInstance()->get(WatchPatterns::class);
$watchPatterns->excludeReads($patterns);
return $this;
}
} }
+235
View File
@@ -0,0 +1,235 @@
<?php
declare(strict_types=1);
namespace Pest\Plugins\Tia;
use PHPUnit\Event\Dispatcher;
use PHPUnit\Event\DispatchingEmitter;
use PHPUnit\Event\Emitter;
use PHPUnit\Event\Event;
use PHPUnit\Event\Facade as EventFacade;
use PHPUnit\Event\Telemetry\System;
use PHPUnit\Event\Telemetry\SystemCpuTimeMeter;
use PHPUnit\Event\Telemetry\SystemGarbageCollectorStatusProvider;
use PHPUnit\Event\Telemetry\SystemMemoryMeter;
use PHPUnit\Event\Telemetry\SystemStopWatch;
use PHPUnit\TextUI\CliArguments\Builder;
use PHPUnit\TextUI\CliArguments\XmlConfigurationFileFinder;
use PHPUnit\TextUI\XmlConfiguration\DefaultConfiguration;
use PHPUnit\TextUI\XmlConfiguration\Loader;
use Throwable;
/**
* @internal
*/
final readonly class ConfigurationFile
{
private const string SUPPRESSED = 'none';
private const array DEFAULT_NAMES = ['phpunit.xml', 'phpunit.dist.xml', 'phpunit.xml.dist'];
private const array VALUE_OPTIONS = ['--configuration', '--bootstrap', '--include-path', '--coverage-filter'];
/**
* @param list<string>|null $includePaths
* @param list<string> $coverageFilter
*/
private function __construct(
private ?string $path,
private bool $suppressed,
private ?string $bootstrap = null,
private ?array $includePaths = null,
private array $coverageFilter = [],
) {}
/**
* @param array<int, string> $arguments
*/
public static function fromArguments(array $arguments, ?string $generatedPath = null): self
{
try {
$configuration = new Builder(EventFacade::emitter())->fromParameters(self::configurationParameters($arguments));
} catch (Throwable) {
return self::projectDefault();
}
$bootstrap = $configuration->hasBootstrap() ? self::resolved($configuration->bootstrap()) : null;
$includePaths = $configuration->hasIncludePath()
? array_map(self::resolved(...), explode(PATH_SEPARATOR, $configuration->includePath()))
: null;
$coverageFilter = $configuration->hasCoverageFilter() ? $configuration->coverageFilter() : [];
if (! $configuration->hasConfigurationFile() && ! $configuration->useDefaultConfiguration()) {
return new self(null, true, $bootstrap, $includePaths, $coverageFilter);
}
$file = new XmlConfigurationFileFinder()->find($configuration);
$path = $file === false ? false : realpath($file);
if ($path !== false && $generatedPath !== null && $path === realpath($generatedPath)) {
return new self(null, false, $bootstrap, $includePaths, $coverageFilter);
}
return new self($path === false ? null : $path, false, $bootstrap, $includePaths, $coverageFilter);
}
public static function at(string $path): self
{
return new self($path, false);
}
public static function projectDefault(): self
{
return new self(null, false);
}
public function sourceScope(string $projectRoot): ?SourceScope
{
$path = $this->suppressed ? null : ($this->path ?? $this->defaultIn($projectRoot));
if ($path === null) {
return SourceScope::fromSource($projectRoot, DefaultConfiguration::create()->source(), $this->coverageFilter);
}
try {
$source = new Loader($this->silentEmitter())->load($path)->source();
} catch (Throwable) {
return null;
}
return SourceScope::fromSource($projectRoot, $source, $this->coverageFilter);
}
public function bootstrapFingerprint(string $projectRoot): ?string
{
return $this->bootstrap === null ? null : $this->relativeTo($projectRoot, $this->bootstrap);
}
public function includePathFingerprint(string $projectRoot): ?string
{
if ($this->includePaths === null) {
return null;
}
$paths = array_map(
fn (string $path): string => $this->relativeTo($projectRoot, $path),
$this->includePaths,
);
return implode("\0", $paths);
}
public function fingerprint(string $projectRoot): ?string
{
if ($this->suppressed) {
return self::SUPPRESSED;
}
$path = $this->path ?? $this->defaultIn($projectRoot);
if ($path === null || ! is_file($path)) {
return null;
}
$hash = @hash_file('xxh128', $path);
return $hash === false ? null : $this->relativeTo($projectRoot, $path).':'.$hash;
}
private function defaultIn(string $projectRoot): ?string
{
foreach (self::DEFAULT_NAMES as $name) {
if (is_file($projectRoot.DIRECTORY_SEPARATOR.$name)) {
return $projectRoot.DIRECTORY_SEPARATOR.$name;
}
}
return null;
}
private function relativeTo(string $projectRoot, string $path): string
{
$root = rtrim($this->withForwardSlashes(realpath($projectRoot) ?: $projectRoot), '/').'/';
$resolvedPath = $this->withForwardSlashes(self::resolved($path));
if ($resolvedPath.'/' === $root) {
return '.';
}
return str_starts_with($resolvedPath, $root) ? substr($resolvedPath, strlen($root)) : $resolvedPath;
}
/**
* @param array<int, string> $arguments
* @return list<string>
*/
private static function configurationParameters(array $arguments): array
{
$arguments = array_values($arguments);
$parameters = [];
foreach ($arguments as $index => $argument) {
if ($argument === '--no-configuration') {
$parameters[] = $argument;
continue;
}
$option = self::withLongConfigurationOption($argument);
foreach (self::VALUE_OPTIONS as $name) {
if ($option === $name && isset($arguments[$index + 1])) {
$parameters[] = $name;
$parameters[] = $arguments[$index + 1];
} elseif (str_starts_with($option, $name.'=')) {
$parameters[] = $name;
$parameters[] = substr($option, strlen($name.'='));
}
}
}
return $parameters;
}
private static function withLongConfigurationOption(string $argument): string
{
if ($argument === '-c') {
return '--configuration';
}
if (str_starts_with($argument, '-c')) {
return '--configuration='.substr($argument, 2);
}
return $argument;
}
private function silentEmitter(): Emitter
{
return new DispatchingEmitter(
new class implements Dispatcher
{
public function dispatch(Event $event): void {}
},
new System(
new SystemStopWatch,
new SystemMemoryMeter,
new SystemGarbageCollectorStatusProvider,
new SystemCpuTimeMeter,
),
);
}
private function withForwardSlashes(string $path): string
{
return DIRECTORY_SEPARATOR === '\\' ? str_replace('\\', '/', $path) : $path;
}
private static function resolved(string $path): string
{
$real = $path === '' ? false : realpath($path);
return $real === false ? $path : $real;
}
}
File diff suppressed because it is too large Load Diff
+65 -19
View File
@@ -4,16 +4,17 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia; namespace Pest\Plugins\Tia;
use Pest\Exceptions\GitTimedOut;
use Pest\Plugins\Tia\Contracts\Lockfile; use Pest\Plugins\Tia\Contracts\Lockfile;
use Pest\Support\Git;
use Symfony\Component\Process\Exception\ExceptionInterface as ProcessException; use Symfony\Component\Process\Exception\ExceptionInterface as ProcessException;
use Symfony\Component\Process\Process;
/** /**
* @internal * @internal
*/ */
final readonly class Fingerprint final readonly class Fingerprint
{ {
private const int SCHEMA_VERSION = 18; private const int SCHEMA_VERSION = 19;
/** /**
* @var array<int, class-string<Lockfile>> * @var array<int, class-string<Lockfile>>
@@ -23,23 +24,46 @@ final readonly class Fingerprint
]; ];
/** /**
* @param array<int, string> $arguments
* @return array{ * @return array{
* structural: array<string, int|string|null>, * structural: array<string, int|string|null>,
* environmental: array<string, int|string|null>, * environmental: array<string, int|string|null>,
* } * }
*/ */
public static function compute(string $projectRoot): array public static function compute(string $projectRoot, ?ConfigurationFile $configuration = null, array $arguments = []): array
{ {
$configuration ??= ConfigurationFile::projectDefault();
$structural = [
'schema' => self::SCHEMA_VERSION,
'composer_lock' => self::composerLockHash($projectRoot),
'phpunit_configuration' => $configuration->fingerprint($projectRoot),
'vite_config' => self::viteConfigHash($projectRoot),
'package_lock' => self::packageLockHash($projectRoot),
'js_config' => self::jsConfigHash($projectRoot),
...self::commandLineOverrides($projectRoot, $configuration),
];
$prefix = self::projectPrefix($projectRoot);
if ($prefix !== '') {
$structural['project_prefix'] = $prefix;
}
$externalRoots = ExternalSources::rootsFor($projectRoot, $arguments);
if ($externalRoots !== []) {
$structural['external_roots'] = hash('xxh128', serialize($externalRoots));
}
$includePaths = ExternalSources::includePaths($projectRoot, $arguments);
if ($includePaths !== []) {
$structural['include_path'] = hash('xxh128', serialize($includePaths));
}
return [ return [
'structural' => [ 'structural' => $structural,
'schema' => self::SCHEMA_VERSION,
'composer_lock' => self::composerLockHash($projectRoot),
'phpunit_xml' => self::trackedHash($projectRoot, 'phpunit.xml'),
'phpunit_xml_dist' => self::trackedHash($projectRoot, 'phpunit.xml.dist'),
'vite_config' => self::viteConfigHash($projectRoot),
'package_lock' => self::packageLockHash($projectRoot),
'js_config' => self::jsConfigHash($projectRoot),
],
'environmental' => [ 'environmental' => [
'php_minor' => PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION, 'php_minor' => PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION,
@@ -47,6 +71,17 @@ final readonly class Fingerprint
]; ];
} }
/**
* @return array<string, string>
*/
private static function commandLineOverrides(string $projectRoot, ConfigurationFile $configuration): array
{
return array_filter([
'phpunit_bootstrap' => $configuration->bootstrapFingerprint($projectRoot),
'phpunit_include_path' => $configuration->includePathFingerprint($projectRoot),
], fn (?string $value): bool => $value !== null);
}
/** /**
* @param array<string, mixed> $a * @param array<string, mixed> $a
* @param array<string, mixed> $b * @param array<string, mixed> $b
@@ -276,20 +311,31 @@ final readonly class Fingerprint
return $cache[$key]; return $cache[$key];
} }
if (! is_dir($projectRoot.'/.git') && ! is_file($projectRoot.'/.git')) { if (! self::isGitRepository($projectRoot)) {
return $cache[$key] = true; return $cache[$key] = true;
} }
$process = new Process(['git', 'check-ignore', '-q', '--', $relativePath], $projectRoot);
$process->setTimeout(5.0);
try { try {
$process->run(); $result = new Git($projectRoot)->checkIgnore([$relativePath]);
} catch (ProcessException) { } catch (ProcessException|GitTimedOut) {
return $cache[$key] = true; return $cache[$key] = true;
} }
return $cache[$key] = $process->getExitCode() !== 0; return $cache[$key] = $result['exitCode'] !== 0;
}
private static function projectPrefix(string $projectRoot): string
{
static $cache = [];
return $cache[$projectRoot] ??= new Git($projectRoot)->pathPrefix();
}
private static function isGitRepository(string $projectRoot): bool
{
static $cache = [];
return $cache[$projectRoot] ??= new Git($projectRoot)->isRepository();
} }
private static function contentHashOrNull(string $path): ?string private static function contentHashOrNull(string $path): ?string
+48 -23
View File
@@ -4,8 +4,10 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia; namespace Pest\Plugins\Tia;
use JsonException;
use Pest\Factories\TestCaseFactory; use Pest\Factories\TestCaseFactory;
use Pest\Factories\TestCaseMethodFactory; use Pest\Factories\TestCaseMethodFactory;
use Pest\Support\Arr;
use Pest\Support\Container; use Pest\Support\Container;
use Pest\Support\View; use Pest\Support\View;
use Pest\TestSuite; use Pest\TestSuite;
@@ -20,6 +22,10 @@ final class Graph
{ {
public const string WORKSPACE_BRANCH_PREFIX = '@workspace:'; public const string WORKSPACE_BRANCH_PREFIX = '@workspace:';
private const int LEGACY_SCHEMA = 1;
private const int SCHEMA = 2;
/** /**
* @var array<string, string> * @var array<string, string>
*/ */
@@ -589,7 +595,7 @@ final class Graph
{ {
$generated = []; $generated = [];
foreach ($this->fileIds as $path => $id) { foreach ($this->files as $id => $path) {
$hash = $this->livewireGeneratedHash($path); $hash = $this->livewireGeneratedHash($path);
if ($hash === null) { if ($hash === null) {
@@ -655,13 +661,7 @@ final class Graph
if (isset($handledBlade[$rel])) { if (isset($handledBlade[$rel])) {
continue; continue;
} }
if (! isset($this->fileIds[$rel])) { if (! isset($this->fileIds[$rel]) || $this->isFrameworkBootPath($rel)) {
if (! is_file($this->projectRoot.'/'.$rel)) {
continue;
}
$watchedPaths[] = $rel;
} elseif ($this->isFrameworkBootPath($rel)) {
$watchedPaths[] = $rel; $watchedPaths[] = $rel;
} }
} }
@@ -1132,7 +1132,7 @@ final class Graph
} }
} }
$names = array_keys($normalised); $names = Arr::stringKeys($normalised);
sort($names); sort($names);
$this->testInertiaComponents[$testRel] = $names; $this->testInertiaComponents[$testRel] = $names;
@@ -1162,7 +1162,7 @@ final class Graph
continue; continue;
} }
$keys = array_keys($names); $keys = Arr::stringKeys($names);
sort($keys); sort($keys);
$out[$path] = $keys; $out[$path] = $keys;
} }
@@ -1646,7 +1646,7 @@ final class Graph
{ {
$survivors = array_fill_keys($keep, true); $survivors = array_fill_keys($keep, true);
foreach (array_keys($this->baselines) as $branch) { foreach (Arr::stringKeys($this->baselines) as $branch) {
if (str_starts_with($branch, self::WORKSPACE_BRANCH_PREFIX)) { if (str_starts_with($branch, self::WORKSPACE_BRANCH_PREFIX)) {
continue; continue;
} }
@@ -1704,7 +1704,7 @@ final class Graph
*/ */
public static function branchesIn(string $json): array public static function branchesIn(string $json): array
{ {
$data = json_decode($json, true); $data = ByteSafeJson::decode($json);
if (! is_array($data) || ! is_array($data['baselines'] ?? null)) { if (! is_array($data) || ! is_array($data['baselines'] ?? null)) {
return []; return [];
@@ -1712,8 +1712,8 @@ final class Graph
$branches = []; $branches = [];
foreach (array_keys($data['baselines']) as $branch) { foreach (Arr::stringKeys($data['baselines']) as $branch) {
if (is_string($branch) && $branch !== '') { if ($branch !== '') {
$branches[] = $branch; $branches[] = $branch;
} }
} }
@@ -1721,11 +1721,35 @@ final class Graph
return $branches; return $branches;
} }
public static function decode(string $json, string $projectRoot): ?self /**
* @return array<array-key, mixed>|null
*/
private static function payload(string $json): ?array
{ {
$data = json_decode($json, true); $data = json_decode($json, true);
if (! is_array($data) || ($data['schema'] ?? null) !== 1) { if (! is_array($data)) {
return null;
}
if (($data['schema'] ?? null) === self::LEGACY_SCHEMA) {
return $data;
}
if (($data['schema'] ?? null) !== self::SCHEMA) {
return null;
}
$restored = ByteSafeJson::restore($data, $json);
return is_array($restored) ? $restored : null;
}
public static function decode(string $json, string $projectRoot): ?self
{
$data = self::payload($json);
if ($data === null) {
return null; return null;
} }
@@ -1824,8 +1848,8 @@ final class Graph
if (is_array($baseline['tree'] ?? null)) { if (is_array($baseline['tree'] ?? null)) {
foreach ($baseline['tree'] as $path => $hash) { foreach ($baseline['tree'] as $path => $hash) {
if (is_string($path) && is_string($hash)) { if (is_string($hash)) {
$tree[$path] = $hash; $tree[(string) $path] = $hash;
} }
} }
} }
@@ -1928,10 +1952,13 @@ final class Graph
return $out; return $out;
} }
public function encode(): ?string /**
* @throws JsonException
*/
public function encode(): string
{ {
$payload = [ $payload = [
'schema' => 1, 'schema' => self::SCHEMA,
'fingerprint' => $this->fingerprint, 'fingerprint' => $this->fingerprint,
'files' => $this->files, 'files' => $this->files,
'edges' => $this->edges, 'edges' => $this->edges,
@@ -1941,9 +1968,7 @@ final class Graph
'js_file_to_components' => $this->jsFileToComponents, 'js_file_to_components' => $this->jsFileToComponents,
]; ];
$json = json_encode($payload, JSON_UNESCAPED_SLASHES); return ByteSafeJson::encode($payload);
return $json === false ? null : $json;
} }
private function relative(string $path): ?string private function relative(string $path): ?string
+47 -34
View File
@@ -89,13 +89,16 @@ final class ReadCapture
private static function disable(): void private static function disable(): void
{ {
if (in_array(self::PROTOCOL, stream_get_wrappers(), true)) {
stream_wrapper_unregister(self::PROTOCOL);
}
if (self::$previousWrapper === null) { if (self::$previousWrapper === null) {
stream_wrapper_restore(self::PROTOCOL); stream_wrapper_restore(self::PROTOCOL);
return; return;
} }
stream_wrapper_unregister(self::PROTOCOL);
stream_wrapper_register(self::PROTOCOL, self::$previousWrapper); stream_wrapper_register(self::PROTOCOL, self::$previousWrapper);
} }
@@ -124,16 +127,22 @@ final class ReadCapture
public function dir_closedir(): bool public function dir_closedir(): bool
{ {
closedir($this->resource()); $this->forward('dir_closedir', function (mixed $resource): bool {
closedir($resource);
return true;
});
return true; return true;
} }
public function dir_opendir(string $path): bool public function dir_opendir(string $path, int $options): bool
{ {
$handle = $this->withOriginalWrapper(fn () => opendir($path, $this->context)); $handle = $this->withOriginalWrapper(fn (): mixed => self::$previousWrapper === null
? opendir($path, $this->context)
: $this->openDirectoryThroughPreviousWrapper(self::$previousWrapper, $path, $options));
if (! is_resource($handle)) { if ($handle === false) {
return false; return false;
} }
@@ -144,14 +153,18 @@ final class ReadCapture
public function dir_readdir(): string|false public function dir_readdir(): string|false
{ {
return readdir($this->resource()); $entry = $this->forward('dir_readdir', fn (mixed $resource): string|false => readdir($resource));
return is_string($entry) ? $entry : false;
} }
public function dir_rewinddir(): bool public function dir_rewinddir(): bool
{ {
rewinddir($this->resource()); return $this->forward('dir_rewinddir', function (mixed $resource): bool {
rewinddir($resource);
return true; return true;
}) === true;
} }
public function mkdir(string $path, int $mode, int $options): bool public function mkdir(string $path, int $mode, int $options): bool
@@ -286,21 +299,13 @@ final class ReadCapture
public function url_stat(string $path, int $flags): array|false public function url_stat(string $path, int $flags): array|false
{ {
return $this->withOriginalWrapper(function () use ($path, $flags): array|false { return $this->withOriginalWrapper(function () use ($path, $flags): array|false {
$isQuiet = ($flags & STREAM_URL_STAT_QUIET) !== 0; set_error_handler(static fn (): bool => true);
if (($flags & STREAM_URL_STAT_LINK) !== 0) { try {
if ($isQuiet && ! is_link($path) && ! file_exists($path)) { return ($flags & STREAM_URL_STAT_LINK) !== 0 ? lstat($path) : stat($path);
return false; } finally {
} restore_error_handler();
return @lstat($path);
} }
if ($isQuiet && ! file_exists($path)) {
return false;
}
return @stat($path);
}); });
} }
@@ -309,7 +314,7 @@ final class ReadCapture
*/ */
private function openNatively(string $path, string $mode, int $options): mixed private function openNatively(string $path, string $mode, int $options): mixed
{ {
return ($options & STREAM_REPORT_ERRORS) !== 0 return ($options & (STREAM_REPORT_ERRORS | self::STREAM_OPEN_FOR_INCLUDE)) !== 0
? fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context) ? fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context)
: @fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context); : @fopen($path, $mode, ($options & STREAM_USE_PATH) !== 0, $this->context);
} }
@@ -325,7 +330,25 @@ final class ReadCapture
$wrapper->context = $this->context; $wrapper->context = $this->context;
} }
if (! method_exists($wrapper, 'stream_open') || $wrapper->stream_open($path, $mode, $options, $openedPath) !== true) { if (! is_callable([$wrapper, 'stream_open']) || $wrapper->stream_open($path, $mode, $options, $openedPath) !== true) {
return false;
}
return $wrapper;
}
/**
* @param class-string $wrapperClass
*/
private function openDirectoryThroughPreviousWrapper(string $wrapperClass, string $path, int $options): object|false
{
$wrapper = new $wrapperClass;
if (property_exists($wrapper, 'context')) {
$wrapper->context = $this->context;
}
if (! is_callable([$wrapper, 'dir_opendir']) || $wrapper->dir_opendir($path, $options) !== true) {
return false; return false;
} }
@@ -341,16 +364,6 @@ final class ReadCapture
return str_contains($mode, 'r') || str_contains($mode, '+'); return str_contains($mode, 'r') || str_contains($mode, '+');
} }
/**
* @return resource
*/
private function resource(): mixed
{
assert(is_resource($this->handle));
return $this->handle;
}
/** /**
* @param Closure(resource): mixed $native * @param Closure(resource): mixed $native
*/ */
@@ -360,7 +373,7 @@ final class ReadCapture
return $native($this->handle); return $native($this->handle);
} }
if (! method_exists($this->handle, $method)) { if (! is_callable([$this->handle, $method])) {
return false; return false;
} }
+84 -3
View File
@@ -4,6 +4,9 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia; namespace Pest\Plugins\Tia;
use Closure;
use Pest\Support\Arr;
use Pest\Support\Container;
use Pest\TestSuite; use Pest\TestSuite;
use ReflectionClass; use ReflectionClass;
@@ -44,10 +47,19 @@ final class Recorder
private ?SourceScope $sourceScope = null; private ?SourceScope $sourceScope = null;
public function activate(): void private bool $coverageFilterApplied = false;
/** @var (Closure(string): bool)|null */
private ?Closure $recordsTestFile = null;
public function activate(?ConfigurationFile $configuration = null): void
{ {
$this->active = true; $this->active = true;
$this->captureCoverage = true; $this->captureCoverage = true;
if ($configuration instanceof ConfigurationFile) {
$this->restrictCoverageToSourceScope($configuration);
}
} }
public function activateLinkTracking(): void public function activateLinkTracking(): void
@@ -55,6 +67,14 @@ final class Recorder
$this->active = true; $this->active = true;
} }
/**
* @param Closure(string): bool $recordsTestFile
*/
public function recordOnly(Closure $recordsTestFile): void
{
$this->recordsTestFile = $recordsTestFile;
}
public function isActive(): bool public function isActive(): bool
{ {
return $this->active; return $this->active;
@@ -101,9 +121,15 @@ final class Recorder
return; return;
} }
if ($this->recordsTestFile instanceof Closure && ! ($this->recordsTestFile)($file)) {
return;
}
$this->currentTestFile = $file; $this->currentTestFile = $file;
ReadCapture::start($this); if ($this->watchPatterns()->isReadCaptureEnabled()) {
ReadCapture::start($this);
}
if ($this->classUsesDatabase($className)) { if ($this->classUsesDatabase($className)) {
$this->perTestUsesDatabase[$file] = true; $this->perTestUsesDatabase[$file] = true;
@@ -201,9 +227,34 @@ final class Recorder
return; return;
} }
$relative = $this->projectRelative($real);
if ($relative !== null && $this->watchPatterns()->excludesRead($relative)) {
return;
}
$this->linkSource($real); $this->linkSource($real);
} }
private function projectRelative(string $realPath): ?string
{
$root = rtrim(TestSuite::getInstance()->rootPath, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
if (! str_starts_with($realPath, $root)) {
return null;
}
return str_replace(DIRECTORY_SEPARATOR, '/', substr($realPath, strlen($root)));
}
private function watchPatterns(): WatchPatterns
{
$watchPatterns = Container::getInstance()->get(WatchPatterns::class);
assert($watchPatterns instanceof WatchPatterns);
return $watchPatterns;
}
private function classUsesDatabase(string $className): bool private function classUsesDatabase(string $className): bool
{ {
if (array_key_exists($className, $this->classUsesDatabaseCache)) { if (array_key_exists($className, $this->classUsesDatabaseCache)) {
@@ -301,7 +352,7 @@ final class Recorder
$out = []; $out = [];
foreach ($this->perTestInertiaComponents as $testFile => $components) { foreach ($this->perTestInertiaComponents as $testFile => $components) {
$names = array_keys($components); $names = Arr::stringKeys($components);
sort($names); sort($names);
$out[$testFile] = $names; $out[$testFile] = $names;
} }
@@ -382,6 +433,30 @@ final class Recorder
return $out; return $out;
} }
private function restrictCoverageToSourceScope(ConfigurationFile $configuration): void
{
if ($this->coverageFilterApplied || ! $this->driverAvailable() || $this->driver !== 'xdebug') {
return;
}
$projectRoot = TestSuite::getInstance()->rootPath;
$scope = $configuration->sourceScope($projectRoot);
if (! $scope instanceof SourceScope) {
return;
}
$excludedPaths = $scope->coverageExcludePaths($projectRoot);
if ($excludedPaths === []) {
return;
}
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_PATH_EXCLUDE, $excludedPaths);
$this->coverageFilterApplied = true;
}
private function sourceScope(): SourceScope private function sourceScope(): SourceScope
{ {
return $this->sourceScope ??= SourceScope::fromProjectRoot(TestSuite::getInstance()->rootPath); return $this->sourceScope ??= SourceScope::fromProjectRoot(TestSuite::getInstance()->rootPath);
@@ -391,6 +466,11 @@ final class Recorder
{ {
ReadCapture::stop(); ReadCapture::stop();
if ($this->coverageFilterApplied) {
\xdebug_set_filter(\XDEBUG_FILTER_CODE_COVERAGE, \XDEBUG_FILTER_NONE, []);
$this->coverageFilterApplied = false;
}
$this->currentTestFile = null; $this->currentTestFile = null;
$this->perTestFiles = []; $this->perTestFiles = [];
$this->perTestTables = []; $this->perTestTables = [];
@@ -399,6 +479,7 @@ final class Recorder
$this->classFileCache = []; $this->classFileCache = [];
$this->classUsesDatabaseCache = []; $this->classUsesDatabaseCache = [];
$this->sourceScope = null; $this->sourceScope = null;
$this->recordsTestFile = null;
$this->active = false; $this->active = false;
$this->captureCoverage = false; $this->captureCoverage = false;
} }
+129 -18
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia; namespace Pest\Plugins\Tia;
use PHPUnit\TextUI\Configuration\Registry; use PHPUnit\TextUI\Configuration\Registry;
use PHPUnit\TextUI\Configuration\Source;
use Throwable; use Throwable;
/** /**
@@ -33,9 +34,17 @@ final class SourceScope
'bootstrap/cache', 'bootstrap/cache',
]; ];
/**
* @return list<string>
*/
public static function noiseDirectories(): array
{
return [...self::TOP_LEVEL_NOISE, ...self::NESTED_NOISE];
}
/** /**
* @param list<string> $includes Absolute, normalised directory paths. * @param list<string> $includes Absolute, normalised directory paths.
* @param list<string> $excludes Absolute, normalised directory paths. * @param list<array{path: string, prefix: string, suffix: string}> $excludes Absolute, normalised directory paths with the file name prefix and suffix they apply to.
*/ */
public function __construct( public function __construct(
private readonly array $includes, private readonly array $includes,
@@ -44,30 +53,51 @@ final class SourceScope
public static function fromProjectRoot(string $projectRoot): self public static function fromProjectRoot(string $projectRoot): self
{ {
$phpunitIncludes = [];
$phpunitExcludes = [];
try { try {
$source = Registry::get()->source(); $source = Registry::get()->source();
foreach ($source->includeDirectories() as $dir) {
$phpunitIncludes[] = self::normalise($dir->path());
}
foreach ($source->excludeDirectories() as $dir) {
$phpunitExcludes[] = self::normalise($dir->path());
}
} catch (Throwable) { } catch (Throwable) {
// return self::build($projectRoot, [], []);
} }
return self::fromSource($projectRoot, $source, []);
}
/**
* @param list<string> $coverageFilter
*/
public static function fromSource(string $projectRoot, Source $source, array $coverageFilter): self
{
$phpunitIncludes = array_map(self::normalise(...), $coverageFilter);
$phpunitExcludes = [];
foreach ($source->includeDirectories() as $dir) {
$phpunitIncludes[] = self::normalise($dir->path());
}
foreach ($source->excludeDirectories() as $dir) {
$phpunitExcludes[] = [
'path' => self::normalise(@realpath($dir->path()) ?: $dir->path()),
'prefix' => $dir->prefix(),
'suffix' => $dir->suffix(),
];
}
return self::build($projectRoot, $phpunitIncludes, $phpunitExcludes);
}
/**
* @param list<string> $phpunitIncludes
* @param list<array{path: string, prefix: string, suffix: string}> $phpunitExcludes
*/
private static function build(string $projectRoot, array $phpunitIncludes, array $phpunitExcludes): self
{
$rootIncludes = self::topLevelProjectDirs($projectRoot); $rootIncludes = self::topLevelProjectDirs($projectRoot);
$includes = array_values(array_unique([...$phpunitIncludes, ...$rootIncludes])); $includes = array_values(array_unique([...$phpunitIncludes, ...$rootIncludes]));
$excludes = array_values(array_unique([ $excludes = [
...$phpunitExcludes, ...$phpunitExcludes,
...self::nestedNoiseDirs($projectRoot), ...self::nestedNoiseDirs($projectRoot),
])); ];
if ($includes === []) { if ($includes === []) {
$includes = [self::normalise($projectRoot)]; $includes = [self::normalise($projectRoot)];
@@ -100,6 +130,30 @@ final class SourceScope
return array_values(array_unique($out)); return array_values(array_unique($out));
} }
/**
* @return list<string>
*/
public function coverageExcludePaths(string $projectRoot): array
{
$out = [];
foreach (self::noiseDirectories() as $relative) {
$real = @realpath($projectRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative));
if ($real === false || ! is_dir($real)) {
continue;
}
$directory = self::normalise($real);
if ($this->rejectsEveryFileIn($directory) && ! $this->hasCaseTwin($directory)) {
$out[] = $directory.DIRECTORY_SEPARATOR;
}
}
return $out;
}
public function contains(string $absoluteFile): bool public function contains(string $absoluteFile): bool
{ {
if (isset($this->containsCache[$absoluteFile])) { if (isset($this->containsCache[$absoluteFile])) {
@@ -111,7 +165,9 @@ final class SourceScope
$candidate = self::normalise($candidate); $candidate = self::normalise($candidate);
foreach ($this->excludes as $excluded) { foreach ($this->excludes as $excluded) {
if ($this->startsWithDir($candidate, $excluded)) { if ($this->startsWithDir($candidate, $excluded['path'])
&& str_starts_with(basename($candidate), $excluded['prefix'])
&& str_ends_with(basename($candidate), $excluded['suffix'])) {
return $this->containsCache[$absoluteFile] = false; return $this->containsCache[$absoluteFile] = false;
} }
} }
@@ -166,7 +222,7 @@ final class SourceScope
} }
/** /**
* @return list<string> * @return list<array{path: string, prefix: string, suffix: string}>
*/ */
private static function nestedNoiseDirs(string $projectRoot): array private static function nestedNoiseDirs(string $projectRoot): array
{ {
@@ -174,12 +230,67 @@ final class SourceScope
foreach (self::NESTED_NOISE as $relative) { foreach (self::NESTED_NOISE as $relative) {
$abs = $projectRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative); $abs = $projectRoot.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $relative);
$out[] = self::normalise(@realpath($abs) ?: $abs); $out[] = ['path' => self::normalise(@realpath($abs) ?: $abs), 'prefix' => '', 'suffix' => ''];
} }
return $out; return $out;
} }
private function rejectsEveryFileIn(string $directory): bool
{
foreach ($this->includes as $included) {
if ($this->overlapsIgnoringCase($directory, $included) && ! $this->overlaps($directory, $included)) {
return false;
}
}
foreach ($this->excludes as $excluded) {
if ($excluded['prefix'] === '' && $excluded['suffix'] === '' && $this->startsWithDir($directory, $excluded['path'])) {
return true;
}
}
return array_all($this->includes, fn (string $included): bool => ! $this->overlapsIgnoringCase($directory, $included));
}
private function hasCaseTwin(string $directory): bool
{
$segments = explode(DIRECTORY_SEPARATOR, $directory);
$parent = array_shift($segments).DIRECTORY_SEPARATOR;
foreach ($segments as $segment) {
if ($segment === '') {
continue;
}
$entries = @scandir($parent);
if ($entries === false) {
return true;
}
foreach ($entries as $entry) {
if ($entry !== $segment && strtolower($entry) === strtolower($segment)) {
return true;
}
}
$parent = rtrim($parent, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$segment;
}
return false;
}
private function overlaps(string $first, string $second): bool
{
return $this->startsWithDir($first, $second) || $this->startsWithDir($second, $first);
}
private function overlapsIgnoringCase(string $first, string $second): bool
{
return $this->overlaps(strtolower($first), strtolower($second));
}
private static function normalise(string $path): string private static function normalise(string $path): string
{ {
return rtrim($path, '/\\'); return rtrim($path, '/\\');
+19 -18
View File
@@ -4,6 +4,9 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia; namespace Pest\Plugins\Tia;
use Pest\Exceptions\GitTimedOut;
use Pest\Support\Git;
/** /**
* @internal * @internal
*/ */
@@ -92,9 +95,6 @@ final class Storage
return null; return null;
} }
/**
* `git@github.com:foo/bar.git`, `ssh://git@github.com/foo/bar`
*/
private static function projectKey(string $projectRoot): string private static function projectKey(string $projectRoot): string
{ {
$origin = self::originIdentity($projectRoot); $origin = self::originIdentity($projectRoot);
@@ -102,6 +102,12 @@ final class Storage
$realpath = @realpath($projectRoot); $realpath = @realpath($projectRoot);
$input = $origin ?? ($realpath === false ? $projectRoot : $realpath); $input = $origin ?? ($realpath === false ? $projectRoot : $realpath);
$prefix = $origin === null ? '' : self::gitPrefix($projectRoot);
if ($prefix !== '') {
$input .= '/'.$prefix;
}
$hash = substr(hash('sha256', $input), 0, 16); $hash = substr(hash('sha256', $input), 0, 16);
$slug = self::slug(basename($projectRoot)); $slug = self::slug(basename($projectRoot));
@@ -116,12 +122,10 @@ final class Storage
return null; return null;
} }
// git@host:org/repo(.git)
if (preg_match('#^[\w.-]+@([\w.-]+):([\w./-]+?)(?:\.git)?/?$#', $url, $m) === 1) { if (preg_match('#^[\w.-]+@([\w.-]+):([\w./-]+?)(?:\.git)?/?$#', $url, $m) === 1) {
return strtolower($m[1].'/'.$m[2]); return strtolower($m[1].'/'.$m[2]);
} }
// scheme://[user@]host[:port]/org/repo(.git) — https, ssh, git, file
if (preg_match('#^[a-z]+://(?:[^@/]+@)?([^/:]+)(?::\d+)?/([\w./-]+?)(?:\.git)?/?$#i', $url, $m) === 1) { if (preg_match('#^[a-z]+://(?:[^@/]+@)?([^/:]+)(?::\d+)?/([\w./-]+?)(?:\.git)?/?$#i', $url, $m) === 1) {
return strtolower($m[1].'/'.$m[2]); return strtolower($m[1].'/'.$m[2]);
} }
@@ -131,23 +135,20 @@ final class Storage
private static function rawOriginUrl(string $projectRoot): ?string private static function rawOriginUrl(string $projectRoot): ?string
{ {
$config = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config'; try {
return new Git($projectRoot)->originUrl();
if (! is_file($config)) { } catch (GitTimedOut) {
return null; return null;
} }
}
$raw = @file_get_contents($config); private static function gitPrefix(string $projectRoot): string
{
if ($raw === false) { try {
return null; return new Git($projectRoot)->pathPrefix();
} catch (GitTimedOut) {
return '';
} }
if (preg_match('/\[remote "origin"\][^\[]*?url\s*=\s*(\S+)/s', $raw, $match) === 1) {
return trim($match[1]);
}
return null;
} }
private static function slug(string $name): string private static function slug(string $name): string
+2 -3
View File
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia\WatchDefaults; namespace Pest\Plugins\Tia\WatchDefaults;
use Composer\InstalledVersions;
use Pest\Browser\Support\BrowserTestIdentifier; use Pest\Browser\Support\BrowserTestIdentifier;
use Pest\Factories\TestCaseFactory; use Pest\Factories\TestCaseFactory;
use Pest\Plugins\Tia\Contracts\WatchDefault; use Pest\Plugins\Tia\Contracts\WatchDefault;
use Pest\Support\InstalledPackages;
use Pest\TestSuite; use Pest\TestSuite;
/** /**
@@ -17,8 +17,7 @@ final readonly class Browser implements WatchDefault
{ {
public function applicable(): bool public function applicable(): bool
{ {
return class_exists(InstalledVersions::class) return InstalledPackages::has('pestphp/pest-plugin-browser');
&& InstalledVersions::isInstalled('pestphp/pest-plugin-browser');
} }
public function defaults(string $projectRoot, string $testPath): array public function defaults(string $projectRoot, string $testPath): array
+3 -4
View File
@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia\WatchDefaults; namespace Pest\Plugins\Tia\WatchDefaults;
use Composer\InstalledVersions;
use Pest\Plugins\Tia\Contracts\WatchDefault; use Pest\Plugins\Tia\Contracts\WatchDefault;
use Pest\Support\InstalledPackages;
/** /**
* @internal * @internal
@@ -14,9 +14,8 @@ final readonly class Inertia implements WatchDefault
{ {
public function applicable(): bool public function applicable(): bool
{ {
return class_exists(InstalledVersions::class) return InstalledPackages::has('inertiajs/inertia-laravel')
&& (InstalledVersions::isInstalled('inertiajs/inertia-laravel') || InstalledPackages::has('rompetomp/inertia-bundle');
|| InstalledVersions::isInstalled('rompetomp/inertia-bundle'));
} }
public function defaults(string $projectRoot, string $testPath): array public function defaults(string $projectRoot, string $testPath): array
+2 -3
View File
@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia\WatchDefaults; namespace Pest\Plugins\Tia\WatchDefaults;
use Composer\InstalledVersions;
use Pest\Plugins\Tia\Contracts\WatchDefault; use Pest\Plugins\Tia\Contracts\WatchDefault;
use Pest\Support\InstalledPackages;
/** /**
* @internal * @internal
@@ -14,8 +14,7 @@ final readonly class Laravel implements WatchDefault
{ {
public function applicable(): bool public function applicable(): bool
{ {
return class_exists(InstalledVersions::class) return InstalledPackages::has('laravel/framework');
&& InstalledVersions::isInstalled('laravel/framework');
} }
public function defaults(string $projectRoot, string $testPath): array public function defaults(string $projectRoot, string $testPath): array
+2 -3
View File
@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia\WatchDefaults; namespace Pest\Plugins\Tia\WatchDefaults;
use Composer\InstalledVersions;
use Pest\Plugins\Tia\Contracts\WatchDefault; use Pest\Plugins\Tia\Contracts\WatchDefault;
use Pest\Support\InstalledPackages;
/** /**
* @internal * @internal
@@ -14,8 +14,7 @@ final readonly class Livewire implements WatchDefault
{ {
public function applicable(): bool public function applicable(): bool
{ {
return class_exists(InstalledVersions::class) return InstalledPackages::has('livewire/livewire');
&& InstalledVersions::isInstalled('livewire/livewire');
} }
public function defaults(string $projectRoot, string $testPath): array public function defaults(string $projectRoot, string $testPath): array
+2 -3
View File
@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia\WatchDefaults; namespace Pest\Plugins\Tia\WatchDefaults;
use Composer\InstalledVersions;
use Pest\Plugins\Tia\Contracts\WatchDefault; use Pest\Plugins\Tia\Contracts\WatchDefault;
use Pest\Support\InstalledPackages;
/** /**
* @internal * @internal
@@ -14,8 +14,7 @@ final readonly class Symfony implements WatchDefault
{ {
public function applicable(): bool public function applicable(): bool
{ {
return class_exists(InstalledVersions::class) return InstalledPackages::has('symfony/framework-bundle');
&& InstalledVersions::isInstalled('symfony/framework-bundle');
} }
public function defaults(string $projectRoot, string $testPath): array public function defaults(string $projectRoot, string $testPath): array
+47 -4
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia; namespace Pest\Plugins\Tia;
use Pest\Plugins\Tia\Contracts\WatchDefault; use Pest\Plugins\Tia\Contracts\WatchDefault;
use Pest\Support\Arr;
use Pest\TestSuite; use Pest\TestSuite;
/** /**
@@ -43,6 +44,13 @@ final class WatchPatterns
private bool $defaultsEnabled = true; private bool $defaultsEnabled = true;
/**
* @var list<string>
*/
private array $excludedReadPatterns = [];
private bool $readCaptureEnabled = true;
/** /**
* @var array<string, array{include: string, excludes: array<int, string>, allowDotfiles: bool}> * @var array<string, array{include: string, excludes: array<int, string>, allowDotfiles: bool}>
*/ */
@@ -110,6 +118,39 @@ final class WatchPatterns
])); ]));
} }
/**
* @param list<string>|null $patterns
*/
public function excludeReads(?array $patterns = null): void
{
if ($patterns === null) {
$this->readCaptureEnabled = false;
return;
}
$this->excludedReadPatterns = array_values(array_unique([
...$this->excludedReadPatterns,
...$patterns,
]));
}
public function isReadCaptureEnabled(): bool
{
return $this->readCaptureEnabled;
}
/**
* @param string $file Project-relative path.
*/
public function excludesRead(string $file): bool
{
return array_any(
$this->excludedReadPatterns,
fn (string $pattern): bool => $this->keyMatches($pattern, $file),
);
}
/** /**
* @param string $projectRoot Absolute path. * @param string $projectRoot Absolute path.
* @param array<int, string> $changedFiles Project-relative paths. * @param array<int, string> $changedFiles Project-relative paths.
@@ -133,7 +174,7 @@ final class WatchPatterns
} }
} }
return array_keys($matched); return Arr::stringKeys($matched);
} }
/** /**
@@ -144,17 +185,17 @@ final class WatchPatterns
{ {
$matched = []; $matched = [];
foreach ($patterns as $key => $dirs) { foreach (Arr::stringKeys($patterns) as $key) {
if (! $this->keyMatches($key, $file)) { if (! $this->keyMatches($key, $file)) {
continue; continue;
} }
foreach ($dirs as $dir) { foreach ($patterns[$key] as $dir) {
$matched[$dir] = true; $matched[$dir] = true;
} }
} }
return array_keys($matched); return Arr::stringKeys($matched);
} }
private function usesDefaultsFor(string $file): bool private function usesDefaultsFor(string $file): bool
@@ -279,6 +320,8 @@ final class WatchPatterns
$this->defaultPatterns = []; $this->defaultPatterns = [];
$this->excludedDefaultPatterns = []; $this->excludedDefaultPatterns = [];
$this->defaultsEnabled = true; $this->defaultsEnabled = true;
$this->excludedReadPatterns = [];
$this->readCaptureEnabled = true;
$this->parsed = []; $this->parsed = [];
$this->enabled = false; $this->enabled = false;
$this->locally = false; $this->locally = false;
+4 -1
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Pest\Repositories; namespace Pest\Repositories;
use Pest\Exceptions\ShouldNotHappen; use Pest\Exceptions\ShouldNotHappen;
use RuntimeException;
/** /**
* @internal * @internal
@@ -48,7 +49,9 @@ final readonly class Snapshot
@mkdir($directory, 0755, true); @mkdir($directory, 0755, true);
} }
file_put_contents($this->filename, $contents); if (@file_put_contents($this->filename, $contents) !== strlen($contents)) {
throw new RuntimeException(sprintf('Unable to write snapshot at [%s].', $this->path()));
}
return $this; return $this;
} }
+14 -9
View File
@@ -13,6 +13,8 @@ use Pest\TestSuite;
*/ */
final class SnapshotRepository final class SnapshotRepository
{ {
private const int MAX_FILENAME_BYTES = 255;
private static ?string $key = null; private static ?string $key = null;
private static int $ordinal = 0; private static int $ordinal = 0;
@@ -95,15 +97,18 @@ final class SnapshotRepository
$relativePath = substr($testFile, strlen($startPath)); $relativePath = substr($testFile, strlen($startPath));
$relativePath = substr($relativePath, 0, (int) strrpos($relativePath, '.')); $relativePath = substr($relativePath, 0, (int) strrpos($relativePath, '.'));
return new Snapshot( $directory = $this->testsPath.'/'.$this->snapshotsPath.$relativePath;
sprintf( $description = TestSuite::getInstance()->getDescription().$suffix;
'%s/%s%s.snap', $extension = '.snap';
$this->testsPath.'/'.$this->snapshotsPath.$relativePath, $filename = $description.$extension;
TestSuite::getInstance()->getDescription(),
$suffix, if (strlen($filename) > self::MAX_FILENAME_BYTES && ! is_file($directory.'/'.$filename)) {
), $digest = '__'.hash('xxh128', $description);
dirname($this->testsPath).'/', $prefix = mb_strcut($description, 0, self::MAX_FILENAME_BYTES - strlen($digest.$extension), 'UTF-8');
); $filename = $prefix.$digest.$extension;
}
return new Snapshot($directory.'/'.$filename, dirname($this->testsPath).'/');
} }
private function synchronize(): void private function synchronize(): void
+7 -3
View File
@@ -7,6 +7,7 @@ namespace Pest\Restarters;
use Composer\XdebugHandler\XdebugHandler; use Composer\XdebugHandler\XdebugHandler;
use Pest\Contracts\Restarter; use Pest\Contracts\Restarter;
use Pest\Plugins\Tia; use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\Fingerprint; use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph; use Pest\Plugins\Tia\Graph;
use Pest\Plugins\Tia\Storage; use Pest\Plugins\Tia\Storage;
@@ -86,10 +87,13 @@ final class XdebugRestarter implements Restarter
return false; return false;
} }
return $this->tiaWillReplay($projectRoot); return $this->tiaWillReplay($projectRoot, $arguments);
} }
private function tiaWillReplay(string $projectRoot): bool /**
* @param array<int, string> $arguments
*/
private function tiaWillReplay(string $projectRoot, array $arguments): bool
{ {
$path = Storage::tempDir($projectRoot).DIRECTORY_SEPARATOR.Tia::KEY_GRAPH; $path = Storage::tempDir($projectRoot).DIRECTORY_SEPARATOR.Tia::KEY_GRAPH;
@@ -111,7 +115,7 @@ final class XdebugRestarter implements Restarter
return Fingerprint::structuralMatches( return Fingerprint::structuralMatches(
$graph->fingerprint(), $graph->fingerprint(),
Fingerprint::compute($projectRoot), Fingerprint::compute($projectRoot, ConfigurationFile::fromArguments($arguments), $arguments),
); );
} }
} }
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Pest\Subscribers;
use PHPUnit\Event\TestRunner\EventFacadeSealed;
use PHPUnit\Event\TestRunner\EventFacadeSealedSubscriber;
final readonly class EnsureCommandLineIncludePathComesFirst implements EventFacadeSealedSubscriber
{
/**
* @var list<string>
*/
private array $directories;
public function __construct(string $includePath)
{
$this->directories = array_values(array_filter(
explode(PATH_SEPARATOR, $includePath),
fn (string $directory): bool => $directory !== '',
));
}
public function notify(EventFacadeSealed $event): void
{
$this->apply();
}
public function apply(): void
{
if ($this->directories === []) {
return;
}
$otherDirectories = array_filter(
explode(PATH_SEPARATOR, (string) get_include_path()),
fn (string $directory): bool => ! in_array($directory, $this->directories, true),
);
ini_set('include_path', implode(PATH_SEPARATOR, [...$this->directories, ...$otherDirectories]));
}
}
+9
View File
@@ -9,6 +9,15 @@ namespace Pest\Support;
*/ */
final class Arr final class Arr
{ {
/**
* @param array<array-key, mixed> $array
* @return list<string>
*/
public static function stringKeys(array $array): array
{
return array_map(strval(...), array_keys($array));
}
/** /**
* @param array<array-key, mixed> $array * @param array<array-key, mixed> $array
*/ */
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
/**
* @internal
*/
final class ComposerProject
{
public static function rootPath(string $autoloadPath): string
{
$vendorPath = dirname($autoloadPath);
$vendorPath = realpath($vendorPath) ?: $vendorPath;
$rootPath = dirname($vendorPath);
$metadataPath = $vendorPath.'/composer/installed.php';
if (! is_file($metadataPath)) {
return $rootPath;
}
$installed = require $metadataPath;
$root = is_array($installed) ? ($installed['root'] ?? null) : null;
$installPath = is_array($root) ? ($root['install_path'] ?? null) : null;
if (! is_string($installPath)) {
return $rootPath;
}
return realpath($installPath) ?: $rootPath;
}
}
+274 -7
View File
@@ -4,6 +4,9 @@ declare(strict_types=1);
namespace Pest\Support; namespace Pest\Support;
use Closure;
use Pest\Exceptions\GitTimedOut;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
/** /**
@@ -13,6 +16,8 @@ final readonly class Git
{ {
private const float TIMEOUT = 5.0; private const float TIMEOUT = 5.0;
private const int BATCH_BYTES = 8_388_608;
public function __construct( public function __construct(
private ?string $directory = null, private ?string $directory = null,
private float $timeout = self::TIMEOUT, private float $timeout = self::TIMEOUT,
@@ -49,6 +54,22 @@ final readonly class Git
return $output === '' ? null : $output; return $output === '' ? null : $output;
} }
/**
* @param array<int, string> $arguments
*/
private function outputLine(array $arguments): ?string
{
$output = $this->raw($arguments);
if ($output === null) {
return null;
}
$line = str_ends_with($output, "\n") ? substr($output, 0, -1) : $output;
return $line === '' ? null : $line;
}
/** /**
* @param array<int, string> $arguments * @param array<int, string> $arguments
*/ */
@@ -57,20 +78,45 @@ final readonly class Git
return $this->result($arguments)['exitCode'] === 0; return $this->result($arguments)['exitCode'] === 0;
} }
/**
* @param array<int, string> $paths
* @return array{exitCode: int, ignored: array<int, string>, errorOutput: string}
*/
public function checkIgnore(array $paths): array
{
$result = $this->result(
['check-ignore', '-z', '--stdin'],
implode("\x00", array_map(static fn (string $path): string => './'.$path, $paths)),
);
$ignored = [];
foreach (explode("\x00", rtrim($result['output'], "\x00")) as $path) {
if ($path !== '') {
$ignored[] = str_starts_with($path, './') ? substr($path, 2) : $path;
}
}
return ['exitCode' => $result['exitCode'], 'ignored' => $ignored, 'errorOutput' => $result['errorOutput']];
}
/** /**
* @param array<int, string> $arguments * @param array<int, string> $arguments
* @return array{exitCode: int, output: string, errorOutput: string} * @return array{exitCode: int, output: string, errorOutput: string}
*/ */
public function result(array $arguments, ?string $input = null): array public function result(array $arguments, ?string $input = null): array
{ {
$process = new Process(['git', ...$arguments], $this->directory); $process = $this->process($arguments);
$process->setTimeout($this->timeout);
if ($input !== null) { if ($input !== null) {
$process->setInput($input); $process->setInput($input);
} }
$process->run(); try {
$process->run();
} catch (ProcessTimedOutException) {
throw new GitTimedOut($arguments, $this->timeout);
}
return [ return [
'exitCode' => $process->getExitCode() ?? 1, 'exitCode' => $process->getExitCode() ?? 1,
@@ -79,6 +125,17 @@ final readonly class Git
]; ];
} }
/**
* @param array<int, string> $arguments
*/
private function process(array $arguments): Process
{
$process = new Process(['git', ...$arguments], $this->directory, ['GIT_LITERAL_PATHSPECS' => '0', 'LC_ALL' => 'C', 'LANGUAGE' => '']);
$process->setTimeout($this->timeout);
return $process;
}
public function isRepository(): bool public function isRepository(): bool
{ {
return $this->succeeds(['rev-parse', '--git-dir']); return $this->succeeds(['rev-parse', '--git-dir']);
@@ -104,14 +161,224 @@ final readonly class Git
return $this->raw(['show', $sha.':'.$path]); return $this->raw(['show', $sha.':'.$path]);
} }
public function subdirectoryPrefix(): ?string /**
* @param list<string> $paths
* @param Closure(int, string|null): void $receive
*/
public function showEach(string $sha, array $paths, Closure $receive): bool
{ {
$prefix = $this->output(['rev-parse', '--show-prefix']); $batched = [];
if ($prefix === null) { foreach ($paths as $position => $path) {
if ($this->fitsBatchLine($path)) {
$batched[] = $position;
} else {
$receive($position, $this->show($sha, $path));
}
}
if ($batched === []) {
return true;
}
$objects = $this->batchCheck($sha, array_map(static fn (int $position): string => $paths[$position], $batched));
if ($objects === null) {
return false;
}
$blobs = [];
foreach ($objects as $line => $object) {
$position = $batched[$line];
if ($object === null) {
$receive($position, null);
} elseif ($object['type'] !== 'blob') {
$receive($position, $this->show($sha, $paths[$position]));
} else {
$blobs[$position] = $object;
}
}
return array_all($this->groupBlobs($blobs), fn (array $group): bool => $this->readBlobs($group, $receive));
}
/**
* @param list<string> $paths
* @return list<array{oid: string, type: string, bytes: int}|null>|null
*/
private function batchCheck(string $sha, array $paths): ?array
{
$result = $this->result(['cat-file', '--batch-check'], implode('', array_map(static fn (string $path): string => $sha.':'.$path."\n", $paths)));
$headers = $result['exitCode'] === 0 ? explode("\n", $result['output']) : [];
if (array_pop($headers) !== '' || count($headers) !== count($paths)) {
return null; return null;
} }
return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/'); $objects = [];
foreach ($headers as $header) {
$object = $this->parseCheckLine($header);
if ($object === false) {
return null;
}
$objects[] = $object;
}
return $objects;
}
/**
* @return array{oid: string, type: string, bytes: int}|false|null
*/
private function parseCheckLine(string $header): array|false|null
{
if (preg_match('/^([0-9a-f]+) ([a-z]+) (\d+)$/', $header, $matches) !== 1) {
return str_ends_with($header, ' missing') || str_ends_with($header, ' ambiguous') ? null : false;
}
return ['oid' => $matches[1], 'type' => $matches[2], 'bytes' => (int) $matches[3] + strlen($header) + 2];
}
/**
* @param array<int, array{oid: string, type: string, bytes: int}> $blobs
* @return list<non-empty-array<int, string>>
*/
private function groupBlobs(array $blobs): array
{
$groups = [];
$group = [];
$groupBytes = 0;
foreach ($blobs as $position => $blob) {
if ($group !== [] && $groupBytes + $blob['bytes'] > self::BATCH_BYTES) {
$groups[] = $group;
$group = [];
$groupBytes = 0;
}
$group[$position] = $blob['oid'];
$groupBytes += $blob['bytes'];
}
if ($group !== []) {
$groups[] = $group;
}
return $groups;
}
private function fitsBatchLine(string $path): bool
{
return ! str_contains($path, "\n") && ! str_ends_with($path, "\r");
}
/**
* @param non-empty-array<int, string> $blobs
* @param Closure(int, string|null): void $receive
*/
private function readBlobs(array $blobs, Closure $receive): bool
{
$arguments = ['cat-file', '--batch'];
$process = $this->process($arguments);
$process->setInput(implode("\n", $blobs)."\n");
$process->start();
try {
return $this->streamBlobs($process, $blobs, $receive);
} catch (ProcessTimedOutException) {
throw new GitTimedOut($arguments, $this->timeout);
}
}
/**
* @param non-empty-array<int, string> $blobs
* @param Closure(int, string|null): void $receive
*/
private function streamBlobs(Process $process, array $blobs, Closure $receive): bool
{
$positions = array_keys($blobs);
$buffer = '';
$next = 0;
foreach ($process->getIterator(Process::ITER_SKIP_ERR) as $chunk) {
$buffer .= $chunk;
while ($next < count($positions) && ($blob = $this->takeBlob($buffer)) !== null) {
$position = $positions[$next++];
if ($blob === false || $blob['oid'] !== $blobs[$position]) {
$process->stop(0);
return false;
}
$receive($position, $blob['content']);
}
}
$process->wait();
return $next === count($positions) && $buffer === '' && $process->getExitCode() === 0;
}
/**
* @return array{oid: string, content: string}|false|null
*/
private function takeBlob(string &$buffer): array|false|null
{
$headerEnd = strpos($buffer, "\n");
if ($headerEnd === false) {
return null;
}
if (preg_match('/^([0-9a-f]+) blob (\d+)$/', substr($buffer, 0, $headerEnd), $matches) !== 1) {
return false;
}
$end = $headerEnd + 1 + (int) $matches[2];
if (strlen($buffer) <= $end) {
return null;
}
if ($buffer[$end] !== "\n") {
return false;
}
$content = substr($buffer, $headerEnd + 1, (int) $matches[2]);
$buffer = substr($buffer, $end + 1);
return ['oid' => $matches[1], 'content' => $content];
}
public function repositoryRoot(): ?string
{
$root = $this->outputLine(['rev-parse', '--show-toplevel']);
return $root === null ? null : rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $root), '/');
}
public function pathPrefix(): string
{
$prefix = $this->outputLine(['rev-parse', '--show-prefix']);
if ($prefix === null) {
return '';
}
$prefix = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $prefix), '/');
return $prefix === '' ? '' : $prefix.'/';
}
public function originUrl(): ?string
{
return $this->output(['config', '--get', 'remote.origin.url']);
} }
} }
+55
View File
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Pest\Support;
use Composer\InstalledVersions;
final readonly class InstalledPackages
{
/**
* @param array<int, array{root: array{install_path?: string}, versions: array<string, array{dev_requirement?: bool}>}> $installedSets
*/
public function __construct(private array $installedSets) {}
public static function fromComposer(): self
{
if (! class_exists(InstalledVersions::class)) {
return new self([]);
}
/** @var array<int, array{root: array{install_path?: string}, versions: array<string, array{dev_requirement?: bool}>}> $installedSets */
$installedSets = InstalledVersions::getAllRawData();
return new self($installedSets);
}
public static function has(string $package, bool $includeDevRequirements = true): bool
{
return self::fromComposer()->contains($package, $includeDevRequirements);
}
public function contains(string $package, bool $includeDevRequirements = true): bool
{
foreach ($this->installedSets as $installedSet) {
if ($this->isBundledInPhar($installedSet)) {
continue;
}
if (isset($installedSet['versions'][$package])) {
return $includeDevRequirements || ($installedSet['versions'][$package]['dev_requirement'] ?? false) === false;
}
}
return false;
}
/**
* @param array{root: array{install_path?: string}} $installedSet
*/
private function isBundledInPhar(array $installedSet): bool
{
return str_starts_with($installedSet['root']['install_path'] ?? '', 'phar://');
}
}
+14 -16
View File
@@ -46,33 +46,31 @@ final class GitDirtyTestCaseFilter implements TestCaseFilter
private function loadChangedFiles(): void private function loadChangedFiles(): void
{ {
$status = new Git(timeout: 60.0)->raw(['status', '--short', '--', '*.php']); $git = new Git($this->projectRoot, timeout: 60.0);
$status = $git->raw(['status', '--porcelain=v1', '-z', '--no-renames', '--', '*.php']);
$prefix = $git->raw(['rev-parse', '--show-prefix']);
if ($status === null) { if ($status === null || $prefix === null) {
throw new MissingDependency('Filter by dirty files', 'git'); throw new MissingDependency('Filter by dirty files', 'git');
} }
$output = preg_split('/\R+/', $status, flags: PREG_SPLIT_NO_EMPTY); $pathOffset = 3 + strlen(rtrim($prefix, "\r\n"));
assert(is_array($output));
$dirtyFiles = []; $dirtyFiles = [];
foreach ($output as $dirtyFile) { foreach (explode("\0", $status) as $entry) {
$dirtyFiles[substr($dirtyFile, 3)] = trim(substr($dirtyFile, 0, 3)); if ($entry === '' || trim(substr($entry, 0, 2)) === 'D') {
continue;
}
$dirtyFiles[] = substr($entry, $pathOffset);
} }
$dirtyFiles = array_filter($dirtyFiles, fn (string $status): bool => $status !== 'D');
$dirtyFiles = array_map(
fn (string $file, string $status): string => in_array($status, ['R', 'RM'], true)
? explode(' -> ', $file)[1]
: $file, array_keys($dirtyFiles), $dirtyFiles,
);
$dirtyFiles = array_filter( $dirtyFiles = array_filter(
$dirtyFiles, $dirtyFiles,
fn (string $file): bool => str_starts_with('.'.DIRECTORY_SEPARATOR.$file, TestSuite::getInstance()->testPath) fn (string $file): bool => (
str_starts_with('.'.DIRECTORY_SEPARATOR.$file, TestSuite::getInstance()->testPath)
|| str_starts_with($file, TestSuite::getInstance()->testPath) || str_starts_with($file, TestSuite::getInstance()->testPath)
) && is_file($this->projectRoot.DIRECTORY_SEPARATOR.$file)
); );
$dirtyFiles = array_values($dirtyFiles); $dirtyFiles = array_values($dirtyFiles);
+4
View File
@@ -13,6 +13,10 @@ use Tests\TestCase;
| |
*/ */
if (! class_exists(TestCase::class)) {
require_once __DIR__.'/TestCase.php';
}
pest()->extend(TestCase::class)->in('Feature'); pest()->extend(TestCase::class)->in('Feature');
/* /*
@@ -54,7 +54,7 @@
EXECUTION OPTIONS: EXECUTION OPTIONS:
--parallel ........................................... Run tests in parallel --parallel ........................................... Run tests in parallel
--update-snapshots Update snapshots for tests using the "toMatchSnapshot" expectation --update-snapshots Update snapshots for tests using the "toMatchSnapshot" expectation
--update-shards Update shards.json with test timing data for time-balanced sharding --update-shards Update the shards file with timing data for time-balanced sharding
--globals-backup ................. Backup and restore $GLOBALS for each test --globals-backup ................. Backup and restore $GLOBALS for each test
--static-backup ......... Backup and restore static properties for each test --static-backup ......... Backup and restore static properties for each test
--strict-coverage ................... Be strict about code coverage metadata --strict-coverage ................... Be strict about code coverage metadata
+480 -4
View File
@@ -33,6 +33,8 @@
✓ matching describe block names → outer → middle → it should not call afterEach functions for sibling describe blocks with the same name ✓ matching describe block names → outer → middle → it should not call afterEach functions for sibling describe blocks with the same name
✓ matching describe block names → outer → inner → it does not get executed before the test ✓ matching describe block names → outer → inner → it does not get executed before the test
✓ matching describe block names → outer → inner → it should not call afterEach functions for descendent of sibling describe blocks with the same name ✓ matching describe block names → outer → inner → it should not call afterEach functions for descendent of sibling describe blocks with the same name
✓ hierarchical test naming → block one → the same name → it does not call afterEach from sibling describe with same name
✓ hierarchical test naming → block two → the same name → it correctly calls afterEach from own describe hierarchy
PASS Tests\Features\Assignee PASS Tests\Features\Assignee
✓ it may be associated with an assignee [@nunomaduro, @taylorotwell] ✓ it may be associated with an assignee [@nunomaduro, @taylorotwell]
@@ -56,6 +58,8 @@
✓ matching name → it should not call the before each on the describe block with the same name ✓ matching name → it should not call the before each on the describe block with the same name
✓ called on all tests → beforeEach should be called ✓ called on all tests → beforeEach should be called
✓ called on all tests → beforeEach should be called for all tests ✓ called on all tests → beforeEach should be called for all tests
✓ hierarchical test naming → block one → the same name → it does not call beforeEach from sibling describe with same name
✓ hierarchical test naming → block two → the same name → it correctly calls beforeEach from own describe hierarchy
PASS Tests\Features\BeforeEachProxiesToTestCallWithExpectations PASS Tests\Features\BeforeEachProxiesToTestCallWithExpectations
✓ runs 1 ✓ runs 1
@@ -73,6 +77,14 @@
↓ is marked as todo 3 ↓ is marked as todo 3
↓ shouldBeMarkedAsTodo ↓ shouldBeMarkedAsTodo
PASS Tests\Features\Configuration
✓ preserves an existing .pest.xml file with dataset "explicit configuration"
✓ preserves an existing .pest.xml file with dataset "discovered configuration"
✓ preserves an existing .pest.xml file with dataset "generated configuration"
✓ removes the generated configuration when it finishes with dataset "sequential"
✓ removes the generated configuration when it finishes with dataset "parallel"
✓ preserves a replacement for the generated configuration
WARN Tests\Features\Coverage WARN Tests\Features\Coverage
✓ it has plugin ✓ it has plugin
- it adds coverage if --coverage exist → Coverage is not available - it adds coverage if --coverage exist → Coverage is not available
@@ -327,6 +339,8 @@
✓ depends on describe using with → foo with (3) ✓ depends on describe using with → foo with (3)
✓ depends on describe using with → bar with (3) ✓ depends on describe using with → bar with (3)
✓ with test after describe → it should run the before each ✓ with test after describe → it should run the before each
✓ sibling describes may share the same it() description → block one → it can be created
✓ sibling describes may share the same it() description → block two → it can be created
PASS Tests\Features\DescriptionLess PASS Tests\Features\DescriptionLess
✓ get 'foo' ✓ get 'foo'
@@ -348,6 +362,7 @@
✓ it catch exceptions ✓ it catch exceptions
✓ it catch exceptions and messages ✓ it catch exceptions and messages
✓ it catch exceptions, messages and code ✓ it catch exceptions, messages and code
✓ it catch exceptions by interface
✓ it can just define the message ✓ it can just define the message
✓ it can just define the code ✓ it can just define the code
✓ it not catch exceptions if given condition is false ✓ it not catch exceptions if given condition is false
@@ -401,6 +416,12 @@
✓ it works with nested properties ✓ it works with nested properties
✓ it works with higher order tests ✓ it works with higher order tests
PASS Tests\Features\Expect\LongSnapshotNames
✓ creates and matches snapshots with long dataset labels
PASS Tests\Features\Expect\SnapshotWriteFailure
✓ reports a missing snapshot that cannot be written
PASS Tests\Features\Expect\each PASS Tests\Features\Expect\each
✓ an exception is thrown if the the type is not iterable ✓ an exception is thrown if the the type is not iterable
✓ it expects on each item ✓ it expects on each item
@@ -1001,6 +1022,8 @@
✓ failures with multi-dimensional arrays and custom message ✓ failures with multi-dimensional arrays and custom message
✓ not failures ✓ not failures
✓ not failures with multi-dimensional arrays ✓ not failures with multi-dimensional arrays
✓ not pass with multi-dimensional arrays
✓ not failures with only multi-dimensional arrays
PASS Tests\Features\Expect\toHaveLength PASS Tests\Features\Expect\toHaveLength
✓ it passes with ('Fortaleza') ✓ it passes with ('Fortaleza')
@@ -1179,8 +1202,11 @@
✓ failures 6 ✓ failures 6
✓ failures 7 ✓ failures 7
✓ failures 8 ✓ failures 8
✓ failures 9
✓ failures 10
✓ failures with custom message ✓ failures with custom message
✓ not failures ✓ not failures
✓ not failures with interface
✓ closure missing parameter ✓ closure missing parameter
✓ closure missing type-hint ✓ closure missing type-hint
✓ it can handle a non-defined exception ✓ it can handle a non-defined exception
@@ -1302,10 +1328,11 @@
… a "describe" group of tests → it is incompleted … a "describe" group of tests → it is incompleted
PASS Tests\Features\Init PASS Tests\Features\Init
✓ init creates a suite when the tests directory is missing ✓ init creates a runnable suite when the tests directory is missing
✓ init creates a suite when --init is not the first argument ✓ init creates a suite when --init is not the first argument
✓ init creates a suite when --init is passed with a value ✓ init creates a suite when --init is passed with a value
✓ a missing tests directory does not crash while resolving tia state ✓ a missing tests directory does not crash while resolving tia state
✓ init writes the plain stubs when only a tool bundled in a PHAR installs Laravel
PASS Tests\Features\Issue PASS Tests\Features\Issue
✓ it may be associated with an issue #1, #2 ✓ it may be associated with an issue #1, #2
@@ -1380,6 +1407,10 @@
! notice → This is a notice description // tests/Features/Notices.php:6 ! notice → This is a notice description // tests/Features/Notices.php:6
! a "describe" group of tests → notice → This is a notice description // tests/Features/Notices.php:13 ! a "describe" group of tests → notice → This is a notice description // tests/Features/Notices.php:13
PASS Tests\Features\Only
✓ limits focus to the invocation that discovers it with dataset "sequential"
✓ limits focus to the invocation that discovers it with dataset "parallel"
PASS Tests\Features\Pr PASS Tests\Features\Pr
✓ it may be associated with an pr #1, #2 ✓ it may be associated with an pr #1, #2
✓ nested → it may be associated with an pr #1, #4, #5, #6, #3 ✓ nested → it may be associated with an pr #1, #4, #5, #6, #3
@@ -1802,6 +1833,13 @@
✓ compute comparable coverage with (32.53333333333333, 32.5) ✓ compute comparable coverage with (32.53333333333333, 32.5)
✓ compute comparable coverage with (32.57777771232132, 32.5) ✓ compute comparable coverage with (32.57777771232132, 32.5)
✓ compute comparable coverage with (100.0, 100.0) ✓ compute comparable coverage with (100.0, 100.0)
✓ coverage options accept a space separated value with dataset "min with equals sign"
✓ coverage options accept a space separated value with dataset "min with space"
✓ coverage options accept a space separated value with dataset "exactly with equals sign"
✓ coverage options accept a space separated value with dataset "exactly with space"
✓ coverage options accept a space separated value with dataset "both with space"
✓ coverage options do not consume arguments owned by phpunit
✓ value less coverage options do not consume the next argument
PASS Tests\Plugins\Traits PASS Tests\Plugins\Traits
✓ it allows global uses ✓ it allows global uses
@@ -1836,6 +1874,15 @@
PASS Tests\Unit\Overrides\ThrowableBuilder PASS Tests\Unit\Overrides\ThrowableBuilder
✓ collision editor can be added to the stack trace ✓ collision editor can be added to the stack trace
PASS Tests\Unit\Plugins\Actions\CallsAddsOutput
✓ exit code observers run after every output plugin
✓ exit code observers receive unchanged codes when there are no output plugins with (0)
✓ exit code observers receive unchanged codes when there are no output plugins with (1)
✓ exit code observers receive unchanged codes when there are no output plugins with (2)
✓ exit code observers receive unchanged codes when there are no output plugins with (42)
✓ output plugins work without exit code observers
✓ exit code observers are not called when an output plugin throws
PASS Tests\Unit\Plugins\Concerns\HandleArguments PASS Tests\Unit\Plugins\Concerns\HandleArguments
✓ method hasArgument with ('--long-argument', true) ✓ method hasArgument with ('--long-argument', true)
✓ method hasArgument with ('-a', true) ✓ method hasArgument with ('-a', true)
@@ -1846,12 +1893,17 @@
✓ popArgument preserves duplicate values when removing a missing argument ✓ popArgument preserves duplicate values when removing a missing argument
✓ popArgument preserves duplicate values when removing an existing argument ✓ popArgument preserves duplicate values when removing an existing argument
PASS Tests\Unit\Plugins\Concerns\PushArgument
✓ pushArgument inserts before the option separator when the keys have gaps
PASS Tests\Unit\Plugins\Environment PASS Tests\Unit\Plugins\Environment
✓ environment is set to CI when --ci option is used ✓ environment is set to CI when --ci option is used
✓ environment is set to Local when --ci option is not used ✓ environment is set to Local when --ci option is not used
PASS Tests\Unit\Plugins\Retry PASS Tests\Unit\Plugins\Retry
✓ it orders by defects and stop on defects if when --retry is used ✓ it orders by defects and stop on defects if when --retry is used
✓ it rejects retry with a parallel flag with ('--parallel')
✓ it rejects retry with a parallel flag with ('-p')
PASS Tests\Unit\Plugins\Shard PASS Tests\Unit\Plugins\Shard
✓ getShard → it parses valid shard format with ('1/2', 1, 2) ✓ getShard → it parses valid shard format with ('1/2', 1, 2)
@@ -1874,7 +1926,7 @@
✓ buildFilterArgument → it generates compact filter for single test ✓ buildFilterArgument → it generates compact filter for single test
✓ buildFilterArgument → it generates compact filter for multiple tests with common prefix ✓ buildFilterArgument → it generates compact filter for multiple tests with common prefix
✓ buildFilterArgument → it generates compact filter for tests with different namespaces ✓ buildFilterArgument → it generates compact filter for tests with different namespaces
✓ buildFilterArgument → it returns empty string for empty test list ✓ buildFilterArgument → it generates a filter that selects no tests for an empty test list
✓ buildFilterArgument → it generates compact filter for deeply nested namespaces ✓ buildFilterArgument → it generates compact filter for deeply nested namespaces
✓ buildFilterArgument → it handles mix of nested and flat namespaces ✓ buildFilterArgument → it handles mix of nested and flat namespaces
✓ buildFilterArgument → it does not match a class outside of the shard when another class name is its prefix ✓ buildFilterArgument → it does not match a class outside of the shard when another class name is its prefix
@@ -1903,9 +1955,118 @@
✓ buildListTestsCommand → it strips --processes N (space-separated) when building the list-tests command ✓ buildListTestsCommand → it strips --processes N (space-separated) when building the list-tests command
✓ buildListTestsCommand → it strips --runner when building the list-tests command ✓ buildListTestsCommand → it strips --runner when building the list-tests command
✓ buildListTestsCommand → it strips a space-separated --runner and its value when building the list-tests command ✓ buildListTestsCommand → it strips a space-separated --runner and its value when building the list-tests command
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--max-batch-size=N"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--max-batch-size N"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "-m N"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "-mN"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "-m=N"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--processes N"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--max-processes=N"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--passthru-php"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--tmp-dir"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--functional"
✓ buildListTestsCommand → it strips paratest-only options when building the list-tests command with dataset "--no-test-tokens"
✓ addOutput → it displays shard information after test execution ✓ addOutput → it displays shard information after test execution
✓ addOutput → it uses singular form for single test file ✓ addOutput → it uses singular form for single test file
✓ addOutput → it returns original exit code when shard is not set ✓ addOutput → it returns original exit code when shard is not set
✓ timings file → it reads and writes shards.json until a plugin overrides the filename
✓ timings file → it prefers timings supplied by a plugin over the ones collected from the test run
✓ timings file → it records known tests without supplied timings as zero
✓ timings file → it keeps timings supplied by a plugin even when the test suite did not pass
✓ timings file → it strips coverage arguments when building the list-tests command
✓ timings file → it strips the separate path of a coverage argument when building the list-tests command
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-jsonl')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--coverage-filter')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--min')
✓ timings file → it strips the separate value of a coverage option when building the list-tests command with ('--exactly')
✓ timings file → it strips the separate value of the parallel processes option when building the list-tests command
✓ timings file → it keeps a unit saved with no test classes, but drops one emptied by removed classes
✓ timings file → it drops test classes that no longer exist from the stored units
✓ units → it treats a bare timing as a unit bundling only its own test class
✓ units → it keeps the test classes a unit bundles together in one shard
✓ units → it owns every unit when the run is not time-balanced
✓ units → it owns only the units allocated to the current shard
✓ units → it owns a unit the timings file does not know in every shard, and reports the file as out of date
✓ units → it keeps a unit that bundles no test class when writing
✓ units → it collects every test class the given units bundle
✓ units → it writes bundled units, and reads back both shapes
PASS Tests\Unit\Plugins\Tia\ByteSafeJson
✓ it round-trips keys and values that are not valid UTF-8
✓ it keeps valid UTF-8 as plain JSON
✓ it does not confuse a real string with an escaped one
✓ it leaves a malformed escape untouched
✓ it returns null for invalid JSON
✓ it throws with the reason when a value cannot be encoded
✓ it carries a string that is not valid UTF-8 through a parallel global
PASS Tests\Unit\Plugins\Tia\ChangedFiles
✓ it resolves the project prefix inside the repository
✓ it keeps a space that begins the name of the project directory
✓ it keeps the character that ends the name of the repository root with dataset "a space"
✓ it keeps the character that ends the name of the repository root with dataset "a carriage return"
✓ it reports working tree changes relative to the project, dropping siblings
✓ it reports committed changes relative to the project, dropping siblings
✓ it drops a file whose content came back to its baseline across the prefix boundary
✓ it honours a gitignore inside the project
✓ it leaves a project at the repository root untouched
✓ it reports the changes it left outside the project
✓ it reports nothing outside the project for a project at the repository root
✓ it ties a fingerprint to the project location inside the repository
✓ it sees a committed non-ascii path that git would otherwise quote
✓ it sees a committed non-ascii path at the repository root too
✓ it keeps a tracked outside change and drops an untracked ignored one
✓ it keeps a tracked project change that the ignore rules match
✓ it reads committed paths from the repository root even when git is told to be relative
✓ it tells a working tree change outside the project from a committed one
✓ it keeps a changed file whose name is a number as a string
✓ it keeps a changed file outside the project whose name is a number as a string
✓ it matches no external root for a changed file whose name is a number
✓ it hashes an external input without reading it into memory
✓ it sees a whitespace change inside an external input
✓ it reports a changed file whose name looks like a pathspec
✓ it reports an external input that the listing no longer names
✓ it reports no change for an external input it cannot read
✓ it keeps a snapshotted file whose name is a number as a string
✓ it keeps a branch whose name is a number as a string
✓ it reads the baseline of many changed files and keeps their order
✓ it reads many baselines with one call and gives the same content as one call per file
✓ it reads no baseline when the commit does not exist
✓ it reads the baseline of each file again when the batch fails with dataset "a failed check"
✓ it reads the baseline of each file again when the batch fails with dataset "a check line that does not parse"
✓ it reads the baseline of each file again when the batch fails with dataset "a check without a line"
✓ it reads the baseline of each file again when the batch fails with dataset "a failed read"
✓ it reads the baseline of each file again when the batch fails with dataset "a header that does not parse after one blob"
✓ it reads the baseline of each file again when the batch fails with dataset "a missing blob"
✓ it reads the baseline of each file again when the batch fails with dataset "bytes after the last blob"
✓ it reads the baseline of each file again when the batch fails with dataset "a blob without its line feed"
✓ it reads the baseline of each file again when the batch fails with dataset "another blob than the one asked"
✓ it raises a timed out read of the baseline blobs instead of answering
✓ it reads the baseline of many large changed files within a small memory limit
PASS Tests\Unit\Plugins\Tia\ConfigurationFile
✓ it fingerprints the path and the content of the configuration file
✓ it tells an identical copy under another name apart from the original
✓ it resolves a configuration directory the way PHPUnit does
✓ it gives a run with --no-configuration its own fingerprint
✓ it fingerprints the configuration Pest generates the way the Xdebug restarter does with dataset "first name"
✓ it fingerprints the configuration Pest generates the way the Xdebug restarter does with dataset "fallback name"
✓ it fingerprints the configuration Pest generates the way the Xdebug restarter does with dataset "random name"
✓ it fingerprints an explicit configuration apart from the one Pest generates
✓ it keeps the bootstrap and the include path the command line sets with the configuration Pest generates
✓ it keeps the fingerprint of a run that sets no bootstrap and no include path
✓ it fingerprints the bootstrap the command line sets relative to the project with dataset "separate value"
✓ it fingerprints the bootstrap the command line sets relative to the project with dataset "equals form"
✓ it tells two bootstraps apart
✓ it tells a bootstrap with a backslash in its name apart from a bootstrap in a directory
✓ it fingerprints each include path the command line sets relative to the project
✓ it fingerprints the bootstrap of a run with --no-configuration
✓ it fingerprints an include path equal to the project root as the project root
✓ it keeps an empty include path entry empty
✓ it keeps the fingerprint of a relative bootstrap when the working directory changes during the run
✓ it tells an include path through a symlink to a directory with a separator in its name apart from two include paths
✓ it builds the source scope from the coverage filter and the source of the configuration
✓ it gives no source scope when the configuration cannot be read
PASS Tests\Unit\Plugins\Tia\ContentHash PASS Tests\Unit\Plugins\Tia\ContentHash
✓ of() → it returns false when file does not exist ✓ of() → it returns false when file does not exist
@@ -1951,6 +2112,89 @@
WARN Tests\Unit\Plugins\Tia\DeletedTestCoverage WARN Tests\Unit\Plugins\Tia\DeletedTestCoverage
- cached hits of a deleted test are dropped while a replayed test stays → Coverage is not available - cached hits of a deleted test are dropped while a replayed test stays → Coverage is not available
WARN Tests\Unit\Plugins\Tia\ExternalSources
✓ it finds a psr-4 root that escapes the project
✓ it finds a path repository
✓ it finds a phpunit source directory outside the project
✓ it finds nothing when the project only loads its own code
✓ it finds nothing for a project at the repository root
✓ it reports a root that sits outside the repository as unverifiable
✓ it reports nothing unverifiable when every declaration stays inside the repository
✓ it reports a bootstrap outside the repository as unverifiable
✓ it matches only the changes that fall under an external root
✓ it finds an autoload file that escapes the project and matches it exactly
✓ it finds a phpunit bootstrap that escapes the project
✓ it keeps a declared root that no longer exists on disk
✓ it treats a classmap entry as a file only when it names one
✓ it finds a testsuite directory outside the project
✓ it keeps the directory before a wildcard in a path repository
✓ it keeps the directory before a single character wildcard
✓ it matches a deleted package that a wildcard declared
✓ it covers the whole repository when a declaration reaches its root
✓ it reads the configuration that the command line selects
✓ it accepts the configuration argument in its joined form
✓ it resolves a configuration path against its own directory
✓ it follows a symlink that leaves the project
✓ it keeps a real directory inside the project out of the roots
✓ it finds a bootstrap file that the command line names
✓ it finds every directory that an include path names
✓ it resolves a command line path against the directory the command ran in
✓ it keeps a declaration that a commit deleted under the directory the command ran in
✓ it watches the paths of the configuration Pest generates in the directory the command ran in
✓ it treats a classmap directory that carries a dot as a directory
✓ it accepts the configuration argument attached to its short flag
✓ it reads no configuration when the run asks for none
✓ it reads no default configuration when the command line names one
✓ it finds an include path that the configuration names
✓ it matches a submodule that a commit moved
✓ it matches a submodule that holds a declared file
✓ it reads the configuration of the directory the command ran in
✓ it reads a configuration that a directory argument names
✓ it reads the dist name that phpunit tries before the older one
✓ it finds a bootstrap that a single test suite names
✓ it watches the directory before a wildcard that a configuration names
✓ it lists the files of a root that the repository ignores as ignored inputs
✓ it lists the ignored files under a declared root as ignored inputs
✓ it lists an ignored bootstrap file inside vendor as an ignored input
✓ it lists the ignored files under a declared root inside a dot directory
✓ it lists an ignored link to a file but no ignored link to a directory or to nothing
✓ it watches the path that composer resolved for a path repository
✓ it watches the path that composer installed when the project has no lock file
✓ it watches the path that composer installed into a custom vendor directory
✓ it watches the path that composer installed into the vendor directory the run loaded
✓ it watches the installed path and the locked path when they differ
✓ it reads a path that composer resolved as a literal path
✓ it reads the manifest and the lock file that the COMPOSER variable names
✓ it lists the ignored files when git is told to read every pathspec literally
- it treats a network path as absolute on Windows → Network paths only exist on Windows.
✓ it reports an ignored repository under a declared root as unverifiable
✓ it finds a root that the repository ignores next to a file whose name looks like a pathspec
✓ it reports no repository that sits in a noise directory under a declared root as unverifiable
✓ it reports a repository under an inner declared root even when an outer root counts it as noise
✓ it reports a root inside an ignored repository as unverifiable
✓ it reads a bootstrap whose name holds a wildcard character as a literal file
✓ it reads a psr-4 directory whose name holds a wildcard character as a literal directory
✓ it reads an include path whose name holds a wildcard character as a literal directory
✓ it reads every path of an include path list
✓ it watches the configuration directory when an include path list starts with a separator
✓ it watches nothing for an empty include path, as PHPUnit adds nothing
✓ it resolves every path of an include path list after the first one from the working directory
✓ it watches the directory before a bracket and a brace path as it is
✓ it watches the directory an escaped brace names
✓ it watches every directory a double star pattern reaches like PHPUnit
✓ it also watches a directory whose real name looks like a pattern
✓ it keeps an existing absolute directory with brackets in its path as it is
✓ it watches the directories a bracket pattern matches even when its literal name also exists
✓ it cuts a path at a brace only when the glob of its reader expands braces
✓ it lists no ignored file of the project itself as an ignored input
✓ it keeps the roots of the run when a test changes the working directory
- it keeps the drive letter when it resolves a missing directory against a Windows base → Drive letters exist only on Windows.
✓ it resolves a path that starts with a drive letter against its base outside Windows
- it treats a path from the root of the current drive as absolute on Windows → Paths from the root of the current drive exist only on Windows.
- it keeps the current drive when it resolves a missing path from the root of that drive → Paths from the root of the current drive exist only on Windows.
- it keeps the network share when it resolves a missing directory against a UNC base → UNC paths exist only on Windows.
✓ it reads a leading double slash as the root outside Windows
PASS Tests\Unit\Plugins\Tia\FileState PASS Tests\Unit\Plugins\Tia\FileState
✓ keysWithPrefix() → it lists keys matching the prefix ✓ keysWithPrefix() → it lists keys matching the prefix
✓ keysWithPrefix() → it ignores in-flight temporary files from concurrent writes ✓ keysWithPrefix() → it ignores in-flight temporary files from concurrent writes
@@ -1959,6 +2203,11 @@
✓ compute() → it fingerprints tracked structural files in a regular clone ✓ compute() → it fingerprints tracked structural files in a regular clone
✓ compute() → it fingerprints tracked structural files inside a linked git worktree ✓ compute() → it fingerprints tracked structural files inside a linked git worktree
✓ compute() → it excludes gitignored untracked files from the fingerprint ✓ compute() → it excludes gitignored untracked files from the fingerprint
✓ compute() → it keeps the command line bootstrap and include path out of a run that sets neither
✓ compute() → it tells a bootstrap whose name looks like an include path apart from a bootstrap and an include path
✓ compute() → it tells a relative include path from the absolute path it names
✓ compute() → it stores an include path whose name is not utf-8 as text json can encode
✓ compute() → it changes when the order of the include path changes and not when its spelling does
PASS Tests\Unit\Plugins\Tia\Graph PASS Tests\Unit\Plugins\Tia\Graph
✓ shouldRerunStatus() → it re-runs failures and errors, replays successes ✓ shouldRerunStatus() → it re-runs failures and errors, replays successes
@@ -1991,6 +2240,12 @@
✓ Laravel boot files → it watches the config and bootstrap files in the Laravel defaults ✓ Laravel boot files → it watches the config and bootstrap files in the Laravel defaults
✓ clearResults() → it drops the results of the fallback branch too ✓ clearResults() → it drops the results of the fallback branch too
✓ branch baseline over the fallback → it reads results written after an earlier read ✓ branch baseline over the fallback → it reads results written after an earlier read
✓ pruneMissingBranches() → it keeps a branch whose name is a number
✓ decode() → it keeps a file of the last run tree whose name is a number
✓ encode() and decode() → it round-trips paths that are not valid UTF-8
✓ encode() and decode() → it lists a branch whose name is not valid UTF-8
✓ legacy schema → it reads a graph of the previous schema without unescaping its strings
✓ legacy schema → it rebuilds a graph of an unknown schema but still lists its branches
PASS Tests\Unit\Plugins\Tia\IsEnabledForRun PASS Tests\Unit\Plugins\Tia\IsEnabledForRun
✓ does not throw when an integer --random-order-seed is passed as a separate argv element ✓ does not throw when an integer --random-order-seed is passed as a separate argv element
@@ -2018,12 +2273,26 @@
✓ it detects an added or removed non-platform dependency ✓ it detects an added or removed non-platform dependency
✓ it is independent of package ordering ✓ it is independent of package ordering
PASS Tests\Unit\Plugins\Tia\NumericInertiaPages
✓ it selects the tests of a changed Inertia page whose name is a number
✓ it keeps an Inertia page whose name is a number after the graph is decoded
✓ it records an Inertia page whose name is a number as a string
✓ it selects the tests of a shared module of an Inertia page whose name is a number
PASS Tests\Unit\Plugins\Tia\NumericSourceFileNames
✓ it selects the tests of a changed source file whose name is a number
✓ it selects the tests of a numeric source file after the graph is decoded
PASS Tests\Unit\Plugins\Tia\NumericTableDependencies PASS Tests\Unit\Plugins\Tia\NumericTableDependencies
✓ it exports numeric table dependencies from the recorder as strings ✓ it exports numeric table dependencies from the recorder as strings
✓ it persists numeric tables as JSON strings and selects only their migration readers after reload ✓ it persists numeric tables as JSON strings and selects only their migration readers after reload
✓ it preserves numeric worker tables through payload cleaning union and graph reload ✓ it preserves numeric worker tables through payload cleaning union and graph reload
✓ it preserves observed and migration added numeric tables when augmenting database tests ✓ it preserves observed and migration added numeric tables when augmenting database tests
PASS Tests\Unit\Plugins\Tia\NumericWatchPatterns
✓ it matches a watch pattern whose key is a number
✓ it selects the tests under a watch target whose name is a number
PASS Tests\Unit\Plugins\Tia\ReadCapture PASS Tests\Unit\Plugins\Tia\ReadCapture
✓ reads → it links a project file the test reads with dataset "file_get_contents" ✓ reads → it links a project file the test reads with dataset "file_get_contents"
✓ reads → it links a project file the test reads with dataset "file" ✓ reads → it links a project file the test reads with dataset "file"
@@ -2038,29 +2307,59 @@
✓ the file wrapper → it is restored when the recorder resets ✓ the file wrapper → it is restored when the recorder resets
✓ the file wrapper → it passes filesystem operations through while a test records ✓ the file wrapper → it passes filesystem operations through while a test records
✓ the file wrapper → it writes with LOCK_EX while a test records ✓ the file wrapper → it writes with LOCK_EX while a test records
✓ the file wrapper → it reports a missing path to the error handler as plain PHP does while a test records
✓ the file wrapper → it reports why an include failed as plain PHP does while a test records
✓ the file wrapper → it keeps no memory for each filesystem call while a test records
✓ the file wrapper → it keeps no memory for each test it records
✓ the file wrapper → it is restored quietly when the test already restored it
✓ the file wrapper → it is restored quietly when the test unregistered it
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a link to an existing file" ✓ the file wrapper → it reports symlinks as links while a test records with dataset "a link to an existing file"
✓ the file wrapper → it reports symlinks as links while a test records with dataset "a dangling link" ✓ the file wrapper → it reports symlinks as links while a test records with dataset "a dangling link"
✓ a wrapper already registered for file:// → it opens reads through it and still links them ✓ a wrapper already registered for file:// → it opens reads through it and still links them
✓ a wrapper already registered for file:// → it keeps the include flag for the files a test includes ✓ a wrapper already registered for file:// → it keeps the include flag for the files a test includes
✓ a wrapper already registered for file:// → it is registered again after the test ✓ a wrapper already registered for file:// → it is registered again after the test
✓ a __call wrapper already registered for file:// → it passes reads, includes and directory listings through it
✓ withoutReadCapture() → it does not link a file matching an excluded glob
✓ withoutReadCapture() → it still links a file outside the excluded globs
✓ withoutReadCapture() → it keeps the file wrapper registered while globs are excluded
✓ withoutReadCapture() → it links every read when the list of globs is empty
✓ withoutReadCapture() → it registers no wrapper and links no read when called without globs
✓ withoutReadCapture() → it keeps the explicit links when called without globs
✓ withoutReadCapture() → it leaves a wrapper already registered for file:// untouched when called without globs
PASS Tests\Unit\Plugins\Tia\Recorder WARN Tests\Unit\Plugins\Tia\Recorder
✓ activateLinkTracking() → it tracks tables without a coverage driver ✓ activateLinkTracking() → it tracks tables without a coverage driver
✓ activateLinkTracking() → it tracks inertia components without a coverage driver ✓ activateLinkTracking() → it tracks inertia components without a coverage driver
✓ activateLinkTracking() → it tracks linked sources across consecutive tests ✓ activateLinkTracking() → it tracks linked sources across consecutive tests
✓ activateLinkTracking() → it records nothing while inactive ✓ activateLinkTracking() → it records nothing while inactive
- activate() → it keeps xdebug from tracing the vendor directory of the project → Xdebug is not installed.
✓ recordOnly() → it records only the test files it accepts
✓ recordOnly() → it records each test file again after a reset
PASS Tests\Unit\Plugins\Tia\ResultKey PASS Tests\Unit\Plugins\Tia\ResultKey
✓ it keys a result per dataset row rather than per method ✓ it keys a result per dataset row rather than per method
✓ it records assertions against the same per-dataset key ✓ it records assertions against the same per-dataset key
✓ it leaves a test without a dataset keyed by class and method ✓ it leaves a test without a dataset keyed by class and method
PASS Tests\Unit\Plugins\Tia\SourceScope
✓ contains() → it excludes only the files matching the suffix of an excluded directory
✓ contains() → it excludes only the files matching the prefix of an excluded directory
✓ contains() → it excludes every file of an excluded directory without a prefix or suffix
✓ coverageExcludePaths() → it excludes each noise directory of the project that the scope rejects
✓ coverageExcludePaths() → it keeps a noise directory that holds an included directory
✓ coverageExcludePaths() → it keeps a noise directory below an included directory
✓ coverageExcludePaths() → it keeps a noise directory whose name an included directory shares in another case
✓ coverageExcludePaths() → it keeps a noise directory that has a sibling with the same name in another case
✓ coverageExcludePaths() → it keeps each noise directory when an included directory is the project root in another case
✓ coverageExcludePaths() → it keeps a linked noise directory whose target has a sibling with the same name in another case
WARN Tests\Unit\Plugins\Tia\StaleCoverageLines WARN Tests\Unit\Plugins\Tia\StaleCoverageLines
- a remeasured file drops line numbers that the current file no longer has → Coverage is not available - a remeasured file drops line numbers that the current file no longer has → Coverage is not available
PASS Tests\Unit\Plugins\Tia\Storage PASS Tests\Unit\Plugins\Tia\Storage
✓ it uses a project-relative configured directory ✓ it uses a project-relative configured directory
✓ it uses an absolute configured directory ✓ it uses an absolute configured directory
✓ it keeps the state directory of a project at the repository root
PASS Tests\Unit\Plugins\Tia\TableExtractor PASS Tests\Unit\Plugins\Tia\TableExtractor
✓ fromSql() → it extracts tables from plain DML ✓ fromSql() → it extracts tables from plain DML
@@ -2173,6 +2472,9 @@
✓ it keeps every import a single file component declares with ('default-export-in-line-comment') ✓ it keeps every import a single file component declares with ('default-export-in-line-comment')
✓ it keeps every import a single file component declares with ('default-export-in-block-comment') ✓ it keeps every import a single file component declares with ('default-export-in-block-comment')
✓ it keeps every import a single file component declares with ('default-export-in-string') ✓ it keeps every import a single file component declares with ('default-export-in-string')
✓ it keeps every import a single file component declares with ('generic-attribute')
✓ it keeps every import a single file component declares with ('generic-attribute-single-quoted')
✓ it keeps every import a single file component declares with ('generic-attribute-before-lang')
✓ it reports the script block language so the parser matches it with ('script-setup') ✓ it reports the script block language so the parser matches it with ('script-setup')
✓ it reports the script block language so the parser matches it with ('plain-script-with-default') ✓ it reports the script block language so the parser matches it with ('plain-script-with-default')
✓ it reports the script block language so the parser matches it with ('typescript-lang') ✓ it reports the script block language so the parser matches it with ('typescript-lang')
@@ -2187,6 +2489,9 @@
✓ it reports the script block language so the parser matches it with ('default-export-in-line-comment') ✓ it reports the script block language so the parser matches it with ('default-export-in-line-comment')
✓ it reports the script block language so the parser matches it with ('default-export-in-block-comment') ✓ it reports the script block language so the parser matches it with ('default-export-in-block-comment')
✓ it reports the script block language so the parser matches it with ('default-export-in-string') ✓ it reports the script block language so the parser matches it with ('default-export-in-string')
✓ it reports the script block language so the parser matches it with ('generic-attribute')
✓ it reports the script block language so the parser matches it with ('generic-attribute-single-quoted')
✓ it reports the script block language so the parser matches it with ('generic-attribute-before-lang')
✓ it always leaves a default export for importers to resolve against with ('script-setup') ✓ it always leaves a default export for importers to resolve against with ('script-setup')
✓ it always leaves a default export for importers to resolve against with ('plain-script-with-default') ✓ it always leaves a default export for importers to resolve against with ('plain-script-with-default')
✓ it always leaves a default export for importers to resolve against with ('typescript-lang') ✓ it always leaves a default export for importers to resolve against with ('typescript-lang')
@@ -2201,6 +2506,12 @@
✓ it always leaves a default export for importers to resolve against with ('default-export-in-line-comment') ✓ it always leaves a default export for importers to resolve against with ('default-export-in-line-comment')
✓ it always leaves a default export for importers to resolve against with ('default-export-in-block-comment') ✓ it always leaves a default export for importers to resolve against with ('default-export-in-block-comment')
✓ it always leaves a default export for importers to resolve against with ('default-export-in-string') ✓ it always leaves a default export for importers to resolve against with ('default-export-in-string')
✓ it always leaves a default export for importers to resolve against with ('generic-attribute')
✓ it always leaves a default export for importers to resolve against with ('generic-attribute-single-quoted')
✓ it always leaves a default export for importers to resolve against with ('generic-attribute-before-lang')
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute')
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute-single-quoted')
✓ it ends the opening script tag after a quoted attribute that holds a closing angle bracket with ('generic-attribute-before-lang')
✓ it does not add a second default export when the block already has one ✓ it does not add a second default export when the block already has one
✓ it drops template and style markup that the parser would reject ✓ it drops template and style markup that the parser would reject
✓ it stubs assets as JS modules so rolldown does not reject them as CSS with ('/app/resources/css/app.css') ✓ it stubs assets as JS modules so rolldown does not reject them as CSS with ('/app/resources/css/app.css')
@@ -2211,7 +2522,10 @@
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-line-comment') ✓ it ignores a default export that only appears in a comment or string with ('default-export-in-line-comment')
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-block-comment') ✓ it ignores a default export that only appears in a comment or string with ('default-export-in-block-comment')
✓ it ignores a default export that only appears in a comment or string with ('default-export-in-string') ✓ it ignores a default export that only appears in a comment or string with ('default-export-in-string')
✓ it loads the rolldown that Vite+ exposes as vite/rolldown
✓ it finds no rolldown when neither rolldown nor vite/rolldown resolves
- it bundles a script setup component that mentions export default in a comment → rolldown is not resolvable. - it bundles a script setup component that mentions export default in a comment → rolldown is not resolvable.
- it bundles a generic component whose script tag holds a closing angle bracket → rolldown is not resolvable.
PASS Tests\Unit\Plugins\Tia\WatchPatterns PASS Tests\Unit\Plugins\Tia\WatchPatterns
✓ it keeps the built-in fallbacks enabled by default ✓ it keeps the built-in fallbacks enabled by default
@@ -2228,6 +2542,16 @@
✓ it retains recorded Inertia dependencies when default watches are disabled ✓ it retains recorded Inertia dependencies when default watches are disabled
✓ it retains recorded migration tables when default watches are disabled ✓ it retains recorded migration tables when default watches are disabled
✓ it uses custom mappings for an unknown Vue page with defaults disabled ✓ it uses custom mappings for an unknown Vue page with defaults disabled
✓ it captures every read by default
✓ it excludes reads of files matching a glob
✓ it matches read globs like watch patterns
✓ it does not exclude a dotfile unless the glob names it
✓ it accumulates read exclusions from repeated calls
✓ it does not turn read capture off for an empty exclusion list
✓ it turns read capture off without a list of globs
✓ it keeps read capture off when globs are added afterwards
✓ it captures reads again on reset
✓ it does not change the default watch fallbacks of an excluded read
PASS Tests\Unit\Plugins\Tia\WorkerToken PASS Tests\Unit\Plugins\Tia\WorkerToken
✓ prefers the per-process UNIQUE_TEST_TOKEN over the per-slot TEST_TOKEN, so two workers recycled into the same slot get different tokens ✓ prefers the per-process UNIQUE_TEST_TOKEN over the per-slot TEST_TOKEN, so two workers recycled into the same slot get different tokens
@@ -2247,10 +2571,15 @@
✓ last → it should return the last element for an array without changing the internal pointer ✓ last → it should return the last element for an array without changing the internal pointer
✓ last → it should return the last element for an associative array without changing the internal pointer ✓ last → it should return the last element for an associative array without changing the internal pointer
✓ last → it should return the last element for an mixed key array without changing the internal pointer ✓ last → it should return the last element for an mixed key array without changing the internal pointer
✓ stringKeys → it returns every key as a string
PASS Tests\Unit\Support\Backtrace PASS Tests\Unit\Support\Backtrace
✓ it gets file name from called file ✓ it gets file name from called file
PASS Tests\Unit\Support\ComposerProject
✓ it reads the project root that composer recorded
✓ it falls back to the parent of the vendor directory when composer recorded no install path
PASS Tests\Unit\Support\Container PASS Tests\Unit\Support\Container
✓ it exists ✓ it exists
✓ it gets an instance ✓ it gets an instance
@@ -2295,9 +2624,23 @@
✓ it ensures the given closures reports the correct class name ✓ it ensures the given closures reports the correct class name
✓ it ensures the given closures reports the correct class name and suggests the [pest()] function ✓ it ensures the given closures reports the correct class name and suggests the [pest()] function
PASS Tests\Unit\Support\Git
✓ it raises a timed out command instead of answering with ('result')
✓ it raises a timed out command instead of answering with ('raw')
✓ it raises a timed out command instead of answering with ('output')
✓ it raises a timed out command instead of answering with ('succeeds')
PASS Tests\Unit\Support\HigherOrderMessage PASS Tests\Unit\Support\HigherOrderMessage
✓ undefined method exceptions ✓ undefined method exceptions
PASS Tests\Unit\Support\InstalledPackages
✓ it finds a package that the project installs
✓ it ignores a package that only a tool bundled in a PHAR installs
✓ it leaves out a development requirement when asked
✓ it reads an installed set that has no install path
✓ it reads the packages that Composer loaded
✓ it is the only class of src that reads Composer packages
PASS Tests\Unit\Support\Reflection PASS Tests\Unit\Support\Reflection
✓ it gets file name from closure ✓ it gets file name from closure
✓ it gets property values ✓ it gets property values
@@ -2384,6 +2727,14 @@
PASS Tests\Visual\Collision PASS Tests\Visual\Collision
✓ collision with (['']) ✓ collision with ([''])
PASS Tests\Visual\Dirty
✓ dirty selects paths with spaces and Unicode with dataset "repository root"
✓ dirty selects paths with spaces and Unicode with dataset "project subdirectory"
✓ dirty selects paths with spaces and Unicode with dataset "subdirectory with leading space"
✓ dirty ignores a test removed after staging a modification with dataset "sequential"
✓ dirty ignores a test removed after staging a modification with dataset "parallel"
✓ dirty selects an unresolved test only while its file exists
PASS Tests\Visual\FailingBoot PASS Tests\Visual\FailingBoot
✓ a failure in the boot files renders only that failure ✓ a failure in the boot files renders only that failure
@@ -2394,11 +2745,19 @@
✓ junit output ✓ junit output
✓ junit with parallel ✓ junit with parallel
PASS Tests\Visual\NestedVendorDirectory
✓ runs with a nested Composer vendor directory with dataset "Composer proxy"
✓ runs with a nested Composer vendor directory with dataset "Composer proxy with workers"
✓ runs with a nested Composer vendor directory with dataset "direct execution with workers"
PASS Tests\Visual\Parallel PASS Tests\Visual\Parallel
✓ parallel ✓ parallel
✓ a parallel test can extend another test with same name ✓ a parallel test can extend another test with same name
✓ parallel reports invalid datasets as failures ✓ parallel reports invalid datasets as failures
✓ parallel lets extensions register event subscribers ✓ parallel lets extensions register event subscribers
✓ sets Laravel parallel flags with dataset "without database options"
✓ sets Laravel parallel flags with dataset "recreate databases"
✓ sets Laravel parallel flags with dataset "drop databases"
✓ parallel can have multiple exclude-groups ✓ parallel can have multiple exclude-groups
✓ parallel can have multiple groups ✓ parallel can have multiple groups
✓ parallel accepts the options that the workers ignore with ('--no-results') ✓ parallel accepts the options that the workers ignore with ('--no-results')
@@ -2409,14 +2768,127 @@
✓ parallel does not record the test run history when asked not to with ('--do-not-record-test-run-history') ✓ parallel does not record the test run history when asked not to with ('--do-not-record-test-run-history')
✓ parallel group-filtered run is not considered empty when a worker ends on a fully filtered file ✓ parallel group-filtered run is not considered empty when a worker ends on a fully filtered file
✓ parallel group-filtered run still fails when the selection matches no tests ✓ parallel group-filtered run still fails when the selection matches no tests
✓ parallel accepts a path after the option separator
PASS Tests\Visual\ParallelIncludePath
✓ parallel resolves requires through the include path with dataset "value in the same argument"
✓ parallel resolves requires through the include path with dataset "value as a separate argument"
✓ parallel resolves requires through the include path with dataset "absolute path"
✓ parallel resolves requires through the include path with dataset "several paths"
✓ parallel resolves requires through the include path with dataset "directory name with an equals sign"
✓ parallel resolves requires through the include path with dataset "absolute directory name with an equals sign"
✓ parallel resolves requires through the include path with dataset "require in the bootstrap file"
✓ parallel resolves requires through the include path with dataset "command line before the XML include path"
✓ parallel resolves requires through the include path with dataset "command line before the XML include path in the bootstrap file"
✓ parallel places the include path before the argument separator
✓ parallel fails to resolve requires without the include path
PASS Tests\Visual\ParallelIncludePathLeadingSpace
✓ parallel keeps the leading space of an include path in the same argument as serial phpunit does
PASS Tests\Visual\ParallelIncludePathOptionWithLeadingSpace
✓ parallel reads an include path option with a leading space as serial phpunit does
PASS Tests\Visual\ParallelIncludePathTrailingSpace
✓ parallel workers keep the trailing space of an include path as serial phpunit does
PASS Tests\Visual\ParallelIncludePathWhitespace
✓ parallel accepts an include path of whitespace as serial phpunit does
PASS Tests\Visual\ParallelIncludePathWithoutValue
✓ parallel keeps the pest runner when the include path option has no value
PASS Tests\Visual\ParallelNestedDatasets PASS Tests\Visual\ParallelNestedDatasets
✓ parallel loads nested datasets from nested directories ✓ parallel loads nested datasets from nested directories
PASS Tests\Visual\ParallelStopOn
✓ parallel stop-on fixtures run completely without a stop flag with dataset "failure"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "error"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "risky"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "incomplete"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "warning"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "notice"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "deprecation"
✓ parallel stop-on fixtures run completely without a stop flag with dataset "skipped"
✓ parallel honors stop-on flags with worker recycling with dataset "failure" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "failure" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "defect" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "defect" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "error" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "error" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "risky" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "risky" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "incomplete" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "incomplete" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "warning" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "warning" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "notice" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "notice" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "deprecation" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "deprecation" / (1)
✓ parallel honors stop-on flags with worker recycling with dataset "skipped" / (0)
✓ parallel honors stop-on flags with worker recycling with dataset "skipped" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "failure" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "failure" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "defect" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "defect" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "error" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "error" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "risky" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "risky" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "incomplete" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "incomplete" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "warning" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "warning" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "notice" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "notice" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "deprecation" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "deprecation" / (1)
✓ parallel honors numeric stop-on thresholds with dataset "skipped" / (0)
✓ parallel honors numeric stop-on thresholds with dataset "skipped" / (1)
✓ parallel stop-on-defect includes errors warnings and risky tests with ('errors', 'failed', 2)
✓ parallel stop-on-defect includes errors warnings and risky tests with ('warns', 'warning', 0)
✓ parallel stop-on-defect includes errors warnings and risky tests with ('is risky', 'risky', 1)
✓ parallel stop-on-defect allows incomplete and skipped tests with ('is incomplete', 'incomplete')
✓ parallel stop-on-defect allows incomplete and skipped tests with ('is skipped', 'skipped')
✓ parallel does not count the same failure twice with (0)
✓ parallel does not count the same failure twice with (1)
✓ parallel counts issues hidden by the progress output with ('--stop-on-warning', 'has combined issues', 'failed', …)
✓ parallel counts issues hidden by the progress output with ('--stop-on-defect=2', 'has combined issues', 'failed', …)
✓ parallel counts issues hidden by the progress output with ('--stop-on-warning=2', 'has repeated warnings', 'warning', …)
✓ parallel counts issues hidden by the progress output with ('--stop-on-notice=2', 'has repeated notifications', 'notice', …)
✓ parallel stops only on the requested deprecation message with ('user deprecation', 1)
✓ parallel stops only on the requested deprecation message with ('another deprecation', 2)
✓ parallel honors stop-on flags from XML
✓ parallel CLI thresholds override XML stop-on flags
✓ parallel clamps empty and non-positive thresholds like PHPUnit with ('')
✓ parallel clamps empty and non-positive thresholds like PHPUnit with ('0')
✓ parallel clamps empty and non-positive thresholds like PHPUnit with ('-2')
✓ parallel counts a shared issue only once across recycled workers with ('warning', 'shares warning', 'warning')
✓ parallel counts a shared issue only once across recycled workers with ('defect', 'shares warning', 'warning')
✓ parallel counts a shared issue only once across recycled workers with ('notice', 'shares notice', 'notice')
✓ parallel combines stop-on counts from different workers and cleans up their files
PASS Tests\Visual\ParallelWorkerAutoload
✓ loads the autoloader of the parent process in a parallel worker
PASS Tests\Visual\Shard
✓ an empty shard runs no tests with dataset "sequential"
✓ an empty shard runs no tests with dataset "parallel"
✓ an empty shard runs no tests with dataset "sequential with fail-on-empty-test-suite"
✓ an empty shard runs no tests with dataset "parallel with fail-on-empty-test-suite"
✓ an empty shard lists no tests
✓ a non-empty shard runs its assigned test
✓ shard accepts a path after the option separator
PASS Tests\Visual\SingleTestOrDirectory PASS Tests\Visual\SingleTestOrDirectory
✓ allows to run a single test ✓ allows to run a single test
✓ allows to run a directory ✓ allows to run a directory
✓ allows to run a single test using its namespace
✓ keeps namespace filters unchanged
✓ converts a namespace after the retry flag
✓ it disable decorating printer when colors is set to never ✓ it disable decorating printer when colors is set to never
✓ allows to run a single test after the option separator
WARN Tests\Visual\Success WARN Tests\Visual\Success
- visual snapshot of test suite on success - visual snapshot of test suite on success
@@ -2424,6 +2896,8 @@
WARN Tests\Visual\TeamCity WARN Tests\Visual\TeamCity
- visual snapshot of team city with ('Failure.php') - visual snapshot of team city with ('Failure.php')
- visual snapshot of team city with ('SuccessOnly.php') - visual snapshot of team city with ('SuccessOnly.php')
✓ preserves TeamCity text in a test filter with dataset "attached value"
✓ preserves TeamCity text in a test filter with dataset "separate value"
WARN Tests\Visual\Todo WARN Tests\Visual\Todo
- todos - todos
@@ -2437,9 +2911,11 @@
WARN Tests\Visual\Version WARN Tests\Visual\Version
- visual snapshot of help command output - visual snapshot of help command output
✓ prints information when the tests directory is missing with dataset "help"
✓ prints information when the tests directory is missing with dataset "version"
PASS Testsexternal\Features\Expect\toMatchSnapshot PASS Testsexternal\Features\Expect\toMatchSnapshot
✓ pass with dataset with ('my-datas-set-value') ✓ pass with dataset with ('my-datas-set-value')
✓ within describe → pass with dataset with ('my-datas-set-value') ✓ within describe → pass with dataset with ('my-datas-set-value')
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 38 skipped, 1756 passed (3817 assertions) Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 45 skipped, 2169 passed (4762 assertions)
+1
View File
@@ -14,6 +14,7 @@ arch()->preset()->php()->ignoring([
'xdebug_start_code_coverage', 'xdebug_start_code_coverage',
'xdebug_stop_code_coverage', 'xdebug_stop_code_coverage',
'xdebug_get_code_coverage', 'xdebug_get_code_coverage',
'xdebug_set_filter',
]); ]);
arch()->preset()->strict()->ignoring([ arch()->preset()->strict()->ignoring([
+26
View File
@@ -100,3 +100,29 @@ describe('matching describe block names', function (): void {
}); });
}); });
}); });
describe('hierarchical test naming', function (): void {
describe('block one', function (): void {
describe('the same name', function (): void {
it('does not call afterEach from sibling describe with same name', function (): void {
expect($this)->not->toHaveProperty('example');
});
});
});
describe('block two', function (): void {
describe('the same name', function (): void {
beforeEach(function (): void {
$this->example = false;
});
afterEach(function (): void {
expect($this->example)->toBeFalse();
});
it('correctly calls afterEach from own describe hierarchy', function (): void {
expect($this->example)->toBeFalse();
});
});
});
});
+26
View File
@@ -126,3 +126,29 @@ describe('called on all tests', function (): void {
expect($this->baz)->toBe(2); expect($this->baz)->toBe(2);
}); });
}); });
describe('hierarchical test naming', function (): void {
describe('block one', function (): void {
describe('the same name', function (): void {
it('does not call beforeEach from sibling describe with same name', function (): void {
expect($this)->not->toHaveProperty('example');
});
});
});
describe('block two', function (): void {
beforeEach(function (): void {
$this->example = false;
});
describe('the same name', function (): void {
beforeEach(function (): void {
$this->result = $this->example;
});
it('correctly calls beforeEach from own describe hierarchy', function (): void {
expect($this->result)->toBeFalse();
});
});
});
});
+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('preserves an existing .pest.xml file', function (array $arguments, bool $hasDefaultConfiguration): void {
$project = Project::withoutGit();
$configuration = $project->path('.pest.xml');
$contents = $arguments === [] ? 'An existing project file.' : (string) file_get_contents($project->path('phpunit.xml'));
$project->write('.pest.xml', $contents);
if (! $hasDefaultConfiguration) {
unlink($project->path('phpunit.xml'));
}
$result = $project->pest('tests/Unit/GreeterTest.php', '--cache-directory', $project->path('.phpunit.cache'), ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain('2 passed')
->and(glob($project->path('.pest*.xml')))->toHaveCount(1)
->and($configuration)->toBeFile()
->and(file_get_contents($configuration))->toBe($contents);
})->with([
'explicit configuration' => [['--configuration=.pest.xml'], false],
'discovered configuration' => [[], true],
'generated configuration' => [[], false],
])->group('integration');
test('removes the generated configuration when it finishes', function (array $arguments): void {
$project = Project::withoutGit();
unlink($project->path('phpunit.xml'));
$result = $project->pest('tests/Unit/GreeterTest.php', '--cache-directory', $project->path('.phpunit.cache'), ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain('2 passed')
->and(glob($project->path('.pest*.xml')))->toBe([]);
})->with(Project::SEQUENTIAL_AND_PARALLEL)->group('integration');
test('preserves a replacement for the generated configuration', function (): void {
$project = Project::withoutGit();
unlink($project->path('phpunit.xml'));
$project->write('replacement.xml', 'A replacement project file.');
$project->write('tests/Unit/ReplaceConfigurationTest.php', <<<'PHP'
<?php
test('replaces the configuration', function (): void {
expect(rename('replacement.xml', '.pest.xml'))->toBeTrue();
});
PHP);
$result = $project->pest('tests/Unit/ReplaceConfigurationTest.php', '--cache-directory', $project->path('.phpunit.cache'));
expect($result->exitCode)->toBe(0, $result->describe())
->and($project->path('.pest.xml'))->toBeFile()
->and(file_get_contents($project->path('.pest.xml')))->toBe('A replacement project file.');
})->group('integration');
+14
View File
@@ -108,3 +108,17 @@ describe('with test after describe', function (): void {
expect($this->count)->toBe(2); expect($this->count)->toBe(2);
}); });
}); });
describe('sibling describes may share the same it() description', function (): void {
describe('block one', function (): void {
it('can be created', function (): void {
expect(true)->toBeTrue();
});
});
describe('block two', function (): void {
it('can be created', function (): void {
expect(true)->toBeTrue();
});
});
});
+4
View File
@@ -16,6 +16,10 @@ it('catch exceptions, messages and code', function (): void {
throw new Exception('Something bad happened', 1); throw new Exception('Something bad happened', 1);
})->throws(Exception::class, 'Something bad happened', 1); })->throws(Exception::class, 'Something bad happened', 1);
it('catch exceptions by interface', function (): void {
throw new Exception('Something bad happened');
})->throws(Throwable::class, 'Something bad happened');
it('can just define the message', function (): void { it('can just define the message', function (): void {
throw new Exception('Something bad happened'); throw new Exception('Something bad happened');
})->throws('Something bad happened'); })->throws('Something bad happened');
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('creates and matches snapshots with long dataset labels', function (): void {
$project = Project::withoutGit();
$testFile = 'tests/Unit/SnapshotNamesTest.php';
$snapshotDirectory = $project->path('tests/.pest/snapshots/Unit/SnapshotNamesTest');
$project->write($testFile, <<<'FIXTURE'
<?php
$prefix = str_repeat('日本', 135);
test('stores a snapshot', function (string $value): void {
expect($value)->toMatchSnapshot()
->and(strtoupper($value))->toMatchSnapshot(as: 'upper');
})->with([
'short' => ['short'],
$prefix.' one' => ['one'],
$prefix.' two' => ['two'],
]);
FIXTURE);
$first = $project->pest($testFile, '--update-snapshots');
$snapshots = glob($snapshotDirectory.'/*.snap');
expect($first->exitCode)->toBe(0, $first->describe())
->and($snapshots)->toHaveCount(6)
->and(array_map(file_get_contents(...), $snapshots))->toEqualCanonicalizing(['short', 'SHORT', 'one', 'ONE', 'two', 'TWO'])
->and($snapshotDirectory.'/stores_a_snapshot_with_data_set__dataset__short__.snap')->toBeFile()
->and($snapshotDirectory.'/stores_a_snapshot_with_data_set__dataset__short____upper.snap')->toBeFile();
foreach ($snapshots as $snapshot) {
$filename = basename($snapshot);
expect(strlen($filename))->toBeLessThanOrEqual(255)
->and(mb_check_encoding($filename, 'UTF-8'))->toBeTrue();
}
$second = $project->pestWithEnvironment($project->path(), ['CI' => 'true'], $testFile);
expect($second->exitCode)->toBe(0, $second->describe())
->and($second->tally())->toContain('3 passed');
})->group('integration');
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('reports a missing snapshot that cannot be written', function (): void {
$project = Project::withoutGit();
$testFile = 'tests/Unit/BlockedSnapshotTest.php';
$directory = 'tests/.pest/snapshots/Unit/BlockedSnapshotTest';
$project->write($directory, 'An existing file.');
$project->write($testFile, <<<'PHP'
<?php
test('stores a snapshot', function (): void {
expect('content')->toMatchSnapshot();
});
PHP);
$run = $project->pest($testFile, '--update-snapshots');
expect($run->exitCode)->toBe(2, $run->describe())
->and(str_replace('\\', '/', $run->output))->toContain("Unable to write snapshot at [$directory/stores_a_snapshot.snap].")
->not->toContain('Snapshot created at')
->and(file_get_contents($project->path($directory)))->toBe('An existing file.');
})->group('integration');
+8
View File
@@ -33,3 +33,11 @@ test('not failures', function (): void {
test('not failures with multi-dimensional arrays', function (): void { test('not failures with multi-dimensional arrays', function (): void {
expect(['a' => 1, 'b', 'c' => 'world', 'foo' => ['bar' => ['bir' => 'biz']]])->not->toHaveKeys(['foo' => ['bar' => 'bir'], 'c', 'z']); expect(['a' => 1, 'b', 'c' => 'world', 'foo' => ['bar' => ['bir' => 'biz']]])->not->toHaveKeys(['foo' => ['bar' => 'bir'], 'c', 'z']);
})->throws(ExpectationFailedException::class); })->throws(ExpectationFailedException::class);
test('not pass with multi-dimensional arrays', function (): void {
expect(['a' => 1, 'b', 'c' => 'world', 'foo' => ['bar' => ['bir' => 'biz']]])->not->toHaveKeys(['foo' => ['bar' => ['baz']], 'z']);
});
test('not failures with only multi-dimensional arrays', function (): void {
expect(['a' => 1, 'b', 'c' => 'world', 'foo' => ['bar' => ['bir' => 'biz']]])->not->toHaveKeys(['foo' => ['bar' => ['bir']]]);
})->throws(ExpectationFailedException::class);
+22 -1
View File
@@ -28,7 +28,12 @@ test('passes', function (): void {
->toThrow(function (RuntimeException $e): void {}, 'actual message') ->toThrow(function (RuntimeException $e): void {}, 'actual message')
->and(function (): void { ->and(function (): void {
throw new CustomException('foo'); throw new CustomException('foo');
})->toThrow(new CustomException('foo')); })->toThrow(new CustomException('foo'))
->and(function (): void {
throw new RuntimeException('actual message');
})->toThrow(Throwable::class)
->toThrow(function (Throwable $e): void {})
->toThrow(Throwable::class, 'actual message');
}); });
test('failures 1', function (): void { test('failures 1', function (): void {
@@ -78,6 +83,16 @@ test('failures 8', function (): void {
})->toThrow(new CustomException('expected message')); })->toThrow(new CustomException('expected message'));
})->throws(ExpectationFailedException::class); })->throws(ExpectationFailedException::class);
test('failures 9', function (): void {
expect(function (): void {})->toThrow(Throwable::class);
})->throws(ExpectationFailedException::class, 'Exception ['.Throwable::class.'] not thrown.');
test('failures 10', function (): void {
expect(function (): void {
throw new Exception('actual message');
})->toThrow(JsonSerializable::class);
})->throws(ExpectationFailedException::class, 'Failed asserting that an instance of class Exception is an instance of interface JsonSerializable.');
test('failures with custom message', function (): void { test('failures with custom message', function (): void {
expect(function (): void { expect(function (): void {
throw new RuntimeException('actual message'); throw new RuntimeException('actual message');
@@ -90,6 +105,12 @@ test('not failures', function (): void {
})->not->toThrow(RuntimeException::class); })->not->toThrow(RuntimeException::class);
})->throws(ExpectationFailedException::class); })->throws(ExpectationFailedException::class);
test('not failures with interface', function (): void {
expect(function (): void {
throw new RuntimeException;
})->not->toThrow(Throwable::class);
})->throws(ExpectationFailedException::class);
test('closure missing parameter', function (): void { test('closure missing parameter', function (): void {
expect(function (): void {})->toThrow(function (): void {}); expect(function (): void {})->toThrow(function (): void {});
})->throws(InvalidArgumentException::class, 'The given closure must have a single parameter type-hinted as the class string.'); })->throws(InvalidArgumentException::class, 'The given closure must have a single parameter type-hinted as the class string.');
+75 -7
View File
@@ -4,7 +4,7 @@ declare(strict_types=1);
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
test('init creates a suite when the tests directory is missing', function (): void { test('init creates a runnable suite when the tests directory is missing', function (): void {
$root = makeInitProject(); $root = makeInitProject();
try { try {
@@ -17,6 +17,11 @@ test('init creates a suite when the tests directory is missing', function (): vo
->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Pest.php')->toBeFile() ->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Pest.php')->toBeFile()
->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'TestCase.php')->toBeFile() ->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'TestCase.php')->toBeFile()
->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Unit'.DIRECTORY_SEPARATOR.'ExampleTest.php')->toBeFile(); ->and($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Unit'.DIRECTORY_SEPARATOR.'ExampleTest.php')->toBeFile();
$suite = runInitProject($root, '--colors=never');
expect($suite->getExitCode())->toBe(0)
->and($suite->getOutput())->toContain('2 passed (2 assertions)');
} finally { } finally {
removeInitProject($root); removeInitProject($root);
} }
@@ -58,7 +63,7 @@ test('a missing tests directory does not crash while resolving tia state', funct
$root = makeInitProject(); $root = makeInitProject();
try { try {
$process = runInitProject($root, '--version'); $process = runInitProject($root);
expect($process->getExitCode())->not->toBe(0) expect($process->getExitCode())->not->toBe(0)
->and($process->getOutput())->toContain('does not exist') ->and($process->getOutput())->toContain('does not exist')
@@ -69,6 +74,23 @@ test('a missing tests directory does not crash while resolving tia state', funct
} }
}); });
test('init writes the plain stubs when only a tool bundled in a PHAR installs Laravel', function (): void {
$root = makeInitProject();
try {
$toolLoader = makeLaravelToolPhar($root);
$process = runInitProjectWithPhpOptions(['-d', 'auto_prepend_file='.$toolLoader], $root, '--init');
expect($process->getExitCode())->toBe(0)
->and(file_get_contents($root.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Pest.php'))
->toContain("require_once __DIR__.'/TestCase.php';")
->not->toContain('RefreshDatabase');
} finally {
removeInitProject($root);
}
})->skipOnWindows();
function makeInitProject(): string function makeInitProject(): string
{ {
$root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-init-'.bin2hex(random_bytes(4)); $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-init-'.bin2hex(random_bytes(4));
@@ -85,6 +107,11 @@ function makeInitProject(): string
true, true,
); );
file_put_contents(
$root.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php',
"<?php\n\nreturn require_once {$autoload};\n",
);
file_put_contents($root.DIRECTORY_SEPARATOR.'run.php', <<<PHP file_put_contents($root.DIRECTORY_SEPARATOR.'run.php', <<<PHP
<?php <?php
@@ -100,10 +127,6 @@ require {$autoload};
\$arguments = array_slice(\$argv, 1); \$arguments = array_slice(\$argv, 1);
if (\$arguments === []) {
\$arguments = ['--version'];
}
\$GLOBALS['_composer_bin_dir'] = getcwd().'/vendor/bin'; \$GLOBALS['_composer_bin_dir'] = getcwd().'/vendor/bin';
\$_SERVER['argv'] = ['pest', ...\$arguments]; \$_SERVER['argv'] = ['pest', ...\$arguments];
@@ -128,10 +151,55 @@ PHP);
return $root; return $root;
} }
function makeLaravelToolPhar(string $root): string
{
$phar = $root.DIRECTORY_SEPARATOR.'tool.phar';
$build = new Process([
PHP_BINARY,
'-d',
'phar.readonly=0',
'-r',
<<<'PHP'
$phar = new Phar($argv[1]);
$phar->addFromString('vendor/composer/installed.php', <<<'INSTALLED'
<?php
return [
'root' => ['name' => 'tool/dumper', 'install_path' => __DIR__.'/../../'],
'versions' => ['laravel/framework' => ['pretty_version' => 'v12.0.0', 'version' => '12.0.0.0', 'dev_requirement' => false]],
];
INSTALLED);
$phar->setStub('<?php __HALT_COMPILER();');
PHP,
$phar,
]);
$build->mustRun();
$loader = $root.DIRECTORY_SEPARATOR.'tool-loader.php';
file_put_contents($loader, sprintf(
"<?php\n\nrequire_once %s;\n\n(new Composer\\Autoload\\ClassLoader(%s))->register();\n",
var_export(dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'composer'.DIRECTORY_SEPARATOR.'ClassLoader.php', true),
var_export('phar://'.$phar.'/vendor', true),
));
return $loader;
}
function runInitProject(string $root, string ...$command): Process function runInitProject(string $root, string ...$command): Process
{
return runInitProjectWithPhpOptions([], $root, ...$command);
}
/**
* @param array<int, string> $phpOptions
*/
function runInitProjectWithPhpOptions(array $phpOptions, string $root, string ...$command): Process
{ {
$process = new Process( $process = new Process(
[PHP_BINARY, 'run.php', ...$command], [PHP_BINARY, ...$phpOptions, 'run.php', ...$command],
$root, $root,
[ [
'PEST_NO_SUPPORT' => 'true', 'PEST_NO_SUPPORT' => 'true',
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('limits focus to the invocation that discovers it', function (array $arguments): void {
$project = Project::withoutGit();
$testFile = 'tests/Unit/FocusTest.php';
$project->write('vendor/pestphp/pest/.temp/.gitkeep', '');
$project->write($testFile, <<<'FIXTURE'
<?php
use Symfony\Component\Process\Process;
test('runs with a named focus group in CI', function (): void {
expect(true)->toBeTrue();
})->only('named-focus');
test('runs an independent Pest invocation', function (): void {
foreach ([[], ['--parallel', '--processes=2']] as $arguments) {
$process = new Process(
[PHP_BINARY, 'vendor/pestphp/pest/bin/pest', 'tests/Unit/GreeterTest.php', '--cache-directory', '.home/nested', ...$arguments],
env: ['PARATEST' => '0'],
);
$process->mustRun();
expect($process->getOutput())->toContain('2 passed');
}
})->only();
test('runs without focus in CI', function (): void {
expect(true)->toBeTrue();
});
FIXTURE);
$focused = $project->pest($testFile, '--cache-directory', $project->path('.home/focused'), ...$arguments);
expect($focused->exitCode)->toBe(0, $focused->describe())
->and($focused->tally())->toContain('1 passed (2 assertions)');
$ci = $project->pest($testFile, '--ci', '--cache-directory', $project->path('.home/ci'), ...$arguments);
expect($ci->exitCode)->toBe(0, $ci->describe())
->and($ci->tally())->toContain('3 passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->group('integration');
+5 -7
View File
@@ -2,6 +2,7 @@
use Pest\Plugins\Tia; use Pest\Plugins\Tia;
use Pest\Plugins\Tia\ChangedFiles; use Pest\Plugins\Tia\ChangedFiles;
use Pest\Plugins\Tia\ConfigurationFile;
use Pest\Plugins\Tia\FileState; use Pest\Plugins\Tia\FileState;
use Pest\Plugins\Tia\Fingerprint; use Pest\Plugins\Tia\Fingerprint;
use Pest\Plugins\Tia\Graph; use Pest\Plugins\Tia\Graph;
@@ -13,6 +14,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
$projectRoot = dirname(__DIR__, 2); $projectRoot = dirname(__DIR__, 2);
$home = sys_get_temp_dir().'/pest-tia-'.bin2hex(random_bytes(8)); $home = sys_get_temp_dir().'/pest-tia-'.bin2hex(random_bytes(8));
$fixture = 'tests/Fixtures/Suites/TiaReplayHooks.php'; $fixture = 'tests/Fixtures/Suites/TiaReplayHooks.php';
$configuration = 'tests/Fixtures/Suites/TiaReplayHooks.xml';
mkdir($home, 0755, true); mkdir($home, 0755, true);
@@ -24,7 +26,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
$id = fn (string $description): string => 'P\Tests\Fixtures\Suites\TiaReplayHooks::'.Str::evaluable($description); $id = fn (string $description): string => 'P\Tests\Fixtures\Suites\TiaReplayHooks::'.Str::evaluable($description);
$graph = new Graph($projectRoot); $graph = new Graph($projectRoot);
$graph->setFingerprint(Fingerprint::compute($projectRoot)); $graph->setFingerprint(Fingerprint::compute($projectRoot, ConfigurationFile::at($projectRoot.DIRECTORY_SEPARATOR.$configuration)));
$graph->setRecordedAtSha($branch, $sha); $graph->setRecordedAtSha($branch, $sha);
$graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? [])); $graph->setLastRunTree($branch, $changedFiles->snapshotTree($changedFiles->since($sha) ?? []));
$graph->markKnownTestFiles([$fixture]); $graph->markKnownTestFiles([$fixture]);
@@ -32,10 +34,6 @@ it('does not run user hooks when replaying cached skipped and incomplete results
$graph->setResult($branch, $id('replayed skip'), 1, 'cached skip', 0.01, 0, $fixture); $graph->setResult($branch, $id('replayed skip'), 1, 'cached skip', 0.01, 0, $fixture);
$graph->setResult($branch, $id('replayed incomplete'), 2, 'cached incomplete', 0.01, 0, $fixture); $graph->setResult($branch, $id('replayed incomplete'), 2, 'cached incomplete', 0.01, 0, $fixture);
$json = $graph->encode();
expect($json)->not->toBeNull();
$originalHome = getenv('HOME'); $originalHome = getenv('HOME');
putenv('HOME='.$home); putenv('HOME='.$home);
@@ -45,10 +43,10 @@ it('does not run user hooks when replaying cached skipped and incomplete results
putenv($originalHome === false ? 'HOME' : 'HOME='.$originalHome); putenv($originalHome === false ? 'HOME' : 'HOME='.$originalHome);
} }
expect($storage->write(Tia::KEY_GRAPH, (string) $json))->toBeTrue(); expect($storage->write(Tia::KEY_GRAPH, $graph->encode()))->toBeTrue();
$process = new Process( $process = new Process(
['php', 'bin/pest', '--configuration', 'tests/Fixtures/Suites/TiaReplayHooks.xml', '--tia'], ['php', 'bin/pest', '--configuration', $configuration, '--tia'],
$projectRoot, $projectRoot,
[ [
'COLLISION_PRINTER' => 'DefaultPrinter', 'COLLISION_PRINTER' => 'DefaultPrinter',
+202
View File
@@ -0,0 +1,202 @@
<?php
declare(strict_types=1);
use Pest\Support\Coverage;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function writeAlternateConfiguration(Project $project, string $failOnRisky = 'false'): void
{
$project->write('phpunit.alternate.xml', str_replace(
'failOnRisky="true"',
sprintf('failOnRisky="%s"', $failOnRisky),
(string) file_get_contents($project->path('phpunit.xml')),
));
}
test('naming the default configuration file or its directory still replays the graph', function (array $arguments): void {
$project = Project::make('master');
$project->seed('master');
$result = $project->pest('--tia', ...$arguments);
expect($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe());
})->with([
'file' => [['--configuration', 'phpunit.xml']],
'short option' => [['-c', 'phpunit.xml']],
'equals form' => [['--configuration=phpunit.xml']],
'directory' => [['--configuration', '.']],
])->skipOnWindows();
test('a graph recorded under one configuration file is not replayed under another', function (array $arguments): void {
$project = Project::make('master');
writeAlternateConfiguration($project);
$project->git()->commit('add an alternate configuration');
$project->seed('master');
$result = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('editing the configuration file in use stops the replay', function (array $arguments): void {
$project = Project::make('master');
writeAlternateConfiguration($project);
$project->git()->commit('add an alternate configuration');
$project->seed('master', configuration: 'phpunit.alternate.xml');
$unchanged = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($unchanged->replayed())->toBe(Project::TOTAL_TESTS, $unchanged->describe());
writeAlternateConfiguration($project, failOnRisky: 'true');
$project->git()->commit('change the alternate configuration');
$edited = $project->pest('--tia', '--configuration', 'phpunit.alternate.xml', ...$arguments);
expect($edited->exitCode)->toBe(0, $edited->describe())
->and($edited->replayed())->toBe(0, $edited->describe())
->and($edited->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('editing a configuration file that git ignores stops the replay', function (): void {
$project = Project::make('master');
$project->write('.gitignore', "phpunit.xml\n");
$project->git()->run(['rm', '--cached', '--quiet', 'phpunit.xml']);
$project->git()->commit('stop tracking phpunit.xml');
$project->seed('master');
$unchanged = $project->pest('--tia');
expect($unchanged->replayed())->toBe(Project::TOTAL_TESTS, $unchanged->describe());
$project->write('phpunit.xml', str_replace(
'failOnRisky="true"',
'failOnRisky="false"',
(string) file_get_contents($project->path('phpunit.xml')),
));
$edited = $project->pest('--tia');
expect($edited->exitCode)->toBe(0, $edited->describe())
->and($edited->replayed())->toBe(0, $edited->describe())
->and($edited->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->skipOnWindows();
test('an identical copy of the configuration file under another name does not replay the graph', function (array $arguments): void {
$project = Project::make('master');
$project->write('phpunit.copy.xml', (string) file_get_contents($project->path('phpunit.xml')));
$project->git()->commit('add an identical copy of the configuration');
$project->seed('master');
$result = $project->pest('--tia', '--configuration', 'phpunit.copy.xml', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
function removeConfiguration(Project $project): void
{
$project->git()->run(['rm', '--quiet', 'phpunit.xml']);
$project->write('.gitignore', file_get_contents($project->path('.gitignore'))."/.pest*.xml\n");
$project->git()->commit('use the configuration Pest generates');
$project->write('vendor/pestphp/pest/.temp/.gitkeep', '');
}
test('a project without a configuration file replays the graph', function (array $arguments): void {
$project = Project::make('master');
removeConfiguration($project);
$project->seed('master');
$result = $project->pest('--tia', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('a leftover generated configuration file does not discard the graph', function (array $arguments): void {
$project = Project::make('master');
removeConfiguration($project);
$project->seed('master');
$project->write('.pest.xml', (string) file_get_contents($project->path('vendor/pestphp/pest/resources/base-phpunit.xml')));
$replayed = $project->pest('--tia', ...$arguments);
expect($replayed->exitCode)->toBe(0, $replayed->describe())
->and($replayed->replayed())->toBe(Project::TOTAL_TESTS, $replayed->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('a graph recorded under one bootstrap is not replayed under the bootstrap the command line sets', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/AlternateBootstrap.php', "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n");
$project->git()->commit('add an alternate bootstrap');
$project->seed('master');
$result = $project->pest('--tia', '--bootstrap', 'tests/AlternateBootstrap.php', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('a graph recorded under the bootstrap the command line sets is replayed under the same bootstrap', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/AlternateBootstrap.php', "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n");
$project->git()->commit('add an alternate bootstrap');
$project->pest('--tia', '--bootstrap', 'tests/AlternateBootstrap.php', ...$arguments);
$result = $project->pest('--tia', '--bootstrap', 'tests/AlternateBootstrap.php', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a graph recorded under a bootstrap whose name looks like an include path is not replayed under that bootstrap and include path', function (array $arguments): void {
$project = Project::make('master');
$bootstrap = "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n";
$project->write('tests/Boot.php', $bootstrap);
$project->write('tests/Boot.php;include-path=app', $bootstrap);
$project->git()->commit('add two bootstraps');
$project->pest('--tia', '--bootstrap', 'tests/Boot.php;include-path=app', ...$arguments);
$result = $project->pest('--tia', '--bootstrap', 'tests/Boot.php', '--include-path', 'app');
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a graph recorded under a bootstrap with a backslash in its name is not replayed under the bootstrap in a directory', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Boot.php', "<?php\n\nrequire __DIR__.'/../vendor/autoload.php';\n");
$project->write('tests\\Boot.php', "<?php\n\nrequire __DIR__.'/vendor/autoload.php';\n");
$project->git()->commit('add two bootstraps');
$project->pest('--tia', '--bootstrap', 'tests\\Boot.php', ...$arguments);
$result = $project->pest('--tia', '--bootstrap', 'tests/Boot.php', ...$arguments);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a graph recorded without an include path is not replayed under the include path the command line sets', function (): void {
$project = Project::make('master');
$project->seed('master');
$result = $project->pest('--tia', '--include-path', 'app');
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->replayed())->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->skipOnWindows();
-12
View File
@@ -158,18 +158,6 @@ test('the default branch baseline survives every branch that comes and goes', fu
->and($project->graph()['baselines']['master']['results'])->toHaveCount(Project::TOTAL_TESTS); ->and($project->graph()['baselines']['master']['results'])->toHaveCount(Project::TOTAL_TESTS);
})->skipOnWindows(); })->skipOnWindows();
test('a project below the git repository root refuses to run and writes nothing', function (array $arguments): void {
$project = Project::make('master');
$nested = $project->nested();
$result = $project->pestIn($nested, '--tia', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->output)->toContain('Tia mode requires the git repository root')
->and($project->path('.home/.pest'))->not->toBeDirectory()
->and($nested.DIRECTORY_SEPARATOR.'.pest')->not->toBeDirectory();
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('a repository with no commits says so, and leaves plain runs alone', function (): void { test('a repository with no commits says so, and leaves plain runs alone', function (): void {
$project = Project::withoutGit(); $project = Project::withoutGit();
$project->git()->run(['init', '--quiet']); $project->git()->run(['init', '--quiet']);
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
use Pest\Support\Coverage;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function addTestFileThatReadsOutsideTheCoverageSource(Project $project): void
{
$project->write('support/salutation.php', <<<'PHP'
<?php
return 'visitor';
PHP);
$project->write('tests/Integration/WelcomeTest.php', <<<'PHP'
<?php
declare(strict_types=1);
use Fixture\App\Greeter;
test('welcomes a visitor', function (): void {
$name = require dirname(__DIR__, 2).'/support/salutation.php';
expect((new Greeter)->greet($name))->toBe('Hello, visitor!');
});
PHP);
$project->git()->commit('add a test file the graph does not know');
$project->seed('master');
}
function forgetWelcomeTest(Project $project): void
{
$project->mutateGraph(function (array $graph): array {
unset($graph['edges']['tests/Integration/WelcomeTest.php']);
return $graph;
});
}
test('a coverage replay does not narrow the edges of a test file the graph does not know', function (array $arguments): void {
$project = Project::make('master');
addTestFileThatReadsOutsideTheCoverageSource($project);
$baseline = $project->pest('--tia', '--coverage', ...$arguments);
expect($baseline->exitCode)->toBe(0, $baseline->describe());
forgetWelcomeTest($project);
$coverage = $project->pest('--tia', '--coverage', ...$arguments);
expect($coverage->exitCode)->toBe(0, $coverage->describe())
->and($coverage->uncached())->toBe(1, $coverage->describe())
->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php');
$project->write('support/salutation.php', <<<'PHP'
<?php
return 'stranger';
PHP);
$project->git()->commit('change the salutation');
$result = $project->pest('--tia', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a coverage replay with affected test files does not mark a test file the graph does not know as known', function (array $arguments): void {
$project = Project::make('master');
addTestFileThatReadsOutsideTheCoverageSource($project);
$baseline = $project->pest('--tia', '--coverage', ...$arguments);
expect($baseline->exitCode)->toBe(0, $baseline->describe());
forgetWelcomeTest($project);
$project->write('app/Calculator.php', str_replace(
'return $a + $b;',
'return ($a + $b);',
(string) file_get_contents($project->path('app/Calculator.php')),
));
$project->git()->commit('touch the calculator');
$coverage = $project->pest('--tia', '--coverage', ...$arguments);
expect($coverage->exitCode)->toBe(0, $coverage->describe())
->and($coverage->affected())->toBeGreaterThan(0, $coverage->describe())
->and($coverage->uncached())->toBe(1, $coverage->describe())
->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
@@ -179,6 +179,19 @@ test('tia still requires git', function (): void {
->and($result->exitCode)->not->toBe(0); ->and($result->exitCode)->not->toBe(0);
})->skipOnWindows(); })->skipOnWindows();
test('tia still requires git when git speaks another language', function (): void {
$project = Project::withoutGit();
$result = $project->pestWithEnvironment($project->path(), [
'LC_ALL' => 'es_ES.UTF-8',
'LANG' => 'es_ES.UTF-8',
'LANGUAGE' => 'es',
], '--tia');
expect($result->output)->toContain('The [Tia mode] feature requires [git].')
->and($result->exitCode)->toBe(1, $result->describe());
})->skipOnWindows();
test('a failing git shows its own error instead of asking for git', function (): void { test('a failing git shows its own error instead of asking for git', function (): void {
$project = Project::make('master'); $project = Project::make('master');
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('a filtered configuration alone does not announce tia on a partial run without --tia', function (): void {
$project = Project::make('master');
$project->write('tests/Pest.php', <<<'PHP'
<?php
declare(strict_types=1);
require_once __DIR__.'/../app/Calculator.php';
require_once __DIR__.'/../app/Greeter.php';
pest()->tia()->filtered();
PHP);
$project->git()->commit('filter tia runs');
$result = $project->pest('--no-tia', 'tests/Unit');
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain('4 passed')
->and($result->output)->not->toContain('TIA does not apply to partial runs');
})->skipOnWindows();
+3 -3
View File
@@ -29,10 +29,10 @@ test('an explicit path turns filtered mode off', function (): void {
$result = $project->pest('--tia', '--filtered', 'tests/Unit'); $result = $project->pest('--tia', '--filtered', 'tests/Unit');
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->output)->not->toContain('No affected tests found')
->and($result->output)->not->toContain('No affected tests found')
->and($result->tally())->toContain('4 passed') ->and($result->tally())->toContain('4 passed')
->and($delta->writtenCount())->toBe(4, $delta->summary()) ->and($result->replayed())->toBe(4, $result->describe())
->and($delta->writtenCount())->toBe(0, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows(); })->skipOnWindows();
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('a run without tia finishes when git cannot read the working tree', function (): void {
$project = Project::make('master');
$project->seed('master');
file_put_contents($project->path('.git/index'), 'not an index');
$result = $project->pest();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->not->toContain('could not read the git repository')
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->skipOnWindows();
+1 -1
View File
@@ -179,7 +179,7 @@ test('a graph from a schema this build does not know is rebuilt, not read', func
$project->seed('master'); $project->seed('master');
$project->mutateGraph(function (array $graph): array { $project->mutateGraph(function (array $graph): array {
$graph['schema'] = 2; $graph['schema'] = 99;
return $graph; return $graph;
}); });
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('a changed file whose name is not valid UTF-8 keeps the graph writable', function (array $arguments): void {
$project = Project::make('master');
$project->seed('master');
$project->write("caf\xe9.txt", "one\n");
$first = $project->pest('--tia', ...$arguments);
expect($first->exitCode)->toBe(0, $first->describe())
->and($first->output)->not->toContain('Could not write the dependency graph')
->and($project->graph()['baselines']['master']['tree'] ?? [])->toHaveKey("caf\xe9.txt");
$second = $project->pest('--tia', ...$arguments);
expect($second->exitCode)->toBe(0, $second->describe())
->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->onlyOnLinux();
+25 -19
View File
@@ -21,28 +21,29 @@ test('a filtered run rewrites only the test that ran', function (): void {
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows(); })->skipOnWindows();
test('a filtered run under --tia announces that tia does not apply', function (): void { test('a filtered run under --tia replays the selected test', function (): void {
$project = Project::make('master'); $project = Project::make('master');
$project->seed('master'); $project->seed('master');
$result = $project->pest('--tia', '--filter=adds two numbers'); $result = $project->pest('--tia', '--filter=adds two numbers');
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->output)->not->toContain('TIA does not apply to partial runs')
->and($delta->writtenCount())->toBe(1, $delta->summary()) ->and($result->replayed())->toBe(1, $result->describe())
->and($delta->writtenCount())->toBe(0, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows(); })->skipOnWindows();
test('a test suffix narrows the tier even though every test runs', function (): void { test('a test suffix narrows the tier and replays every selected test', function (): void {
$project = Project::make('master'); $project = Project::make('master');
$project->seed('master'); $project->seed('master');
$result = $project->pest('--tia', '--test-suffix=Test.php'); $result = $project->pest('--tia', '--test-suffix=Test.php');
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed') ->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe())
->and($delta->writtenCount())->toBe(Project::TOTAL_TESTS, $delta->summary()) ->and($delta->writtenCount())->toBe(0, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows(); })->skipOnWindows();
@@ -73,7 +74,7 @@ test('a dirty run narrows to the uncommitted test edit', function (): void {
$result = $project->pest('--tia', '--dirty'); $result = $project->pest('--tia', '--dirty');
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->affected())->toBe(3, $result->describe())
->and($result->tally())->toContain('3 passed') ->and($result->tally())->toContain('3 passed')
->and($delta->removed())->toBe(0, $delta->summary()) ->and($delta->removed())->toBe(0, $delta->summary())
->and($delta->structureMoved())->toBeFalse($delta->summary()); ->and($delta->structureMoved())->toBeFalse($delta->summary());
@@ -86,13 +87,14 @@ test('filtered mode yields to an explicit filter', function (): void {
$result = $project->pest('--tia', '--filtered', '--filter=adds two numbers'); $result = $project->pest('--tia', '--filtered', '--filter=adds two numbers');
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->output)->not->toContain('No affected tests found')
->and($result->tally())->toContain('1 passed') ->and($result->tally())->toContain('1 passed')
->and($delta->writtenCount())->toBe(1, $delta->summary()) ->and($result->replayed())->toBe(1, $result->describe())
->and($delta->writtenCount())->toBe(0, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows(); })->skipOnWindows();
test('an env flag narrows exactly like the option it mirrors', function (string $variable): void { test('an env flag narrows exactly like the option it mirrors', function (string $variable, int $replayed): void {
$project = Project::make('master'); $project = Project::make('master');
$project->seed('master'); $project->seed('master');
@@ -102,10 +104,14 @@ test('an env flag narrows exactly like the option it mirrors', function (string
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->output)->not->toContain('TIA does not apply to partial runs')
->and($delta->writtenCount())->toBe(1, $delta->summary()) ->and($result->replayed())->toBe($replayed, $result->describe())
->and($delta->writtenCount())->toBe(1 - $replayed, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->with(['PEST_TIA', 'PEST_TIA_FILTERED'])->skipOnWindows(); })->with([
'PEST_TIA' => ['PEST_TIA', 1],
'PEST_TIA_FILTERED' => ['PEST_TIA_FILTERED', 0],
])->skipOnWindows();
test('a partial run does not purge the graph even with --fresh', function (): void { test('a partial run does not purge the graph even with --fresh', function (): void {
$project = Project::make('master'); $project = Project::make('master');
@@ -151,20 +157,20 @@ test('a shard is a partial run', function (): void {
$result = $project->pest('--tia', '--shard=1/2'); $result = $project->pest('--tia', '--shard=1/2');
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->replayed())->toBeGreaterThan(0, $result->describe())
->and($delta->removed())->toBe(0, $delta->summary()) ->and($delta->removed())->toBe(0, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows(); })->skipOnWindows();
test('a parallel partial run records the test that ran, like a sequential one', function (): void { test('a parallel partial run replays the selected test, like a sequential one', function (): void {
$project = Project::make('master'); $project = Project::make('master');
$project->seed('master'); $project->seed('master');
$result = $project->pest('--tia', '--parallel', '--processes=2', '--filter=adds two numbers'); $result = $project->pest('--tia', '--parallel', '--processes=2', '--filter=adds two numbers');
$delta = $project->delta(); $delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs') expect($result->tally())->toContain('1 passed')
->and($result->tally())->toContain('1 passed') ->and($result->replayed())->toBe(1, $result->describe())
->and($delta->writtenCount())->toBe(1, $delta->summary()) ->and($delta->writtenCount())->toBe(0, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary()); ->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows(); })->skipOnWindows();
+78
View File
@@ -25,6 +25,19 @@ function tiaRecordWithSourceReadingTest(Project $project, string ...$arguments):
$project->pest('--tia', ...$arguments); $project->pest('--tia', ...$arguments);
} }
/**
* @return array<int, string>
*/
function tiaEdgeFiles(Project $project, string $testFile): array
{
$graph = $project->graph() ?? [];
return array_map(
fn (int $id): string => $graph['files'][$id],
$graph['edges'][$testFile] ?? [],
);
}
test('a test that reads a file records an edge to it', function (array $arguments): void { test('a test that reads a file records an edge to it', function (array $arguments): void {
$project = Project::make('master'); $project = Project::make('master');
@@ -108,3 +121,68 @@ test('a file a test reads does not select it when another file changes', functio
expect($result->affected())->toBe(4, $result->describe()) expect($result->affected())->toBe(4, $result->describe())
->and($result->replayed())->toBe(3, $result->describe()); ->and($result->replayed())->toBe(3, $result->describe());
})->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available'); })->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a test that reads an excluded file records no edge to it', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutReadCapture(['app/Greeter.php']);\n");
tiaRecordWithSourceReadingTest($project, ...$arguments);
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php')
->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a test that reads a file outside the excluded globs still records an edge to it', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutReadCapture(['lang/*.json']);\n");
tiaRecordWithSourceReadingTest($project, ...$arguments);
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->toContain('app/Greeter.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('no read records an edge when read capture is off', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutReadCapture();\n");
tiaRecordWithSourceReadingTest($project, ...$arguments);
expect(tiaEdgeFiles($project, 'tests/Unit/GreeterTest.php'))->toContain('app/Greeter.php')
->and(tiaEdgeFiles($project, 'tests/Unit/GreeterSourceTest.php'))->not->toContain('app/Greeter.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a watch pattern reruns tests after an excluded file changes', function (array $arguments): void {
$project = Project::make('master');
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).<<<'PHP'
pest()->tia()
->withoutReadCapture(['data/*.json'])
->watch(['data/*.json' => 'tests/Unit/GreeterTest.php']);
PHP);
$project->write('data/status.json', '"ready"');
$testFile = 'tests/Unit/GreeterTest.php';
$project->write($testFile, str_replace(
' expect((new Greeter)->greet(\'Nuno\'))->toBe(\'Hello, Nuno!\');',
' expect(file_get_contents(__DIR__.\'/../../data/status.json\'))->toBe(\'"ready"\');',
file_get_contents($project->path($testFile)),
));
$project->git()->commit('add a watched JSON fixture');
$project->seed('master');
$project->write('data/status.json', '"broken"');
$project->git()->commit('change the watched fixture');
$result = $project->pest('--tia', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->affected())->toBe(2, $result->describe())
->and($result->replayed())->toBe(4, $result->describe())
->and($result->output)->toContain('greets a person', 'broken');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+27
View File
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
test('a partial run without a coverage driver names its selection, not the full suite', function (): void {
$project = Project::make('master');
$project->seed('master');
$project->write('app/Calculator.php', str_replace(
'return $a + $b;',
'return $b + $a;',
(string) file_get_contents($project->path().'/app/Calculator.php'),
));
$result = $project->pestWithEnvironment($project->path(), ['XDEBUG_MODE' => 'off'], '--tia', 'tests/Unit');
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->toContain('no coverage driver is available')
->and($result->tally())->toContain('4 passed')
->and($result->output)->not->toContain('Running the full suite');
})->skipOnWindows();
+169
View File
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
use Pest\Plugins\Tia;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function tiaEditGreeterTest(Project $project): void
{
$project->write('tests/Unit/GreeterTest.php', <<<'PHP'
<?php
declare(strict_types=1);
use Fixture\App\Greeter;
test('greets a person', function (): void {
expect((new Greeter)->greet('Nuno'))->toBe('Hello, Nuno!');
})->group('greeter');
test('greets the world', function (): void {
expect((new Greeter)->greet('world'))->toBe('Hello, world!');
})->group('greeter');
test('greets again', function (): void {
expect((new Greeter)->greet('again'))->toBe('Hello, again!');
})->group('greeter');
PHP);
}
test('a partial run replays the unaffected tests of its selection', function (array $selection, int $affected, int $replayed, array $mode): void {
$project = Project::make('master');
$project->seed('master');
tiaEditGreeterTest($project);
$result = $project->pest('--tia', ...$selection, ...$mode);
$delta = $project->delta();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->not->toContain('TIA does not apply to partial runs')
->and($result->tally())->toContain(($affected + $replayed).' passed')
->and($result->affected())->toBe($affected, $result->describe())
->and($result->replayed())->toBe($replayed, $result->describe())
->and($delta->structureMoved())->toBeFalse($delta->summary())
->and($delta->shaMoved())->toBeFalse($delta->summary())
->and($delta->treeMoved())->toBeFalse($delta->summary())
->and($delta->removed())->toBe(0, $delta->summary());
})->with([
'an explicit path' => [['tests/Unit'], 3, 2],
'--filter' => [['--filter=greets a person|adds two numbers'], 1, 1],
'--group' => [['--group=greeter'], 3, 0],
'--exclude-group' => [['--exclude-group=greeter'], 0, 4],
'--testsuite' => [['--testsuite=default'], 3, 4],
'--dirty' => [['--dirty'], 3, 0],
])->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('a partial run re-runs a cached failure in its selection', function (): void {
$project = Project::make('master');
$project->seed('master', failing: ['adds two numbers']);
$result = $project->pest('--tia', 'tests/Unit');
$delta = $project->delta();
expect($result->tally())->toContain('4 passed')
->and($result->replayed())->toBe(3, $result->describe())
->and($delta->writtenCount())->toBe(1, $delta->summary())
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows();
test('a partial run leaves the affected tests to the next complete run', function (): void {
$project = Project::make('master');
$project->seed('master');
tiaEditGreeterTest($project);
$project->pest('--tia', '--exclude-group=greeter');
$result = $project->pest('--tia');
expect($result->affected())->toBe(3, $result->describe())
->and($result->replayed())->toBe(4, $result->describe());
})->skipOnWindows();
test('a partial run without a graph runs its selection and records nothing', function (): void {
$project = Project::make('master');
$result = $project->pest('--tia', 'tests/Unit');
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->toContain('a partial run cannot record the dependency graph')
->and($result->tally())->toContain('4 passed')
->and($result->replayed())->toBe(0, $result->describe())
->and($project->graphExists())->toBeFalse();
})->skipOnWindows();
test('a partial run with a coverage report runs its selection directly', function (): void {
$project = Project::make('master');
$project->seed('master');
$result = $project->pest('--tia', 'tests/Unit', '--coverage-text');
$delta = $project->delta();
expect($result->output)->toContain('TIA does not apply to partial runs')
->and($result->replayed())->toBe(0, $result->describe())
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
})->skipOnWindows();
test('a partial run in a repository a complete run refuses runs its selection directly', function (Closure $prepare): void {
$project = $prepare();
$result = $project->pest('--tia', 'tests/Unit');
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain('4 passed')
->and($result->output)->toContain('TIA does not apply to partial runs')
->and($project->graphExists())->toBeFalse();
})->with([
'no remote' => [function (): Project {
$project = Project::make('master');
$project->git()->removeOrigin();
$project->git()->switchTo('feature-x', new: true);
return $project;
}],
'no default branch' => [function (): Project {
$project = Project::make('master');
$project->git()->unsetOriginHead();
$project->git()->config('init.defaultBranch', 'main');
$project->git()->switchTo('feature-x', new: true);
return $project;
}],
'no commits' => [function (): Project {
$project = Project::withoutGit();
$project->git()->run(['init', '--quiet']);
$project->git()->run(['checkout', '--quiet', '-b', 'master']);
$project->git()->addOrigin();
return $project;
}],
'no git' => [fn (): Project => Project::withoutGit()],
])->skipOnWindows();
test('a partial run leaves a graph recorded in a different environment alone', function (string $section, string $key, string $value): void {
$project = Project::make('master');
$project->seed('master');
$project->mutateGraph(function (array $graph) use ($section, $key, $value): array {
$graph['fingerprint'][$section][$key] = $value;
return $graph;
});
file_put_contents($project->graphDir().'/'.Tia::KEY_COVERAGE_CACHE, 'cached coverage');
$project->snapshot();
$result = $project->pest('--tia', '--filter=adds two numbers');
$delta = $project->delta();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->toContain('The graph was recorded in a different environment ('.$key.')')
->and($result->tally())->toContain('1 passed')
->and($result->replayed())->toBe(0, $result->describe())
->and($delta->isHardSuppressed())->toBeTrue($delta->summary())
->and($project->graphDir().'/'.Tia::KEY_COVERAGE_CACHE)->toBeFile();
})->with([
'another PHP minor version' => ['environmental', 'php_minor', '7.4'],
'another lockfile' => ['structural', 'composer_lock', 'a-lockfile-this-project-never-had'],
])->skipOnWindows();
+118
View File
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\ExecutableFinder;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function fakeGitPath(Project $project, string $case): string
{
$git = (new ExecutableFinder)->find('git');
assert(is_string($git));
$directory = $project->path('.fake-git');
$realGit = escapeshellarg($git);
mkdir($directory);
file_put_contents($directory.'/git', <<<SH
#!/bin/sh
case "\$1 \$2" in
{$case}
esac
exec {$realGit} "\$@"
SH);
chmod($directory.'/git', 0755);
if (! is_dir($project->path('.git/info'))) {
mkdir($project->path('.git/info'));
}
file_put_contents($project->path('.git/info/exclude'), "/.fake-git/\n", FILE_APPEND);
return $directory.PATH_SEPARATOR.getenv('PATH');
}
test('a slow git while naming the branch records nothing without --tia', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = fakeGitPath($project, '"symbolic-ref "*) exec sleep 6 ;;');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
$delta = $project->delta();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
->and($result->output)->not->toContain('Git did not answer')
->and($delta->baselineUntouched('master'))->toBeTrue($delta->summary());
})->skipOnWindows();
test('a slow branch listing after the suite keeps the run results without --tia', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = fakeGitPath($project, '"for-each-ref "*) exec sleep 6 ;;');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
$delta = $project->delta();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
->and($result->output)->not->toContain('Git did not answer')
->and($project->branchKeys())->toBe(['master'])
->and($delta->writtenCount())->toBe(Project::TOTAL_TESTS, $delta->summary());
})->skipOnWindows();
test('a run without --tia records nothing when git cannot name the current branch', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = fakeGitPath($project, '"rev-parse --abbrev-ref") exit 128 ;;');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
$delta = $project->delta();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
->and($project->branchKeys())->toBe(['master'])
->and($delta->baselineUntouched('master'))->toBeTrue($delta->summary());
})->skipOnWindows();
test('a slow git stops a --tia run with the timeout', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = fakeGitPath($project, '"symbolic-ref "*) exec sleep 6 ;;');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path], '--tia');
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->output)->toContain('Git did not answer within 5 seconds: git symbolic-ref')
->and($result->output)->not->toContain('default branch');
})->skipOnWindows();
test('a slow git check-ignore keeps composer.lock in the fingerprint', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = fakeGitPath($project, '"check-ignore -z") exec sleep 6 ;;');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path], '--tia');
$delta = $project->delta();
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->output)->not->toContain('Git did not answer')
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe())
->and($delta->structureMoved())->toBeFalse($delta->summary());
})->skipOnWindows();
test('a slow git stops a --tia run with the command that timed out first', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = fakeGitPath($project, '"symbolic-ref "*|"rev-parse --git-dir") exec sleep 6 ;;');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path], '--tia');
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->output)->toContain('Git did not answer within 5 seconds: git symbolic-ref');
})->skipOnWindows();
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
use Symfony\Component\Process\ExecutableFinder;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function slowGitAtBootPath(Project $project, string $command): string
{
$git = (new ExecutableFinder)->find('git');
assert(is_string($git));
$directory = $project->path('.slow-git');
$realGit = escapeshellarg($git);
$slept = escapeshellarg($directory.'/slept');
mkdir($directory);
file_put_contents($directory.'/git', <<<SH
#!/bin/sh
case "\$1 \$2" in
"{$command}") [ -e {$slept} ] || { touch {$slept}; exec sleep 6; } ;;
esac
exec {$realGit} "\$@"
SH);
chmod($directory.'/git', 0755);
return $directory.PATH_SEPARATOR.getenv('PATH');
}
test('a slow git while reading the origin url does not stop a run without --tia', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = slowGitAtBootPath($project, 'config --get');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
->and($project->path('.slow-git/slept'))->toBeFile('the slow git never ran');
})->skipOnWindows();
test('a slow git while reading the path prefix does not stop a run without --tia', function (): void {
$project = Project::make('master');
$project->seed('master');
$path = slowGitAtBootPath($project, 'rev-parse --show-prefix');
$result = $project->pestWithEnvironment($project->path(), ['PATH' => $path]);
expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
->and($project->path('.slow-git/slept'))->toBeFile('the slow git never ran');
})->skipOnWindows();
+23
View File
@@ -2,6 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
use PHPUnit\Framework\TestStatus\TestStatus;
use Tests\Fixtures\Tia\Project; use Tests\Fixtures\Tia\Project;
afterEach(function (): void { afterEach(function (): void {
@@ -385,3 +386,25 @@ test('a full suite run without a coverage driver clears the tree it could not re
->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe()) ->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe())
->and($delta->writtenCount())->toBe(0, $delta->summary()); ->and($delta->writtenCount())->toBe(0, $delta->summary());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); })->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('a full suite run without a coverage driver records the results it ran', function (array $arguments): void {
$project = Project::make('master');
$project->seed('master');
$id = Project::testId('tests/Unit/CalculatorTest.php', 'adds two numbers');
expect($project->graph()['baselines']['master']['results'][$id]['status'])->toBe(TestStatus::success()->asInt());
$project->write('app/Calculator.php', str_replace(
'return $a + $b;',
'return $a - $b;',
(string) file_get_contents($project->path().'/app/Calculator.php'),
));
$project->git()->commit('break the adder');
$result = $project->pestWithEnvironment($project->path(), ['XDEBUG_MODE' => 'off'], '--tia', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->output)->toContain('no coverage driver is available')
->and($project->graph()['baselines']['master']['results'][$id]['status'])->toBe(TestStatus::failure()->asInt());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+69
View File
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
use Pest\Support\Coverage;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function addTestFileTheGraphDoesNotKnow(Project $project): void
{
$project->write('tests/Integration/WelcomeTest.php', <<<'PHP'
<?php
declare(strict_types=1);
use Fixture\App\Greeter;
test('welcomes a visitor', function (): void {
expect((new Greeter)->greet('visitor'))->toBe('Hello, visitor!');
});
PHP);
$project->git()->commit('add a test file the graph does not know');
}
test('a replay records a test file the graph does not know', function (array $arguments): void {
$project = Project::make('master');
addTestFileTheGraphDoesNotKnow($project);
$project->seed('master');
$first = $project->pest('--tia', ...$arguments);
expect($first->exitCode)->toBe(0, $first->describe())
->and($first->replayed())->toBe(Project::TOTAL_TESTS, $first->describe())
->and($first->uncached())->toBe(1, $first->describe())
->and($project->graph()['edges'] ?? [])->toHaveKey('tests/Integration/WelcomeTest.php');
$second = $project->pest('--tia', ...$arguments);
expect($second->exitCode)->toBe(0, $second->describe())
->and($second->replayed())->toBe(Project::TOTAL_TESTS + 1, $second->describe())
->and($second->uncached())->toBe(0, $second->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a replay that records a test file the graph does not know keeps the edges of the known test files', function (array $arguments): void {
$project = Project::make('master');
addTestFileTheGraphDoesNotKnow($project);
$project->seed('master', failing: ['greets a person']);
$project->mutateGraph(function (array $graph): array {
$graph['edges']['tests/Unit/GreeterTest.php'][] = array_search('app/Calculator.php', $graph['files'], true);
return $graph;
});
$known = $project->graph()['edges'] ?? [];
$result = $project->pest('--tia', ...$arguments);
$edges = $project->graph()['edges'] ?? [];
expect($result->exitCode)->toBe(0, $result->describe())
->and($edges)->toHaveKey('tests/Integration/WelcomeTest.php');
unset($edges['tests/Integration/WelcomeTest.php']);
expect($edges)->toBe($known);
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
+28
View File
@@ -63,3 +63,31 @@ test('still runs every test without a baseline when defaults are disabled', func
expect($result->exitCode)->toBe(0, $result->describe()) expect($result->exitCode)->toBe(0, $result->describe())
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed'); ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); })->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
test('runs dependent tests when a watched path is removed', function (array $gitArguments, array $arguments): void {
$project = Project::make('master');
$project->write('schema/api.graphql', "type Query { status: String }\n");
$project->write('tests/Pest.php', file_get_contents($project->path('tests/Pest.php')).
"\npest()->tia()->withoutDefaultWatchPatterns()->watch(['schema/*.graphql' => 'tests/Unit/GreeterTest.php']);\n");
$test = 'tests/Unit/GreeterTest.php';
$project->write($test, str_replace(
"test('greets a person', function (): void {",
"test('greets a person', function (): void {\n expect('schema/api.graphql')->toBeFile();",
file_get_contents($project->path($test)),
));
$project->git()->commit('add a watched schema and its test');
$project->seed('master');
$project->git()->run($gitArguments);
$project->git()->commit('remove the watched path');
$result = $project->pest('--tia', '--filtered', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe())
->and($result->affected())->toBe(2, $result->describe())
->and($result->output)->toContain('greets a person', 'schema/api.graphql');
})->with([
'deleted' => [['rm', '--', 'schema/api.graphql']],
'renamed' => [['mv', '--', 'schema/api.graphql', 'moved.graphql']],
])->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="../../vendor/autoload.php">
<php>
<includePath>ParallelIncludePath/xml-lib</includePath>
</php>
</phpunit>
@@ -0,0 +1,11 @@
<?php
$valueRequiredWhileLoading = require 'parallel-include-path.inc';
test('requires a file through the include path while loading', function () use ($valueRequiredWhileLoading) {
expect($valueRequiredWhileLoading)->toBe('resolved through the include path');
});
test('requires a file through the include path while running', function () {
expect(require 'parallel-include-path.inc')->toBe('resolved through the include path');
});
@@ -0,0 +1,7 @@
<?php
require_once __DIR__.'/../../../vendor/autoload.php';
if ((require 'parallel-include-path.inc') !== 'resolved through the include path') {
throw new RuntimeException('The bootstrap file did not resolve the command line include path first.');
}
@@ -0,0 +1,3 @@
<?php
return 'resolved through the include path';
@@ -0,0 +1,3 @@
<?php
return 'resolved through the include path';

Some files were not shown because too many files have changed in this diff Show More