mirror of
https://github.com/pestphp/pest.git
synced 2026-12-03 22:45:06 +01:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 14a3efd918 | |||
| 8b6607e344 | |||
| 94f4f1ff48 | |||
| f0dd0d4d85 | |||
| 4b4474dd77 | |||
| 942d6aead1 | |||
| 7cdebc6a95 | |||
| c9c3a8c34a | |||
| 06400e721e | |||
| c42a2719e4 | |||
| 2440001cfc | |||
| e68976ea9d | |||
| 17d709e32b | |||
| 46df02dc28 | |||
| fc17365bd1 | |||
| 20a5aacaca | |||
| eac05bcee9 | |||
| b5b2ba7d7f | |||
| 627092ecfc | |||
| 2692613f09 | |||
| e763a87b42 | |||
| 4a65054f83 | |||
| b8c2265d66 | |||
| 39cbdcd52b | |||
| aba2b79609 | |||
| 1af74a215c | |||
| cfe89d20ac | |||
| 2c7cc1dc87 | |||
| 9b36f44b3e | |||
| 2e58918201 | |||
| a8d4770c0b |
@@ -3,12 +3,15 @@
|
||||
/tests export-ignore
|
||||
/scripts export-ignore
|
||||
/.github export-ignore
|
||||
/.hod export-ignore
|
||||
.editorconfig export-ignore
|
||||
.gitattributes export-ignore
|
||||
.gitignore export-ignore
|
||||
/phpstan.neon export-ignore
|
||||
/phpunit.xml export-ignore
|
||||
/CHANGELOG.md export-ignore
|
||||
/AGENTS.md export-ignore
|
||||
/CLAUDE.md export-ignore
|
||||
/CONTRIBUTING.md export-ignore
|
||||
/docker-compose.yml export-ignore
|
||||
/Makefile export-ignore
|
||||
|
||||
@@ -14,3 +14,6 @@ coverage.xml
|
||||
.vscode/
|
||||
.STREAM.md
|
||||
|
||||
|
||||
/.claude/skills/
|
||||
/.agents/skills/
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# The intention of this project
|
||||
|
||||
Pest is a testing framework for PHP with a focus on simplicity. A PHP developer uses it to write the tests of an application or of a package, and an AI agent reads its output. It is a package, and `src/Functions.php` holds its public API.
|
||||
|
||||
Install the dependencies with `composer install`. Run the tests with `composer test`. Start the program with `./bin/pest`.
|
||||
|
||||
- `src/` — the framework: the plugins, the expectation API, the test case and the console output
|
||||
- `bin/` — the executable `pest` and the worker of the parallel runner
|
||||
- `overrides/` — the classes of PHPUnit that Pest replaces, which `src/Bootstrappers/BootOverrides.php` loads at boot
|
||||
- `resources/` — the views of the console output and the base configuration of PHPUnit
|
||||
- `stubs/` — the files that `pest --init` writes into a project
|
||||
- `tests/` — the tests of the framework, in Pest itself
|
||||
- `tests-external/` — the tests that must sit outside `tests/`
|
||||
- `docker/` — the image that runs the tests on one version of PHP
|
||||
@@ -0,0 +1,34 @@
|
||||
8fee50af5e8d9ff55db278de9701b10e11dfef6eecfc4127f2608c85f0f0fdd1 .agents/skills/code-immutability/SKILL.md
|
||||
d489e18e5863e814795f5674a58f507e98fbbeb341a218dbd5bc9173d39554d3 .agents/skills/code-immutability/agents/openai.yaml
|
||||
0c47a67a1bcb590b057984fa4e9c4704fb3485652864f3e5ac6a3ba8200e74f4 .agents/skills/code-messages/SKILL.md
|
||||
fc01d0c81e189623e6e7c912498f46f63f489bbe59967cccde742ea2c4e31b5a .agents/skills/code-messages/agents/openai.yaml
|
||||
3d39b47c159c0bbdc413781afe12cdb9fcad4086d4810a6c11dfd0c909d90e81 .agents/skills/code-quality/SKILL.md
|
||||
f47191e1bad34e547d1b3ee3ae111c417c383ec5459d467bfae5e832d86275c9 .agents/skills/code-quality/agents/openai.yaml
|
||||
9d5e921bdfa05ef955657d59702e79a83b44853c075d513793bb76a7f479004f .agents/skills/code-slop/SKILL.md
|
||||
520a3834948850bf7e2232d92341f07ff7bfc9e67247818b56fb576ca6dbf169 .agents/skills/code-slop/agents/openai.yaml
|
||||
2f9d68ed1b93eb74bc1c23cad34a88b765bd0ab306faacab1105d9489ede8ad1 .agents/skills/code-tooling/SKILL.md
|
||||
868c67118e15aa9eb8f4ee35228fc2d04b1c0cf129ee3fec9177113a77f5863e .agents/skills/code-tooling/agents/openai.yaml
|
||||
5df241fc65e271c93d13708f868f9a624669bcfc06b3d84af9cf6fce03a25558 .agents/skills/deps-upgrade/SKILL.md
|
||||
984c7232ae1681ebba980ede2a0543db9a850dd2406990cdfa011384f929e981 .agents/skills/deps-upgrade/agents/openai.yaml
|
||||
275df9900027499c1ab97ab2675b2992e4267559bd61933a637d6a15d25a9350 .agents/skills/init/SKILL.md
|
||||
14ea76cbc5a8f35356ccf6aa20beddb249c6bc4aeb9999ec722c3acf92389d57 .agents/skills/init/agents/openai.yaml
|
||||
3f7f77275ada85b55ed874cea8ada94ad6f838800311f46ecb2a31b68ae95ac7 .agents/skills/snapshots-update/SKILL.md
|
||||
bb5339d7abcaba163a384a00a9ba8607ddf8b6820a63be3570e9b6fc6a912479 .agents/skills/snapshots-update/agents/openai.yaml
|
||||
8fee50af5e8d9ff55db278de9701b10e11dfef6eecfc4127f2608c85f0f0fdd1 .claude/skills/code-immutability/SKILL.md
|
||||
d489e18e5863e814795f5674a58f507e98fbbeb341a218dbd5bc9173d39554d3 .claude/skills/code-immutability/agents/openai.yaml
|
||||
0c47a67a1bcb590b057984fa4e9c4704fb3485652864f3e5ac6a3ba8200e74f4 .claude/skills/code-messages/SKILL.md
|
||||
fc01d0c81e189623e6e7c912498f46f63f489bbe59967cccde742ea2c4e31b5a .claude/skills/code-messages/agents/openai.yaml
|
||||
3d39b47c159c0bbdc413781afe12cdb9fcad4086d4810a6c11dfd0c909d90e81 .claude/skills/code-quality/SKILL.md
|
||||
f47191e1bad34e547d1b3ee3ae111c417c383ec5459d467bfae5e832d86275c9 .claude/skills/code-quality/agents/openai.yaml
|
||||
9d5e921bdfa05ef955657d59702e79a83b44853c075d513793bb76a7f479004f .claude/skills/code-slop/SKILL.md
|
||||
520a3834948850bf7e2232d92341f07ff7bfc9e67247818b56fb576ca6dbf169 .claude/skills/code-slop/agents/openai.yaml
|
||||
2f9d68ed1b93eb74bc1c23cad34a88b765bd0ab306faacab1105d9489ede8ad1 .claude/skills/code-tooling/SKILL.md
|
||||
868c67118e15aa9eb8f4ee35228fc2d04b1c0cf129ee3fec9177113a77f5863e .claude/skills/code-tooling/agents/openai.yaml
|
||||
5df241fc65e271c93d13708f868f9a624669bcfc06b3d84af9cf6fce03a25558 .claude/skills/deps-upgrade/SKILL.md
|
||||
984c7232ae1681ebba980ede2a0543db9a850dd2406990cdfa011384f929e981 .claude/skills/deps-upgrade/agents/openai.yaml
|
||||
275df9900027499c1ab97ab2675b2992e4267559bd61933a637d6a15d25a9350 .claude/skills/init/SKILL.md
|
||||
14ea76cbc5a8f35356ccf6aa20beddb249c6bc4aeb9999ec722c3acf92389d57 .claude/skills/init/agents/openai.yaml
|
||||
3f7f77275ada85b55ed874cea8ada94ad6f838800311f46ecb2a31b68ae95ac7 .claude/skills/snapshots-update/SKILL.md
|
||||
bb5339d7abcaba163a384a00a9ba8607ddf8b6820a63be3570e9b6fc6a912479 .claude/skills/snapshots-update/agents/openai.yaml
|
||||
d1e4a22c7e3b8b833d873b139d331d85fb9f5247818911b35082ae9a8f6edf9f AGENTS.md
|
||||
336cc4fbf19beaada7ccf9986414fa91851a8d7a07dfb3ccbe800a69eed0ab49 CLAUDE.md
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: snapshots-update
|
||||
description: "Write each snapshot of this project again, then run the integration suite until it passes. Use when the user asks to update the snapshots, when a test of `tests/Visual/` fails, or when `composer test:integration` fails after a change of the number of the tests."
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Snapshots
|
||||
|
||||
Write each snapshot of this project again, then run `composer test:integration` until it passes.
|
||||
|
||||
`tests/Pest.php` puts each test of `tests/Visual/` in the group `integration`, and each of those tests asserts the output of a full run of the suite. Thus a change of the number of the tests, of the number of the assertions, or of one line of the output of `bin/pest` breaks the integration suite, and this skill repairs it.
|
||||
|
||||
Obey the order of the sections. Section 3 writes the number of the tests of a clean run, and section 4 writes that number into `tests/.snapshots/success.txt`. The reverse order writes the failure of the test `parallel` into that snapshot, and the integration suite then fails on the test `visual snapshot of test suite on success`.
|
||||
|
||||
## 1. Read the working tree
|
||||
|
||||
Run `git status --short`. Name each file that carries a change, then continue with that change in place, because the user starts this skill in the middle of a change.
|
||||
|
||||
Write no commit and no tag during this work. Leave each change in the working tree.
|
||||
|
||||
## 2. Turn off the coverage driver
|
||||
|
||||
Put `XDEBUG_MODE=off` in front of each command of this skill. `.github/workflows/tests.yml` gives `coverage: none` to each job, thus a run of this project on GitHub collects no coverage, and `tests/.snapshots/success.txt` holds the line `it adds coverage if --coverage exist → Coverage is not available`. A run with a coverage driver writes one test more as passed, and the snapshot then fails on GitHub.
|
||||
|
||||
Run `php -m | grep -iE "xdebug|pcov"` and read the name of each coverage driver of this computer. `XDEBUG_MODE=off` turns off `xdebug`. Add `-d pcov.enabled=0` to `php` for `pcov`, and run the command of the composer script `update:snapshots` directly for that flag.
|
||||
|
||||
## 3. Write the summary of the parallel run
|
||||
|
||||
Run this command with a timeout of 900 seconds:
|
||||
|
||||
```
|
||||
XDEBUG_MODE=off COLLISION_PRINTER=DefaultPrinter COLLISION_IGNORE_DURATION=true PAO_DISABLE=1 php bin/pest --parallel --processes=3 --exclude-group=integration
|
||||
```
|
||||
|
||||
Read the line that starts with `Tests:`. Take the text after `Tests:` up to and with `(<number> assertions)`, such as `2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1578 passed (3426 assertions)`. That text is the summary.
|
||||
|
||||
Run `grep -n "assertions)';" tests/Visual/Parallel.php`. The command gives one line, and that line holds the value of `$expected` of the test `parallel`. Write the summary in that line when the two texts differ, and change no other line of the file.
|
||||
|
||||
## 4. Write each snapshot again
|
||||
|
||||
Run `XDEBUG_MODE=off composer update:snapshots` with a timeout of 1800 seconds. The command runs `REBUILD_SNAPSHOTS=true php bin/pest --update-snapshots --exclude-group=tia`, and it writes `tests/.snapshots/success.txt` and each file under `tests/.pest/snapshots/`. The command starts a full suite inside a test of `tests/Visual/`, thus the command needs some minutes.
|
||||
|
||||
The command exits with the code 2 after a correct run. Read the output and accept these three results:
|
||||
|
||||
- a `FAILED` test of `tests/Visual/`, because the test reads the old snapshot and writes the new snapshot in the same run.
|
||||
- a `FAILED` test of `tests/Features/Flaky.php`, because `--update-snapshots` writes each snapshot and a flaky test stops the retry when a snapshot changes.
|
||||
- a `RISKY` test that performs no assertion, because a test that only writes a snapshot asserts nothing.
|
||||
|
||||
Run `XDEBUG_MODE=off composer test:unit` for a `FAILED` test outside `tests/Visual/` and outside `tests/Features/Flaky.php`. That command writes no snapshot, thus it separates a regression of the code from an effect of `--update-snapshots`. Stop when the test fails again, give the report of section 6, and write no snapshot again.
|
||||
|
||||
Run `grep -c "Coverage is not available" tests/.snapshots/success.txt`. The count is 1. Return to section 2 for the count 0, because a coverage driver of this computer stays on.
|
||||
|
||||
## 5. Run the integration suite
|
||||
|
||||
Run `XDEBUG_MODE=off composer test:integration` with a timeout of 3600 seconds.
|
||||
|
||||
Read each test that failed, then take one action.
|
||||
|
||||
| Test that failed | Action |
|
||||
| --- | --- |
|
||||
| the test `parallel` of `tests/Visual/Parallel.php` | Return to section 3, because the numbers of the suite moved after the last measure. |
|
||||
| a different test of `tests/Visual/` | Return to section 3, because `tests/.snapshots/success.txt` holds the numbers of section 3. |
|
||||
| a test outside `tests/Visual/` | Stop. Give the report of section 6, and write no snapshot again. |
|
||||
|
||||
Return to section 3 two times at the most. Give the report of section 6 after the last run, and name each test that failed in that run.
|
||||
|
||||
## 6. Report
|
||||
|
||||
Give four items:
|
||||
|
||||
- each file that this work changed, from `git status --short`.
|
||||
- the summary that `tests/Visual/Parallel.php` holds now, and the summary that the file held before this work.
|
||||
- the result of the last run of `composer test:integration`, and the name of each test that failed in that run.
|
||||
- each section that you repeated, and the reason.
|
||||
@@ -0,0 +1,5 @@
|
||||
interface:
|
||||
display_name: "Snapshots Update"
|
||||
short_description: "Write each snapshot of this project again"
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
@@ -0,0 +1,75 @@
|
||||
# The project
|
||||
|
||||
Read `.hod/PROJECT.md` first. It holds the intention of this project.
|
||||
|
||||
`hod` writes this file. Write no sentence in it, because `hod update` writes it again. Write the intention of the project in `.hod/PROJECT.md`. Write a rule in a file in `.hod/rules/`. Write a skill in a directory in `.hod/skills/`.
|
||||
|
||||
---
|
||||
|
||||
## 1. The reader of this file
|
||||
|
||||
This file is for a coding agent. No user reads it. Write an instruction that an agent obeys during its work, then stop. Do not write an introduction, a conclusion, an argument for a decision that the project made, or a sentence that no agent can obey. Give a reason only when the reason changes the next decision of the agent.
|
||||
|
||||
Start each rule with a verb in the imperative. Put the condition before the instruction. Give the exact path, the exact command and the exact name that the agent must use. If a rule needs a test, give the command that does the test.
|
||||
|
||||
The public files are different. `README.md`, the website, the release notes and the `description` in each manifest are for a user. Section 3 controls them. Section 5 controls each message that you give the user.
|
||||
|
||||
---
|
||||
|
||||
## 2. How to write for an agent
|
||||
|
||||
Write in [ASD-STE100](https://www.asd-ste100.org) Simplified Technical English: one instruction in one sentence, the imperative, the active voice, one meaning for one word, no contraction, and no synonym for variety. The standard holds the full rules. Do not copy them here. Four items keep their exact form: a quotation from a standard, an identifier in the code, a path or a command, and a name from a different supplier.
|
||||
|
||||
Write GitHub flavored Markdown. Put one `#` heading in a file. Write one paragraph on one line, thus a change stays small in `git diff`. Number the sections of a long file, thus a different file can point to "section 3". Put a path, a command and a name from the code in `code font`.
|
||||
|
||||
Write the intention of the project in `.hod/PROJECT.md`. Write a decision about one directory in the `AGENTS.md` file of that directory. If `.hod/PROJECT.md` and the `AGENTS.md` file of a directory disagree, obey `.hod/PROJECT.md` and correct the other file.
|
||||
|
||||
Write no new rule. This is the correct result of each task, and a task that adds a command, a module or a workflow does not change it. A rule needs a fault that happened: name the decision that you made wrong, or name the decision that these files refused to give you. A wrong change that you imagine is not a fault, thus write no rule to protect the code that you write today.
|
||||
|
||||
A fact that you learned during one task is not a rule. Use it in that task, then write no sentence for it.
|
||||
|
||||
`.hod/PROJECT.md` holds two items: the intention of the project, and a reason that the code cannot hold. Write no sentence below that level.
|
||||
|
||||
Write no sentence for a fact that an agent finds when it reads the code. The cost of that read does not change the answer: a fact that four files hold is in the code. Put the fact in the code first, because a test stops the agent that breaks it and a sentence here does not.
|
||||
|
||||
Ask the user before you write a rule. Give the fault, and write the rule after the user agrees. Give the file the path `.hod/rules/<name>.md`. Give `<name>` two or three words with a hyphen between them, and name the subject of the rule. Give the file `name` and `description` in its front matter, and write one rule in one file. Run `hod update --project` after the write, thus this file names the rule in section 6. Keep the number of the rules: delete a rule file in the same change, or ask the user to accept one more rule. A correction from the user is a rule and needs no question: write it in a file before you continue the work.
|
||||
|
||||
Give no new part of the program its own rule, because the code of that part holds its design. Delete text that follows the order of a file of source code: that text describes the file, and the file describes itself. Replace an old rule. Do not write a second rule near it. Delete a rule that the project does not obey. Do not keep a record of what the project stopped doing, in a file or in a directory. Git holds the history.
|
||||
|
||||
---
|
||||
|
||||
## 3. How to write the public text
|
||||
|
||||
These rules control `README.md`, the website, the release notes, the announcement and the `description` in each manifest. Sections 1 and 2 do not control these files.
|
||||
|
||||
The voice is calm and certain. Say what the project does, then stop. Do not say that the project is fast, simple, powerful or intelligent. Show the command and let the reader form that opinion. Cut each superlative. Cut each sentence that a competitor can also write about itself.
|
||||
|
||||
Write for one person and call that person "you". Put the result first and the mechanism second. Keep the sentences short, and let one sentence stand alone when it carries the idea. A demonstration is the strongest argument: one command in a terminal is worth one paragraph of adjectives.
|
||||
|
||||
The care is in the small parts. The alignment of the output, the words in an error message, the space around the text on the page: the reader feels this work before the reader reads one sentence. The project is for people who enjoy their work, thus the text is warm. Put one dry joke on one page, at the most. Do not explain it.
|
||||
|
||||
Obey three limits. Do not promise a feature that does not exist today. Do not give a number without its source. Do not name a different product to make a comparison.
|
||||
|
||||
---
|
||||
|
||||
## 4. How to write the code
|
||||
|
||||
These rules control each file of source code and each manifest in this repository. Sections 1, 2 and 3 do not control these files.
|
||||
|
||||
Write no comment. Delete each comment that you find in a file that you change. Turn off the lint that asks for a documentation comment, because that lint asks you to say the name of an item again.
|
||||
|
||||
Put the intention in the code. Give each item a name that says what the item does. Give each value a type that makes a wrong value impossible. Split a long function into two functions with two names. A name and a type stay correct, and a comment does not.
|
||||
|
||||
Write a reason that the code cannot hold in a file in `.hod/rules/`, with the path of the code. Do not write it above the code.
|
||||
|
||||
When a library reads the text of a comment as data, such as the description of a command on a help screen, write that text in an attribute or a field of that library instead.
|
||||
|
||||
A tool that writes a comment into a file that it owns keeps that comment. Do not delete it: the tool fails until it writes the comment again.
|
||||
|
||||
---
|
||||
|
||||
## 5. How to write a message to the user
|
||||
|
||||
Write each message that you give the user in the English of section 2: one instruction in one sentence, the imperative, the active voice, one meaning for one word, and no contraction. A question, a report, a plan and an answer obey this rule.
|
||||
|
||||
Give the result first. Give the exact path, the exact command and the exact name. Write no sentence that says the work again, and no adjective that gives the reader no new fact.
|
||||
@@ -1,34 +1 @@
|
||||
# CLAUDE.md
|
||||
|
||||
**Do not edit this file.** Agents must never add, remove, or reword anything here. If a change seems needed, say so and let a human do it.
|
||||
|
||||
## Ask before testing
|
||||
|
||||
When asked to review code or build a feature, do not run the test suite and do not write new tests. Make the change, report it, then ask the user whether tests should be added — describing the tests you have in mind — and wait for the user to confirm.
|
||||
|
||||
Two reasons this matters here: the suite takes minutes, and `tests/.snapshots/success.txt` plus the tally in `tests/Visual/Parallel.php` encode the whole suite's result, so a single added test breaks both.
|
||||
|
||||
Once the user confirms:
|
||||
|
||||
```bash
|
||||
composer test:unit # fast, excludes the visual group
|
||||
composer test:integration # visual and snapshot tests
|
||||
composer test # everything CI runs, in CI's order
|
||||
composer update:snapshots # only when a test was added or removed
|
||||
```
|
||||
|
||||
## TIA scenario tests
|
||||
|
||||
`tests/Features/Tia/*` scaffold a throwaway git project, run a real `pest` subprocess against it, and diff the TIA graph it wrote. They exist because TIA's contract is about what a run *writes* — replay, branch keys, and the COMPLETE / RESULTS-ONLY / HARD-SUPPRESSED tiers are invisible to ordinary assertions, and every case used to be measured by hand against a playground app.
|
||||
|
||||
Add one whenever a change touches branch resolution, replay, filtered mode, or the write tiers. How:
|
||||
|
||||
- `Project::make('master')` scaffolds; `seed('master')` writes a graph and sentinels every cached result (`time=9.999`, `assertions=42`) so any rewrite shows up.
|
||||
- `$project->pest('--tia', …)` runs it; `$project->delta()` compares against that snapshot. `writtenCount()` is the discriminator — `0` means "replayed", not "wrote the same values". `mutateGraph()` bends one entry; overlays in `tests/Fixtures/Tia/overlays/<name>/` supply a different `tests/Pest.php`.
|
||||
- Keep expectations driver-independent: a cold recording run needs pcov/xdebug and behaves differently without one. Seed a graph instead of recording one.
|
||||
|
||||
Run them by file (a directory argument finds nothing) or by `--filter`:
|
||||
|
||||
```bash
|
||||
php bin/pest tests/Features/Tia/PartialRunWriteTier.php
|
||||
```
|
||||
@AGENTS.md
|
||||
|
||||
@@ -37,6 +37,7 @@ We cannot thank our sponsors enough for their incredible support in funding Pest
|
||||
- **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)**
|
||||
- **[Typesense](https://typesense.org/?ref=nunomaduro)**
|
||||
- **[Pixel](https://wearepixel.com.au/?ref=nunomaduro)**
|
||||
- **[NativePHP](https://nativephp.com/?ref=nunomaduro)**
|
||||
- [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest)
|
||||
- [Zapiet](https://zapiet.com/?ref=nunomaduro)
|
||||
- [LoadForge](https://loadforge.com/?ref=nunomaduro)
|
||||
|
||||
+15
-14
@@ -18,19 +18,20 @@
|
||||
],
|
||||
"require": {
|
||||
"php": "^8.4",
|
||||
"brianium/paratest": "^7.24.0",
|
||||
"brianium/paratest": "^7.25.0",
|
||||
"nunomaduro/collision": "^8.9.5",
|
||||
"nunomaduro/termwind": "^2.4.0",
|
||||
"pestphp/pest-plugin": "^5.0.0",
|
||||
"pestphp/pest-plugin-arch": "^5.0.0",
|
||||
"pestphp/pest-plugin-mutate": "^5.0.2",
|
||||
"pestphp/pest-plugin-profanity": "^5.0.0",
|
||||
"phpunit/phpunit": "^13.3.0",
|
||||
"symfony/process": "^8.1.0"
|
||||
"phpunit/phpunit": "^13.3.6",
|
||||
"symfony/process": "^8.1.7"
|
||||
},
|
||||
"conflict": {
|
||||
"filp/whoops": "<2.18.3",
|
||||
"phpunit/phpunit": ">13.3.0",
|
||||
"laravel/boost": "<2.6.0",
|
||||
"phpunit/phpunit": ">13.3.6",
|
||||
"sebastian/exporter": "<7.0.0",
|
||||
"webmozart/assert": "<1.11.0"
|
||||
},
|
||||
@@ -60,9 +61,9 @@
|
||||
},
|
||||
"require-dev": {
|
||||
"pestphp/pest-dev-tools": "^5.0.0",
|
||||
"pestphp/pest-plugin-browser": "^5.0.1",
|
||||
"pestphp/pest-plugin-phpstan": "^5.0.2",
|
||||
"pestphp/pest-plugin-rector": "^5.0.3",
|
||||
"pestphp/pest-plugin-browser": "^5.1.0",
|
||||
"pestphp/pest-plugin-phpstan": "^5.2.1",
|
||||
"pestphp/pest-plugin-rector": "^5.0.4",
|
||||
"pestphp/pest-plugin-type-coverage": "^5.0.2",
|
||||
"psy/psysh": "^0.12.24"
|
||||
},
|
||||
@@ -88,15 +89,15 @@
|
||||
"rector --dry-run",
|
||||
"pint --parallel --test"
|
||||
],
|
||||
"test:profanity": "php bin/pest --profanity --compact",
|
||||
"test:profanity": "XDEBUG_MODE=off php bin/pest --profanity --compact",
|
||||
"test:type:check": "phpstan analyse --ansi --memory-limit=-1 --debug",
|
||||
"test:type:coverage": "php -d memory_limit=-1 bin/pest --type-coverage --min=100",
|
||||
"test:unit": "php bin/pest --exclude-group=integration --compact",
|
||||
"test:inline": "php bin/pest --configuration=phpunit.inline.xml",
|
||||
"test:parallel": "php bin/pest --exclude-group=integration --parallel --processes=3",
|
||||
"test:integration": "php bin/pest --group=integration -v",
|
||||
"test:type:coverage": "XDEBUG_MODE=off php -d memory_limit=-1 bin/pest --type-coverage --min=100",
|
||||
"test:unit": "XDEBUG_MODE=off php bin/pest --exclude-group=integration --compact",
|
||||
"test:inline": "XDEBUG_MODE=off php bin/pest --configuration=phpunit.inline.xml",
|
||||
"test:parallel": "XDEBUG_MODE=off php bin/pest --exclude-group=integration --parallel --processes=3",
|
||||
"test:integration": "XDEBUG_MODE=off php bin/pest --group=integration -v",
|
||||
"test:tia": "php bin/pest --group=tia -v",
|
||||
"update:snapshots": "REBUILD_SNAPSHOTS=true php bin/pest --update-snapshots --exclude-group=tia",
|
||||
"update:snapshots": "XDEBUG_MODE=off REBUILD_SNAPSHOTS=true php bin/pest --update-snapshots --exclude-group=tia",
|
||||
"test": [
|
||||
"@test:lint",
|
||||
"@test:type:check",
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
use Pest\Rector\Rules\UseToMatchArrayRector;
|
||||
use Pest\Rector\Set\PestSetList;
|
||||
use Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector;
|
||||
use Rector\CodingStyle\Rector\ArrowFunction\ArrowFunctionDelegatingCallToFirstClassCallableRector;
|
||||
use Rector\Config\RectorConfig;
|
||||
use Rector\DeadCode\Rector\ClassMethod\RemoveDuplicatedReturnSelfDocblockRector;
|
||||
@@ -51,6 +52,9 @@ return RectorConfig::configure()
|
||||
AddArrowFunctionReturnTypeRector::class => [
|
||||
__DIR__.'/tests',
|
||||
],
|
||||
IssetOnPropertyObjectToPropertyExistsRector::class => [
|
||||
__DIR__.'/tests',
|
||||
],
|
||||
])
|
||||
->withPreparedSets(
|
||||
deadCode: true,
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
---
|
||||
name: pest-testing
|
||||
description: "Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, architecture tests, or faster test runs with Test Impact Analysis. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, Tia (--tia), sharding, and all Pest 5 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
# Pest Testing 5
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Pest 5 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Creating Tests
|
||||
|
||||
All tests must be written using Pest. Use `{{ $assist->artisanCommand('make:test --pest {name}') }}`.
|
||||
|
||||
The `{name}` argument should include only the path and test name, but should not include the test suite.
|
||||
- Incorrect: `{{ $assist->artisanCommand('make:test --pest Feature/SomeFeatureTest') }}` will generate `tests/Feature/Feature/SomeFeatureTest.php`
|
||||
- Correct: `{{ $assist->artisanCommand('make:test --pest SomeControllerTest') }}` will generate `tests/Feature/SomeControllerTest.php`
|
||||
- Incorrect: `{{ $assist->artisanCommand('make:test --pest --unit Unit/SomeServiceTest') }}` will generate `tests/Unit/Unit/SomeServiceTest.php`
|
||||
- Correct: `{{ $assist->artisanCommand('make:test --pest --unit SomeServiceTest') }}` will generate `tests/Unit/SomeServiceTest.php`
|
||||
|
||||
### Test Organization
|
||||
|
||||
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
|
||||
- Browser tests: `tests/Browser/` directory.
|
||||
- Do NOT remove tests without approval - these are core application code.
|
||||
|
||||
### Basic Test Structure
|
||||
|
||||
Pest supports both `test()` and `it()` functions. Before writing new tests, check existing test files in the same directory to match the project's convention. Use `test()` if existing tests use `test()`, or `it()` if they use `it()`.
|
||||
|
||||
@boostsnippet("Basic Pest Test Example", "php")
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
@endboostsnippet
|
||||
|
||||
### Running Tests
|
||||
|
||||
- Run minimal tests with filter before finalizing: `{{ $assist->artisanCommand('test --compact --filter=testName') }}`.
|
||||
- Run all tests: `{{ $assist->artisanCommand('test --compact') }}`.
|
||||
- Run file: `{{ $assist->artisanCommand('test --compact tests/Feature/ExampleTest.php') }}`.
|
||||
- Run only tests affected by recent changes (Tia): `./vendor/bin/pest --parallel --tia`.
|
||||
|
||||
## Assertions
|
||||
|
||||
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
|
||||
|
||||
@boostsnippet("Pest Response Assertion", "php")
|
||||
it('returns all', function () {
|
||||
$this->postJson('/api/docs', [])->assertSuccessful();
|
||||
});
|
||||
@endboostsnippet
|
||||
|
||||
| Use | Instead of |
|
||||
|-----|------------|
|
||||
| `assertSuccessful()` | `assertStatus(200)` |
|
||||
| `assertNotFound()` | `assertStatus(404)` |
|
||||
| `assertForbidden()` | `assertStatus(403)` |
|
||||
|
||||
## Mocking
|
||||
|
||||
Import mock function before use: `use function Pest\Laravel\mock;`
|
||||
|
||||
## Datasets
|
||||
|
||||
Use datasets for repetitive tests (validation rules, etc.):
|
||||
|
||||
@boostsnippet("Pest Dataset Example", "php")
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
@endboostsnippet
|
||||
|
||||
## Pest 5 Features
|
||||
|
||||
| Feature | Purpose |
|
||||
|---------|---------|
|
||||
| Tia (Test Impact Analysis) | Rerun only tests affected by recent changes |
|
||||
| Time-Balanced Sharding | Split tests across CI shards by execution time |
|
||||
| New Validation Expectations | `toBeEmail()`, `toBeUlid()`, `toBeIpAddress()`, and more |
|
||||
| Browser Testing | Full integration tests in real browsers |
|
||||
| Smoke Testing | Validate multiple pages quickly |
|
||||
| Visual Regression | Compare screenshots for visual changes |
|
||||
| Architecture Testing | Enforce code conventions |
|
||||
|
||||
### Tia (Test Impact Analysis)
|
||||
|
||||
Tia reruns only tests affected by recent changes and replays cached results for the rest, dramatically reducing suite duration:
|
||||
|
||||
@boostsnippet("Tia Example", "shell")
|
||||
./vendor/bin/pest --parallel --tia
|
||||
@endboostsnippet
|
||||
|
||||
- Replayed tests are not skipped — cached tests store everything they produced, including covered lines and branches.
|
||||
- Detects Laravel, Symfony, Livewire, and Inertia automatically.
|
||||
|
||||
### New Validation Expectations
|
||||
|
||||
Pest 5 ships eight new validation matchers, all supporting `.not` negation:
|
||||
|
||||
@boostsnippet("Pest 5 Validation Expectations", "php")
|
||||
expect('nuno@pestphp.com')->toBeEmail();
|
||||
expect('01ARZ3NDEKTSV4RRFFQ69G5FAV')->toBeUlid();
|
||||
expect('192.168.1.1')->toBeIpAddress();
|
||||
expect('00:1a:2b:3c:4d:5e')->toBeMacAddress();
|
||||
expect('example.com')->toBeHostname();
|
||||
expect('example.co.uk')->toBeDomain();
|
||||
expect('Zm9vYmFy')->toBeBase64();
|
||||
expect('deadbeef')->toBeHexadecimal();
|
||||
@endboostsnippet
|
||||
|
||||
### Time-Balanced Sharding
|
||||
|
||||
Distribute tests across CI shards by execution time rather than count:
|
||||
|
||||
@boostsnippet("Pest Sharding Example", "shell")
|
||||
./vendor/bin/pest --update-shards
|
||||
./vendor/bin/pest --shard=1/4
|
||||
@endboostsnippet
|
||||
|
||||
Commit `tests/.pest/shards.json` to the repository so CI shards stay consistent.
|
||||
|
||||
### Browser Test Example
|
||||
|
||||
Browser tests run in real browsers for full integration testing:
|
||||
|
||||
- Browser tests live in `tests/Browser/`.
|
||||
- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.
|
||||
- Use `RefreshDatabase` for clean state per test.
|
||||
- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.
|
||||
- Test on multiple browsers (Chrome, Firefox, Safari) if requested.
|
||||
- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging.
|
||||
|
||||
@boostsnippet("Pest Browser Test Example", "php")
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in');
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavaScriptErrors()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!');
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
@endboostsnippet
|
||||
|
||||
### Smoke Testing
|
||||
|
||||
Quickly validate multiple pages have no JavaScript errors:
|
||||
|
||||
@boostsnippet("Pest Smoke Testing Example", "php")
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
|
||||
@endboostsnippet
|
||||
|
||||
### Visual Regression Testing
|
||||
|
||||
Capture and compare screenshots to detect visual changes.
|
||||
|
||||
### Architecture Testing
|
||||
|
||||
@boostsnippet("Architecture Test Example", "php")
|
||||
arch('controllers')
|
||||
->expect('App\Http\Controllers')
|
||||
->toExtendNothing()
|
||||
->toHaveSuffix('Controller');
|
||||
@endboostsnippet
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Not importing `use function Pest\Laravel\mock;` before using mock
|
||||
- Using `assertStatus(200)` instead of `assertSuccessful()`
|
||||
- Forgetting datasets for repetitive validation tests
|
||||
- Deleting tests without approval
|
||||
- Forgetting `assertNoJavaScriptErrors()` in browser tests
|
||||
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`
|
||||
@@ -344,6 +344,8 @@ trait Testable
|
||||
|
||||
$this->tearDown();
|
||||
|
||||
TestSuite::getInstance()->snapshots->forget();
|
||||
|
||||
Closure::bind(fn (): array => $this->mockObjects = [], $this, TestCase::class)();
|
||||
|
||||
foreach (array_keys(array_diff_key(get_object_vars($this), $initialProperties)) as $property) {
|
||||
@@ -408,16 +410,25 @@ trait Testable
|
||||
private function __resolveTestArguments(array $arguments): array
|
||||
{
|
||||
$method = TestSuite::getInstance()->tests->get(self::$__filename)->getMethod($this->name());
|
||||
|
||||
if ($method->repetitions > 1) {
|
||||
$firstArgument = array_shift($arguments);
|
||||
$arguments[] = $firstArgument;
|
||||
}
|
||||
|
||||
$underlyingTest = Reflection::getFunctionVariable($this->__test, 'closure');
|
||||
$testParameterTypesByName = Reflection::getFunctionArguments($underlyingTest);
|
||||
$testParameterTypes = array_values($testParameterTypesByName);
|
||||
|
||||
if ($method->repetitions > 1) {
|
||||
$firstArgument = array_shift($arguments);
|
||||
|
||||
if (array_is_list($arguments)) {
|
||||
$arguments[] = $firstArgument;
|
||||
} else {
|
||||
$testParameterNames = array_keys($testParameterTypesByName);
|
||||
$iterationParameterName = $testParameterNames[count($arguments)] ?? null;
|
||||
|
||||
if ($iterationParameterName !== null) {
|
||||
$arguments[$iterationParameterName] = $firstArgument;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (count($arguments) !== 1) {
|
||||
foreach ($arguments as $argumentIndex => $argumentValue) {
|
||||
if (! $argumentValue instanceof Closure) {
|
||||
|
||||
+40
-1
@@ -34,6 +34,7 @@ use Pest\Support\Reflection;
|
||||
use PHPUnit\Architecture\Elements\ObjectDescription;
|
||||
use PHPUnit\Framework\ExpectationFailedException;
|
||||
use ReflectionEnum;
|
||||
use ReflectionFunction;
|
||||
use ReflectionMethod;
|
||||
use ReflectionProperty;
|
||||
|
||||
@@ -329,8 +330,9 @@ final class Expectation
|
||||
}
|
||||
|
||||
$closure = $this->getExpectationClosure($method);
|
||||
$reflectionClosure = new \ReflectionFunction($closure);
|
||||
$reflectionClosure = new ReflectionFunction($closure);
|
||||
$expectation = $reflectionClosure->getClosureThis();
|
||||
$parameters = $this->positionalParameters($reflectionClosure, $parameters);
|
||||
|
||||
if ($reflectionClosure->getReturnType()?->__toString() === ArchExpectation::class) {
|
||||
return $closure(...$parameters);
|
||||
@@ -346,6 +348,43 @@ final class Expectation
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $parameters
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function positionalParameters(ReflectionFunction $closure, array $parameters): array
|
||||
{
|
||||
if ($parameters === [] || array_is_list($parameters)) {
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
$positional = [];
|
||||
|
||||
foreach ($closure->getParameters() as $position => $parameter) {
|
||||
if ($parameter->isVariadic()) {
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
$name = $parameter->getName();
|
||||
|
||||
if (array_key_exists($position, $parameters)) {
|
||||
$positional[] = $parameters[$position];
|
||||
|
||||
unset($parameters[$position]);
|
||||
} elseif (array_key_exists($name, $parameters)) {
|
||||
$positional[] = $parameters[$name];
|
||||
|
||||
unset($parameters[$name]);
|
||||
} elseif ($parameter->isDefaultValueAvailable()) {
|
||||
$positional[] = $parameter->getDefaultValue();
|
||||
} else {
|
||||
return $parameters;
|
||||
}
|
||||
}
|
||||
|
||||
return $parameters === [] ? $positional : $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ExpectationNotFound
|
||||
*/
|
||||
|
||||
@@ -187,8 +187,8 @@ final class TestCaseMethodFactory
|
||||
$attributesCode
|
||||
public function $methodName(...\$arguments)
|
||||
{
|
||||
if (count(\$arguments) === 1 && \$arguments[0] instanceof __PestDatasetProviderError) {
|
||||
throw \$arguments[0]->getPrevious() ?? \$arguments[0];
|
||||
if (count(\$arguments) === 1 && \$arguments[array_key_first(\$arguments)] instanceof __PestDatasetProviderError) {
|
||||
throw \$arguments[array_key_first(\$arguments)]->getPrevious() ?? \$arguments[array_key_first(\$arguments)];
|
||||
}
|
||||
|
||||
return \$this->__runTest(
|
||||
|
||||
+28
-30
@@ -14,7 +14,7 @@ use InvalidArgumentException;
|
||||
use JsonSerializable;
|
||||
use Pest\Exceptions\InvalidExpectationValue;
|
||||
use Pest\Matchers\Any;
|
||||
use Pest\Plugins\Snapshot;
|
||||
use Pest\Plugins\Snapshot as SnapshotPlugin;
|
||||
use Pest\Support\Arr;
|
||||
use Pest\Support\Exporter;
|
||||
use Pest\Support\NullClosure;
|
||||
@@ -712,10 +712,11 @@ final class Expectation
|
||||
/**
|
||||
* @return self<TValue>
|
||||
*/
|
||||
public function toMatchSnapshot(string $message = ''): self
|
||||
public function toMatchSnapshot(string $message = '', ?string $as = null): self
|
||||
{
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
$snapshots->startNewExpectation();
|
||||
|
||||
$snapshot = $as === null ? $snapshots->next() : $snapshots->named($as);
|
||||
|
||||
$testCase = TestSuite::getInstance()->test;
|
||||
assert($testCase instanceof TestCase);
|
||||
@@ -733,39 +734,36 @@ final class Expectation
|
||||
default => InvalidExpectationValue::expected('array|object|string'),
|
||||
};
|
||||
|
||||
if (! $snapshots->has()) {
|
||||
if (! Snapshot::shouldCreateMissingSnapshots()) {
|
||||
$filename = $snapshots->filename();
|
||||
|
||||
Assert::fail($message === '' ? "Snapshot is missing at [$filename]. Run Pest with --update-snapshots to create it." : $message);
|
||||
if (! $snapshot->exists()) {
|
||||
if (! SnapshotPlugin::shouldCreateMissingSnapshots()) {
|
||||
Assert::fail($message === '' ? "Snapshot is missing at [{$snapshot->path()}]. Run Pest with --update-snapshots to create it." : $message);
|
||||
}
|
||||
|
||||
$filename = $snapshots->save($string);
|
||||
$snapshot->write($string);
|
||||
|
||||
TestSuite::getInstance()->registerSnapshotChange("Snapshot created at [$filename]");
|
||||
} else {
|
||||
[$filename, $content] = $snapshots->get();
|
||||
TestSuite::getInstance()->registerSnapshotChange("Snapshot created at [{$snapshot->path()}]");
|
||||
|
||||
$normalizedContent = strtr($content, ["\r\n" => "\n", "\r" => "\n"]);
|
||||
$normalizedString = strtr($string, ["\r\n" => "\n", "\r" => "\n"]);
|
||||
|
||||
if (Snapshot::$updateSnapshots && $normalizedContent !== $normalizedString) {
|
||||
$snapshots->save($string);
|
||||
|
||||
TestSuite::getInstance()->registerSnapshotChange("Snapshot updated at [$filename]");
|
||||
} else {
|
||||
if (Snapshot::$updateSnapshots) {
|
||||
TestSuite::getInstance()->registerSnapshotChange("Snapshot unchanged at [$filename]");
|
||||
}
|
||||
|
||||
Assert::assertSame(
|
||||
$normalizedContent,
|
||||
$normalizedString,
|
||||
$message === '' ? "Failed asserting that the string value matches its snapshot ($filename)." : $message
|
||||
);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (SnapshotPlugin::$updateSnapshots) {
|
||||
if (! $snapshot->matches($string)) {
|
||||
$snapshot->write($string);
|
||||
|
||||
TestSuite::getInstance()->registerSnapshotChange("Snapshot updated at [{$snapshot->path()}]");
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
TestSuite::getInstance()->registerSnapshotChange("Snapshot unchanged at [{$snapshot->path()}]");
|
||||
}
|
||||
|
||||
Assert::assertSame(
|
||||
$snapshot->normalize($snapshot->read()),
|
||||
$snapshot->normalize($string),
|
||||
$message === '' ? "Failed asserting that the string value matches its snapshot ({$snapshot->path()})." : $message
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ namespace Pest;
|
||||
|
||||
function version(): string
|
||||
{
|
||||
return '5.0.5';
|
||||
return '5.3.0';
|
||||
}
|
||||
|
||||
function testDirectory(string $file = ''): string
|
||||
|
||||
@@ -369,7 +369,7 @@ final class WrapperRunner implements RunnerInterface
|
||||
$failedEvents = array_merge_recursive($testResultSum->testFailedEvents(), $testResult->testFailedEvents());
|
||||
|
||||
$testResultSum = new TestResult(
|
||||
(int) $testResultSum->hasTests() + (int) $testResult->hasTests(),
|
||||
ResultReflection::numberOfTests($testResultSum) + self::numberOfTestsSeenByWorker($testResult),
|
||||
$testResultSum->numberOfTestsRun() + $testResult->numberOfTestsRun(),
|
||||
$testResultSum->numberOfAssertions() + $testResult->numberOfAssertions(),
|
||||
array_merge_recursive($testResultSum->testErroredEvents(), $testResult->testErroredEvents()),
|
||||
@@ -500,6 +500,11 @@ final class WrapperRunner implements RunnerInterface
|
||||
return $exitcode;
|
||||
}
|
||||
|
||||
private static function numberOfTestsSeenByWorker(TestResult $result): int
|
||||
{
|
||||
return max(ResultReflection::numberOfTests($result), $result->numberOfTestsRun());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{self: non-negative-int, direct: non-negative-int, indirect: non-negative-int, unknown: non-negative-int}
|
||||
*/
|
||||
|
||||
@@ -132,7 +132,13 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
|
||||
$this->ensureFilterLengthIsSafe($filter);
|
||||
|
||||
return [...$arguments, '--filter', $filter];
|
||||
$arguments = [...$arguments, '--filter', $filter];
|
||||
|
||||
if ($this->hasArgument('--do-not-fail-on-empty-test-suite', $arguments) || $this->hasArgument('--fail-on-empty-test-suite', $arguments)) {
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
return $this->pushArgument('--do-not-fail-on-empty-test-suite', $arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -200,7 +206,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
{
|
||||
$filtered = $this->removeParallelArguments($arguments);
|
||||
|
||||
return ['php', ...$filtered, '--test-directory='.$testPath, '--list-tests'];
|
||||
return [PHP_BINARY, ...$filtered, '--test-directory='.$testPath, '--list-tests'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,9 +234,7 @@ final class Shard implements AddsOutput, HandlesArguments, Terminable
|
||||
$parts = explode('\\', $class);
|
||||
$current = &$tree;
|
||||
foreach ($parts as $part) {
|
||||
if (! isset($current[$part])) {
|
||||
$current[$part] = [];
|
||||
}
|
||||
$current[$part] ??= [];
|
||||
$current = &$current[$part];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Pest\Plugins;
|
||||
|
||||
use Pest\Contracts\Plugins\HandlesArguments;
|
||||
use Pest\Support\Ci;
|
||||
use Pest\TestSuite;
|
||||
|
||||
/**
|
||||
@@ -16,34 +17,9 @@ final class Snapshot implements HandlesArguments
|
||||
|
||||
public static bool $updateSnapshots = false;
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private const array CI_ENVIRONMENT_VARIABLES = [
|
||||
'CI',
|
||||
'GITHUB_ACTIONS',
|
||||
'GITLAB_CI',
|
||||
'CIRCLECI',
|
||||
'TRAVIS',
|
||||
'APPVEYOR',
|
||||
'BITBUCKET_BUILD_NUMBER',
|
||||
'BUILDKITE',
|
||||
'TEAMCITY_VERSION',
|
||||
'JENKINS_URL',
|
||||
'SYSTEM_COLLECTIONURI',
|
||||
'CI_NAME',
|
||||
'TASKCLUSTER_ROOT_URL',
|
||||
'DRONE',
|
||||
'WERCKER',
|
||||
'NEVERCODE',
|
||||
'SEMAPHORE',
|
||||
'NETLIFY',
|
||||
'NOW_BUILDER',
|
||||
];
|
||||
|
||||
public static function shouldCreateMissingSnapshots(): bool
|
||||
{
|
||||
return self::$updateSnapshots || ! self::runningOnCI();
|
||||
return self::$updateSnapshots || ! Ci::isRunning();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -149,13 +125,4 @@ final class Snapshot implements HandlesArguments
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function runningOnCI(): bool
|
||||
{
|
||||
if (Environment::name() === Environment::CI) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return array_any(self::CI_ENVIRONMENT_VARIABLES, fn (string $environmentVariable): bool => getenv($environmentVariable) !== false);
|
||||
}
|
||||
}
|
||||
|
||||
+63
-25
@@ -20,7 +20,7 @@ use Pest\Panic;
|
||||
use Pest\Plugins\Concerns\HandleArguments;
|
||||
use Pest\Plugins\Tia\BaselineSync;
|
||||
use Pest\Plugins\Tia\ChangedFiles;
|
||||
use Pest\Plugins\Tia\CiDefaultBranch;
|
||||
use Pest\Plugins\Tia\CiBranch;
|
||||
use Pest\Plugins\Tia\Contracts\State;
|
||||
use Pest\Plugins\Tia\CoverageCollector;
|
||||
use Pest\Plugins\Tia\Fingerprint;
|
||||
@@ -196,10 +196,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private bool $unreadableGraphReported = false;
|
||||
|
||||
private bool $detachedHead = false;
|
||||
|
||||
private bool $graphUnreachable = false;
|
||||
|
||||
private bool $fullSuiteFallbackRan = false;
|
||||
|
||||
/** @var array<int, string> */
|
||||
private array $originalArguments = [];
|
||||
|
||||
@@ -281,19 +281,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private function deleteState(string $key): bool
|
||||
{
|
||||
if ($this->detachedHead) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->state->delete($key);
|
||||
}
|
||||
|
||||
private function saveGraph(Graph $graph): bool
|
||||
{
|
||||
if ($this->detachedHead) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$json = $graph->encode();
|
||||
|
||||
if ($json === null) {
|
||||
@@ -684,7 +676,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $exitCode;
|
||||
}
|
||||
|
||||
if ($this->replayRan || $this->graphUnreachable) {
|
||||
if ($this->replayRan || $this->graphUnreachable || $this->fullSuiteFallbackRan) {
|
||||
$this->bumpRecordedSha();
|
||||
}
|
||||
|
||||
@@ -791,8 +783,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $this->reconcileFingerprint($rebuilt, $current);
|
||||
}
|
||||
|
||||
$this->deleteState(self::KEY_GRAPH);
|
||||
$this->deleteState(self::KEY_COVERAGE_CACHE);
|
||||
if ($this->canRebuildGraph()) {
|
||||
$this->deleteState(self::KEY_GRAPH);
|
||||
$this->deleteState(self::KEY_COVERAGE_CACHE);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -849,8 +843,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$fingerprint = Fingerprint::compute($projectRoot);
|
||||
$this->startFingerprint = $fingerprint;
|
||||
|
||||
if ($forceRebuild && ! $this->detachedHead) {
|
||||
Storage::purge($projectRoot);
|
||||
if ($forceRebuild && $this->canRebuildGraph()) {
|
||||
$this->purgeState();
|
||||
}
|
||||
|
||||
$graph = ($forceRebuild || $this->forceRefetch) ? null : $this->loadGraph($projectRoot);
|
||||
@@ -910,6 +904,29 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $this->enterRecordMode($arguments);
|
||||
}
|
||||
|
||||
private function purgeState(): void
|
||||
{
|
||||
foreach ([
|
||||
self::KEY_GRAPH,
|
||||
self::KEY_AFFECTED,
|
||||
self::KEY_COVERAGE_CACHE,
|
||||
self::KEY_COVERAGE_MARKER,
|
||||
self::KEY_FETCH_COOLDOWN,
|
||||
] as $key) {
|
||||
$this->state->delete($key);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
self::KEY_WORKER_EDGES_PREFIX,
|
||||
self::KEY_WORKER_RESULTS_PREFIX,
|
||||
self::KEY_WORKER_NO_DRIVER_PREFIX,
|
||||
] as $prefix) {
|
||||
foreach ($this->state->keysWithPrefix($prefix) as $key) {
|
||||
$this->state->delete($key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
* @return array<int, string>
|
||||
@@ -1044,6 +1061,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$coverageAvailable = $this->piggybackCoverage || $this->recorder->driverAvailable();
|
||||
|
||||
if ($hasProjectPhpSourceChanges && ! $coverageAvailable) {
|
||||
$this->fullSuiteFallbackRan = true;
|
||||
|
||||
$this->renderBadge('WARN', 'Detected PHP source changes but no coverage driver is available.');
|
||||
$this->renderChild('Running the full suite to avoid using a stale dependency graph.');
|
||||
$this->renderChild('Install / enable pcov or xdebug (mode: coverage) so edges can be safely refreshed after PHP refactors.');
|
||||
@@ -1229,11 +1248,16 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
$recorder = $this->recorder;
|
||||
|
||||
if (! $this->piggybackCoverage && ! $recorder->driverAvailable()) {
|
||||
$this->requestWorkerResults();
|
||||
$this->emitCoverageDriverMissing();
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
if (! $this->piggybackCoverage && ! in_array('--no-coverage', $arguments, true)) {
|
||||
$arguments[] = '--no-coverage';
|
||||
}
|
||||
|
||||
if (Parallel::isEnabled()) {
|
||||
$this->purgeWorkerPartials();
|
||||
|
||||
@@ -1274,6 +1298,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
private function canRebuildGraph(): bool
|
||||
{
|
||||
return ! $this->piggybackCoverage && $this->recorder->driverAvailable();
|
||||
}
|
||||
|
||||
private function renderFreshGraph(): void
|
||||
{
|
||||
if ($this->driftLabel === null && $this->freshGraphReason !== null) {
|
||||
@@ -1497,7 +1526,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
private function workerToken(): string
|
||||
{
|
||||
$raw = $_SERVER['TEST_TOKEN'] ?? $_ENV['TEST_TOKEN'] ?? null;
|
||||
$raw = $_SERVER['UNIQUE_TEST_TOKEN'] ?? $_ENV['UNIQUE_TEST_TOKEN']
|
||||
?? $_SERVER['TEST_TOKEN'] ?? $_ENV['TEST_TOKEN'] ?? null;
|
||||
|
||||
$token = is_scalar($raw) ? (string) $raw : (string) getmypid();
|
||||
$token = preg_replace('/[^A-Za-z0-9_-]/', '', $token);
|
||||
@@ -1528,9 +1558,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
foreach (['files', 'tables', 'inertia'] as $section) {
|
||||
foreach ($data[$section] as $testFile => $values) {
|
||||
if (! isset($merged[$section][$testFile])) {
|
||||
$merged[$section][$testFile] = [];
|
||||
}
|
||||
$merged[$section][$testFile] ??= [];
|
||||
|
||||
foreach ($values as $value) {
|
||||
$merged[$section][$testFile][$value] = true;
|
||||
@@ -1941,10 +1969,17 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
|
||||
Parallel::setGlobal(self::FALLBACK_BRANCH_GLOBAL, $this->fallbackBranch);
|
||||
|
||||
$currentBranch = $changedFiles->currentBranch();
|
||||
$this->branch = $changedFiles->currentBranch()
|
||||
?? CiBranch::detectCurrent()
|
||||
?? $this->workspaceBranch($projectRoot);
|
||||
}
|
||||
|
||||
$this->detachedHead = $currentBranch === null;
|
||||
$this->branch = $currentBranch ?? $this->fallbackBranch;
|
||||
private function workspaceBranch(string $projectRoot): string
|
||||
{
|
||||
$realProjectRoot = realpath($projectRoot);
|
||||
$hash = hash('sha256', $realProjectRoot === false ? $projectRoot : $realProjectRoot);
|
||||
|
||||
return Graph::WORKSPACE_BRANCH_PREFIX.substr($hash, 0, 16);
|
||||
}
|
||||
|
||||
private function resolveFallbackBranch(ChangedFiles $changedFiles): ?string
|
||||
@@ -1956,7 +1991,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
}
|
||||
|
||||
return $this->watchPatterns->defaultBranch()
|
||||
?? CiDefaultBranch::detect()
|
||||
?? CiBranch::detectDefault()
|
||||
?? $changedFiles->defaultBranch()
|
||||
?? $this->soleRecordedBranch();
|
||||
}
|
||||
@@ -1969,7 +2004,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
|
||||
return null;
|
||||
}
|
||||
|
||||
$branches = Graph::branchesIn($json);
|
||||
$branches = array_values(array_filter(
|
||||
Graph::branchesIn($json),
|
||||
fn (string $branch): bool => ! str_starts_with($branch, Graph::WORKSPACE_BRANCH_PREFIX),
|
||||
));
|
||||
|
||||
return count($branches) === 1 ? $branches[0] : null;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ namespace Pest\Plugins\Tia;
|
||||
use Pest\Exceptions\BaselineFetchFailed;
|
||||
use Pest\Panic;
|
||||
use Pest\Plugins\Tia;
|
||||
use Pest\Plugins\Tia\Baselines\BaseRemote;
|
||||
use Pest\Plugins\Tia\Contracts\State;
|
||||
use Pest\Support\Ci;
|
||||
use Pest\Support\View;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Process\Process;
|
||||
@@ -17,10 +19,6 @@ use Symfony\Component\Process\Process;
|
||||
*/
|
||||
final readonly class BaselineSync
|
||||
{
|
||||
private const string DEFAULT_WORKFLOW_FILE = 'tia-baseline.yml';
|
||||
|
||||
private const string ARTIFACT_NAME = 'pest-tia-baseline';
|
||||
|
||||
private const string GRAPH_ASSET = Tia::KEY_GRAPH;
|
||||
|
||||
private const string COVERAGE_ASSET = Tia::KEY_COVERAGE_CACHE;
|
||||
@@ -31,27 +29,12 @@ final readonly class BaselineSync
|
||||
|
||||
private const int FETCH_COOLDOWN_SECONDS = 86400;
|
||||
|
||||
private const array DIAGNOSES = [
|
||||
'network' => [
|
||||
'pattern' => '/could not resolve host|connection refused|connection reset|temporary failure in name resolution|network is unreachable|no route to host|i\/o timeout|tls handshake|getaddrinfo/i',
|
||||
'message' => 'network error (offline or DNS unreachable). Try again when connected.',
|
||||
],
|
||||
'gh-auth' => [
|
||||
'pattern' => '/authentication failed|not logged in|requires authentication|bad credentials|401/i',
|
||||
'message' => 'authentication failed — run `gh auth login` and retry.',
|
||||
],
|
||||
'rate-limit' => [
|
||||
'pattern' => '/rate limit|too many requests|secondary rate limit/i',
|
||||
'message' => 'GitHub API rate limit hit — try again later.',
|
||||
],
|
||||
'not-found' => [
|
||||
'pattern' => '/404|not found|repository not found/i',
|
||||
'message' => 'workflow or artifact not found in repo.',
|
||||
],
|
||||
'forbidden' => [
|
||||
'pattern' => '/403|forbidden|access denied/i',
|
||||
'message' => 'access denied — check that your `gh` token has repo + actions read scope.',
|
||||
],
|
||||
/**
|
||||
* @var array<int, class-string<BaseRemote>>
|
||||
*/
|
||||
private const array REMOTES = [
|
||||
Baselines\GitHubRemote::class,
|
||||
Baselines\GitLabRemote::class,
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
@@ -60,11 +43,6 @@ final readonly class BaselineSync
|
||||
private WatchPatterns $watchPatterns,
|
||||
) {}
|
||||
|
||||
private function workflowFile(): string
|
||||
{
|
||||
return $this->watchPatterns->baselineWorkflow() ?? self::DEFAULT_WORKFLOW_FILE;
|
||||
}
|
||||
|
||||
private function renderBadge(string $type, string $content): void
|
||||
{
|
||||
View::render('components.badge', ['type' => $type, 'content' => $content]);
|
||||
@@ -77,12 +55,14 @@ final readonly class BaselineSync
|
||||
|
||||
public function fetchIfAvailable(string $projectRoot, bool $force = false, bool $hasAnchor = false): bool
|
||||
{
|
||||
$repo = $this->detectGitHubRepo($projectRoot);
|
||||
$detected = $this->detectRemote($projectRoot);
|
||||
|
||||
if ($repo === null) {
|
||||
if ($detected === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
[$remote, $repo] = $detected;
|
||||
|
||||
if (! $force && ($remaining = $this->cooldownRemaining()) !== null) {
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'Last fetch found no baseline — next auto-retry in %s. Override with --refetch.',
|
||||
@@ -92,7 +72,7 @@ final readonly class BaselineSync
|
||||
return false;
|
||||
}
|
||||
|
||||
$result = $this->download($repo, $projectRoot, $hasAnchor);
|
||||
$result = $this->download($remote, $repo, $projectRoot, $hasAnchor);
|
||||
$payload = $result['payload'];
|
||||
$failureKind = $result['failureKind'];
|
||||
|
||||
@@ -118,6 +98,23 @@ final readonly class BaselineSync
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: BaseRemote, 1: string}|null
|
||||
*/
|
||||
private function detectRemote(string $projectRoot): ?array
|
||||
{
|
||||
foreach (self::REMOTES as $class) {
|
||||
$remote = new $class($this->watchPatterns);
|
||||
$repo = $remote->detect($projectRoot);
|
||||
|
||||
if ($repo !== null) {
|
||||
return [$remote, $repo];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function cooldownRemaining(): ?int
|
||||
{
|
||||
$raw = $this->state->read(Tia::KEY_FETCH_COOLDOWN);
|
||||
@@ -164,7 +161,7 @@ final readonly class BaselineSync
|
||||
|
||||
private function emitPublishInstructions(): void
|
||||
{
|
||||
if ($this->isCi()) {
|
||||
if (Ci::isRunning()) {
|
||||
$this->renderBadge('INFO', 'No baseline yet — this run will produce one.');
|
||||
|
||||
return;
|
||||
@@ -174,59 +171,17 @@ final readonly class BaselineSync
|
||||
$this->renderChild('See https://pestphp.com/docs/tia for how to publish one from CI.');
|
||||
}
|
||||
|
||||
private function isCi(): bool
|
||||
{
|
||||
return getenv('GITHUB_ACTIONS') === 'true'
|
||||
|| getenv('GITLAB_CI') === 'true'
|
||||
|| getenv('CIRCLECI') === 'true';
|
||||
}
|
||||
|
||||
private function detectGitHubRepo(string $projectRoot): ?string
|
||||
{
|
||||
$gitConfig = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
$url = $match[1];
|
||||
|
||||
if (preg_match('#^git@github\.com:([\w.-]+/[\w.-]+?)(?:\.git)?$#', $url, $m) === 1) {
|
||||
return $m[1];
|
||||
}
|
||||
|
||||
if (preg_match('#^https?://github\.com/([\w.-]+/[\w.-]+?)(?:\.git)?/?$#', $url, $m) === 1) {
|
||||
return $m[1];
|
||||
}
|
||||
|
||||
if (preg_match('#^ssh://(?:[^@/]+@)?github\.com(?::\d+)?/([\w.-]+/[\w.-]+?)(?:\.git)?/?$#i', $url, $m) === 1) {
|
||||
return $m[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{payload: array{graph: string, coverage: ?string, sizeOnDisk: int}|null, failureKind: ?string}
|
||||
*/
|
||||
private function download(string $repo, string $projectRoot, bool $hasAnchor = false): array
|
||||
private function download(BaseRemote $remote, string $repo, string $projectRoot, bool $hasAnchor = false): array
|
||||
{
|
||||
$this->validateGhDependencies($hasAnchor);
|
||||
$this->validateCliDependencies($remote, $hasAnchor);
|
||||
|
||||
[$runId, $listError] = $this->latestSuccessfulRunIdWithError($repo);
|
||||
[$runId, $listError] = $remote->latestSuccessfulRunId($repo);
|
||||
|
||||
if ($listError !== null) {
|
||||
$this->panicOnClassifiedError($listError, 'Failed to query baseline runs', $hasAnchor);
|
||||
$this->panicOnClassifiedError($remote, $listError, 'Failed to query baseline runs', $hasAnchor);
|
||||
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'Failed to query baseline runs — %s',
|
||||
@@ -258,7 +213,7 @@ final readonly class BaselineSync
|
||||
return ['payload' => null, 'failureKind' => null];
|
||||
}
|
||||
|
||||
$download = $this->downloadArtifact($repo, $runId, $runCacheDir, $hasAnchor);
|
||||
$download = $this->downloadArtifact($remote, $repo, $runId, $runCacheDir, $hasAnchor);
|
||||
|
||||
if (! $download['success']) {
|
||||
return ['payload' => null, 'failureKind' => $download['failureKind']];
|
||||
@@ -274,7 +229,7 @@ final readonly class BaselineSync
|
||||
/**
|
||||
* @param array{kind: string, message: string} $diagnosis
|
||||
*/
|
||||
private function panicOnClassifiedError(array $diagnosis, string $contextPrefix, bool $hasAnchor): void
|
||||
private function panicOnClassifiedError(BaseRemote $remote, array $diagnosis, string $contextPrefix, bool $hasAnchor): void
|
||||
{
|
||||
if (! in_array($diagnosis['kind'], ['forbidden', 'not-found'], true)) {
|
||||
return;
|
||||
@@ -282,25 +237,25 @@ final readonly class BaselineSync
|
||||
|
||||
Panic::with(new BaselineFetchFailed(
|
||||
sprintf('%s — %s', $contextPrefix, $diagnosis['message']),
|
||||
sprintf('Verify workflow [%s], artifact [%s], and gh token scope.', $this->workflowFile(), self::ARTIFACT_NAME),
|
||||
sprintf('Verify your CI baseline configuration and `%s` token scope.', $remote->cliName()),
|
||||
$hasAnchor,
|
||||
));
|
||||
}
|
||||
|
||||
private function validateGhDependencies(bool $hasAnchor): void
|
||||
private function validateCliDependencies(BaseRemote $remote, bool $hasAnchor): void
|
||||
{
|
||||
if (! $this->commandExists('gh')) {
|
||||
if (! $remote->cliExists()) {
|
||||
Panic::with(new BaselineFetchFailed(
|
||||
'GitHub CLI (gh) not found — cannot fetch baseline.',
|
||||
'Install it from https://cli.github.com.',
|
||||
sprintf('%s CLI (%s) not found — cannot fetch baseline.', $remote->providerLabel(), $remote->cliName()),
|
||||
sprintf('Install it from %s.', $remote->installUrl()),
|
||||
$hasAnchor,
|
||||
));
|
||||
}
|
||||
|
||||
if (! $this->ghAuthenticated()) {
|
||||
if (! $remote->cliAuthenticated()) {
|
||||
Panic::with(new BaselineFetchFailed(
|
||||
'GitHub CLI (gh) is not authenticated — cannot fetch baseline.',
|
||||
'Run `gh auth login` and retry.',
|
||||
sprintf('%s CLI (%s) is not authenticated — cannot fetch baseline.', $remote->providerLabel(), $remote->cliName()),
|
||||
sprintf('Run `%s` and retry.', $remote->loginCommand()),
|
||||
$hasAnchor,
|
||||
));
|
||||
}
|
||||
@@ -309,9 +264,9 @@ final readonly class BaselineSync
|
||||
/**
|
||||
* @return array{success: bool, failureKind: ?string}
|
||||
*/
|
||||
private function downloadArtifact(string $repo, string $runId, string $runCacheDir, bool $hasAnchor): array
|
||||
private function downloadArtifact(BaseRemote $remote, string $repo, string $runId, string $runCacheDir, bool $hasAnchor): array
|
||||
{
|
||||
$artifactSize = $this->artifactSize($repo, $runId);
|
||||
$artifactSize = $remote->artifactSize($repo, $runId);
|
||||
|
||||
$this->output->writeln('');
|
||||
$this->renderChild($artifactSize !== null
|
||||
@@ -325,12 +280,7 @@ final readonly class BaselineSync
|
||||
$repo,
|
||||
));
|
||||
|
||||
$process = new Process([
|
||||
'gh', 'run', 'download', $runId,
|
||||
'-R', $repo,
|
||||
'-n', self::ARTIFACT_NAME,
|
||||
'-D', $runCacheDir,
|
||||
]);
|
||||
$process = new Process($remote->downloadCommand($repo, $runId, $runCacheDir));
|
||||
$process->setTimeout(900.0);
|
||||
$process->start();
|
||||
|
||||
@@ -351,9 +301,9 @@ final readonly class BaselineSync
|
||||
|
||||
$this->cleanup($runCacheDir);
|
||||
|
||||
$diagnosis = $this->classifyGhError($process->getErrorOutput().$process->getOutput());
|
||||
$diagnosis = $remote->classifyError($process->getErrorOutput().$process->getOutput());
|
||||
|
||||
$this->panicOnClassifiedError($diagnosis, 'Baseline download failed', $hasAnchor);
|
||||
$this->panicOnClassifiedError($remote, $diagnosis, 'Baseline download failed', $hasAnchor);
|
||||
|
||||
$this->renderBadge('WARN', sprintf(
|
||||
'Baseline download failed — %s',
|
||||
@@ -375,7 +325,7 @@ final readonly class BaselineSync
|
||||
|
||||
Panic::with(new BaselineFetchFailed(
|
||||
'Baseline downloaded but the artifact is missing expected files (graph.json).',
|
||||
'Your CI publish step is broken — check the workflow that uploads pest-tia-baseline.',
|
||||
'Your CI publish step is broken — check the job that uploads the TIA baseline artifact.',
|
||||
$hasAnchor,
|
||||
));
|
||||
}
|
||||
@@ -383,28 +333,6 @@ final readonly class BaselineSync
|
||||
return $payload;
|
||||
}
|
||||
|
||||
private function artifactSize(string $repo, string $runId): ?int
|
||||
{
|
||||
$process = new Process([
|
||||
'gh', 'api',
|
||||
sprintf('repos/%s/actions/runs/%s/artifacts', $repo, $runId),
|
||||
'--jq', sprintf(
|
||||
'.artifacts[] | select(.name == "%s") | .size_in_bytes', // @pest-ignore-type
|
||||
self::ARTIFACT_NAME,
|
||||
),
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = trim($process->getOutput());
|
||||
|
||||
return is_numeric($size) ? (int) $size : null;
|
||||
}
|
||||
|
||||
private function renderDownloadProgress(float $startedAt, int $tick): void
|
||||
{
|
||||
static $frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
||||
@@ -526,69 +454,6 @@ final readonly class BaselineSync
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?array{kind: string, message: string}}
|
||||
*/
|
||||
private function latestSuccessfulRunIdWithError(string $repo): array
|
||||
{
|
||||
$process = new Process([
|
||||
'gh', 'run', 'list',
|
||||
'-R', $repo,
|
||||
'--workflow', $this->workflowFile(),
|
||||
'--status', 'success',
|
||||
'--limit', '1',
|
||||
'--json', 'databaseId',
|
||||
'--jq', '.[0].databaseId // empty',
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return [null, $this->classifyGhError($process->getErrorOutput().$process->getOutput())];
|
||||
}
|
||||
|
||||
$runId = trim($process->getOutput());
|
||||
|
||||
return [$runId === '' ? null : $runId, null];
|
||||
}
|
||||
|
||||
private function ghAuthenticated(): bool
|
||||
{
|
||||
$process = new Process(['gh', 'auth', 'status']);
|
||||
$process->setTimeout(10.0);
|
||||
$process->run();
|
||||
|
||||
return $process->isSuccessful();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{kind: string, message: string}
|
||||
*/
|
||||
private function classifyGhError(string $output): array
|
||||
{
|
||||
$output = trim($output);
|
||||
|
||||
if ($output === '') {
|
||||
return ['kind' => 'unknown', 'message' => 'unknown error'];
|
||||
}
|
||||
|
||||
foreach (self::DIAGNOSES as $kind => $diagnosis) {
|
||||
if (preg_match($diagnosis['pattern'], $output) === 1) {
|
||||
return ['kind' => $kind, 'message' => $diagnosis['message']];
|
||||
}
|
||||
}
|
||||
|
||||
return ['kind' => 'unknown', 'message' => trim(strtok($output, "\n"))];
|
||||
}
|
||||
|
||||
private function commandExists(string $cmd): bool
|
||||
{
|
||||
$process = new Process(['which', $cmd]);
|
||||
$process->run();
|
||||
|
||||
return $process->isSuccessful();
|
||||
}
|
||||
|
||||
private function cleanup(string $dir): void
|
||||
{
|
||||
if (! is_dir($dir)) {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\Baselines;
|
||||
|
||||
use Pest\Plugins\Tia\WatchPatterns;
|
||||
use Symfony\Component\Process\ExecutableFinder;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
abstract readonly class BaseRemote // @pest-arch-ignore-line
|
||||
{
|
||||
public function __construct(protected WatchPatterns $watchPatterns) {}
|
||||
|
||||
abstract public function detect(string $projectRoot): ?string;
|
||||
|
||||
abstract public function cliName(): string;
|
||||
|
||||
abstract public function installUrl(): string;
|
||||
|
||||
abstract public function loginCommand(): string;
|
||||
|
||||
abstract public function providerLabel(): string;
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?array{kind: string, message: string}}
|
||||
*/
|
||||
abstract public function latestSuccessfulRunId(string $repo): array;
|
||||
|
||||
abstract public function artifactSize(string $repo, string $runId): ?int;
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
abstract public function downloadCommand(string $repo, string $runId, string $destDir): array;
|
||||
|
||||
public function cliExists(): bool
|
||||
{
|
||||
return new ExecutableFinder()->find($this->cliName()) !== null;
|
||||
}
|
||||
|
||||
public function cliAuthenticated(): bool
|
||||
{
|
||||
$process = new Process([$this->cliName(), 'auth', 'status']);
|
||||
$process->setTimeout(10.0);
|
||||
$process->run();
|
||||
|
||||
return $process->isSuccessful();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{kind: string, message: string}
|
||||
*/
|
||||
public function classifyError(string $output): array
|
||||
{
|
||||
$output = trim($output);
|
||||
|
||||
if ($output === '') {
|
||||
return ['kind' => 'unknown', 'message' => 'unknown error'];
|
||||
}
|
||||
|
||||
foreach ($this->diagnoses() as $kind => $diagnosis) {
|
||||
if (preg_match($diagnosis['pattern'], $output) === 1) {
|
||||
return ['kind' => $kind, 'message' => $diagnosis['message']];
|
||||
}
|
||||
}
|
||||
|
||||
return ['kind' => 'unknown', 'message' => trim(strtok($output, "\n"))];
|
||||
}
|
||||
|
||||
protected function readOriginUrl(string $projectRoot): ?string // @pest-arch-ignore-line
|
||||
{
|
||||
$gitConfig = $projectRoot.DIRECTORY_SEPARATOR.'.git'.DIRECTORY_SEPARATOR.'config';
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: string}|null
|
||||
*/
|
||||
protected function parseRemoteUrl(string $url): ?array // @pest-arch-ignore-line
|
||||
{
|
||||
if (preg_match('#^git@([^:]+):([\w./-]+?)(?:\.git)?$#', $url, $m) === 1) {
|
||||
return [$m[1], $m[2]];
|
||||
}
|
||||
|
||||
if (preg_match('#^https?://([^/]+)/([\w./-]+?)(?:\.git)?/?$#', $url, $m) === 1) {
|
||||
return [$m[1], $m[2]];
|
||||
}
|
||||
|
||||
if (preg_match('#^ssh://(?:[^@/]+@)?([^:/]+)(?::\d+)?/([\w./-]+?)(?:\.git)?/?$#i', $url, $m) === 1) {
|
||||
return [$m[1], $m[2]];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function resolveDefaultBranch(string $repo): string // @pest-arch-ignore-line
|
||||
{
|
||||
$configured = $this->watchPatterns->defaultBranch();
|
||||
|
||||
if ($configured !== null) {
|
||||
return $configured;
|
||||
}
|
||||
|
||||
$process = new Process(['git', 'symbolic-ref', 'refs/remotes/origin/HEAD']);
|
||||
$process->setTimeout(5.0);
|
||||
$process->run();
|
||||
|
||||
if ($process->isSuccessful()) {
|
||||
$ref = trim($process->getOutput());
|
||||
|
||||
$branch = str_replace('refs/remotes/origin/', '', $ref);
|
||||
|
||||
if ($branch !== '') {
|
||||
return $branch;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->remoteDefaultBranch($repo) ?? 'main';
|
||||
}
|
||||
|
||||
abstract protected function remoteDefaultBranch(string $repo): ?string; // @pest-arch-ignore-line
|
||||
|
||||
/**
|
||||
* @return array<string, array{pattern: string, message: string}>
|
||||
*/
|
||||
abstract protected function diagnoses(): array; // @pest-arch-ignore-line
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\Baselines;
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final readonly class GitHubRemote extends BaseRemote
|
||||
{
|
||||
private const string DEFAULT_WORKFLOW_FILE = 'tia-baseline.yml';
|
||||
|
||||
private const string ARTIFACT_NAME = 'pest-tia-baseline';
|
||||
|
||||
public function detect(string $projectRoot): ?string
|
||||
{
|
||||
$url = $this->readOriginUrl($projectRoot);
|
||||
|
||||
if ($url === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parsed = $this->parseRemoteUrl($url);
|
||||
|
||||
if ($parsed === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$hostname, $path] = $parsed;
|
||||
|
||||
return strcasecmp($hostname, 'github.com') === 0 ? $path : null;
|
||||
}
|
||||
|
||||
public function cliName(): string
|
||||
{
|
||||
return 'gh';
|
||||
}
|
||||
|
||||
public function installUrl(): string
|
||||
{
|
||||
return 'https://cli.github.com';
|
||||
}
|
||||
|
||||
public function loginCommand(): string
|
||||
{
|
||||
return 'gh auth login';
|
||||
}
|
||||
|
||||
public function providerLabel(): string
|
||||
{
|
||||
return 'GitHub';
|
||||
}
|
||||
|
||||
public function latestSuccessfulRunId(string $repo): array
|
||||
{
|
||||
$process = new Process([
|
||||
'gh', 'run', 'list',
|
||||
'-R', $repo,
|
||||
'--workflow', $this->workflowFile(),
|
||||
'--status', 'success',
|
||||
'--limit', '1',
|
||||
'--json', 'databaseId',
|
||||
'--jq', '.[0].databaseId // empty',
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return [null, $this->classifyError($process->getErrorOutput().$process->getOutput())];
|
||||
}
|
||||
|
||||
$runId = trim($process->getOutput());
|
||||
|
||||
return [$runId === '' ? null : $runId, null];
|
||||
}
|
||||
|
||||
public function artifactSize(string $repo, string $runId): ?int
|
||||
{
|
||||
$process = new Process([
|
||||
'gh', 'api',
|
||||
sprintf('repos/%s/actions/runs/%s/artifacts', $repo, $runId),
|
||||
'--jq', sprintf(
|
||||
'.artifacts[] | select(.name === "%s") | .size_in_bytes',
|
||||
self::ARTIFACT_NAME,
|
||||
),
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = trim($process->getOutput());
|
||||
|
||||
return is_numeric($size) ? (int) $size : null;
|
||||
}
|
||||
|
||||
public function downloadCommand(string $repo, string $runId, string $destDir): array
|
||||
{
|
||||
return [
|
||||
'gh', 'run', 'download', $runId,
|
||||
'-R', $repo,
|
||||
'-n', self::ARTIFACT_NAME,
|
||||
'-D', $destDir,
|
||||
];
|
||||
}
|
||||
|
||||
protected function remoteDefaultBranch(string $repo): ?string // @pest-arch-ignore-line
|
||||
{
|
||||
$process = new Process([
|
||||
'gh', 'api',
|
||||
sprintf('repos/%s', $repo),
|
||||
'--jq', '.default_branch',
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$branch = trim($process->getOutput());
|
||||
|
||||
return $branch !== '' ? $branch : null;
|
||||
}
|
||||
|
||||
protected function diagnoses(): array // @pest-arch-ignore-line
|
||||
{
|
||||
return [
|
||||
'network' => [
|
||||
'pattern' => '/could not resolve host|connection refused|connection reset|temporary failure in name resolution|network is unreachable|no route to host|i\/o timeout|tls handshake|getaddrinfo/i',
|
||||
'message' => 'network error (offline or DNS unreachable). Try again when connected.',
|
||||
],
|
||||
'gh-auth' => [
|
||||
'pattern' => '/authentication failed|not logged in|requires authentication|bad credentials|401/i',
|
||||
'message' => 'authentication failed — run `gh auth login` and retry.',
|
||||
],
|
||||
'rate-limit' => [
|
||||
'pattern' => '/rate limit|too many requests|secondary rate limit/i',
|
||||
'message' => 'GitHub API rate limit hit — try again later.',
|
||||
],
|
||||
'not-found' => [
|
||||
'pattern' => '/404|not found|repository not found/i',
|
||||
'message' => 'workflow or artifact not found in repo.',
|
||||
],
|
||||
'forbidden' => [
|
||||
'pattern' => '/403|forbidden|access denied/i',
|
||||
'message' => 'access denied — check that your `gh` token has repo + actions read scope.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function workflowFile(): string
|
||||
{
|
||||
return $this->watchPatterns->baselineWorkflow() ?? self::DEFAULT_WORKFLOW_FILE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Plugins\Tia\Baselines;
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final readonly class GitLabRemote extends BaseRemote
|
||||
{
|
||||
private const string DEFAULT_JOB_NAME = 'tia-baseline';
|
||||
|
||||
public function detect(string $projectRoot): ?string
|
||||
{
|
||||
$url = $this->readOriginUrl($projectRoot);
|
||||
|
||||
if ($url === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parsed = $this->parseRemoteUrl($url);
|
||||
|
||||
if ($parsed === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$hostname, $path] = $parsed;
|
||||
|
||||
if (strcasecmp($hostname, 'github.com') === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (strcasecmp($hostname, 'gitlab.com') === 0) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
if (! $this->cliExists()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function cliName(): string
|
||||
{
|
||||
return 'glab';
|
||||
}
|
||||
|
||||
public function installUrl(): string
|
||||
{
|
||||
return 'https://gitlab.com/gitlab-org/cli#installation';
|
||||
}
|
||||
|
||||
public function loginCommand(): string
|
||||
{
|
||||
return 'glab auth login';
|
||||
}
|
||||
|
||||
public function providerLabel(): string
|
||||
{
|
||||
return 'GitLab';
|
||||
}
|
||||
|
||||
public function latestSuccessfulRunId(string $repo): array
|
||||
{
|
||||
$encodedRepo = rawurlencode($repo);
|
||||
$jobName = $this->jobName();
|
||||
$defaultBranch = $this->resolveDefaultBranch($repo);
|
||||
|
||||
$process = new Process([
|
||||
'glab', 'api',
|
||||
sprintf('projects/%s/jobs?scope[]=success&per_page=100', $encodedRepo),
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return [null, $this->classifyError($process->getErrorOutput().$process->getOutput())];
|
||||
}
|
||||
|
||||
$runId = $this->findPipelineId($process->getOutput(), $jobName, $defaultBranch);
|
||||
|
||||
return [$runId, null];
|
||||
}
|
||||
|
||||
public function artifactSize(string $repo, string $runId): ?int
|
||||
{
|
||||
$encodedRepo = rawurlencode($repo);
|
||||
$jobName = $this->jobName();
|
||||
|
||||
$process = new Process([
|
||||
'glab', 'api',
|
||||
sprintf('projects/%s/pipelines/%s/jobs', $encodedRepo, $runId),
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->findArtifactSize($process->getOutput(), $jobName);
|
||||
}
|
||||
|
||||
public function downloadCommand(string $repo, string $runId, string $destDir): array
|
||||
{
|
||||
return [
|
||||
'glab', 'job', 'artifact',
|
||||
$this->resolveDefaultBranch($repo),
|
||||
$this->jobName(),
|
||||
'-R', $repo,
|
||||
'--path', $destDir,
|
||||
];
|
||||
}
|
||||
|
||||
protected function remoteDefaultBranch(string $repo): ?string // @pest-arch-ignore-line
|
||||
{
|
||||
$process = new Process([
|
||||
'glab', 'api',
|
||||
sprintf('projects/%s', rawurlencode($repo)),
|
||||
]);
|
||||
$process->setTimeout(30.0);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$project = json_decode($process->getOutput(), true);
|
||||
$branch = is_array($project) ? ($project['default_branch'] ?? null) : null;
|
||||
|
||||
return is_string($branch) && $branch !== '' ? $branch : null;
|
||||
}
|
||||
|
||||
protected function diagnoses(): array // @pest-arch-ignore-line
|
||||
{
|
||||
return [
|
||||
'network' => [
|
||||
'pattern' => '/could not resolve host|connection refused|connection reset|temporary failure|network is unreachable|no route to host|tls handshake|dial tcp/i',
|
||||
'message' => 'network error (offline or DNS unreachable). Try again when connected.',
|
||||
],
|
||||
'glab-auth' => [
|
||||
'pattern' => '/authentication failed|not logged in|requires authentication|unauthorized|401|token expired|invalid token/i',
|
||||
'message' => 'authentication failed — run `glab auth login` and retry.',
|
||||
],
|
||||
'rate-limit' => [
|
||||
'pattern' => '/rate limit|too many requests|429/i',
|
||||
'message' => 'GitLab API rate limit hit — try again later.',
|
||||
],
|
||||
'not-found' => [
|
||||
'pattern' => '/404|not found|project not found|does not exist/i',
|
||||
'message' => 'pipeline, job, or artifact not found in project.',
|
||||
],
|
||||
'forbidden' => [
|
||||
'pattern' => '/403|forbidden|access denied|insufficient scope/i',
|
||||
'message' => 'access denied — check that your `glab` token has read_api scope.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function jobName(): string
|
||||
{
|
||||
return $this->watchPatterns->baselineJob() ?? self::DEFAULT_JOB_NAME;
|
||||
}
|
||||
|
||||
private function findPipelineId(string $output, string $jobName, string $defaultBranch): ?string
|
||||
{
|
||||
$jobs = json_decode($output, true);
|
||||
|
||||
if (! is_array($jobs)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($jobs as $job) {
|
||||
if (! is_array($job)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (($job['name'] ?? null) !== $jobName || ($job['ref'] ?? null) !== $defaultBranch) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$id = $job['pipeline']['id'] ?? null;
|
||||
|
||||
return is_int($id) || is_string($id) ? (string) $id : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function findArtifactSize(string $output, string $jobName): ?int
|
||||
{
|
||||
$jobs = json_decode($output, true);
|
||||
|
||||
if (! is_array($jobs)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($jobs as $job) {
|
||||
if (! is_array($job) || ($job['name'] ?? null) !== $jobName || ! is_array($job['artifacts'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$size = 0;
|
||||
|
||||
foreach ($job['artifacts'] as $artifact) {
|
||||
if (is_array($artifact) && is_int($artifact['size'] ?? null)) {
|
||||
$size += $artifact['size'];
|
||||
}
|
||||
}
|
||||
|
||||
return $size;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -297,7 +297,23 @@ final readonly class ChangedFiles
|
||||
|
||||
private function shaIsReachable(string $sha): bool
|
||||
{
|
||||
return $this->git->succeeds(['merge-base', '--is-ancestor', $sha, 'HEAD']);
|
||||
if ($this->git->succeeds(['merge-base', '--is-ancestor', $sha, 'HEAD'])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$parents = $this->git->raw(['show', '--no-patch', '--format=%P', $sha]);
|
||||
|
||||
if ($parents === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$parents = explode(' ', trim($parents));
|
||||
|
||||
if (count($parents) < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return array_all($parents, fn (string $parent): bool => $this->git->succeeds(['merge-base', '--is-ancestor', $parent, 'HEAD']));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -9,7 +9,7 @@ use Pest\Plugins\Tia\Contracts\Ci;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CiDefaultBranch
|
||||
final class CiBranch
|
||||
{
|
||||
/**
|
||||
* @var array<int, class-string<Ci>>
|
||||
@@ -19,7 +19,20 @@ final class CiDefaultBranch
|
||||
Cis\GitHub::class,
|
||||
];
|
||||
|
||||
public static function detect(): ?string
|
||||
public static function detectCurrent(): ?string
|
||||
{
|
||||
foreach (self::CIS as $class) {
|
||||
$branch = (new $class)->currentBranch();
|
||||
|
||||
if ($branch !== null) {
|
||||
return $branch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function detectDefault(): ?string
|
||||
{
|
||||
foreach (self::CIS as $class) {
|
||||
$branch = (new $class)->defaultBranch();
|
||||
@@ -14,6 +14,11 @@ final readonly class GitHub implements Ci
|
||||
{
|
||||
use ReadsEnvironment;
|
||||
|
||||
public function currentBranch(): ?string
|
||||
{
|
||||
return $this->environment('GITHUB_REF_NAME');
|
||||
}
|
||||
|
||||
public function defaultBranch(): ?string
|
||||
{
|
||||
$path = $this->environment('GITHUB_EVENT_PATH');
|
||||
|
||||
@@ -14,6 +14,11 @@ final readonly class GitLab implements Ci
|
||||
{
|
||||
use ReadsEnvironment;
|
||||
|
||||
public function currentBranch(): ?string
|
||||
{
|
||||
return $this->environment('CI_COMMIT_BRANCH');
|
||||
}
|
||||
|
||||
public function defaultBranch(): ?string
|
||||
{
|
||||
return $this->environment('CI_DEFAULT_BRANCH');
|
||||
|
||||
@@ -61,7 +61,7 @@ final class Configuration
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function baselined(?string $workflow = null): self
|
||||
public function baselined(?string $workflow = null, ?string $job = null): self
|
||||
{
|
||||
/** @var WatchPatterns $watchPatterns */
|
||||
$watchPatterns = Container::getInstance()->get(WatchPatterns::class);
|
||||
@@ -71,6 +71,10 @@ final class Configuration
|
||||
$watchPatterns->setBaselineWorkflow($workflow);
|
||||
}
|
||||
|
||||
if ($job !== null) {
|
||||
$watchPatterns->setBaselineJob($job);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,5 +9,7 @@ namespace Pest\Plugins\Tia\Contracts;
|
||||
*/
|
||||
interface Ci
|
||||
{
|
||||
public function currentBranch(): ?string;
|
||||
|
||||
public function defaultBranch(): ?string;
|
||||
}
|
||||
|
||||
@@ -9,11 +9,9 @@ use Pest\Plugins\Tia\Contracts\State;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class FileState implements State
|
||||
final readonly class FileState implements State
|
||||
{
|
||||
private readonly string $rootDir;
|
||||
|
||||
private ?string $resolvedRoot = null;
|
||||
private string $rootDir;
|
||||
|
||||
public function __construct(string $rootDir)
|
||||
{
|
||||
@@ -106,17 +104,9 @@ final class FileState implements State
|
||||
|
||||
private function resolvedRoot(): ?string
|
||||
{
|
||||
if ($this->resolvedRoot !== null) {
|
||||
return $this->resolvedRoot;
|
||||
}
|
||||
|
||||
$resolved = @realpath($this->rootDir);
|
||||
|
||||
if ($resolved === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->resolvedRoot = $resolved;
|
||||
return $resolved === false ? null : $resolved;
|
||||
}
|
||||
|
||||
private function ensureRoot(): bool
|
||||
|
||||
@@ -40,7 +40,7 @@ final readonly class Fingerprint
|
||||
'js_config' => self::jsConfigHash($projectRoot),
|
||||
],
|
||||
'environmental' => [
|
||||
'php_minor' => PHP_MAJOR_VERSION,
|
||||
'php_minor' => PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION,
|
||||
|
||||
],
|
||||
];
|
||||
|
||||
@@ -18,6 +18,8 @@ use PHPUnit\TextUI\Configuration\Registry;
|
||||
*/
|
||||
final class Graph
|
||||
{
|
||||
public const string WORKSPACE_BRANCH_PREFIX = '@workspace:';
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
@@ -1020,9 +1022,7 @@ final class Graph
|
||||
|
||||
private function ensureBaseline(string $branch): void
|
||||
{
|
||||
if (! isset($this->baselines[$branch])) {
|
||||
$this->baselines[$branch] = ['sha' => null, 'tree' => [], 'results' => []];
|
||||
}
|
||||
$this->baselines[$branch] ??= ['sha' => null, 'tree' => [], 'results' => []];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1067,9 +1067,7 @@ final class Graph
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($this->edges[$rel])) {
|
||||
$this->edges[$rel] = [];
|
||||
}
|
||||
$this->edges[$rel] ??= [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1632,6 +1630,10 @@ final class Graph
|
||||
$survivors = array_fill_keys($keep, true);
|
||||
|
||||
foreach (array_keys($this->baselines) as $branch) {
|
||||
if (str_starts_with($branch, self::WORKSPACE_BRANCH_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($survivors[$branch])) {
|
||||
unset($this->baselines[$branch]);
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ final class ResultCollector
|
||||
|
||||
public function hasUnfinishedTest(): bool
|
||||
{
|
||||
return $this->currentTestId !== null;
|
||||
return $this->currentTestId !== null && ! isset($this->results[$this->currentTestId]);
|
||||
}
|
||||
|
||||
public function recordAssertions(string $testId, int $assertions): void
|
||||
|
||||
@@ -48,6 +48,8 @@ final class WatchPatterns
|
||||
|
||||
private ?string $baselineWorkflow = null;
|
||||
|
||||
private ?string $baselineJob = null;
|
||||
|
||||
public function useDefaults(string $projectRoot): void
|
||||
{
|
||||
$testPath = TestSuite::getInstance()->testPath;
|
||||
@@ -203,6 +205,18 @@ final class WatchPatterns
|
||||
return $this->baselineWorkflow;
|
||||
}
|
||||
|
||||
public function setBaselineJob(string $job): void
|
||||
{
|
||||
$job = trim($job);
|
||||
|
||||
$this->baselineJob = $job === '' ? null : $job;
|
||||
}
|
||||
|
||||
public function baselineJob(): ?string
|
||||
{
|
||||
return $this->baselineJob;
|
||||
}
|
||||
|
||||
public function reset(): void
|
||||
{
|
||||
$this->patterns = [];
|
||||
@@ -213,6 +227,7 @@ final class WatchPatterns
|
||||
$this->baselined = false;
|
||||
$this->defaultBranch = null;
|
||||
$this->baselineWorkflow = null;
|
||||
$this->baselineJob = null;
|
||||
}
|
||||
|
||||
private function keyMatches(string $key, string $file): bool
|
||||
|
||||
+1
-3
@@ -111,9 +111,7 @@ final class Preset
|
||||
*/
|
||||
private function baseNamespaces(): array
|
||||
{
|
||||
if (self::$baseNamespaces === null) {
|
||||
self::$baseNamespaces = Composer::userNamespaces();
|
||||
}
|
||||
self::$baseNamespaces ??= Composer::userNamespaces();
|
||||
|
||||
return self::$baseNamespaces;
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ final class DatasetsRepository
|
||||
$datasets[$index] = self::getScopedDataset($data, $currentTestFile);
|
||||
}
|
||||
|
||||
if (is_callable($datasets[$index])) {
|
||||
if (! is_array($datasets[$index]) && is_callable($datasets[$index])) {
|
||||
$datasets[$index] = call_user_func($datasets[$index]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Repositories;
|
||||
|
||||
use Pest\Exceptions\ShouldNotHappen;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final readonly class Snapshot
|
||||
{
|
||||
public function __construct(
|
||||
private string $filename,
|
||||
private string $basePath,
|
||||
) {}
|
||||
|
||||
public function exists(): bool
|
||||
{
|
||||
return file_exists($this->filename);
|
||||
}
|
||||
|
||||
public function path(): string
|
||||
{
|
||||
return str_replace($this->basePath, '', $this->filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ShouldNotHappen
|
||||
*/
|
||||
public function read(): string
|
||||
{
|
||||
$contents = file_get_contents($this->filename);
|
||||
|
||||
if ($contents === false) {
|
||||
throw ShouldNotHappen::fromMessage('Snapshot file could not be read.');
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
public function write(string $contents): self
|
||||
{
|
||||
$directory = dirname($this->filename);
|
||||
|
||||
if (! is_dir($directory)) {
|
||||
@mkdir($directory, 0755, true);
|
||||
}
|
||||
|
||||
file_put_contents($this->filename, $contents);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ShouldNotHappen
|
||||
*/
|
||||
public function matches(string $value): bool
|
||||
{
|
||||
return $this->normalize($this->read()) === $this->normalize($value);
|
||||
}
|
||||
|
||||
public function normalize(string $value): string
|
||||
{
|
||||
return strtr($value, ["\r\n" => "\n", "\r" => "\n"]);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Pest\Repositories;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Pest\Exceptions\ShouldNotHappen;
|
||||
use Pest\TestSuite;
|
||||
|
||||
@@ -12,8 +13,9 @@ use Pest\TestSuite;
|
||||
*/
|
||||
final class SnapshotRepository
|
||||
{
|
||||
/** @var array<string, int> */
|
||||
private static array $expectationsCounter = [];
|
||||
private static ?string $key = null;
|
||||
|
||||
private static int $ordinal = 0;
|
||||
|
||||
public function __construct(
|
||||
private readonly string $rootPath,
|
||||
@@ -21,47 +23,39 @@ final class SnapshotRepository
|
||||
private readonly string $snapshotsPath,
|
||||
) {}
|
||||
|
||||
public function has(): bool
|
||||
public function current(): Snapshot
|
||||
{
|
||||
return file_exists($this->getSnapshotFilename());
|
||||
$this->synchronize();
|
||||
|
||||
return $this->snapshot(self::$ordinal > 1 ? '__'.self::$ordinal : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: string}
|
||||
*
|
||||
* @throws ShouldNotHappen
|
||||
*/
|
||||
public function get(): array
|
||||
public function next(): Snapshot
|
||||
{
|
||||
$contents = file_get_contents($snapshotFilename = $this->getSnapshotFilename());
|
||||
$this->synchronize();
|
||||
|
||||
if ($contents === false) {
|
||||
throw ShouldNotHappen::fromMessage('Snapshot file could not be read.');
|
||||
self::$ordinal++;
|
||||
|
||||
return $this->current();
|
||||
}
|
||||
|
||||
public function named(string $name): Snapshot
|
||||
{
|
||||
$this->synchronize();
|
||||
|
||||
$suffix = trim((string) preg_replace('/[^\w-]+/', '_', $name), '_');
|
||||
|
||||
if ($suffix === '') {
|
||||
throw new InvalidArgumentException('The snapshot name must contain at least one alphanumeric character.');
|
||||
}
|
||||
|
||||
$snapshot = str_replace(dirname($this->testsPath).'/', '', $snapshotFilename);
|
||||
|
||||
return [$snapshot, $contents];
|
||||
return $this->snapshot('__'.$suffix);
|
||||
}
|
||||
|
||||
public function save(string $snapshot): string
|
||||
public function forget(): void
|
||||
{
|
||||
$snapshotFilename = $this->getSnapshotFilename();
|
||||
|
||||
$directory = dirname($snapshotFilename);
|
||||
|
||||
if (! is_dir($directory)) {
|
||||
@mkdir($directory, 0755, true);
|
||||
}
|
||||
|
||||
file_put_contents($snapshotFilename, $snapshot);
|
||||
|
||||
return $this->filename();
|
||||
}
|
||||
|
||||
public function filename(): string
|
||||
{
|
||||
return str_replace(dirname($this->testsPath).'/', '', $this->getSnapshotFilename());
|
||||
self::$key = null;
|
||||
self::$ordinal = 0;
|
||||
}
|
||||
|
||||
public function flush(): void
|
||||
@@ -92,47 +86,81 @@ final class SnapshotRepository
|
||||
}
|
||||
}
|
||||
|
||||
private function getSnapshotFilename(): string
|
||||
private function snapshot(string $suffix): Snapshot
|
||||
{
|
||||
$testFile = TestSuite::getInstance()->getFilename();
|
||||
|
||||
if (str_starts_with($testFile, $this->testsPath)) {
|
||||
$startPath = $this->testsPath;
|
||||
} else {
|
||||
$startPath = $this->rootPath;
|
||||
}
|
||||
$startPath = str_starts_with($testFile, $this->testsPath) ? $this->testsPath : $this->rootPath;
|
||||
|
||||
$relativePath = substr($testFile, strlen($startPath));
|
||||
|
||||
$relativePath = substr($relativePath, 0, (int) strrpos($relativePath, '.'));
|
||||
|
||||
$description = TestSuite::getInstance()->getDescription();
|
||||
return new Snapshot(
|
||||
sprintf(
|
||||
'%s/%s%s.snap',
|
||||
$this->testsPath.'/'.$this->snapshotsPath.$relativePath,
|
||||
TestSuite::getInstance()->getDescription(),
|
||||
$suffix,
|
||||
),
|
||||
dirname($this->testsPath).'/',
|
||||
);
|
||||
}
|
||||
|
||||
if ($this->getCurrentSnapshotCounter() > 1) {
|
||||
$description .= '__'.$this->getCurrentSnapshotCounter();
|
||||
private function synchronize(): void
|
||||
{
|
||||
$key = TestSuite::getInstance()->getFilename().'###'.TestSuite::getInstance()->getDescription();
|
||||
|
||||
if (self::$key === $key) {
|
||||
return;
|
||||
}
|
||||
|
||||
return sprintf('%s/%s.snap', $this->testsPath.'/'.$this->snapshotsPath.$relativePath, $description);
|
||||
}
|
||||
|
||||
private function getCurrentSnapshotKey(): string
|
||||
{
|
||||
return TestSuite::getInstance()->getFilename().'###'.TestSuite::getInstance()->getDescription();
|
||||
}
|
||||
|
||||
private function getCurrentSnapshotCounter(): int
|
||||
{
|
||||
return self::$expectationsCounter[$this->getCurrentSnapshotKey()] ?? 0;
|
||||
self::$key = $key;
|
||||
self::$ordinal = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use `next` and `current` instead.
|
||||
*/
|
||||
public function startNewExpectation(): void
|
||||
{
|
||||
$key = $this->getCurrentSnapshotKey();
|
||||
$this->next();
|
||||
}
|
||||
|
||||
if (! isset(self::$expectationsCounter[$key])) {
|
||||
self::$expectationsCounter[$key] = 0;
|
||||
}
|
||||
/**
|
||||
* @deprecated Use `current` instead.
|
||||
*/
|
||||
public function has(): bool
|
||||
{
|
||||
return $this->current()->exists();
|
||||
}
|
||||
|
||||
self::$expectationsCounter[$key]++;
|
||||
/**
|
||||
* @deprecated Use `current` instead.
|
||||
*
|
||||
* @return array{0: string, 1: string}
|
||||
*
|
||||
* @throws ShouldNotHappen
|
||||
*/
|
||||
public function get(): array
|
||||
{
|
||||
$snapshot = $this->current();
|
||||
|
||||
return [$snapshot->path(), $snapshot->read()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use `current` instead.
|
||||
*/
|
||||
public function save(string $snapshot): string
|
||||
{
|
||||
return $this->current()->write($snapshot)->path();
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use `current` instead.
|
||||
*/
|
||||
public function filename(): string
|
||||
{
|
||||
return $this->current()->path();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,13 +52,8 @@ final class PcovRestarter implements Restarter
|
||||
$env = $this->inheritEnv();
|
||||
$env[self::ENV_RESTARTED] = '1';
|
||||
|
||||
$command = array_merge(
|
||||
[PHP_BINARY, '-d', 'pcov.directory='.$projectRoot],
|
||||
array_values($arguments),
|
||||
);
|
||||
|
||||
$proc = @proc_open(
|
||||
$command,
|
||||
$this->command($projectRoot, $arguments),
|
||||
[STDIN, STDOUT, STDERR],
|
||||
$pipes,
|
||||
null,
|
||||
@@ -74,6 +69,24 @@ final class PcovRestarter implements Restarter
|
||||
exit($exitCode === -1 ? 1 : $exitCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $arguments
|
||||
* @return list<string>
|
||||
*/
|
||||
private function command(string $projectRoot, array $arguments): array
|
||||
{
|
||||
return array_merge(
|
||||
[
|
||||
PHP_BINARY,
|
||||
'-d',
|
||||
'memory_limit='.ini_get('memory_limit'),
|
||||
'-d',
|
||||
'pcov.directory='.$projectRoot,
|
||||
],
|
||||
array_values($arguments),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pest\Support;
|
||||
|
||||
use Pest\Plugins\Environment;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class Ci
|
||||
{
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private const array ENVIRONMENT_VARIABLES = [
|
||||
'CI',
|
||||
'GITHUB_ACTIONS',
|
||||
'GITLAB_CI',
|
||||
'CIRCLECI',
|
||||
'TRAVIS',
|
||||
'APPVEYOR',
|
||||
'BITBUCKET_BUILD_NUMBER',
|
||||
'BUILDKITE',
|
||||
'TEAMCITY_VERSION',
|
||||
'JENKINS_URL',
|
||||
'SYSTEM_COLLECTIONURI',
|
||||
'CI_NAME',
|
||||
'TASKCLUSTER_ROOT_URL',
|
||||
'DRONE',
|
||||
'WERCKER',
|
||||
'NEVERCODE',
|
||||
'SEMAPHORE',
|
||||
'NETLIFY',
|
||||
'NOW_BUILDER',
|
||||
];
|
||||
|
||||
public static function isRunning(): bool
|
||||
{
|
||||
if (Environment::name() === Environment::CI) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return array_any(self::ENVIRONMENT_VARIABLES, fn (string $env): bool => getenv($env) !== false);
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,8 @@ beforeEach(function () {
|
||||
});
|
||||
|
||||
test('pass with dataset', function ($data) {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
[$filename] = TestSuite::getInstance()->snapshots->get();
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
$filename = TestSuite::getInstance()->snapshots->current()->path();
|
||||
|
||||
expect($filename)->toStartWith('tests/.pest/snapshots-external/')
|
||||
->toEndWith('pass_with_dataset_with_data_set____my_datas_set_value___.snap')
|
||||
@@ -25,8 +25,8 @@ test('pass with dataset', function ($data) {
|
||||
|
||||
describe('within describe', function () {
|
||||
test('pass with dataset', function ($data) {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
[$filename] = TestSuite::getInstance()->snapshots->get();
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
$filename = TestSuite::getInstance()->snapshots->current()->path();
|
||||
|
||||
expect($filename)->toStartWith('tests/.pest/snapshots-external/')
|
||||
->toEndWith('pass_with_dataset_with_data_set____my_datas_set_value___.snap')
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar 1
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar 2
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar 1
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar 2
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1>Snapshot</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar
|
||||
+1
@@ -0,0 +1 @@
|
||||
foo bar
|
||||
@@ -0,0 +1 @@
|
||||
the same on every attempt
|
||||
@@ -1,5 +1,5 @@
|
||||
|
||||
Pest Testing Framework 5.0.5.
|
||||
Pest Testing Framework 5.3.0.
|
||||
|
||||
USAGE: pest <file> [options]
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
|
||||
Pest Testing Framework 5.0.5.
|
||||
Pest Testing Framework 5.3.0.
|
||||
|
||||
|
||||
@@ -275,6 +275,7 @@
|
||||
✓ dataset items can mix named and sequential styles with ('Taylor', 'taylor@laravel.com')
|
||||
✓ dataset items can mix named and sequential styles with ('James', 'james@laravel.com') #1
|
||||
✓ dataset items can mix named and sequential styles with ('James', 'james@laravel.com') #2
|
||||
✓ named parameters work with a single argument with ('Taylor')
|
||||
|
||||
PASS Tests\Features\Depends
|
||||
✓ first
|
||||
@@ -439,6 +440,7 @@
|
||||
✓ interceptor can be filter the expected parameter as well
|
||||
✓ interceptor works with negated expectation
|
||||
✓ intercept can add new parameters to the expectation
|
||||
✓ named arguments reach the pipes of an expectation
|
||||
|
||||
PASS Tests\Features\Expect\ray
|
||||
✓ ray calls do not fail when ray is not installed
|
||||
@@ -1122,6 +1124,17 @@
|
||||
✓ multiple snapshot expectations with repeat @ repetition 8 of 10
|
||||
✓ multiple snapshot expectations with repeat @ repetition 9 of 10
|
||||
✓ multiple snapshot expectations with repeat @ repetition 10 of 10
|
||||
✓ pass with named snapshot
|
||||
✓ named snapshots do not depend on the order they are asserted in
|
||||
✓ named snapshots do not consume the ordinal of the unnamed ones
|
||||
✓ named snapshots require a name
|
||||
✓ ordinal snapshots start over once forgotten
|
||||
✓ ordinal snapshots start over on every repetition @ repetition 1 of 3
|
||||
✓ ordinal snapshots start over on every repetition @ repetition 2 of 3
|
||||
✓ ordinal snapshots start over on every repetition @ repetition 3 of 3
|
||||
✓ snapshots of a repeated test are recorded per repetition @ repetition 1 of 3
|
||||
✓ snapshots of a repeated test are recorded per repetition @ repetition 2 of 3
|
||||
✓ snapshots of a repeated test are recorded per repetition @ repetition 3 of 3
|
||||
|
||||
PASS Tests\Features\Expect\toStartWith
|
||||
✓ pass
|
||||
@@ -1224,6 +1237,8 @@
|
||||
✓ it does not retry fails()
|
||||
✓ it retries unexpected exceptions even with throws set
|
||||
✓ it does not leak mock objects between retries
|
||||
✓ it resolves the same snapshot ordinals on every retry
|
||||
✓ it matches the same snapshot on every retry
|
||||
✓ it does not stop retrying when snapshot changes are absent
|
||||
✓ it does not leak dynamic properties between retries
|
||||
! it clears output buffer between retries when expectOutputString is used → Creation of dynamic property PHPUnit\Framework\TestCase\OutputBuffer::$expectedString is deprecated
|
||||
@@ -1455,6 +1470,14 @@
|
||||
✓ multiple times with repeat iterator with multiple dataset ('c') / ('d') @ repetition 2 of 2
|
||||
✓ multiple times with repeat iterator with multiple dataset ('c') / ('e') @ repetition 2 of 2
|
||||
✓ multiple times with repeat iterator with multiple dataset ('c') / ('f') @ repetition 2 of 2
|
||||
✓ multiple times with named dataset arguments ('Taylor', 'taylor@laravel.com') @ repetition 1 of 2
|
||||
✓ multiple times with named dataset arguments ('Nuno', 'enunomaduro@gmail.com') @ repetition 1 of 2
|
||||
✓ multiple times with named dataset arguments ('Taylor', 'taylor@laravel.com') @ repetition 2 of 2
|
||||
✓ multiple times with named dataset arguments ('Nuno', 'enunomaduro@gmail.com') @ repetition 2 of 2
|
||||
✓ multiple times with named dataset arguments and repeat iterator ('Taylor', 'taylor@laravel.com') @ repetition 1 of 2
|
||||
✓ multiple times with named dataset arguments and repeat iterator ('Nuno', 'enunomaduro@gmail.com') @ repetition 1 of 2
|
||||
✓ multiple times with named dataset arguments and repeat iterator ('Taylor', 'taylor@laravel.com') @ repetition 2 of 2
|
||||
✓ multiple times with named dataset arguments and repeat iterator ('Nuno', 'enunomaduro@gmail.com') @ repetition 2 of 2
|
||||
✓ describe blocks → multiple times @ repetition 1 of 3
|
||||
✓ describe blocks → multiple times @ repetition 2 of 3
|
||||
✓ describe blocks → multiple times @ repetition 3 of 3
|
||||
@@ -1764,6 +1787,7 @@
|
||||
✓ it shows the correct description for long texts with newlines
|
||||
✓ it shows the correct description for arrays with many elements
|
||||
✓ it shows the correct description of datasets with html
|
||||
✓ it does not treat a two element dataset of class names as a callable
|
||||
|
||||
PASS Tests\Unit\Expectations\OppositeExpectation
|
||||
✓ it throw expectation failed exception with string argument
|
||||
@@ -2038,10 +2062,17 @@
|
||||
✓ it accepts a page directory candidate only when it matches the casing on disk with ('wrong parent')
|
||||
✓ it accepts a page directory candidate only when it matches the casing on disk with ('absent')
|
||||
|
||||
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
|
||||
✓ falls back to TEST_TOKEN when UNIQUE_TEST_TOKEN is absent
|
||||
|
||||
PASS Tests\Unit\Preset
|
||||
✓ preset invalid name
|
||||
✓ preset → myFramework
|
||||
|
||||
PASS Tests\Unit\Restarters\PcovRestarter
|
||||
✓ it preserves the active memory limit in the restarted process
|
||||
|
||||
PASS Tests\Unit\Support\Arr
|
||||
✓ last → it should return false for an empty arary
|
||||
✓ last → it should return the last element for an array with a single element
|
||||
@@ -2225,4 +2256,4 @@
|
||||
✓ 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, 35 skipped, 1572 passed (3413 assertions)
|
||||
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 35 skipped, 1599 passed (3486 assertions)
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
beforeEach(function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
})->assignee('nunomaduro');
|
||||
|
||||
@@ -494,3 +494,9 @@ test('dataset items can mix named and sequential styles', function (string $name
|
||||
['James', 'james@laravel.com'],
|
||||
['James', 'email' => 'james@laravel.com'],
|
||||
]);
|
||||
|
||||
test('named parameters work with a single argument', function (string $name): void {
|
||||
expect($name)->toBe('Taylor');
|
||||
})->with([
|
||||
['name' => 'Taylor'],
|
||||
]);
|
||||
|
||||
@@ -239,3 +239,14 @@ test('intercept can add new parameters to the expectation', function (): void {
|
||||
|
||||
expect('Foo')->toBe('foo', $ignoreCase);
|
||||
});
|
||||
|
||||
test('named arguments reach the pipes of an expectation', function () use ($state): void {
|
||||
$char = new Char('A');
|
||||
|
||||
$state->reset();
|
||||
|
||||
expect($char)->toBe(expected: new Char('A'))
|
||||
->and($state)
|
||||
->runCount->toHaveKey('char', 1)
|
||||
->appliedCount->toHaveKey('char', 1);
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ beforeEach(function (): void {
|
||||
});
|
||||
|
||||
test('pass', function (): void {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
|
||||
expect($this->snapshotable)->toMatchSnapshot();
|
||||
});
|
||||
@@ -39,7 +39,7 @@ test('pass using pipes', function (): void {
|
||||
});
|
||||
|
||||
test('pass with `__toString`', function (): void {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
|
||||
$object = new class($this->snapshotable)
|
||||
{
|
||||
@@ -55,7 +55,7 @@ test('pass with `__toString`', function (): void {
|
||||
});
|
||||
|
||||
test('pass with `toString`', function (): void {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
|
||||
$object = new class($this->snapshotable)
|
||||
{
|
||||
@@ -71,8 +71,8 @@ test('pass with `toString`', function (): void {
|
||||
});
|
||||
|
||||
test('pass with dataset', function ($data): void {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
[$filename] = TestSuite::getInstance()->snapshots->get();
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
$filename = TestSuite::getInstance()->snapshots->current()->path();
|
||||
|
||||
expect($filename)->toStartWith('tests/.pest/snapshots/')
|
||||
->toEndWith('pass_with_dataset_with_data_set____my_datas_set_value___.snap')
|
||||
@@ -81,8 +81,8 @@ test('pass with dataset', function ($data): void {
|
||||
|
||||
describe('within describe', function (): void {
|
||||
test('pass with dataset', function ($data): void {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
[$filename] = TestSuite::getInstance()->snapshots->get();
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
$filename = TestSuite::getInstance()->snapshots->current()->path();
|
||||
|
||||
expect($filename)->toStartWith('tests/.pest/snapshots/')
|
||||
->toEndWith('pass_with_dataset_with_data_set____my_datas_set_value___.snap')
|
||||
@@ -91,7 +91,7 @@ describe('within describe', function (): void {
|
||||
})->with(['my-datas-set-value']);
|
||||
|
||||
test('pass with `toArray`', function (): void {
|
||||
TestSuite::getInstance()->snapshots->save(json_encode(['key' => $this->snapshotable], JSON_PRETTY_PRINT));
|
||||
TestSuite::getInstance()->snapshots->current()->write(json_encode(['key' => $this->snapshotable], JSON_PRETTY_PRINT));
|
||||
|
||||
$object = new class($this->snapshotable)
|
||||
{
|
||||
@@ -109,7 +109,7 @@ test('pass with `toArray`', function (): void {
|
||||
});
|
||||
|
||||
test('pass with array', function (): void {
|
||||
TestSuite::getInstance()->snapshots->save(json_encode(['key' => $this->snapshotable], JSON_PRETTY_PRINT));
|
||||
TestSuite::getInstance()->snapshots->current()->write(json_encode(['key' => $this->snapshotable], JSON_PRETTY_PRINT));
|
||||
|
||||
expect([
|
||||
'key' => $this->snapshotable,
|
||||
@@ -117,7 +117,7 @@ test('pass with array', function (): void {
|
||||
});
|
||||
|
||||
test('pass with `toSnapshot`', function (): void {
|
||||
TestSuite::getInstance()->snapshots->save(json_encode(['key' => $this->snapshotable], JSON_PRETTY_PRINT));
|
||||
TestSuite::getInstance()->snapshots->current()->write(json_encode(['key' => $this->snapshotable], JSON_PRETTY_PRINT));
|
||||
|
||||
$object = new class($this->snapshotable)
|
||||
{
|
||||
@@ -135,7 +135,7 @@ test('pass with `toSnapshot`', function (): void {
|
||||
});
|
||||
|
||||
test('not failures', function (): void {
|
||||
TestSuite::getInstance()->snapshots->save($this->snapshotable);
|
||||
TestSuite::getInstance()->snapshots->current()->write($this->snapshotable);
|
||||
|
||||
expect($this->snapshotable)->not->toMatchSnapshot();
|
||||
})->throws(ExpectationFailedException::class);
|
||||
@@ -161,3 +161,68 @@ test('multiple snapshot expectations with repeat', function (): void {
|
||||
expect('foo bar 1')->toMatchSnapshot()
|
||||
->and('foo bar 2')->toMatchSnapshot();
|
||||
})->repeat(10);
|
||||
|
||||
test('pass with named snapshot', function (): void {
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
$snapshots->named('header')->write($this->snapshotable);
|
||||
|
||||
expect($snapshots->named('header')->path())
|
||||
->toStartWith('tests/.pest/snapshots/')
|
||||
->toEndWith('pass_with_named_snapshot__header.snap')
|
||||
->and($this->snapshotable)->toMatchSnapshot(as: 'header');
|
||||
});
|
||||
|
||||
test('named snapshots do not depend on the order they are asserted in', function (): void {
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
$snapshots->named('first')->write('foo bar 1');
|
||||
$snapshots->named('second')->write('foo bar 2');
|
||||
|
||||
expect('foo bar 2')->toMatchSnapshot(as: 'second')
|
||||
->and('foo bar 1')->toMatchSnapshot(as: 'first');
|
||||
});
|
||||
|
||||
test('named snapshots do not consume the ordinal of the unnamed ones', function (): void {
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
$snapshots->current()->write('foo bar 1');
|
||||
$snapshots->named('named')->write('foo bar 2');
|
||||
|
||||
expect('foo bar 1')->toMatchSnapshot()
|
||||
->and('foo bar 2')->toMatchSnapshot(as: 'named')
|
||||
->and($snapshots->current()->path())->toEndWith('named_snapshots_do_not_consume_the_ordinal_of_the_unnamed_ones.snap');
|
||||
});
|
||||
|
||||
test('named snapshots require a name', function (): void {
|
||||
TestSuite::getInstance()->snapshots->named('_');
|
||||
})->throws(InvalidArgumentException::class, 'The snapshot name must contain at least one alphanumeric character.');
|
||||
|
||||
test('ordinal snapshots start over once forgotten', function (): void {
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
|
||||
$first = $snapshots->next()->path();
|
||||
|
||||
expect($snapshots->next()->path())->toEndWith('ordinal_snapshots_start_over_once_forgotten__2.snap');
|
||||
|
||||
$snapshots->forget();
|
||||
|
||||
expect($snapshots->next()->path())->toBe($first);
|
||||
});
|
||||
|
||||
test('ordinal snapshots start over on every repetition', function (): void {
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
|
||||
$first = $snapshots->next()->path();
|
||||
|
||||
expect($first)->toContain('ordinal_snapshots_start_over_on_every_repetition')
|
||||
->and($snapshots->next()->path())->toBe(str_replace('.snap', '__2.snap', $first));
|
||||
})->repeat(3);
|
||||
|
||||
test('snapshots of a repeated test are recorded per repetition', function (int $iteration): void {
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
$snapshots->current()->write('foo bar');
|
||||
$snapshots->named('named')->write('foo bar');
|
||||
|
||||
expect('foo bar')->toMatchSnapshot()
|
||||
->and($snapshots->current()->path())->toEndWith("_with_data_set___{$iteration}__.snap")
|
||||
->and('foo bar')->toMatchSnapshot(as: 'named')
|
||||
->and($snapshots->named('named')->path())->toEndWith("_with_data_set___{$iteration}____named.snap");
|
||||
})->repeat(3);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Pest\TestSuite;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
it('passes on first try', function (): void {
|
||||
@@ -231,6 +232,41 @@ it('does not leak mock objects between retries', function (): void {
|
||||
expect($mock->count())->toBe(1);
|
||||
})->flaky(tries: 3);
|
||||
|
||||
it('resolves the same snapshot ordinals on every retry', function (): void {
|
||||
$file = sys_get_temp_dir().'/pest_flaky_snapshot_ordinals';
|
||||
$count = file_exists($file) ? (int) file_get_contents($file) : 0;
|
||||
file_put_contents($file, (string) ++$count);
|
||||
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
|
||||
expect($snapshots->next()->path())->toEndWith('resolves_the_same_snapshot_ordinals_on_every_retry.snap')
|
||||
->and($snapshots->next()->path())->toEndWith('resolves_the_same_snapshot_ordinals_on_every_retry__2.snap');
|
||||
|
||||
if ($count < 3) {
|
||||
throw new Exception('Flaky snapshot ordinals');
|
||||
}
|
||||
|
||||
@unlink($file);
|
||||
})->flaky(tries: 3);
|
||||
|
||||
it('matches the same snapshot on every retry', function (): void {
|
||||
$file = sys_get_temp_dir().'/pest_flaky_snapshot_match';
|
||||
$count = file_exists($file) ? (int) file_get_contents($file) : 0;
|
||||
file_put_contents($file, (string) ++$count);
|
||||
|
||||
$snapshots = TestSuite::getInstance()->snapshots;
|
||||
$snapshots->current()->write('the same on every attempt');
|
||||
|
||||
expect('the same on every attempt')->toMatchSnapshot()
|
||||
->and($snapshots->current()->path())->toEndWith('matches_the_same_snapshot_on_every_retry.snap');
|
||||
|
||||
if ($count < 2) {
|
||||
throw new Exception('Flaky snapshot match');
|
||||
}
|
||||
|
||||
@unlink($file);
|
||||
})->flaky(tries: 3);
|
||||
|
||||
it('does not stop retrying when snapshot changes are absent', function (): void {
|
||||
$file = sys_get_temp_dir().'/pest_flaky_no_snapshot';
|
||||
$count = file_exists($file) ? (int) file_get_contents($file) : 0;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
beforeEach(function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
})->issue(1);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
beforeEach(function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
})->pr(1);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
test('once', function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
})->repeat(times: 1);
|
||||
@@ -44,6 +46,28 @@ test('multiple times with repeat iterator with multiple dataset', function (stri
|
||||
->toBeGreaterThan(0);
|
||||
})->repeat(times: 2)->with(['a', 'b', 'c'], ['d', 'e', 'f']);
|
||||
|
||||
test('multiple times with named dataset arguments', function (string $name, string $email): void {
|
||||
expect($name)
|
||||
->toBeIn(['Taylor', 'Nuno'])
|
||||
->and($email)
|
||||
->toContain('@');
|
||||
})->repeat(times: 2)->with([
|
||||
['name' => 'Taylor', 'email' => 'taylor@laravel.com'],
|
||||
['name' => 'Nuno', 'email' => 'enunomaduro@gmail.com'],
|
||||
]);
|
||||
|
||||
test('multiple times with named dataset arguments and repeat iterator', function (string $name, string $email, int $iteration): void {
|
||||
expect($name)
|
||||
->toBeIn(['Taylor', 'Nuno'])
|
||||
->and($email)
|
||||
->toContain('@')
|
||||
->and($iteration)
|
||||
->toBeIn([1, 2]);
|
||||
})->repeat(times: 2)->with([
|
||||
['name' => 'Taylor', 'email' => 'taylor@laravel.com'],
|
||||
['name' => 'Nuno', 'email' => 'enunomaduro@gmail.com'],
|
||||
]);
|
||||
|
||||
describe('describe blocks', function (): void {
|
||||
test('multiple times', function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
it('allows access to the underlying expectNotToPerformAssertions method', function (): void {
|
||||
$this->expectNotToPerformAssertions();
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ it('does not run user hooks when replaying cached skipped and incomplete results
|
||||
'PARATEST' => 0,
|
||||
'PAO_DISABLE' => '1',
|
||||
'HOME' => $home,
|
||||
'CI_DEFAULT_BRANCH' => $branch,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -115,7 +115,7 @@ test('a narrowed run does not reclaim anything', function (): void {
|
||||
->and($delta->isResultsOnly())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a detached HEAD does not reclaim anything either', function (): void {
|
||||
test('a detached HEAD reclaims missing branches without changing the default baseline', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -130,8 +130,11 @@ test('a detached HEAD does not reclaim anything either', function (): void {
|
||||
$project->pest('--tia');
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($project->branchKeys())->toBe(['master', 'feature-x'])
|
||||
->and($delta->isHardSuppressed())->toBeTrue($delta->summary());
|
||||
expect($project->branchKeys())->toHaveCount(2)
|
||||
->and($project->branchKeys())->toContain('master')
|
||||
->and($project->branchKeys())->not->toContain('feature-x')
|
||||
->and($delta->baselineUntouched('master'))->toBeTrue($delta->summary())
|
||||
->and($delta->structureMoved())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('the default branch baseline survives every branch that comes and goes', function (): void {
|
||||
|
||||
@@ -33,6 +33,34 @@ test('a complete run prunes a deleted test', function (array $arguments): void {
|
||||
->and($delta->structureMoved())->toBeFalse($delta->summary());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a complete run stays complete when the last test is skipped from a hook', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$project->write('tests/Unit/GreeterTest.php', <<<'PHP'
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Fixture\App\Greeter;
|
||||
|
||||
beforeEach(function (): void {
|
||||
test()->markTestSkipped('not today');
|
||||
});
|
||||
|
||||
test('greets a person', function (): void {
|
||||
expect((new Greeter)->greet('Nuno'))->toBe('Hello, Nuno!');
|
||||
});
|
||||
PHP);
|
||||
|
||||
$result = $project->pest(...$arguments);
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($result->tally())->toContain('1 skipped')
|
||||
->and($delta->removed())->toBe(1, $delta->summary())
|
||||
->and($delta->added())->toBe(0, $delta->summary());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a complete run records nothing for a test file the graph does not know', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Support\Coverage;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
@@ -39,6 +40,44 @@ test('a plain run after a coverage run records the whole project scope', functio
|
||||
->and($graph['files'])->toContain('app/Calculator.php');
|
||||
})->skipOnWindows();
|
||||
|
||||
test('xml-configured coverage does not prevent tia recording', function (): void {
|
||||
$project = Project::make('master');
|
||||
|
||||
$project->write('phpunit.xml', <<<'XML_WRAP'
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.0/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
cacheDirectory=".phpunit.cache"
|
||||
colors="true"
|
||||
failOnRisky="true"
|
||||
failOnWarning="false"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="default">
|
||||
<directory suffix="Test.php">./tests</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<coverage>
|
||||
<report>
|
||||
<clover outputFile="coverage/clover.xml" />
|
||||
</report>
|
||||
</coverage>
|
||||
<source>
|
||||
<include>
|
||||
<directory suffix=".php">./app</directory>
|
||||
</include>
|
||||
</source>
|
||||
</phpunit>
|
||||
XML_WRAP);
|
||||
|
||||
$result = $project->pest('--tia');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($project->graphExists())->toBeTrue()
|
||||
->and(array_keys($project->graph()['edges']))->toEqualCanonicalizing(array_keys(Project::EDGES));
|
||||
})->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
|
||||
|
||||
test('a coverage report leaves the edges of an existing graph alone', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -104,17 +104,20 @@ test('filtered mode finds nothing to do on the default branch itself', function
|
||||
->and($delta->isHardSuppressed())->toBeTrue($delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a detached HEAD replays without minting a branch key', function (): void {
|
||||
test('a detached HEAD replays through a workspace baseline', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$project->git()->detach();
|
||||
|
||||
$result = $project->pest('--tia');
|
||||
$hasWorkspaceBranch = array_any($project->branchKeys(), fn (string $branch): bool => str_starts_with($branch, '@workspace:'));
|
||||
|
||||
expect($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe())
|
||||
->and($result->uncached())->toBe(0, $result->describe())
|
||||
->and($project->branchKeys())->toBe(['master']);
|
||||
->and($project->branchKeys())->toHaveCount(2)
|
||||
->and($project->branchKeys())->toContain('master')
|
||||
->and($hasWorkspaceBranch)->toBeTrue();
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a detached HEAD does not write into the default branch baseline', function (array $arguments): void {
|
||||
@@ -125,9 +128,13 @@ test('a detached HEAD does not write into the default branch baseline', function
|
||||
$project->pest(...$arguments);
|
||||
|
||||
$delta = $project->delta();
|
||||
$hasWorkspaceBranch = array_any($project->branchKeys(), fn (string $branch): bool => str_starts_with($branch, '@workspace:'));
|
||||
|
||||
expect($delta->baselineUntouched('master'))->toBeTrue($delta->summary())
|
||||
->and($project->branchKeys())->toBe(['master']);
|
||||
->and($project->branchKeys())->toHaveCount(2)
|
||||
->and($project->branchKeys())->toContain('master')
|
||||
->and($hasWorkspaceBranch)->toBeTrue()
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary());
|
||||
})->with([
|
||||
'sequential' => [['--filter=adds two numbers']],
|
||||
'parallel' => [['--parallel', '--processes=2', '--filter=adds two numbers']],
|
||||
@@ -147,6 +154,26 @@ test('the branch that ran gets its own key and the default branch keeps its base
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a detached CI branch writes into its branch baseline', function (array $environment): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$project->git()->detach();
|
||||
$project->pestWithEnvironment($project->path(), $environment, '--filter=adds two numbers');
|
||||
|
||||
expect($project->branchKeys())->toBe(['master', 'feature-x'])
|
||||
->and(array_any($project->branchKeys(), fn (string $branch): bool => str_starts_with($branch, '@workspace:')))->toBeFalse();
|
||||
})->with([
|
||||
'GitLab' => [[
|
||||
'GITLAB_CI' => 'true',
|
||||
'CI_COMMIT_BRANCH' => 'feature-x',
|
||||
]],
|
||||
'GitHub' => [[
|
||||
'GITHUB_ACTIONS' => 'true',
|
||||
'GITHUB_REF_NAME' => 'feature-x',
|
||||
]],
|
||||
])->skipOnWindows();
|
||||
|
||||
test('the fallback reaches parallel workers', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Plugins\Tia\ChangedFiles;
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
test('a replacement CI merge reuses its baseline and selects changed tests on either parent', function (array $arguments, string $changedBranch): void {
|
||||
$project = Project::make('master');
|
||||
$git = $project->git();
|
||||
$git->switchTo('feature', new: true);
|
||||
$git->commit('feature');
|
||||
$git->run(['checkout', '--detach', 'master']);
|
||||
$git->run(['merge', '--no-ff', '--no-edit', 'feature']);
|
||||
$project->seed('123/merge');
|
||||
|
||||
$git->switchTo($changedBranch);
|
||||
$project->write('tests/Unit/CalculatorTest.php', str_replace(
|
||||
'->add(1, 2)',
|
||||
'->add(2, 1)',
|
||||
file_get_contents($project->path('tests/Unit/CalculatorTest.php')) ?: throw new RuntimeException('Missing calculator test fixture.'),
|
||||
));
|
||||
$git->commit('change calculator');
|
||||
$git->run(['checkout', '--detach', 'master']);
|
||||
$git->run(['merge', '--no-ff', '--no-edit', 'feature']);
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), [
|
||||
'GITHUB_REF_NAME' => '123/merge',
|
||||
], '--tia', ...$arguments);
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->not->toContain('no longer reachable')
|
||||
->and($result->replayed())->toBe(4, $result->describe())
|
||||
->and($result->tally())->toContain('6 passed');
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->with(['feature', 'master'])->skipOnWindows();
|
||||
|
||||
test('a merge baseline is rejected when one of its parents is absent from the current history', function (): void {
|
||||
$project = Project::make('master');
|
||||
$git = $project->git();
|
||||
$git->switchTo('feature', new: true);
|
||||
$git->commit('feature');
|
||||
$git->run(['checkout', '--detach', 'master']);
|
||||
$git->run(['merge', '--no-ff', '--no-edit', 'feature']);
|
||||
$sha = $git->sha();
|
||||
$git->switchTo('master');
|
||||
|
||||
expect(new ChangedFiles($project->path())->since($sha))->toBeNull();
|
||||
})->skipOnWindows();
|
||||
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Tests\Fixtures\Tia\Project;
|
||||
|
||||
afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
/**
|
||||
* @param callable(array<string, mixed>): array<string, mixed>|null $mutator
|
||||
* @return array{0: Project, 1: array<string, string>}
|
||||
*/
|
||||
function tiaPublishedBaselineGitLab(string $mode = 'ok', ?callable $mutator = null): array
|
||||
{
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$payload = $project->detachGraph();
|
||||
|
||||
if ($mutator !== null) {
|
||||
/** @var array<string, mixed> $decoded */
|
||||
$decoded = json_decode($payload, true);
|
||||
$payload = (string) json_encode($mutator($decoded), JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
|
||||
return [$project, $project->glab($mode, $payload)];
|
||||
}
|
||||
|
||||
test('a self-hosted GitLab baseline is fetched when glab is available', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$payload = $project->detachGraph();
|
||||
|
||||
$environment = $project->glab('ok', $payload, 'gitlab.acme.com');
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->toContain('Downloading TIA baseline')
|
||||
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe())
|
||||
->and($project->graphExists())->toBeTrue();
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a published GitLab baseline is fetched instead of recorded locally', function (): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab();
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->toContain('Downloading TIA baseline')
|
||||
->and($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe())
|
||||
->and($project->graphExists())->toBeTrue();
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a fetched GitLab baseline that will not decode is discarded rather than trusted', function (): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab('corrupt');
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->toContain('The dependency graph could not be read')
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($result->replayed())->toBe(0, $result->describe());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a fetched GitLab baseline recorded against another tree is not used', function (): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab('ok', function (array $graph): array {
|
||||
$graph['fingerprint']['structural']['composer_lock'] = 'a-lockfile-this-project-never-had';
|
||||
|
||||
return $graph;
|
||||
});
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and($result->replayed())->toBe(0, $result->describe());
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a GitLab artifact without a graph in it fails loudly', function (): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab('missing-asset');
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->output)->toContain('the artifact is missing expected files')
|
||||
->and($project->graphExists())->toBeFalse();
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a GitLab baseline that cannot be authenticated for fails loudly', function (): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab('unauthenticated');
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->output)->toContain('is not authenticated')
|
||||
->and($project->graphExists())->toBeFalse();
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a GitLab pipeline or job that is not there fails loudly', function (): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab('list-404');
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(1, $result->describe())
|
||||
->and($result->output)->toContain('not found in project')
|
||||
->and($project->graphExists())->toBeFalse();
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a GitLab network failure warns and lets the suite run', function (string $mode): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab($mode);
|
||||
|
||||
$result = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->output)->toContain('network error')
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->with([
|
||||
'querying the runs' => ['list-network'],
|
||||
'downloading the artifact' => ['download-network'],
|
||||
])->skipOnWindows();
|
||||
|
||||
test('no published GitLab baseline yet starts a cooldown', function (): void {
|
||||
[$project, $environment] = tiaPublishedBaselineGitLab('no-runs');
|
||||
|
||||
$discardGraph = function () use ($project): void {
|
||||
if ($project->graphExists()) {
|
||||
$project->detachGraph();
|
||||
}
|
||||
};
|
||||
|
||||
$first = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($first->exitCode)->toBe(0, $first->describe())
|
||||
->and($first->output)->toContain('No baseline published yet')
|
||||
->and($project->graphDir().DIRECTORY_SEPARATOR.'fetch-cooldown.json')->toBeFile();
|
||||
|
||||
$discardGraph();
|
||||
|
||||
$second = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($second->exitCode)->toBe(0, $second->describe())
|
||||
->and($second->output)->toContain('next auto-retry in');
|
||||
|
||||
file_put_contents($project->graphDir().DIRECTORY_SEPARATOR.'fetch-cooldown.json', 'not json{');
|
||||
|
||||
$discardGraph();
|
||||
|
||||
$third = $project->pestWithEnvironment($project->path(), $environment, '--tia', '--baselined');
|
||||
|
||||
expect($third->exitCode)->toBe(0, $third->describe())
|
||||
->and($third->output)->toContain('No baseline published yet')
|
||||
->and($third->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
})->skipOnWindows();
|
||||
@@ -8,7 +8,7 @@ afterEach(function (): void {
|
||||
Project::destroyAll();
|
||||
});
|
||||
|
||||
test('a detached HEAD does not purge the graph on structural drift', function (array $arguments): void {
|
||||
test('a detached HEAD can rebuild the graph on structural drift', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -25,10 +25,10 @@ test('a detached HEAD does not purge the graph on structural drift', function (a
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($project->graphExists())->toBeTrue('the detached run deleted graph.json')
|
||||
->and($delta->isHardSuppressed())->toBeTrue($delta->summary());
|
||||
->and($delta->structureMoved())->toBeTrue($delta->summary());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a detached HEAD does not purge the graph with --fresh either', function (array $arguments): void {
|
||||
test('a detached HEAD can rebuild the graph with --fresh', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -39,10 +39,10 @@ test('a detached HEAD does not purge the graph with --fresh either', function (a
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($project->graphExists())->toBeTrue('the detached --fresh run deleted graph.json')
|
||||
->and($delta->isHardSuppressed())->toBeTrue($delta->summary());
|
||||
->and($delta->structureMoved())->toBeTrue($delta->summary());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a detached HEAD leaves an unreadable graph for a checkout that can rebuild it', function (): void {
|
||||
test('a detached HEAD can replace an unreadable graph for a checkout that can rebuild it', function (): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
@@ -54,7 +54,7 @@ test('a detached HEAD leaves an unreadable graph for a checkout that can rebuild
|
||||
|
||||
expect($result->exitCode)->toBe(0, $result->describe())
|
||||
->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed')
|
||||
->and(file_get_contents($project->graphDir().'/graph.json'))->toBe('{not json');
|
||||
->and(file_get_contents($project->graphDir().'/graph.json'))->not->toBe('{not json');
|
||||
})->skipOnWindows();
|
||||
|
||||
test('a cached failure whose test file was deleted stops widening later runs', function (array $arguments): void {
|
||||
@@ -358,3 +358,30 @@ test('a graph whose recorded commit is gone is re-anchored, not warned about for
|
||||
->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
test('a full suite run without a coverage driver clears the tree it could not refresh', function (array $arguments): void {
|
||||
$project = Project::make('master');
|
||||
$project->seed('master');
|
||||
|
||||
$project->mutateGraph(function (array $graph): array {
|
||||
$graph['baselines']['master']['tree'] = ['app/Calculator.php' => 'deadbeefdeadbeefdeadbeefdeadbeef'];
|
||||
|
||||
return $graph;
|
||||
});
|
||||
|
||||
$environment = ['XDEBUG_MODE' => 'off'];
|
||||
|
||||
$first = $project->pestWithEnvironment($project->path(), $environment, '--tia', ...$arguments);
|
||||
|
||||
expect($first->exitCode)->toBe(0, $first->describe())
|
||||
->and($first->output)->toContain('no coverage driver is available')
|
||||
->and($first->tally())->toContain(Project::TOTAL_TESTS.' passed');
|
||||
|
||||
$project->snapshot();
|
||||
$second = $project->pestWithEnvironment($project->path(), $environment, '--tia', ...$arguments);
|
||||
$delta = $project->delta();
|
||||
|
||||
expect($second->output)->not->toContain('no coverage driver is available')
|
||||
->and($second->replayed())->toBe(Project::TOTAL_TESTS, $second->describe())
|
||||
->and($delta->writtenCount())->toBe(0, $delta->summary());
|
||||
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
beforeEach(function (): void {
|
||||
expect(true)->toBeTrue();
|
||||
})->ticket(1);
|
||||
|
||||
@@ -65,6 +65,11 @@ final readonly class GitRepo
|
||||
$this->run(['remote', 'remove', 'origin']);
|
||||
}
|
||||
|
||||
public function setOriginUrl(string $url): void
|
||||
{
|
||||
$this->run(['remote', 'set-url', 'origin', $url]);
|
||||
}
|
||||
|
||||
public function setOriginHead(string $branch): void
|
||||
{
|
||||
$this->run(['update-ref', 'refs/remotes/origin/'.$branch, 'HEAD']);
|
||||
|
||||
@@ -157,7 +157,7 @@ final class Project
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $environment
|
||||
* @param array<string, string|false> $environment
|
||||
*/
|
||||
public function pestWithEnvironment(string $directory, array $environment, string ...$arguments): PestResult
|
||||
{
|
||||
@@ -172,11 +172,14 @@ final class Project
|
||||
'PAO_DISABLE' => '1',
|
||||
'XDEBUG_MODE' => 'coverage',
|
||||
'HOME' => $this->home(),
|
||||
'GITHUB_EVENT_PATH' => '',
|
||||
'CI_DEFAULT_BRANCH' => '',
|
||||
'GITHUB_ACTIONS' => '',
|
||||
'GITLAB_CI' => '',
|
||||
'CIRCLECI' => '',
|
||||
'CI' => false,
|
||||
'GITHUB_EVENT_PATH' => false,
|
||||
'CI_DEFAULT_BRANCH' => false,
|
||||
'CI_COMMIT_BRANCH' => false,
|
||||
'GITHUB_ACTIONS' => false,
|
||||
'GITHUB_REF_NAME' => false,
|
||||
'GITLAB_CI' => false,
|
||||
'CIRCLECI' => false,
|
||||
...$environment,
|
||||
],
|
||||
);
|
||||
@@ -288,6 +291,25 @@ final class Project
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function glab(string $mode = 'ok', string $payload = '{}', string $host = 'gitlab.com'): array
|
||||
{
|
||||
$this->git()->setOriginUrl(sprintf('git@%s:pestphp/tia-fixture.git', $host));
|
||||
|
||||
self::mirror(__DIR__.'/stubs/glab', $this->path('stub/glab'));
|
||||
chmod($this->path('stub/glab'), 0755);
|
||||
|
||||
$this->write('payload/graph.json', $payload);
|
||||
|
||||
return [
|
||||
'PATH' => $this->path('stub').PATH_SEPARATOR.getenv('PATH'),
|
||||
'GLAB_STUB_MODE' => $mode,
|
||||
'GLAB_STUB_PAYLOAD' => $this->path('payload/graph.json'),
|
||||
];
|
||||
}
|
||||
|
||||
public static function testId(string $testFile, string $description): string
|
||||
{
|
||||
$basename = basename($testFile, '.php');
|
||||
@@ -497,13 +519,21 @@ final class Project
|
||||
throw new RuntimeException(sprintf('Unable to create [%s].', $directory));
|
||||
}
|
||||
|
||||
if (@link($from, $to) || @copy($from, $to)) {
|
||||
if ((self::shareDevice($from, $directory) && @link($from, $to)) || @copy($from, $to)) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RuntimeException(sprintf('Unable to mirror [%s] into [%s].', $from, $to));
|
||||
}
|
||||
|
||||
private static function shareDevice(string $from, string $directory): bool
|
||||
{
|
||||
$source = @stat($from);
|
||||
$target = @stat($directory);
|
||||
|
||||
return $source !== false && $target !== false && $source['dev'] === $target['dev'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<\SplFileInfo>
|
||||
*/
|
||||
|
||||
@@ -16,7 +16,11 @@ if [ "$1" = "run" ] && [ "$2" = "list" ]; then
|
||||
fi
|
||||
|
||||
if [ "$1" = "api" ]; then
|
||||
echo 2048
|
||||
case "$2" in
|
||||
repos/*/actions/runs/*/artifacts) echo 2048 ;;
|
||||
repos/*) printf '{"default_branch":"master"}' ;;
|
||||
*) echo 2048 ;;
|
||||
esac
|
||||
exit 0
|
||||
fi
|
||||
|
||||
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/bin/sh
|
||||
|
||||
if [ "$1" = "auth" ]; then
|
||||
[ "$GLAB_STUB_MODE" = "unauthenticated" ] && exit 1
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$1" = "api" ]; then
|
||||
case "$2" in
|
||||
*jobs\?scope*)
|
||||
case "$GLAB_STUB_MODE" in
|
||||
no-runs) exit 0 ;;
|
||||
list-404) echo "404 Not Found" >&2; exit 1 ;;
|
||||
list-network) echo "could not resolve host" >&2; exit 1 ;;
|
||||
esac
|
||||
printf '[{"name":"tia-baseline","ref":"master","pipeline":{"id":987654321}}]'
|
||||
exit 0
|
||||
;;
|
||||
*pipelines/*/jobs*)
|
||||
printf '[{"name":"tia-baseline","artifacts":[{"size":2048}]}]'
|
||||
exit 0
|
||||
;;
|
||||
projects/*)
|
||||
printf '{"default_branch":"master"}'
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$1" = "job" ] && [ "$2" = "artifact" ]; then
|
||||
case "$GLAB_STUB_MODE" in
|
||||
download-403) echo "403 Forbidden" >&2; exit 1 ;;
|
||||
download-network) echo "connection refused" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
dir=""
|
||||
previous=""
|
||||
for argument in "$@"; do
|
||||
[ "$previous" = "--path" ] && dir="$argument"
|
||||
previous="$argument"
|
||||
done
|
||||
|
||||
[ -z "$dir" ] && exit 1
|
||||
|
||||
case "$GLAB_STUB_MODE" in
|
||||
missing-asset) echo "{}" > "$dir/other.json" ;;
|
||||
corrupt) printf 'not json at all' > "$dir/graph.json" ;;
|
||||
*) cp "$GLAB_STUB_PAYLOAD" "$dir/graph.json" ;;
|
||||
esac
|
||||
|
||||
exit 0
|
||||
fi
|
||||
|
||||
exit 1
|
||||
@@ -109,3 +109,27 @@ it('shows the correct description of datasets with html', function (): void {
|
||||
|
||||
expect($descriptions[0])->toBe('(\'<div class="flex items-center"></div>\')');
|
||||
});
|
||||
|
||||
it('does not treat a two element dataset of class names as a callable', function (): void {
|
||||
$datasets = DatasetsRepository::resolve([
|
||||
[
|
||||
MagicCallDataset::class,
|
||||
AnotherMagicCallDataset::class,
|
||||
],
|
||||
], __FILE__);
|
||||
|
||||
expect(array_values($datasets))->toBe([
|
||||
[MagicCallDataset::class],
|
||||
[AnotherMagicCallDataset::class],
|
||||
]);
|
||||
});
|
||||
|
||||
class MagicCallDataset
|
||||
{
|
||||
public static function __callStatic(string $name, array $arguments): void
|
||||
{
|
||||
throw new RuntimeException('This dataset should not be called.');
|
||||
}
|
||||
}
|
||||
|
||||
class AnotherMagicCallDataset {}
|
||||
|
||||
@@ -367,7 +367,7 @@ describe('buildListTestsCommand', function (): void {
|
||||
$command = $method->invoke($shard, ['bin/pest', '--update-shards'], 'custom/suite');
|
||||
|
||||
expect($command)->toBe([
|
||||
'php',
|
||||
PHP_BINARY,
|
||||
'bin/pest',
|
||||
'--update-shards',
|
||||
'--test-directory=custom/suite',
|
||||
@@ -385,7 +385,7 @@ describe('buildListTestsCommand', function (): void {
|
||||
$command = $method->invoke($shard, ['bin/pest', '--parallel', '--update-shards', '-p'], 'tests');
|
||||
|
||||
expect($command)->toBe([
|
||||
'php',
|
||||
PHP_BINARY,
|
||||
'bin/pest',
|
||||
'--update-shards',
|
||||
'--test-directory=tests',
|
||||
@@ -415,7 +415,7 @@ describe('buildListTestsCommand', function (): void {
|
||||
$command = $method->invoke($shard, ['bin/pest', '--parallel', '--processes=4', '--update-shards'], 'tests');
|
||||
|
||||
expect($command)->toBe([
|
||||
'php',
|
||||
PHP_BINARY,
|
||||
'bin/pest',
|
||||
'--update-shards',
|
||||
'--test-directory=tests',
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
use Pest\Plugins\Tia;
|
||||
|
||||
function tiaWorkerToken(): string
|
||||
{
|
||||
$tia = new ReflectionClass(Tia::class)->newInstanceWithoutConstructor();
|
||||
|
||||
return new ReflectionMethod($tia, 'workerToken')->invoke($tia);
|
||||
}
|
||||
|
||||
beforeEach(function (): void {
|
||||
unset(
|
||||
$_SERVER['TEST_TOKEN'],
|
||||
$_ENV['TEST_TOKEN'],
|
||||
$_SERVER['UNIQUE_TEST_TOKEN'],
|
||||
$_ENV['UNIQUE_TEST_TOKEN'],
|
||||
);
|
||||
});
|
||||
|
||||
test('prefers the per-process UNIQUE_TEST_TOKEN over the per-slot TEST_TOKEN, so two workers recycled into the same slot get different tokens', function (): void {
|
||||
$_SERVER['TEST_TOKEN'] = '2';
|
||||
|
||||
$_SERVER['UNIQUE_TEST_TOKEN'] = '2_6a690d236824c';
|
||||
$processA = tiaWorkerToken();
|
||||
|
||||
$_SERVER['UNIQUE_TEST_TOKEN'] = '2_9f31be04117a';
|
||||
$processB = tiaWorkerToken();
|
||||
|
||||
expect($processA)->toBe('2_6a690d236824c')
|
||||
->and($processB)->toBe('2_9f31be04117a')
|
||||
->and($processA)->not->toBe($processB);
|
||||
});
|
||||
|
||||
test('falls back to TEST_TOKEN when UNIQUE_TEST_TOKEN is absent', function (): void {
|
||||
$_SERVER['TEST_TOKEN'] = '3';
|
||||
|
||||
expect(tiaWorkerToken())->toBe('3');
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Pest\Restarters\PcovRestarter;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
it('preserves the active memory limit in the restarted process', function (): void {
|
||||
$originalMemoryLimit = ini_get('memory_limit');
|
||||
|
||||
try {
|
||||
ini_set('memory_limit', '1234M');
|
||||
|
||||
$command = new ReflectionMethod(PcovRestarter::class, 'command')
|
||||
->invoke(new PcovRestarter, __DIR__, ['-r', 'fwrite(STDOUT, (string) ini_get("memory_limit"));']);
|
||||
|
||||
assert(is_array($command));
|
||||
|
||||
$process = new Process($command);
|
||||
$process->mustRun();
|
||||
|
||||
expect($process->getOutput())->toBe('1234M');
|
||||
} finally {
|
||||
ini_set('memory_limit', (string) $originalMemoryLimit);
|
||||
}
|
||||
});
|
||||
@@ -20,19 +20,7 @@ test('parallel', function () use ($run): void {
|
||||
$output = $run('--exclude-group=integration');
|
||||
$output = implode("\n", array_slice(explode("\n", (string) $output), -10));
|
||||
|
||||
if (getenv('REBUILD_SNAPSHOTS')) {
|
||||
preg_match('/Tests:\s+(.+\(\d+ assertions\))/', $output, $matches);
|
||||
|
||||
$file = file_get_contents(__FILE__);
|
||||
$file = preg_replace(
|
||||
'/\$expected = \'.*?\';/',
|
||||
"\$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1554 passed (3358 assertions)';",
|
||||
$file,
|
||||
);
|
||||
file_put_contents(__FILE__, $file);
|
||||
}
|
||||
|
||||
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1554 passed (3358 assertions)';
|
||||
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 27 skipped, 1581 passed (3431 assertions)';
|
||||
|
||||
expect($output)
|
||||
->toContain("Tests: {$expected}")
|
||||
|
||||
Reference in New Issue
Block a user