Compare commits

...

12 Commits

Author SHA1 Message Date
nuno maduro 627092ecfc chore: bumps deps 2026-08-24 14:06:57 +01:00
nuno maduro 2692613f09 chore: ignore hod 2026-08-24 10:58:51 +01:00
nuno maduro e763a87b42 chore: updates snapshots 2026-08-24 10:51:08 +01:00
nuno maduro 4a65054f83 chore: style 2026-08-24 09:39:08 +01:00
nuno maduro b8c2265d66 fix: snapshot key on retry / repeat 2026-08-24 09:31:34 +01:00
Daniel Polito 39cbdcd52b Prevent memory exhaustion when generating TIA graphs with PCOV (#1875)
* fix(tia): preserve memory limit during pcov restart

* chore: update test expectations

* fix: stabilize tia replay test in ci
2026-08-24 08:41:59 +01:00
Lazizbek Ergashev aba2b79609 fix: exit code with --shard and --parallel (#1883)
* fix: exit code with --shard and --parallel

* fix: match existing argument-handling style in Shard
2026-08-24 08:41:01 +01:00
nuno maduro 1af74a215c chore: new sponsor 2026-08-18 19:42:16 +01:00
Andrew Matia cfe89d20ac Fix repeat with named dataset arguments (#1769) 2026-08-16 15:08:46 +01:00
nuno maduro 2c7cc1dc87 fix: static callable datasets 2026-08-13 18:38:27 +01:00
Lazizbek Ergashev 9b36f44b3e fix(tia): include the PHP minor version in the fingerprint (#1860) 2026-08-13 16:16:15 +01:00
Lazizbek Ergashev 2e58918201 fix(tia): treat a test skipped from a hook as finished (#1863) 2026-08-13 16:15:45 +01:00
51 changed files with 747 additions and 178 deletions
+3
View File
@@ -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
+3
View File
@@ -14,3 +14,6 @@ coverage.xml
.vscode/
.STREAM.md
/.claude/skills/
/.agents/skills/
+7
View File
@@ -0,0 +1,7 @@
# The intention of this project
Write the intention of the project here. Say what the project does and who uses it.
Give the command that installs the dependencies, the command that runs the tests and the command that starts the program. Name each directory and give its function.
Write a decision that one directory needs in the `AGENTS.md` file of that directory.
+14
View File
@@ -0,0 +1,14 @@
1a51f3f6c4eef45e6995bb5ac9a82cf3f23ccad0c68cc4f957796bb9fc198f58 .agents/skills/deps-upgrade/SKILL.md
984c7232ae1681ebba980ede2a0543db9a850dd2406990cdfa011384f929e981 .agents/skills/deps-upgrade/agents/openai.yaml
e68fb750f54ca3b17d6797954cb7838f0415c2faa65496ae68cb3918474c68bf .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
1a51f3f6c4eef45e6995bb5ac9a82cf3f23ccad0c68cc4f957796bb9fc198f58 .claude/skills/deps-upgrade/SKILL.md
984c7232ae1681ebba980ede2a0543db9a850dd2406990cdfa011384f929e981 .claude/skills/deps-upgrade/agents/openai.yaml
e68fb750f54ca3b17d6797954cb7838f0415c2faa65496ae68cb3918474c68bf .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
+74
View File
@@ -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
+75
View File
@@ -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
View File
@@ -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
+1
View File
@@ -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)
+6 -6
View File
@@ -18,19 +18,19 @@
],
"require": {
"php": "^8.4",
"brianium/paratest": "^7.24.0",
"brianium/paratest": "^7.24.1",
"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.1",
"symfony/process": "^8.1.5"
},
"conflict": {
"filp/whoops": "<2.18.3",
"phpunit/phpunit": ">13.3.0",
"phpunit/phpunit": ">13.3.1",
"sebastian/exporter": "<7.0.0",
"webmozart/assert": "<1.11.0"
},
@@ -61,8 +61,8 @@
"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-phpstan": "^5.2.0",
"pestphp/pest-plugin-rector": "^5.0.4",
"pestphp/pest-plugin-type-coverage": "^5.0.2",
"psy/psysh": "^0.12.24"
},
+17 -6
View File
@@ -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
View File
@@ -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
*/
+28 -30
View File
@@ -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
View File
@@ -6,7 +6,7 @@ namespace Pest;
function version(): string
{
return '5.1.1';
return '5.1.2';
}
function testDirectory(string $file = ''): string
+7 -1
View File
@@ -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);
}
/**
+1 -1
View File
@@ -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,
],
];
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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]);
}
+68
View File
@@ -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"]);
}
}
+87 -59
View File
@@ -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();
}
}
+19 -6
View File
@@ -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>
*/
@@ -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')
@@ -0,0 +1,7 @@
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Snapshot</h1>
</div>
</div>
</div>
@@ -0,0 +1 @@
the same on every attempt
@@ -1,5 +1,5 @@
Pest Testing Framework 5.1.1.
Pest Testing Framework 5.1.2.
USAGE: pest <file> [options]
@@ -1,3 +1,3 @@
Pest Testing Framework 5.1.1.
Pest Testing Framework 5.1.2.
+27 -1
View File
@@ -439,6 +439,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 +1123,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 +1236,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 +1469,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 +1786,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
@@ -2042,6 +2065,9 @@
✓ 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 +2251,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, 1596 passed (3481 assertions)
+2
View File
@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
beforeEach(function (): void {
expect(true)->toBeTrue();
})->assignee('nunomaduro');
+11
View File
@@ -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);
});
+76 -11
View File
@@ -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);
+36
View File
@@ -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;
+2
View File
@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
beforeEach(function (): void {
expect(true)->toBeTrue();
})->issue(1);
+2
View File
@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
beforeEach(function (): void {
expect(true)->toBeTrue();
})->pr(1);
+24
View File
@@ -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();
+2
View File
@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
it('allows access to the underlying expectNotToPerformAssertions method', function (): void {
$this->expectNotToPerformAssertions();
+1
View File
@@ -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,
],
);
@@ -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
View File
@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
beforeEach(function (): void {
expect(true)->toBeTrue();
})->ticket(1);
+24
View File
@@ -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 {}
+26
View File
@@ -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);
}
});
+1 -13
View File
@@ -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, 1578 passed (3426 assertions)';
expect($output)
->toContain("Tests: {$expected}")