Compare commits

..

2 Commits

Author SHA1 Message Date
nuno maduro 5d4d2231fb chore: pin GitHub Actions to commit SHAs 2026-05-12 02:07:57 +01:00
nuno maduro a11a3126f2 chore: pin GitHub Actions to commit SHAs 2026-05-12 02:07:56 +01:00
536 changed files with 5863 additions and 13007 deletions
-13
View File
@@ -1,13 +0,0 @@
# Security Policy
**PLEASE DON'T DISCLOSE SECURITY-RELATED ISSUES PUBLICLY, [SEE BELOW](#reporting-a-vulnerability).**
## Reporting a Vulnerability
If you discover a security vulnerability in Pest, please report it privately using one of the following channels:
1. **GitHub Private Vulnerability Reporting** (preferred) — go to the repository's **Security** tab and click **"Report a vulnerability"**. This creates a private advisory visible only to maintainers and provides a structured workflow for triage, fix coordination, and CVE assignment.
2. **Email** — send the details to Nuno Maduro at **enunomaduro@gmail.com**.
All security vulnerabilities will be promptly addressed.
-12
View File
@@ -1,12 +0,0 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
cooldown:
default-days: 5
groups:
github-actions:
patterns:
- "*"
+9 -11
View File
@@ -2,7 +2,7 @@ name: Static Analysis
on: on:
push: push:
branches: [5.x] branches: [4.x]
pull_request: pull_request:
schedule: schedule:
- cron: '0 9 * * *' - cron: '0 9 * * *'
@@ -24,16 +24,16 @@ jobs:
strategy: strategy:
fail-fast: true fail-fast: true
matrix: matrix:
dependency-version: [prefer-stable] dependency-version: [prefer-lowest, prefer-stable]
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Setup PHP - name: Setup PHP
uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # v2
with: with:
php-version: 8.4 php-version: 8.3
tools: composer:v2 tools: composer:v2
coverage: none coverage: none
extensions: sockets extensions: sockets
@@ -44,17 +44,15 @@ jobs:
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
- name: Cache Composer dependencies - name: Cache Composer dependencies
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with: with:
path: ${{ steps.composer-cache.outputs.dir }} path: ${{ steps.composer-cache.outputs.dir }}
key: static-php-8.4-${{ matrix.dependency-version }}-composer-${{ hashFiles('**/composer.json', '**/composer.lock') }} key: static-php-8.3-${{ matrix.dependency-version }}-composer-${{ hashFiles('**/composer.json', '**/composer.lock') }}
restore-keys: | restore-keys: |
static-php-8.4-${{ matrix.dependency-version }}-composer- static-php-8.3-${{ matrix.dependency-version }}-composer-
static-php-8.4-composer- static-php-8.3-composer-
- name: Install Dependencies - name: Install Dependencies
env:
COMPOSER_ROOT_VERSION: 5.x-dev
run: composer update --${{ matrix.dependency-version }} --no-interaction --no-progress --ansi run: composer update --${{ matrix.dependency-version }} --no-interaction --no-progress --ansi
- name: Profanity Check - name: Profanity Check
+9 -8
View File
@@ -2,7 +2,7 @@ name: Tests
on: on:
push: push:
branches: [5.x] branches: [4.x]
pull_request: pull_request:
schedule: schedule:
- cron: '0 9 * * *' - cron: '0 9 * * *'
@@ -24,18 +24,21 @@ jobs:
fail-fast: true fail-fast: true
matrix: matrix:
os: [ubuntu-latest, macos-latest] # windows-latest os: [ubuntu-latest, macos-latest] # windows-latest
symfony: ['8.0'] symfony: ['7.4', '8.0']
php: ['8.4', '8.5'] php: ['8.3', '8.4', '8.5']
dependency_version: [prefer-stable] dependency_version: [prefer-stable]
exclude:
- php: '8.3'
symfony: '8.0'
name: PHP ${{ matrix.php }} - Symfony ^${{ matrix.symfony }} - ${{ matrix.os }} - ${{ matrix.dependency_version }} name: PHP ${{ matrix.php }} - Symfony ^${{ matrix.symfony }} - ${{ matrix.os }} - ${{ matrix.dependency_version }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Setup PHP - name: Setup PHP
uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2 uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # v2
with: with:
php-version: ${{ matrix.php }} php-version: ${{ matrix.php }}
tools: composer:v2 tools: composer:v2
@@ -48,7 +51,7 @@ jobs:
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
- name: Cache Composer dependencies - name: Cache Composer dependencies
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v5 uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with: with:
path: ${{ steps.composer-cache.outputs.dir }} path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ matrix.os }}-php-${{ matrix.php }}-symfony-${{ matrix.symfony }}-composer-${{ hashFiles('**/composer.json', '**/composer.lock') }} key: ${{ matrix.os }}-php-${{ matrix.php }}-symfony-${{ matrix.symfony }}-composer-${{ hashFiles('**/composer.json', '**/composer.lock') }}
@@ -63,8 +66,6 @@ jobs:
- name: Install PHP dependencies - name: Install PHP dependencies
shell: bash shell: bash
env:
COMPOSER_ROOT_VERSION: 5.x-dev
run: composer update --${{ matrix.dependency_version }} --no-interaction --no-progress --ansi --with="symfony/console:^${{ matrix.symfony }}" run: composer update --${{ matrix.dependency_version }} --no-interaction --no-progress --ansi --with="symfony/console:^${{ matrix.symfony }}"
- name: Unit Tests - name: Unit Tests
+1 -1
View File
@@ -1,7 +1,7 @@
.idea/* .idea/*
.idea/codeStyleSettings.xml .idea/codeStyleSettings.xml
.temp/* .temp/*
/composer.lock composer.lock
/vendor/ /vendor/
coverage.xml coverage.xml
.phpunit.result.cache .phpunit.result.cache
-34
View File
@@ -1,34 +0,0 @@
# 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
```
+22 -14
View File
@@ -1,7 +1,7 @@
<p align="center"> <p align="center">
<img src="https://raw.githubusercontent.com/pestphp/art/master/v5/social.png" width="600" alt="PEST"> <img src="https://raw.githubusercontent.com/pestphp/art/master/v4/social.png" width="600" alt="PEST">
<p align="center"> <p align="center">
<a href="https://github.com/pestphp/pest/actions"><img alt="GitHub Workflow Status (5.x)" src="https://img.shields.io/github/actions/workflow/status/pestphp/pest/tests.yml?branch=5.x&label=Tests%205.x"></a> <a href="https://github.com/pestphp/pest/actions"><img alt="GitHub Workflow Status (master)" src="https://img.shields.io/github/actions/workflow/status/pestphp/pest/tests.yml?branch=4.x&label=Tests%204.x"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img alt="Total Downloads" src="https://img.shields.io/packagist/dt/pestphp/pest"></a> <a href="https://packagist.org/packages/pestphp/pest"><img alt="Total Downloads" src="https://img.shields.io/packagist/dt/pestphp/pest"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img alt="Latest Version" src="https://img.shields.io/packagist/v/pestphp/pest"></a> <a href="https://packagist.org/packages/pestphp/pest"><img alt="Latest Version" src="https://img.shields.io/packagist/v/pestphp/pest"></a>
<a href="https://packagist.org/packages/pestphp/pest"><img alt="License" src="https://img.shields.io/packagist/l/pestphp/pest"></a> <a href="https://packagist.org/packages/pestphp/pest"><img alt="License" src="https://img.shields.io/packagist/l/pestphp/pest"></a>
@@ -12,9 +12,9 @@
------ ------
> Pest v5 Now Available: **[Read the announcement »](https://pestphp.com/docs/pest5-now-available)**. > Pest v4 Now Available: **[Read the announcement »](https://pestphp.com/docs/pest-v4-is-here-now-with-browser-testing)**.
**Pest** is an elegant testing framework for PHP developers and AI agents. **Pest** is an elegant PHP testing Framework with a focus on simplicity, meticulously designed to bring back the joy of testing in PHP.
- Explore our docs at **[pestphp.com »](https://pestphp.com)** - Explore our docs at **[pestphp.com »](https://pestphp.com)**
- Follow the creator Nuno Maduro: - Follow the creator Nuno Maduro:
@@ -29,18 +29,26 @@
We cannot thank our sponsors enough for their incredible support in funding Pest's development. Their contributions have been instrumental in making Pest the best it can be. For those who are interested in becoming a sponsor, please visit Nuno Maduro's Sponsor page at **[github.com/sponsors/nunomaduro](https://github.com/sponsors/nunomaduro)**. We cannot thank our sponsors enough for their incredible support in funding Pest's development. Their contributions have been instrumental in making Pest the best it can be. For those who are interested in becoming a sponsor, please visit Nuno Maduro's Sponsor page at **[github.com/sponsors/nunomaduro](https://github.com/sponsors/nunomaduro)**.
- **[PhpStorm](https://jb.gg/nuno)**
- **[CodeRabbit](https://coderabbit.link/nunomaduro)** ### Platinum Sponsors
- **[CodeRabbit](https://coderabbit.ai/?ref=pestphp)**
- **[Mailtrap](https://l.rw.rw/pestphp)**
- **[SerpApi](https://serpapi.com/?ref=nunomaduro)** - **[SerpApi](https://serpapi.com/?ref=nunomaduro)**
- **[Bento](https://bentonow.com/?ref=nunomaduro)** - **[Tighten](https://tighten.com/?ref=nunomaduro)**
- **[CMS Max](https://cmsmax.com/?ref=nunomaduro)**
- **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)** - **[Redberry](https://redberry.international/laravel-development/?utm_source=pest&utm_medium=banner&utm_campaign=pest_sponsorship)**
- **[Typesense](https://typesense.org/?ref=nunomaduro)**
- **[Pixel](https://wearepixel.com.au/?ref=nunomaduro)** ### Gold Sponsors
- **[CMS Max](https://cmsmax.com/?ref=pestphp)**
### Premium Sponsors
- [Zapiet](https://zapiet.com/?ref=pestphp)
- [Load Forge](https://loadforge.com/?ref=pestphp)
- [Route4Me](https://route4me.com/pt?ref=pestphp)
- [Nerdify](https://getnerdify.com/?ref=pestphp)
- [Akaunting](https://akaunting.com/?ref=pestphp)
- [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest) - [TestMu AI](https://www.testmuai.com/?utm_medium=sponsor&utm_source=pest)
- [Zapiet](https://zapiet.com/?ref=nunomaduro)
- [LoadForge](https://loadforge.com/?ref=nunomaduro)
- [Route4Me](https://route4me.com/?ref=nunomaduro)
- [Nerdify](https://getnerdify.com/?ref=nunomaduro)
Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**. Pest is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
+3 -3
View File
@@ -2,10 +2,10 @@
When releasing a new version of Pest there are some checks and updates that need to be done: When releasing a new version of Pest there are some checks and updates that need to be done:
> **For Pest v4 you should use the `4.x` branch instead.** > **For Pest v3 you should use the `3.x` branch instead.**
- Clear your local repository with: `git add . && git reset --hard && git checkout 5.x` - Clear your local repository with: `git add . && git reset --hard && git checkout 4.x`
- On the GitHub repository, check the contents of [github.com/pestphp/pest/compare/{latest_version}...5.x](https://github.com/pestphp/pest/compare/{latest_version}...5.x) - On the GitHub repository, check the contents of [github.com/pestphp/pest/compare/{latest_version}...4.x](https://github.com/pestphp/pest/compare/{latest_version}...4.x)
- Update the version number in [src/Pest.php](src/Pest.php) - Update the version number in [src/Pest.php](src/Pest.php)
- Run the tests locally using: `composer test` - Run the tests locally using: `composer test`
- Commit the Pest file with the message: `git commit -m "release: vX.X.X"` - Commit the Pest file with the message: `git commit -m "release: vX.X.X"`
+19 -173
View File
@@ -25,72 +25,26 @@ const PAGE_DIR_CANDIDATES = [
async function loadRolldown() { async function loadRolldown() {
const projectRequire = createRequire(join(PROJECT_ROOT, 'package.json')) const projectRequire = createRequire(join(PROJECT_ROOT, 'package.json'))
let path = null const path = projectRequire.resolve('rolldown')
try { path = projectRequire.resolve('rolldown') } catch {}
if (path === null) {
// rolldown-vite installs (vite@npm:rolldown-vite) ship rolldown as a
// dependency of the vite package rather than a top-level install.
try {
const viteRequire = createRequire(projectRequire.resolve('vite/package.json'))
path = viteRequire.resolve('rolldown')
} catch {}
}
if (path === null) return null
return await import(pathToFileURL(path).href) return await import(pathToFileURL(path).href)
} }
export function stripJsonComments(raw) {
let out = ''
let inString = false
let quote = ''
let inLine = false
let inBlock = false
for (let i = 0; i < raw.length; i++) {
const c = raw[i]
const n = raw[i + 1]
if (inLine) {
if (c === '\n') { inLine = false; out += c }
continue
}
if (inBlock) {
if (c === '*' && n === '/') { inBlock = false; i++ }
continue
}
if (inString) {
out += c
if (c === '\\') { out += n ?? ''; i++; continue }
if (c === quote) inString = false
continue
}
if (c === '"' || c === "'") { inString = true; quote = c; out += c; continue }
if (c === '/' && n === '/') { inLine = true; i++; continue }
if (c === '/' && n === '*') { inBlock = true; i++; continue }
if (c === '}' || c === ']') out = out.replace(/,\s*$/, '')
out += c
}
return out
}
async function readJsonWithComments(path) { async function readJsonWithComments(path) {
const raw = await readFile(path, 'utf8') const raw = await readFile(path, 'utf8')
return JSON.parse(stripJsonComments(raw)) const stripped = raw
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/(^|[^:])\/\/[^\n]*/g, '$1')
return JSON.parse(stripped)
} }
export async function loadAliasFromTsconfig(projectRoot = PROJECT_ROOT) { async function loadAliasFromTsconfig() {
const alias = {} const alias = {}
for (const name of ['tsconfig.json', 'jsconfig.json']) { for (const name of ['tsconfig.json', 'jsconfig.json']) {
const p = join(projectRoot, name) const p = join(PROJECT_ROOT, name)
if (!existsSync(p)) continue if (!existsSync(p)) continue
let cfg let cfg
try { cfg = await readJsonWithComments(p) } catch { continue } try { cfg = await readJsonWithComments(p) } catch { continue }
const baseUrl = resolve(projectRoot, cfg?.compilerOptions?.baseUrl ?? '.') const baseUrl = resolve(PROJECT_ROOT, cfg?.compilerOptions?.baseUrl ?? '.')
const paths = cfg?.compilerOptions?.paths ?? {} const paths = cfg?.compilerOptions?.paths ?? {}
for (const [key, targets] of Object.entries(paths)) { for (const [key, targets] of Object.entries(paths)) {
if (!key.endsWith('/*')) continue if (!key.endsWith('/*')) continue
@@ -104,74 +58,6 @@ export async function loadAliasFromTsconfig(projectRoot = PROJECT_ROOT) {
return alias return alias
} }
const VITE_CONFIG_FILES = [
'vite.config.ts',
'vite.config.js',
'vite.config.mjs',
'vite.config.cjs',
'vite.config.mts',
'vite.config.cts',
]
function resolveAliasTarget(projectRoot, target) {
if (target.startsWith('/')) {
// Vite resolves a leading slash against the project root, unless the
// config author used a genuinely absolute path.
return existsSync(target) ? target : resolve(projectRoot, '.' + target)
}
return resolve(projectRoot, target)
}
async function usesLaravelVitePlugin(projectRoot) {
const p = join(projectRoot, 'package.json')
if (!existsSync(p)) return false
try {
const pkg = JSON.parse(await readFile(p, 'utf8'))
return Boolean(pkg.dependencies?.['laravel-vite-plugin'] ?? pkg.devDependencies?.['laravel-vite-plugin'])
} catch {
return false
}
}
export async function loadAliasFromViteConfig(projectRoot = PROJECT_ROOT) {
const alias = {}
let source = null
for (const name of VITE_CONFIG_FILES) {
const p = join(projectRoot, name)
if (!existsSync(p)) continue
try { source = await readFile(p, 'utf8') } catch { continue }
break
}
if (source !== null) {
// The config is executable code we cannot import safely, so extract alias
// entries textually: a quoted `@…`/`~…` key, then the last quoted path in
// the value expression — covers `'@': '/resources/js'` as well as
// `'@': path.resolve(__dirname, 'resources/js')`. The value stops at a
// top-level comma; call arguments are kept via the paren group.
for (const m of source.matchAll(/['"`]([@~][\w./-]*)['"`]\s*:\s*((?:\([^)\n]*\)|[^,\n])*)/g)) {
const key = m[1]
if (alias[key] !== undefined) continue
const paths = [...m[2].matchAll(/['"`]([^'"`]+)['"`]/g)].map((p) => p[1])
const target = paths.length > 0 ? paths[paths.length - 1] : null
if (!target || target.includes('*')) continue
alias[key] = resolveAliasTarget(projectRoot, target)
}
}
// laravel-vite-plugin registers '@' → resources/js by default.
if (alias['@'] === undefined && (await usesLaravelVitePlugin(projectRoot))) {
alias['@'] = resolve(projectRoot, 'resources/js')
}
return alias
}
async function listPageFiles(pagesDir) { async function listPageFiles(pagesDir) {
if (!existsSync(pagesDir)) return [] if (!existsSync(pagesDir)) return []
@@ -190,24 +76,6 @@ async function listPageFiles(pagesDir) {
return out return out
} }
// `existsSync()` ignores casing on APFS and NTFS, and on a macOS bind mount seen from
// inside a Linux container, so the `resources/js/Pages` candidate resolves in a project
// whose directory is really `resources/js/pages`. Every page path derives from the
// directory accepted below, so a wrong-cased one detaches the pages tree from the paths
// the PHP side reports. `readdir()` is case-exact everywhere.
export async function matchesDiskCasing(projectRoot, rel) {
let current = projectRoot
for (const segment of rel.split('/')) {
let entries
try { entries = await readdir(current) } catch { return false }
if (!entries.includes(segment)) return false
current = join(current, segment)
}
return true
}
async function discoverPagesDir() { async function discoverPagesDir() {
const override = process.env.TIA_VITE_PAGES_DIR const override = process.env.TIA_VITE_PAGES_DIR
if (override && override.length > 0) { if (override && override.length > 0) {
@@ -217,7 +85,6 @@ async function discoverPagesDir() {
for (const rel of PAGE_DIR_CANDIDATES) { for (const rel of PAGE_DIR_CANDIDATES) {
const abs = resolve(PROJECT_ROOT, rel) const abs = resolve(PROJECT_ROOT, rel)
if (!existsSync(abs)) continue if (!existsSync(abs)) continue
if (!(await matchesDiskCasing(PROJECT_ROOT, rel))) continue
const files = await listPageFiles(abs) const files = await listPageFiles(abs)
if (files.length > 0) return abs if (files.length > 0) return abs
} }
@@ -254,16 +121,8 @@ async function main() {
return return
} }
const loaded = await loadRolldown() const { rolldown } = await loadRolldown()
const alias = await loadAliasFromTsconfig()
if (loaded === null) {
process.stdout.write('{}')
return
}
const { rolldown } = loaded
// The vite config is what the dev server actually resolves with — let it win.
const alias = { ...(await loadAliasFromTsconfig()), ...(await loadAliasFromViteConfig()) }
const aliasKeys = Object.keys(alias) const aliasKeys = Object.keys(alias)
const graph = new Map() const graph = new Map()
@@ -308,7 +167,7 @@ async function main() {
cwd: PROJECT_ROOT, cwd: PROJECT_ROOT,
resolve: { resolve: {
alias, alias,
extensions: ['.tsx', '.ts', '.jsx', '.js', '.mts', '.cts', '.mjs', '.cjs', '.json', '.vue', '.svelte'], extensions: ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.json'],
}, },
transform: { jsx: 'preserve' }, transform: { jsx: 'preserve' },
treeshake: false, treeshake: false,
@@ -333,11 +192,6 @@ async function main() {
stack.add(id) stack.add(id)
const acc = new Set() const acc = new Set()
// A set computed while skipping an in-stack (cyclic) dependency is missing
// that dependency's subtree and must not be memoized — the ancestor call
// completes it for the current traversal, but a cached copy would leak the
// incomplete set into other pages' traversals.
let complete = true
const deps = graph.get(id) const deps = graph.get(id)
if (deps) { if (deps) {
for (const dep of deps) { for (const dep of deps) {
@@ -346,17 +200,13 @@ async function main() {
const rel = relative(PROJECT_ROOT, dep).split(sep).join('/') const rel = relative(PROJECT_ROOT, dep).split(sep).join('/')
acc.add(rel) acc.add(rel)
} }
if (stack.has(dep)) { if (stack.has(dep)) continue
complete = false
continue
}
const child = computeTransitive(dep, stack) const child = computeTransitive(dep, stack)
if (child) for (const r of child) acc.add(r) if (child) for (const r of child) acc.add(r)
if (!transitiveCache.has(dep)) complete = false
} }
} }
stack.delete(id) stack.delete(id)
if (complete) transitiveCache.set(id, acc) transitiveCache.set(id, acc)
return acc return acc
} }
@@ -380,14 +230,10 @@ async function main() {
process.stdout.write(JSON.stringify(payload)) process.stdout.write(JSON.stringify(payload))
} }
const invokedDirectly = process.argv[1] !== undefined try {
&& import.meta.url === pathToFileURL(process.argv[1]).href void pathToFileURL
await main()
if (invokedDirectly) { } catch (err) {
try { process.stderr.write(String(err?.stack ?? err ?? 'unknown error'))
await main() process.exit(1)
} catch (err) {
process.stderr.write(String(err?.stack ?? err ?? 'unknown error'))
process.exit(1)
}
} }
+1
View File
@@ -111,6 +111,7 @@ $bootPest = (static function (): void {
exit; exit;
} }
// It must be a 1 byte string to ensure filesize() is equal to the number of tests executed
$exitCode = $application->runTest(realpath(trim($testPath))); $exitCode = $application->runTest(realpath(trim($testPath)));
fwrite($statusFile, (string) $exitCode); fwrite($statusFile, (string) $exitCode);
+17 -20
View File
@@ -17,20 +17,21 @@
} }
], ],
"require": { "require": {
"php": "^8.4", "php": "^8.3.0",
"brianium/paratest": "^7.24.0", "brianium/paratest": "^7.20.0",
"nunomaduro/collision": "^8.9.5", "composer/xdebug-handler": "^3.0.5",
"nunomaduro/collision": "^8.9.4",
"nunomaduro/termwind": "^2.4.0", "nunomaduro/termwind": "^2.4.0",
"pestphp/pest-plugin": "^5.0.0", "pestphp/pest-plugin": "^4.0.0",
"pestphp/pest-plugin-arch": "^5.0.0", "pestphp/pest-plugin-arch": "^4.0.2",
"pestphp/pest-plugin-mutate": "^5.0.2", "pestphp/pest-plugin-mutate": "^4.0.1",
"pestphp/pest-plugin-profanity": "^5.0.0", "pestphp/pest-plugin-profanity": "^4.2.1",
"phpunit/phpunit": "^13.3.0", "phpunit/phpunit": "^12.5.24",
"symfony/process": "^8.1.0" "symfony/process": "^7.4.8|^8.0.8"
}, },
"conflict": { "conflict": {
"filp/whoops": "<2.18.3", "filp/whoops": "<2.18.3",
"phpunit/phpunit": ">13.3.0", "phpunit/phpunit": ">12.5.24",
"sebastian/exporter": "<7.0.0", "sebastian/exporter": "<7.0.0",
"webmozart/assert": "<1.11.0" "webmozart/assert": "<1.11.0"
}, },
@@ -48,7 +49,6 @@
"Tests\\Fixtures\\Covers\\": "tests/Fixtures/Covers", "Tests\\Fixtures\\Covers\\": "tests/Fixtures/Covers",
"Tests\\Fixtures\\Inheritance\\": "tests/Fixtures/Inheritance", "Tests\\Fixtures\\Inheritance\\": "tests/Fixtures/Inheritance",
"Tests\\Fixtures\\Arch\\": "tests/Fixtures/Arch", "Tests\\Fixtures\\Arch\\": "tests/Fixtures/Arch",
"Tests\\Fixtures\\Tia\\": "tests/Fixtures/Tia",
"Tests\\": "tests/PHPUnit/" "Tests\\": "tests/PHPUnit/"
}, },
"classmap": [ "classmap": [
@@ -59,19 +59,17 @@
] ]
}, },
"require-dev": { "require-dev": {
"pestphp/pest-dev-tools": "^5.0.0", "mrpunyapal/peststan": "^0.2.9",
"pestphp/pest-plugin-browser": "^5.0.1", "pestphp/pest-dev-tools": "^4.1.0",
"pestphp/pest-plugin-phpstan": "^5.0.2", "pestphp/pest-plugin-browser": "^4.3.1",
"pestphp/pest-plugin-rector": "^5.0.3", "pestphp/pest-plugin-type-coverage": "^4.0.4",
"pestphp/pest-plugin-type-coverage": "^5.0.2", "psy/psysh": "^0.12.22"
"psy/psysh": "^0.12.24"
}, },
"minimum-stability": "dev", "minimum-stability": "dev",
"prefer-stable": true, "prefer-stable": true,
"config": { "config": {
"sort-packages": true, "sort-packages": true,
"preferred-install": "dist", "preferred-install": "dist",
"process-timeout": 0,
"allow-plugins": { "allow-plugins": {
"pestphp/pest-plugin": true "pestphp/pest-plugin": true
} }
@@ -95,8 +93,7 @@
"test:inline": "php bin/pest --configuration=phpunit.inline.xml", "test:inline": "php bin/pest --configuration=phpunit.inline.xml",
"test:parallel": "php bin/pest --exclude-group=integration --parallel --processes=3", "test:parallel": "php bin/pest --exclude-group=integration --parallel --processes=3",
"test:integration": "php bin/pest --group=integration -v", "test:integration": "php bin/pest --group=integration -v",
"test:tia": "php bin/pest --group=tia -v", "update:snapshots": "REBUILD_SNAPSHOTS=true php bin/pest --update-snapshots",
"update:snapshots": "REBUILD_SNAPSHOTS=true php bin/pest --update-snapshots --exclude-group=tia",
"test": [ "test": [
"@test:lint", "@test:lint",
"@test:type:check", "@test:type:check",
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
/* /*
+51 -13
View File
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
/* /*
@@ -54,7 +86,7 @@ final class JunitXmlLogger
{ {
private readonly Printer $printer; private readonly Printer $printer;
private readonly Converter $converter; private readonly Converter $converter; // pest-added
private DOMDocument $document; private DOMDocument $document;
@@ -112,7 +144,8 @@ final class JunitXmlLogger
public function __construct(Printer $printer, Facade $facade) public function __construct(Printer $printer, Facade $facade)
{ {
$this->printer = $printer; $this->printer = $printer;
$this->converter = new Converter(Container::getInstance()->get(TestSuite::class)->rootPath); $this->converter = new Converter(Container::getInstance()->get(TestSuite::class)->rootPath); // pest-added
$this->registerSubscribers($facade); $this->registerSubscribers($facade);
$this->createDocument(); $this->createDocument();
} }
@@ -127,9 +160,10 @@ final class JunitXmlLogger
public function testSuiteStarted(Started $event): void public function testSuiteStarted(Started $event): void
{ {
$testSuite = $this->document->createElement('testsuite'); $testSuite = $this->document->createElement('testsuite');
$testSuite->setAttribute('name', $this->converter->getTestSuiteName($event->testSuite())); $testSuite->setAttribute('name', $this->converter->getTestSuiteName($event->testSuite())); // pest-changed
if ($event->testSuite()->isForTestClass()) { if ($event->testSuite()->isForTestClass()) {
$testSuite->setAttribute('file', $this->converter->getTestSuiteLocation($event->testSuite()) ?? ''); $testSuite->setAttribute('file', $this->converter->getTestSuiteLocation($event->testSuite()) ?? ''); // pest-changed
} }
if ($this->testSuiteLevel > 0) { if ($this->testSuiteLevel > 0) {
@@ -346,11 +380,12 @@ final class JunitXmlLogger
assert($this->currentTestCase !== null); assert($this->currentTestCase !== null);
$buffer = $this->converter->getTestCaseMethodName($event->test()); $buffer = $this->converter->getTestCaseMethodName($event->test()); // pest-changed
$throwable = $event->throwable(); $throwable = $event->throwable();
$buffer .= trim( $buffer .= trim(
$this->converter->getExceptionMessage($throwable).PHP_EOL. $this->converter->getExceptionMessage($throwable).PHP_EOL. // pest-changed
$this->converter->getExceptionDetails($throwable), $this->converter->getExceptionDetails($throwable), // pest-changed
); );
$fault = $this->document->createElement( $fault = $this->document->createElement(
@@ -450,15 +485,18 @@ final class JunitXmlLogger
$testCase = $this->document->createElement('testcase'); $testCase = $this->document->createElement('testcase');
$test = $event->test(); $test = $event->test();
$file = $this->converter->getTestCaseLocation($test); $file = $this->converter->getTestCaseLocation($test); // pest-added
$testCase->setAttribute('name', $this->converter->getTestCaseMethodName($test));
$testCase->setAttribute('file', $file); $testCase->setAttribute('name', $this->converter->getTestCaseMethodName($test)); // pest-changed
$testCase->setAttribute('file', $file); // pest-changed
if ($test->isTestMethod()) { if ($test->isTestMethod()) {
assert($test instanceof TestMethod); assert($test instanceof TestMethod);
$className = $this->converter->getTrimmedTestClassName($test); // $testCase->setAttribute('line', (string) $test->line()); // pest-removed
$testCase->setAttribute('class', $className); $className = $this->converter->getTrimmedTestClassName($test); // pest-added
$testCase->setAttribute('classname', str_replace('\\', '.', $className)); $testCase->setAttribute('class', $className); // pest-changed
$testCase->setAttribute('classname', str_replace('\\', '.', $className)); // pest-changed
} }
$this->currentTestCase = $testCase; $this->currentTestCase = $testCase;
@@ -1,42 +0,0 @@
<?php
declare(strict_types=1);
namespace ParaTest\WrapperRunner;
use PHPUnit\TextUI\Output\Printer;
use function preg_match;
/**
* @internal
*/
final readonly class ProgressPrinterOutput implements Printer
{
public function __construct(
private Printer $progressPrinter,
private Printer $outputPrinter,
) {}
public function print(string $buffer): void
{
if (
$buffer === "\n"
|| preg_match('/^ +$/', $buffer) === 1
|| preg_match('/^ \d+ \/ \d+ \(...%\)$/', $buffer) === 1
) {
return;
}
match ($buffer) {
'E', 'F', 'I', 'N', 'D', 'R', 'W', 'S', 'T', '.' => $this->progressPrinter->print($buffer),
default => $this->outputPrinter->print($buffer),
};
}
public function flush(): void
{
$this->progressPrinter->flush();
$this->outputPrinter->flush();
}
}
+113 -11
View File
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
/* /*
@@ -16,32 +48,42 @@ namespace PHPUnit\Runner\Filter;
use Pest\Contracts\HasPrintableTestCaseName; use Pest\Contracts\HasPrintableTestCaseName;
use PHPUnit\Framework\Test; use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestSuite; use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\Phpt\TestCase as PhptTestCase; use PHPUnit\Runner\PhptTestCase;
use RecursiveFilterIterator; use RecursiveFilterIterator;
use RecursiveIterator; use RecursiveIterator;
use function end; use function end;
use function preg_match; use function preg_match;
use function trim; use function sprintf;
use function str_replace;
/** /**
* @extends RecursiveFilterIterator<int, Test, RecursiveIterator<int, Test>>
*
* @internal This class is not covered by the backward compatibility promise for PHPUnit * @internal This class is not covered by the backward compatibility promise for PHPUnit
*/ */
abstract class NameFilterIterator extends RecursiveFilterIterator abstract class NameFilterIterator extends RecursiveFilterIterator
{ {
private readonly CompiledNameFilter $filter; /**
* @psalm-var non-empty-string
*/
private readonly string $regularExpression;
private readonly ?int $dataSetMinimum;
private readonly ?int $dataSetMaximum;
/** /**
* @param RecursiveIterator<int, Test> $iterator * @psalm-param RecursiveIterator<int, Test> $iterator
* @param non-empty-string $filter * @psalm-param non-empty-string $filter
*/ */
public function __construct(RecursiveIterator $iterator, string $filter) public function __construct(RecursiveIterator $iterator, string $filter)
{ {
parent::__construct($iterator); parent::__construct($iterator);
$this->filter = CompiledNameFilter::from($filter); $preparedFilter = $this->prepareFilter($filter);
$this->regularExpression = $preparedFilter['regularExpression'];
$this->dataSetMinimum = $preparedFilter['dataSetMinimum'];
$this->dataSetMaximum = $preparedFilter['dataSetMaximum'];
} }
public function accept(): bool public function accept(): bool
@@ -64,15 +106,75 @@ abstract class NameFilterIterator extends RecursiveFilterIterator
$name = $test::class.'::'.$test->nameWithDataSet(); $name = $test::class.'::'.$test->nameWithDataSet();
} }
$accepted = @preg_match($this->filter->regularExpression(), $name, $matches) === 1; $accepted = @preg_match($this->regularExpression, $name, $matches) === 1;
if ($accepted && $this->filter->hasDataSetRange()) { if ($accepted && isset($this->dataSetMaximum)) {
$set = end($matches); $set = end($matches);
$accepted = $set >= $this->filter->dataSetMinimum() && $set <= $this->filter->dataSetMaximum(); $accepted = $set >= $this->dataSetMinimum && $set <= $this->dataSetMaximum;
} }
return $this->doAccept($accepted); return $this->doAccept($accepted);
} }
abstract protected function doAccept(bool $result): bool; abstract protected function doAccept(bool $result): bool;
/**
* @psalm-param non-empty-string $filter
*
* @psalm-return array{regularExpression: non-empty-string, dataSetMinimum: ?int, dataSetMaximum: ?int}
*/
private function prepareFilter(string $filter): array
{
$dataSetMinimum = null;
$dataSetMaximum = null;
if (@preg_match($filter, '') === false) {
// Handles:
// * testAssertEqualsSucceeds#4
// * testAssertEqualsSucceeds#4-8
if (preg_match('/^(.*?)#(\d+)(?:-(\d+))?$/', $filter, $matches)) {
if (isset($matches[3]) && $matches[2] < $matches[3]) {
$filter = sprintf(
'%s.*with data set #(\d+)$',
$matches[1],
);
$dataSetMinimum = (int) $matches[2];
$dataSetMaximum = (int) $matches[3];
} else {
$filter = sprintf(
'%s.*with data set #%s$',
$matches[1],
$matches[2],
);
}
} // Handles:
// * testDetermineJsonError@JSON_ERROR_NONE
// * testDetermineJsonError@JSON.*
elseif (preg_match('/^(.*?)@(.+)$/', $filter, $matches)) {
$filter = sprintf(
'%s.*with data set "%s"$',
$matches[1],
$matches[2],
);
}
// Escape delimiters in regular expression. Do NOT use preg_quote,
// to keep magic characters.
$filter = sprintf(
'/%s/i',
str_replace(
'/',
'\\/',
$filter,
),
);
}
return [
'regularExpression' => $filter,
'dataSetMinimum' => $dataSetMinimum,
'dataSetMaximum' => $dataSetMaximum,
];
}
} }
@@ -0,0 +1,206 @@
<?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Runner\ResultCache;
use const DIRECTORY_SEPARATOR;
use const LOCK_EX;
use PHPUnit\Framework\TestStatus\TestStatus;
use PHPUnit\Runner\DirectoryDoesNotExistException;
use PHPUnit\Runner\Exception;
use PHPUnit\Util\Filesystem;
use function array_keys;
use function assert;
use function dirname;
use function file_get_contents;
use function file_put_contents;
use function is_array;
use function is_dir;
use function is_file;
use function json_decode;
use function json_encode;
use function Pest\version;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
*
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class DefaultResultCache implements ResultCache
{
private const string DEFAULT_RESULT_CACHE_FILENAME = '.phpunit.result.cache';
private readonly string $cacheFilename;
/**
* @var array<string, TestStatus>
*/
private array $defects = [];
/**
* @var array<string, float>
*/
private array $times = [];
public function __construct(?string $filepath = null)
{
if ($filepath !== null && is_dir($filepath)) {
$filepath .= DIRECTORY_SEPARATOR.self::DEFAULT_RESULT_CACHE_FILENAME;
}
$this->cacheFilename = $filepath ?? $_ENV['PHPUNIT_RESULT_CACHE'] ?? self::DEFAULT_RESULT_CACHE_FILENAME;
}
public function setStatus(ResultCacheId $id, TestStatus $status): void
{
if ($status->isSuccess()) {
return;
}
$this->defects[$id->asString()] = $status;
}
public function status(ResultCacheId $id): TestStatus
{
return $this->defects[$id->asString()] ?? TestStatus::unknown();
}
public function setTime(ResultCacheId $id, float $time): void
{
$this->times[$id->asString()] = $time;
}
public function time(ResultCacheId $id): float
{
return $this->times[$id->asString()] ?? 0.0;
}
public function mergeWith(self $other): void
{
foreach ($other->defects as $id => $defect) {
$this->defects[$id] = $defect;
}
foreach ($other->times as $id => $time) {
$this->times[$id] = $time;
}
}
public function load(): void
{
if (! is_file($this->cacheFilename)) {
return;
}
$contents = file_get_contents($this->cacheFilename);
if ($contents === false) {
return;
}
$data = json_decode(
$contents,
true,
);
if ($data === null) {
return;
}
if (! isset($data['version'])) {
return;
}
if ($data['version'] !== $this->cacheVersion()) {
return;
}
assert(isset($data['defects']) && is_array($data['defects']));
assert(isset($data['times']) && is_array($data['times']));
foreach (array_keys($data['defects']) as $test) {
$data['defects'][$test] = TestStatus::from($data['defects'][$test]);
}
$this->defects = $data['defects'];
$this->times = $data['times'];
}
/**
* @throws Exception
*/
public function persist(): void
{
if (! Filesystem::createDirectory(dirname($this->cacheFilename))) {
throw new DirectoryDoesNotExistException(dirname($this->cacheFilename));
}
$data = [
'version' => $this->cacheVersion(),
'defects' => [],
'times' => $this->times,
];
foreach ($this->defects as $test => $status) {
$data['defects'][$test] = $status->asInt();
}
file_put_contents(
$this->cacheFilename,
json_encode($data),
LOCK_EX,
);
}
/**
* Returns the cache version.
*/
private function cacheVersion(): string
{
return 'pest_'.version();
}
}
@@ -1,302 +0,0 @@
<?php
declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Runner\TestRunHistory;
use const DIRECTORY_SEPARATOR;
use const LOCK_EX;
use const LOCK_UN;
use PHPUnit\Framework\TestStatus\TestStatus;
use PHPUnit\Runner\DirectoryDoesNotExistException;
use PHPUnit\Runner\Exception;
use PHPUnit\Util\Filesystem;
use function array_keys;
use function dirname;
use function fclose;
use function file_get_contents;
use function flock;
use function fopen;
use function ftruncate;
use function fwrite;
use function is_array;
use function is_dir;
use function is_file;
use function is_float;
use function is_int;
use function is_string;
use function json_decode;
use function json_encode;
use function Pest\version;
use function rewind;
use function stream_get_contents;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class DefaultTestRunHistory implements TestRunHistory
{
private const string DEFAULT_FILENAME = '.phpunit.result.cache';
private readonly string $filename;
/**
* @var array<string, TestStatus>
*/
private array $defects = [];
/**
* @var array<string, float>
*/
private array $times = [];
/**
* @var array<string, true>
*/
private array $changedDefects = [];
/**
* @var array<string, true>
*/
private array $changedTimes = [];
public function __construct(?string $filepath = null)
{
if ($filepath !== null && is_dir($filepath)) {
$filepath .= DIRECTORY_SEPARATOR.self::DEFAULT_FILENAME;
}
$this->filename = $filepath ?? $_ENV['PHPUNIT_RESULT_CACHE'] ?? self::DEFAULT_FILENAME;
}
public function setStatus(TestRunHistoryId $id, TestStatus $status): void
{
if ($status->isSuccess()) {
return;
}
$this->defects[$id->asString()] = $status;
$this->changedDefects[$id->asString()] = true;
}
public function remove(TestRunHistoryId $id): void
{
unset($this->defects[$id->asString()]);
$this->changedDefects[$id->asString()] = true;
}
public function status(TestRunHistoryId $id): TestStatus
{
return $this->defects[$id->asString()] ?? TestStatus::unknown();
}
public function setTime(TestRunHistoryId $id, float $time): void
{
$this->times[$id->asString()] = $time;
$this->changedTimes[$id->asString()] = true;
}
public function time(TestRunHistoryId $id): float
{
return $this->times[$id->asString()] ?? 0.0;
}
public function mergeWith(self $other): void
{
foreach ($other->defects as $id => $defect) {
$this->defects[$id] = $defect;
$this->changedDefects[$id] = true;
}
foreach ($other->times as $id => $time) {
$this->times[$id] = $time;
$this->changedTimes[$id] = true;
}
}
public function load(): void
{
if (! is_file($this->filename)) {
return;
}
$contents = file_get_contents($this->filename);
if ($contents === false) {
// @codeCoverageIgnoreStart
return;
// @codeCoverageIgnoreEnd
}
$parsed = $this->parse($contents);
if ($parsed === null) {
return;
}
[$this->defects, $this->times] = $parsed;
$this->changedDefects = [];
$this->changedTimes = [];
}
/**
* @throws Exception
*/
public function persist(): void
{
$this->writeToFile(false);
}
/**
* @throws Exception
*/
public function persistAndPrune(): void
{
$this->writeToFile(true);
}
/**
* @throws Exception
*/
private function writeToFile(bool $prune): void
{
if (! Filesystem::createDirectory(dirname($this->filename))) {
throw new DirectoryDoesNotExistException(dirname($this->filename));
}
$handle = fopen($this->filename, 'c+');
if ($handle === false) {
// @codeCoverageIgnoreStart
return;
// @codeCoverageIgnoreEnd
}
flock($handle, LOCK_EX);
if ($prune) {
$defects = [];
foreach ($this->defects as $id => $status) {
if (isset($this->changedDefects[$id])) {
$defects[$id] = $status;
}
}
$times = [];
foreach ($this->times as $id => $time) {
if (isset($this->changedTimes[$id]) || isset($this->changedDefects[$id])) {
$times[$id] = $time;
}
}
} else {
$parsed = $this->parse((string) stream_get_contents($handle));
if ($parsed !== null) {
[$defects, $times] = $parsed;
foreach (array_keys($this->changedDefects) as $id) {
if (isset($this->defects[$id])) {
$defects[$id] = $this->defects[$id];
} else {
unset($defects[$id]);
}
}
foreach ($this->times as $id => $time) {
if (isset($this->changedTimes[$id])) {
$times[$id] = $time;
}
}
} else {
$defects = $this->defects;
$times = $this->times;
}
}
$data = [
'version' => $this->version(),
'defects' => [],
'times' => $times,
];
foreach ($defects as $test => $status) {
$data['defects'][$test] = $status->asInt();
}
$json = json_encode($data);
if ($json !== false) {
ftruncate($handle, 0);
rewind($handle);
fwrite($handle, $json);
}
flock($handle, LOCK_UN);
fclose($handle);
}
/**
* @return ?array{0: array<string, TestStatus>, 1: array<string, float>}
*/
private function parse(string $contents): ?array
{
$data = json_decode(
$contents,
true,
);
if (! is_array($data)) {
return null;
}
if (! isset($data['version']) || $data['version'] !== $this->version()) {
return null;
}
if (! isset($data['defects'], $data['times']) || ! is_array($data['defects']) || ! is_array($data['times'])) {
return null;
}
$defects = [];
foreach ($data['defects'] as $test => $status) {
if (! is_string($test) || ! is_int($status)) {
continue;
}
$defects[$test] = TestStatus::from($status);
}
$times = [];
foreach ($data['times'] as $test => $time) {
if (! is_string($test) || (! is_float($time) && ! is_int($time))) {
continue;
}
$times[$test] = (float) $time;
}
return [$defects, $times];
}
private function version(): string
{
return 'pest_'.version();
}
}
+34 -2
View File
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
namespace PHPUnit\Runner; namespace PHPUnit\Runner;
@@ -58,11 +90,11 @@ final class TestSuiteLoader
(static function () use ($suiteClassFile) { (static function () use ($suiteClassFile) {
try { try {
include_once $suiteClassFile; include_once $suiteClassFile;
TestSuite::getInstance()->tests->makeIfNeeded($suiteClassFile);
} catch (Throwable $e) { } catch (Throwable $e) {
Panic::with($e); Panic::with($e);
} }
TestSuite::getInstance()->tests->makeIfNeeded($suiteClassFile);
})(); })();
$loadedClasses = array_values( $loadedClasses = array_values(
+118 -119
View File
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
/* /*
@@ -14,14 +46,13 @@ declare(strict_types=1);
namespace PHPUnit\Runner; namespace PHPUnit\Runner;
use PHPUnit\Framework\DataProviderTestSuite; use PHPUnit\Framework\DataProviderTestSuite;
use PHPUnit\Framework\IterativeTestSuite;
use PHPUnit\Framework\Reorderable; use PHPUnit\Framework\Reorderable;
use PHPUnit\Framework\Test; use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite; use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\TestRunHistory\NullTestRunHistory; use PHPUnit\Runner\ResultCache\NullResultCache;
use PHPUnit\Runner\TestRunHistory\TestRunHistory; use PHPUnit\Runner\ResultCache\ResultCache;
use PHPUnit\Runner\TestRunHistory\TestRunHistoryId; use PHPUnit\Runner\ResultCache\ResultCacheId;
use function array_diff; use function array_diff;
use function array_merge; use function array_merge;
@@ -47,13 +78,9 @@ final class TestSuiteSorter
public const int ORDER_DEFECTS_FIRST = 3; public const int ORDER_DEFECTS_FIRST = 3;
public const int ORDER_DURATION_ASCENDING = 4; public const int ORDER_DURATION = 4;
public const int ORDER_SIZE_ASCENDING = 5; public const int ORDER_SIZE = 5;
public const int ORDER_DURATION_DESCENDING = 6;
public const int ORDER_SIZE_DESCENDING = 7;
/** /**
* @var non-empty-array<non-empty-string, positive-int> * @var non-empty-array<non-empty-string, positive-int>
@@ -70,11 +97,11 @@ final class TestSuiteSorter
*/ */
private array $defectSortOrder = []; private array $defectSortOrder = [];
private readonly TestRunHistory $testRunHistory; private readonly ResultCache $cache;
public function __construct(?TestRunHistory $testRunHistory = null) public function __construct(?ResultCache $cache = null)
{ {
$this->testRunHistory = $testRunHistory ?? new NullTestRunHistory; $this->cache = $cache ?? new NullResultCache;
} }
/** /**
@@ -86,10 +113,8 @@ final class TestSuiteSorter
self::ORDER_DEFAULT, self::ORDER_DEFAULT,
self::ORDER_REVERSED, self::ORDER_REVERSED,
self::ORDER_RANDOMIZED, self::ORDER_RANDOMIZED,
self::ORDER_DURATION_ASCENDING, self::ORDER_DURATION,
self::ORDER_SIZE_ASCENDING, self::ORDER_SIZE,
self::ORDER_DURATION_DESCENDING,
self::ORDER_SIZE_DESCENDING,
]; ];
if (! in_array($order, $allowedOrders, true)) { if (! in_array($order, $allowedOrders, true)) {
@@ -109,10 +134,6 @@ final class TestSuiteSorter
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
} }
if ($suite instanceof IterativeTestSuite) {
return;
}
if ($suite instanceof TestSuite) { if ($suite instanceof TestSuite) {
foreach ($suite as $_suite) { foreach ($suite as $_suite) {
$this->reorderTestsInSuite($_suite, $order, $resolveDependencies, $orderDefects); $this->reorderTestsInSuite($_suite, $order, $resolveDependencies, $orderDefects);
@@ -128,37 +149,31 @@ final class TestSuiteSorter
private function sort(TestSuite $suite, int $order, bool $resolveDependencies, int $orderDefects): void private function sort(TestSuite $suite, int $order, bool $resolveDependencies, int $orderDefects): void
{ {
$tests = $suite->tests(); if ($suite->tests() === []) {
if ($tests === []) {
return; return;
} }
if ($order === self::ORDER_REVERSED) { if ($order === self::ORDER_REVERSED) {
$tests = $this->reverse($tests); $suite->setTests($this->reverse($suite->tests()));
} elseif ($order === self::ORDER_RANDOMIZED) { } elseif ($order === self::ORDER_RANDOMIZED) {
$tests = $this->randomize($tests); $suite->setTests($this->randomize($suite->tests()));
} elseif ($order === self::ORDER_DURATION_ASCENDING) { } elseif ($order === self::ORDER_DURATION) {
$tests = $this->sortByDuration($tests); $suite->setTests($this->sortByDuration($suite->tests()));
} elseif ($order === self::ORDER_DURATION_DESCENDING) { } elseif ($order === self::ORDER_SIZE) {
$tests = $this->sortByDurationDescending($tests); $suite->setTests($this->sortBySize($suite->tests()));
} elseif ($order === self::ORDER_SIZE_ASCENDING) {
$tests = $this->sortBySize($tests);
} elseif ($order === self::ORDER_SIZE_DESCENDING) {
$tests = $this->sortBySizeDescending($tests);
} }
if ($orderDefects === self::ORDER_DEFECTS_FIRST) { if ($orderDefects === self::ORDER_DEFECTS_FIRST) {
$tests = $this->sortDefectsFirst($tests); $suite->setTests($this->sortDefectsFirst($suite->tests()));
} }
if ($resolveDependencies && ! ($suite instanceof DataProviderTestSuite)) { if ($resolveDependencies && ! ($suite instanceof DataProviderTestSuite)) {
$tests = $suite->tests();
/** @noinspection PhpParamsInspection */ /** @noinspection PhpParamsInspection */
/** @phpstan-ignore argument.type */ /** @phpstan-ignore argument.type */
$tests = $this->resolveDependencies($tests); $suite->setTests($this->resolveDependencies($tests));
} }
$suite->setTests($tests);
} }
private function addSuiteToDefectSortOrder(TestSuite $suite): void private function addSuiteToDefectSortOrder(TestSuite $suite): void
@@ -171,10 +186,9 @@ final class TestSuiteSorter
$sortId = $test->sortId(); $sortId = $test->sortId();
if (! isset($this->defectSortOrder[$sortId])) { if (! isset($this->defectSortOrder[$sortId])) {
$this->defectSortOrder[$sortId] = $this->testRunHistory->status(TestRunHistoryId::fromReorderable($test))->sortWeight(); $this->defectSortOrder[$sortId] = $this->cache->status(ResultCacheId::fromReorderable($test))->asInt();
$max = max($max, $this->defectSortOrder[$sortId]);
} }
$max = max($max, $this->defectSortOrder[$sortId]);
} }
$this->defectSortOrder[$suite->sortId()] = $max; $this->defectSortOrder[$suite->sortId()] = $max;
@@ -228,20 +242,6 @@ final class TestSuiteSorter
return $tests; return $tests;
} }
/**
* @param list<Test> $tests
* @return list<Test>
*/
private function sortByDurationDescending(array $tests): array
{
usort(
$tests,
fn (Test $left, Test $right) => $this->cmpDuration($right, $left),
);
return $tests;
}
/** /**
* @param list<Test> $tests * @param list<Test> $tests
* @return list<Test> * @return list<Test>
@@ -257,19 +257,12 @@ final class TestSuiteSorter
} }
/** /**
* @param list<Test> $tests * Comparator callback function to sort tests for "reach failure as fast as possible".
* @return list<Test> *
* 1. sort tests by defect weight defined in self::DEFECT_SORT_WEIGHT
* 2. when tests are equally defective, sort the fastest to the front
* 3. do not reorder successful tests
*/ */
private function sortBySizeDescending(array $tests): array
{
usort(
$tests,
fn (Test $left, Test $right) => $this->cmpSize($right, $left),
);
return $tests;
}
private function cmpDefectPriorityAndTime(Test $a, Test $b): int private function cmpDefectPriorityAndTime(Test $a, Test $b): int
{ {
assert($a instanceof Reorderable); assert($a instanceof Reorderable);
@@ -278,72 +271,72 @@ final class TestSuiteSorter
$priorityA = $this->defectSortOrder[$a->sortId()] ?? 0; $priorityA = $this->defectSortOrder[$a->sortId()] ?? 0;
$priorityB = $this->defectSortOrder[$b->sortId()] ?? 0; $priorityB = $this->defectSortOrder[$b->sortId()] ?? 0;
return $priorityB <=> $priorityA; if ($priorityA !== $priorityB) {
// Sort defect weight descending
return $priorityB <=> $priorityA;
}
if ($priorityA > 0 || $priorityB > 0) {
return $this->cmpDuration($a, $b);
}
// do not change execution order
return 0;
} }
/**
* Compares test duration for sorting tests by duration ascending.
*/
private function cmpDuration(Test $a, Test $b): int private function cmpDuration(Test $a, Test $b): int
{ {
return $this->durationWeight($a) <=> $this->durationWeight($b); if (! ($a instanceof Reorderable && $b instanceof Reorderable)) {
} return 0;
private function durationWeight(Test $test): float
{
if ($test instanceof TestSuite) {
$sum = 0.0;
foreach ($test->tests() as $inner) {
$sum += $this->durationWeight($inner);
}
return $sum;
} }
if ($test instanceof Reorderable) { return $this->cache->time(ResultCacheId::fromReorderable($a)) <=> $this->cache->time(ResultCacheId::fromReorderable($b));
return $this->testRunHistory->time(TestRunHistoryId::fromReorderable($test));
}
return 0.0;
} }
/**
* Compares test size for sorting tests small->medium->large->unknown.
*/
private function cmpSize(Test $a, Test $b): int private function cmpSize(Test $a, Test $b): int
{ {
return $this->sizeWeight($a) <=> $this->sizeWeight($b); $sizeA = ($a instanceof TestCase || $a instanceof DataProviderTestSuite)
? $a->size()->asString()
: 'unknown';
$sizeB = ($b instanceof TestCase || $b instanceof DataProviderTestSuite)
? $b->size()->asString()
: 'unknown';
return self::SIZE_SORT_WEIGHT[$sizeA] <=> self::SIZE_SORT_WEIGHT[$sizeB];
} }
/** /**
* @return positive-int * Reorder Tests within a TestCase in such a way as to resolve as many dependencies as possible.
*/ * The algorithm will leave the tests in original running order when it can.
private function sizeWeight(Test $test): int * For more details see the documentation for test dependencies.
{ *
if ($test instanceof TestCase || $test instanceof DataProviderTestSuite) { * Short description of algorithm:
return self::SIZE_SORT_WEIGHT[$test->size()->asString()]; * 1. Pick the next Test from remaining tests to be checked for dependencies.
} * 2. If the test has no dependencies: mark done, start again from the top
* 3. If the test has dependencies but none left to do: mark done, start again from the top
if ($test instanceof TestSuite) { * 4. When we reach the end add any leftover tests to the end. These will be marked 'skipped' during execution.
$max = 0; *
* @param array<TestCase> $tests
foreach ($test->tests() as $inner) { * @return array<TestCase>
$weight = $this->sizeWeight($inner);
if ($weight > $max) {
$max = $weight;
}
}
if ($max > 0) {
return $max;
}
}
return self::SIZE_SORT_WEIGHT['unknown'];
}
/**
* @param list<TestCase> $tests
* @return list<TestCase>
*/ */
private function resolveDependencies(array $tests): array private function resolveDependencies(array $tests): array
{ {
// Pest: Fast-path. If no test in this suite declares dependencies, the
// original O(N^2) algorithm is wasted work — it would splice each test
// one-by-one back into the same order. The check deliberately walks
// TestCase instances directly instead of calling TestSuite::requires(),
// because the latter lazily builds TestSuite::provides() via
// ExecutionOrderDependency::mergeUnique, which is O(N^2) in the total
// number of tests. With thousands of tests that single call alone can
// burn several seconds before the sort even begins. Reading the
// cached TestCase::$dependencies property stays O(N) and costs nothing
// when no test uses `->depends()` / PHPUnit `@depends`.
if (! $this->anyTestHasDependencies($tests)) { if (! $this->anyTestHasDependencies($tests)) {
return $tests; return $tests;
} }
@@ -352,7 +345,7 @@ final class TestSuiteSorter
$i = 0; $i = 0;
$provided = []; $provided = [];
while ($tests !== [] && $i < count($tests)) { do {
if (array_diff($tests[$i]->requires(), $provided) === []) { if (array_diff($tests[$i]->requires(), $provided) === []) {
$provided = array_merge($provided, $tests[$i]->provides()); $provided = array_merge($provided, $tests[$i]->provides());
$newTestOrder = array_merge($newTestOrder, array_splice($tests, $i, 1)); $newTestOrder = array_merge($newTestOrder, array_splice($tests, $i, 1));
@@ -360,12 +353,18 @@ final class TestSuiteSorter
} else { } else {
$i++; $i++;
} }
} } while ($tests !== [] && ($i < count($tests)));
return array_merge($newTestOrder, $tests); return array_merge($newTestOrder, $tests);
} }
/** /**
* Cheaply determines whether any test in the tree declares @depends.
*
* Walks `TestSuite` containers recursively and inspects each `TestCase`
* directly so it never triggers `TestSuite::provides()`, which is O(N^2)
* in the total number of aggregated tests.
*
* @param iterable<Test> $tests * @param iterable<Test> $tests
*/ */
private function anyTestHasDependencies(iterable $tests): bool private function anyTestHasDependencies(iterable $tests): bool
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
/* /*
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
/* /*
@@ -11,7 +43,7 @@ declare(strict_types=1);
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace PHPUnit\TextUI\Output\Default\ProgressPrinter; namespace Pest\Logging\TeamCity\Subscriber;
use PHPUnit\Event\Test\Skipped; use PHPUnit\Event\Test\Skipped;
use PHPUnit\Event\Test\SkippedSubscriber; use PHPUnit\Event\Test\SkippedSubscriber;
@@ -20,21 +52,24 @@ use ReflectionClass;
/** /**
* @internal This class is not covered by the backward compatibility promise for PHPUnit * @internal This class is not covered by the backward compatibility promise for PHPUnit
*/ */
final readonly class TestSkippedSubscriber extends Subscriber implements SkippedSubscriber final class TestSkippedSubscriber extends Subscriber implements SkippedSubscriber
{ {
public function notify(Skipped $event): void public function notify(Skipped $event): void
{ {
if ($event->message() === '__TODO__') { if (str_contains($event->message(), '__TODO__')) {
$this->printTodoItem(); $this->printTodoItem();
} }
$this->printer()->testSkipped(); $this->logger()->testSkipped($event);
} }
/**
* Prints a "T" to the standard PHPUnit output to indicate a todo item.
*/
private function printTodoItem(): void private function printTodoItem(): void
{ {
$mirror = new ReflectionClass($this->printer()); $mirror = new ReflectionClass($this->printer());
$printProgress = $mirror->getMethod('printProgress'); $printerMirror = $mirror->getMethod('printProgress');
$printProgress->invoke($this->printer(), 'T'); $printerMirror->invoke($this->printer(), 'T');
} }
} }
@@ -1,5 +1,37 @@
<?php <?php
/*
* BSD 3-Clause License
*
* Copyright (c) 2001-2023, Sebastian Bergmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
declare(strict_types=1); declare(strict_types=1);
/* /*
* This file is part of PHPUnit. * This file is part of PHPUnit.
+1 -1
View File
@@ -1,7 +1,7 @@
includes: includes:
- phpstan-baseline.neon - phpstan-baseline.neon
- phpstan-pest-extension.neon - phpstan-pest-extension.neon
- vendor/pestphp/pest-plugin-phpstan/extension.neon - vendor/mrpunyapal/peststan/extension.neon
parameters: parameters:
level: 7 level: 7
+1 -2
View File
@@ -18,9 +18,8 @@
<directory suffix=".php">./tests</directory> <directory suffix=".php">./tests</directory>
<directory suffix=".php">./tests-external</directory> <directory suffix=".php">./tests-external</directory>
<exclude>./tests/.snapshots</exclude> <exclude>./tests/.snapshots</exclude>
<exclude>./tests/.tests</exclude>
<exclude>./tests/Fixtures/Inheritance</exclude> <exclude>./tests/Fixtures/Inheritance</exclude>
<exclude>./tests/Fixtures/Suites</exclude>
<exclude>./tests/Fixtures/Tia</exclude>
</testsuite> </testsuite>
</testsuites> </testsuites>
<source> <source>
-8
View File
@@ -1,8 +0,0 @@
{
"exclude": [
"tests/Fixtures/Suites"
],
"rules": {
"Pint/phpdoc_type_annotations_only": true
}
}
-33
View File
@@ -2,55 +2,22 @@
declare(strict_types=1); declare(strict_types=1);
use Pest\Rector\Rules\UseToMatchArrayRector;
use Pest\Rector\Set\PestSetList;
use Rector\CodingStyle\Rector\ArrowFunction\ArrowFunctionDelegatingCallToFirstClassCallableRector; use Rector\CodingStyle\Rector\ArrowFunction\ArrowFunctionDelegatingCallToFirstClassCallableRector;
use Rector\Config\RectorConfig; use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\ClassMethod\RemoveDuplicatedReturnSelfDocblockRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector; use Rector\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveReturnTagIncompatibleWithNativeTypeRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedConstructorParamRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessUnionReturnDocblockRector;
use Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector;
use Rector\TypeDeclaration\Rector\ArrowFunction\AddArrowFunctionReturnTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\NarrowObjectReturnTypeRector; use Rector\TypeDeclaration\Rector\ClassMethod\NarrowObjectReturnTypeRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ReturnNeverTypeRector; use Rector\TypeDeclaration\Rector\ClassMethod\ReturnNeverTypeRector;
return RectorConfig::configure() return RectorConfig::configure()
->withPaths([ ->withPaths([
__DIR__.'/src', __DIR__.'/src',
__DIR__.'/tests',
])
->withSets([
PestSetList::CODING_STYLE,
]) ])
->withSkip([ ->withSkip([
__DIR__.'/src/Plugins/Parallel/Paratest/WrapperRunner.php', __DIR__.'/src/Plugins/Parallel/Paratest/WrapperRunner.php',
__DIR__.'/tests/Fixtures/Arch',
__DIR__.'/tests/Fixtures/Suites',
ReturnNeverTypeRector::class, ReturnNeverTypeRector::class,
ArrowFunctionDelegatingCallToFirstClassCallableRector::class, ArrowFunctionDelegatingCallToFirstClassCallableRector::class,
NarrowObjectReturnTypeRector::class, NarrowObjectReturnTypeRector::class,
RemoveParentDelegatingConstructorRector::class, RemoveParentDelegatingConstructorRector::class,
RemoveDuplicatedReturnSelfDocblockRector::class,
RemoveUselessUnionReturnDocblockRector::class,
RemoveReturnTagIncompatibleWithNativeTypeRector::class => [
__DIR__.'/src/Expectations/HigherOrderExpectation.php',
],
UseToMatchArrayRector::class,
RemoveEmptyClassMethodRector::class => [
__DIR__.'/tests',
],
RemoveUnusedConstructorParamRector::class => [
__DIR__.'/tests',
],
RemoveUnusedPrivatePropertyRector::class => [
__DIR__.'/tests',
],
AddArrowFunctionReturnTypeRector::class => [
__DIR__.'/tests',
],
]) ])
->withPreparedSets( ->withPreparedSets(
deadCode: true, 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`
@@ -7,7 +7,7 @@
<div> <div>
<span class="text-gray mr-1">- </span> <span class="text-gray mr-1">- </span>
<span>composer require pestphp/pest-plugin-browser:^5.0 --dev</span> <span>composer require pestphp/pest-plugin-browser:^4.0 --dev</span>
</div> </div>
<div> <div>
+13
View File
@@ -13,11 +13,15 @@ use Pest\Expectation;
abstract class AbstractPreset // @pest-arch-ignore-line abstract class AbstractPreset // @pest-arch-ignore-line
{ {
/** /**
* The expectations.
*
* @var array<int, Expectation<mixed>|ArchExpectation> * @var array<int, Expectation<mixed>|ArchExpectation>
*/ */
protected array $expectations = []; protected array $expectations = [];
/** /**
* Creates a new preset instance.
*
* @param array<int, string> $userNamespaces * @param array<int, string> $userNamespaces
*/ */
public function __construct( public function __construct(
@@ -27,11 +31,15 @@ abstract class AbstractPreset // @pest-arch-ignore-line
} }
/** /**
* Executes the arch preset.
*
* @internal * @internal
*/ */
abstract public function execute(): void; abstract public function execute(): void;
/** /**
* Ignores the given "targets" or "dependencies".
*
* @param array<int, string>|string $targetsOrDependencies * @param array<int, string>|string $targetsOrDependencies
*/ */
final public function ignoring(array|string $targetsOrDependencies): void final public function ignoring(array|string $targetsOrDependencies): void
@@ -43,6 +51,8 @@ abstract class AbstractPreset // @pest-arch-ignore-line
} }
/** /**
* Runs the given callback for each namespace.
*
* @param callable(Expectation<string>): ArchExpectation ...$callbacks * @param callable(Expectation<string>): ArchExpectation ...$callbacks
*/ */
final public function eachUserNamespace(callable ...$callbacks): void final public function eachUserNamespace(callable ...$callbacks): void
@@ -54,6 +64,9 @@ abstract class AbstractPreset // @pest-arch-ignore-line
} }
} }
/**
* Flushes the expectations.
*/
final public function flush(): void final public function flush(): void
{ {
$this->expectations = []; $this->expectations = [];
+8
View File
@@ -14,6 +14,8 @@ use Pest\Expectation;
final class Custom extends AbstractPreset final class Custom extends AbstractPreset
{ {
/** /**
* Creates a new preset instance.
*
* @param array<int, string> $userNamespaces * @param array<int, string> $userNamespaces
* @param Closure(array<int, string>): array<Expectation<mixed>|ArchExpectation> $execute * @param Closure(array<int, string>): array<Expectation<mixed>|ArchExpectation> $execute
*/ */
@@ -25,11 +27,17 @@ final class Custom extends AbstractPreset
parent::__construct($userNamespaces); parent::__construct($userNamespaces);
} }
/**
* Returns the name of the preset.
*/
public function name(): string public function name(): string
{ {
return $this->name; return $this->name;
} }
/**
* Executes the arch preset.
*/
public function execute(): void public function execute(): void
{ {
$this->expectations = ($this->execute)($this->userNamespaces); $this->expectations = ($this->execute)($this->userNamespaces);
+3
View File
@@ -11,6 +11,9 @@ use Throwable;
*/ */
final class Laravel extends AbstractPreset final class Laravel extends AbstractPreset
{ {
/**
* Executes the arch preset.
*/
public function execute(): void public function execute(): void
{ {
$this->expectations[] = expect('App\Traits') $this->expectations[] = expect('App\Traits')
+3
View File
@@ -9,6 +9,9 @@ namespace Pest\ArchPresets;
*/ */
final class Php extends AbstractPreset final class Php extends AbstractPreset
{ {
/**
* Executes the arch preset.
*/
public function execute(): void public function execute(): void
{ {
$this->expectations[] = expect([ $this->expectations[] = expect([
+3
View File
@@ -12,6 +12,9 @@ use Pest\Expectation;
*/ */
final class Relaxed extends AbstractPreset final class Relaxed extends AbstractPreset
{ {
/**
* Executes the arch preset.
*/
public function execute(): void public function execute(): void
{ {
$this->eachUserNamespace( $this->eachUserNamespace(
+3
View File
@@ -9,6 +9,9 @@ namespace Pest\ArchPresets;
*/ */
final class Security extends AbstractPreset final class Security extends AbstractPreset
{ {
/**
* Executes the arch preset.
*/
public function execute(): void public function execute(): void
{ {
$this->expectations[] = expect([ $this->expectations[] = expect([
+3
View File
@@ -12,6 +12,9 @@ use Pest\Expectation;
*/ */
final class Strict extends AbstractPreset final class Strict extends AbstractPreset
{ {
/**
* Executes the arch preset.
*/
public function execute(): void public function execute(): void
{ {
$this->eachUserNamespace( $this->eachUserNamespace(
+5
View File
@@ -13,6 +13,8 @@ use PHPUnit\Util\ExcludeList;
final class BootExcludeList implements Bootstrapper final class BootExcludeList implements Bootstrapper
{ {
/** /**
* The directories to exclude.
*
* @var array<int, non-empty-string> * @var array<int, non-empty-string>
*/ */
private const array EXCLUDE_LIST = [ private const array EXCLUDE_LIST = [
@@ -23,6 +25,9 @@ final class BootExcludeList implements Bootstrapper
'stubs', 'stubs',
]; ];
/**
* Boots the "exclude list" for PHPUnit to ignore Pest files.
*/
public function boot(): void public function boot(): void
{ {
$baseDirectory = dirname(__DIR__, 2); $baseDirectory = dirname(__DIR__, 2);
+8
View File
@@ -21,6 +21,8 @@ use function Pest\testDirectory;
final class BootFiles implements Bootstrapper final class BootFiles implements Bootstrapper
{ {
/** /**
* The structure of the tests directory.
*
* @var array<int, string> * @var array<int, string>
*/ */
private const array STRUCTURE = [ private const array STRUCTURE = [
@@ -31,6 +33,9 @@ final class BootFiles implements Bootstrapper
'Pest.php', 'Pest.php',
]; ];
/**
* Boots the structure of the tests directory.
*/
public function boot(): void public function boot(): void
{ {
$rootPath = TestSuite::getInstance()->rootPath; $rootPath = TestSuite::getInstance()->rootPath;
@@ -62,6 +67,9 @@ final class BootFiles implements Bootstrapper
$this->bootDatasets($testsPath); $this->bootDatasets($testsPath);
} }
/**
* Loads, if possible, the given file.
*/
private function load(string $filename): void private function load(string $filename): void
{ {
if (! Str::endsWith($filename, '.php')) { if (! Str::endsWith($filename, '.php')) {
+7 -1
View File
@@ -14,12 +14,18 @@ use Symfony\Component\Console\Output\OutputInterface;
*/ */
final readonly class BootKernelDump implements Bootstrapper final readonly class BootKernelDump implements Bootstrapper
{ {
/**
* Creates a new Boot Kernel Dump instance.
*/
public function __construct( public function __construct(
private OutputInterface $output, private OutputInterface $output,
) { ) {
// // ...
} }
/**
* Boots the kernel dump.
*/
public function boot(): void public function boot(): void
{ {
Container::getInstance()->add(KernelDump::class, $kernelDump = new KernelDump( Container::getInstance()->add(KernelDump::class, $kernelDump = new KernelDump(
+6 -2
View File
@@ -13,12 +13,13 @@ use Pest\Exceptions\ShouldNotHappen;
final class BootOverrides implements Bootstrapper final class BootOverrides implements Bootstrapper
{ {
/** /**
* The list of files to be overridden.
*
* @var array<int, string> * @var array<int, string>
*/ */
public const array FILES = [ public const array FILES = [
'ParaTest/WrapperRunner/ProgressPrinterOutput.php',
'Runner/Filter/NameFilterIterator.php', 'Runner/Filter/NameFilterIterator.php',
'Runner/TestRunHistory/DefaultTestRunHistory.php', 'Runner/ResultCache/DefaultResultCache.php',
'Runner/TestSuiteLoader.php', 'Runner/TestSuiteLoader.php',
'Runner/TestSuiteSorter.php', 'Runner/TestSuiteSorter.php',
'TextUI/Command/Commands/WarmCodeCoverageCacheCommand.php', 'TextUI/Command/Commands/WarmCodeCoverageCacheCommand.php',
@@ -28,6 +29,9 @@ final class BootOverrides implements Bootstrapper
'Logging/JUnit/JunitXmlLogger.php', 'Logging/JUnit/JunitXmlLogger.php',
]; ];
/**
* Boots the list of files to be overridden.
*/
public function boot(): void public function boot(): void
{ {
foreach (self::FILES as $file) { foreach (self::FILES as $file) {
+8 -6
View File
@@ -16,6 +16,8 @@ use PHPUnit\Event\Subscriber;
final readonly class BootSubscribers implements Bootstrapper final readonly class BootSubscribers implements Bootstrapper
{ {
/** /**
* The list of Subscribers.
*
* @var array<int, class-string<Subscriber>> * @var array<int, class-string<Subscriber>>
*/ */
private const array SUBSCRIBERS = [ private const array SUBSCRIBERS = [
@@ -33,19 +35,19 @@ final readonly class BootSubscribers implements Bootstrapper
Subscribers\EnsureTiaResultIsRecordedOnSkipped::class, Subscribers\EnsureTiaResultIsRecordedOnSkipped::class,
Subscribers\EnsureTiaResultIsRecordedOnIncomplete::class, Subscribers\EnsureTiaResultIsRecordedOnIncomplete::class,
Subscribers\EnsureTiaResultIsRecordedOnRisky::class, Subscribers\EnsureTiaResultIsRecordedOnRisky::class,
Subscribers\EnsureTiaResultIsRecordedOnNoticeTriggered::class,
Subscribers\EnsureTiaResultIsRecordedOnPhpNoticeTriggered::class,
Subscribers\EnsureTiaResultIsRecordedOnDeprecationTriggered::class,
Subscribers\EnsureTiaResultIsRecordedOnPhpDeprecationTriggered::class,
Subscribers\EnsureTiaResultIsRecordedOnWarningTriggered::class,
Subscribers\EnsureTiaResultIsRecordedOnPhpWarningTriggered::class,
Subscribers\EnsureTiaAssertionsAreRecordedOnFinished::class, Subscribers\EnsureTiaAssertionsAreRecordedOnFinished::class,
]; ];
/**
* Creates a new instance of the Boot Subscribers.
*/
public function __construct( public function __construct(
private Container $container, private Container $container,
) {} ) {}
/**
* Boots the list of Subscribers.
*/
public function boot(): void public function boot(): void
{ {
foreach (self::SUBSCRIBERS as $subscriber) { foreach (self::SUBSCRIBERS as $subscriber) {
+7 -1
View File
@@ -13,12 +13,18 @@ use Symfony\Component\Console\Output\OutputInterface;
*/ */
final readonly class BootView implements Bootstrapper final readonly class BootView implements Bootstrapper
{ {
/**
* Creates a new instance of the Boot View.
*/
public function __construct( public function __construct(
private OutputInterface $output private OutputInterface $output
) { ) {
// // ..
} }
/**
* Boots the view renderer.
*/
public function boot(): void public function boot(): void
{ {
View::renderUsing($this->output); View::renderUsing($this->output);
+12
View File
@@ -16,13 +16,22 @@ use function Termwind\renderUsing;
*/ */
final class Events final class Events
{ {
/**
* Sets the output.
*/
private static ?OutputInterface $output = null; private static ?OutputInterface $output = null;
/**
* Sets the output.
*/
public static function setOutput(OutputInterface $output): void public static function setOutput(OutputInterface $output): void
{ {
self::$output = $output; self::$output = $output;
} }
/**
* Fires before the test method description is printed.
*/
public static function beforeTestMethodDescription(TestResult $result, string $description): string public static function beforeTestMethodDescription(TestResult $result, string $description): string
{ {
if (($context = $result->context) === []) { if (($context = $result->context) === []) {
@@ -64,6 +73,9 @@ final class Events
return $description; return $description;
} }
/**
* Fires after the test method description is printed.
*/
public static function afterTestMethodDescription(TestResult $result): void public static function afterTestMethodDescription(TestResult $result): void
{ {
if (($context = $result->context) === []) { if (($context = $result->context) === []) {
+2
View File
@@ -14,6 +14,8 @@ trait Expectable
/** /**
* @template TValue * @template TValue
* *
* Creates a new Expectation.
*
* @param TValue $value * @param TValue $value
* @return Expectation<TValue> * @return Expectation<TValue>
*/ */
+7
View File
@@ -14,11 +14,15 @@ use Closure;
trait Extendable trait Extendable
{ {
/** /**
* The list of extends.
*
* @var array<string, Closure> * @var array<string, Closure>
*/ */
private static array $extends = []; private static array $extends = [];
/** /**
* Register a new extend.
*
* @param-closure-this T $extend * @param-closure-this T $extend
*/ */
public function extend(string $name, Closure $extend): void public function extend(string $name, Closure $extend): void
@@ -26,6 +30,9 @@ trait Extendable
static::$extends[$name] = $extend; static::$extends[$name] = $extend;
} }
/**
* Checks if given extend name is registered.
*/
public static function hasExtend(string $name): bool public static function hasExtend(string $name): bool
{ {
return array_key_exists($name, static::$extends); return array_key_exists($name, static::$extends);
+12
View File
@@ -9,21 +9,33 @@ namespace Pest\Concerns\Logging;
*/ */
trait WritesToConsole trait WritesToConsole
{ {
/**
* Writes the given success message to the console.
*/
private function writeSuccess(string $message): void private function writeSuccess(string $message): void
{ {
$this->writePestTestOutput($message, 'fg-green, bold', '✓'); $this->writePestTestOutput($message, 'fg-green, bold', '✓');
} }
/**
* Writes the given error message to the console.
*/
private function writeError(string $message): void private function writeError(string $message): void
{ {
$this->writePestTestOutput($message, 'fg-red, bold', ''); $this->writePestTestOutput($message, 'fg-red, bold', '');
} }
/**
* Writes the given warning message to the console.
*/
private function writeWarning(string $message): void private function writeWarning(string $message): void
{ {
$this->writePestTestOutput($message, 'fg-yellow, bold', '-'); $this->writePestTestOutput($message, 'fg-yellow, bold', '-');
} }
/**
* Writes the give message to the console.
*/
private function writePestTestOutput(string $message, string $color, string $symbol): void private function writePestTestOutput(string $message, string $color, string $symbol): void
{ {
$this->writeWithColor($color, "$symbol ", false); $this->writeWithColor($color, "$symbol ", false);
+11
View File
@@ -12,21 +12,30 @@ use Closure;
trait Pipeable trait Pipeable
{ {
/** /**
* The list of pipes.
*
* @var array<string, array<Closure(Closure, mixed ...$arguments): void>> * @var array<string, array<Closure(Closure, mixed ...$arguments): void>>
*/ */
private static array $pipes = []; private static array $pipes = [];
/** /**
* The list of interceptors.
*
* @var array<string, array<Closure(Closure, mixed ...$arguments): void>> * @var array<string, array<Closure(Closure, mixed ...$arguments): void>>
*/ */
private static array $interceptors = []; private static array $interceptors = [];
/**
* Register a pipe to be applied before an expectation is checked.
*/
public function pipe(string $name, Closure $pipe): void public function pipe(string $name, Closure $pipe): void
{ {
self::$pipes[$name][] = $pipe; self::$pipes[$name][] = $pipe;
} }
/** /**
* Register an interceptor that should replace an existing expectation.
*
* @param string|Closure(mixed $value, mixed ...$arguments):bool $filter * @param string|Closure(mixed $value, mixed ...$arguments):bool $filter
*/ */
public function intercept(string $name, string|Closure $filter, Closure $handler): void public function intercept(string $name, string|Closure $filter, Closure $handler): void
@@ -51,6 +60,8 @@ trait Pipeable
} }
/** /**
* Get the list of pipes by the given name.
*
* @return array<int, Closure> * @return array<int, Closure>
*/ */
private function pipes(string $name, object $context, string $scope): array private function pipes(string $name, object $context, string $scope): array
+2
View File
@@ -11,6 +11,8 @@ trait Retrievable
{ {
/** /**
* @template TRetrievableValue * @template TRetrievableValue
*
* Safely retrieve the value at the given key from an object or array.
* @template TRetrievableValue * @template TRetrievableValue
* *
* @param array<string, TRetrievableValue>|object $value * @param array<string, TRetrievableValue>|object $value
+121 -24
View File
@@ -23,8 +23,6 @@ use PHPUnit\Framework\Attributes\PostCondition;
use PHPUnit\Framework\IncompleteTest; use PHPUnit\Framework\IncompleteTest;
use PHPUnit\Framework\SkippedTest; use PHPUnit\Framework\SkippedTest;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestCase\ExceptionExpectation;
use PHPUnit\Framework\TestCase\OutputBuffer;
use ReflectionException; use ReflectionException;
use ReflectionFunction; use ReflectionFunction;
use ReflectionParameter; use ReflectionParameter;
@@ -37,53 +35,105 @@ use Throwable;
*/ */
trait Testable trait Testable
{ {
/**
* The test's description.
*/
private string $__description; private string $__description;
/**
* The test's latest description.
*/
private static string $__latestDescription; private static string $__latestDescription;
/**
* The test's assignees.
*/
private static array $__latestAssignees = []; private static array $__latestAssignees = [];
/**
* The test's notes.
*/
private static array $__latestNotes = []; private static array $__latestNotes = [];
/** /**
* The test's issues.
*
* @var array<int, int> * @var array<int, int>
*/ */
private static array $__latestIssues = []; private static array $__latestIssues = [];
/** /**
* The test's PRs.
*
* @var array<int, int> * @var array<int, int>
*/ */
private static array $__latestPrs = []; private static array $__latestPrs = [];
/** /**
* The test's describing, if any.
*
* @var array<int, string> * @var array<int, string>
*/ */
public array $__describing = []; public array $__describing = [];
/**
* Whether the test has ran or not.
*/
public bool $__ran = false; public bool $__ran = false;
/**
* The active replay mode for this test, set in `setUp()` and checked
* in `__runTest()` / `tearDown()` to skip the body and after-each.
*/
private ReplayType $__replay = ReplayType::None; private ReplayType $__replay = ReplayType::None;
/**
* The cached assertion count to replay, captured when entering replay mode.
*/
private int $__replayAssertions = 0; private int $__replayAssertions = 0;
/**
* The test's test closure.
*/
private Closure $__test; private Closure $__test;
/**
* The test's before each closure.
*/
private ?Closure $__beforeEach = null; private ?Closure $__beforeEach = null;
/**
* The test's after each closure.
*/
private ?Closure $__afterEach = null; private ?Closure $__afterEach = null;
/**
* The test's before all closure.
*/
private static ?Closure $__beforeAll = null; private static ?Closure $__beforeAll = null;
/**
* The test's after all closure.
*/
private static ?Closure $__afterAll = null; private static ?Closure $__afterAll = null;
/**
* The list of snapshot changes, if any.
*/
private array $__snapshotChanges = []; private array $__snapshotChanges = [];
/**
* Resets the test case static properties.
*/
public static function flush(): void public static function flush(): void
{ {
self::$__beforeAll = null; self::$__beforeAll = null;
self::$__afterAll = null; self::$__afterAll = null;
} }
/**
* Adds a new "note" to the Test Case.
*/
public function note(array|string $note): self public function note(array|string $note): self
{ {
$note = is_array($note) ? $note : [$note]; $note = is_array($note) ? $note : [$note];
@@ -93,6 +143,9 @@ trait Testable
return $this; return $this;
} }
/**
* Adds a new "setUpBeforeClass" to the Test Case.
*/
public function __addBeforeAll(?Closure $hook): void public function __addBeforeAll(?Closure $hook): void
{ {
if (! $hook instanceof Closure) { if (! $hook instanceof Closure) {
@@ -104,6 +157,9 @@ trait Testable
: $hook; : $hook;
} }
/**
* Adds a new "tearDownAfterClass" to the Test Case.
*/
public function __addAfterAll(?Closure $hook): void public function __addAfterAll(?Closure $hook): void
{ {
if (! $hook instanceof Closure) { if (! $hook instanceof Closure) {
@@ -115,16 +171,25 @@ trait Testable
: $hook; : $hook;
} }
/**
* Adds a new "setUp" to the Test Case.
*/
public function __addBeforeEach(?Closure $hook): void public function __addBeforeEach(?Closure $hook): void
{ {
$this->__addHook('__beforeEach', $hook); $this->__addHook('__beforeEach', $hook);
} }
/**
* Adds a new "tearDown" to the Test Case.
*/
public function __addAfterEach(?Closure $hook): void public function __addAfterEach(?Closure $hook): void
{ {
$this->__addHook('__afterEach', $hook); $this->__addHook('__afterEach', $hook);
} }
/**
* Adds a new "hook" to the Test Case.
*/
private function __addHook(string $property, ?Closure $hook): void private function __addHook(string $property, ?Closure $hook): void
{ {
if (! $hook instanceof Closure) { if (! $hook instanceof Closure) {
@@ -136,6 +201,9 @@ trait Testable
: $hook; : $hook;
} }
/**
* This method is called before the first test of this Test Case is run.
*/
public static function setUpBeforeClass(): void public static function setUpBeforeClass(): void
{ {
parent::setUpBeforeClass(); parent::setUpBeforeClass();
@@ -153,6 +221,9 @@ trait Testable
} }
} }
/**
* This method is called after the last test of this Test Case is run.
*/
public static function tearDownAfterClass(): void public static function tearDownAfterClass(): void
{ {
$afterAll = TestSuite::getInstance()->afterAll->get(self::$__filename); $afterAll = TestSuite::getInstance()->afterAll->get(self::$__filename);
@@ -166,6 +237,9 @@ trait Testable
parent::tearDownAfterClass(); parent::tearDownAfterClass();
} }
/**
* Gets executed before the Test Case.
*/
protected function setUp(...$arguments): void protected function setUp(...$arguments): void
{ {
TestSuite::getInstance()->test = $this; TestSuite::getInstance()->test = $this;
@@ -204,14 +278,12 @@ trait Testable
/** @var Tia $tia */ /** @var Tia $tia */
$tia = Container::getInstance()->get(Tia::class); $tia = Container::getInstance()->get(Tia::class);
$status = $tia->getStatus(self::$__filename, $this->valueObjectForEvents()->id()); $status = $tia->getStatus(self::$__filename, $this::class.'::'.$this->name());
$replay = ReplayType::fromStatus($status); $replay = ReplayType::fromStatus($status);
if ($replay !== ReplayType::None) { if ($replay !== ReplayType::None) {
assert($status !== null); assert($status !== null);
$this->__replay = $replay;
match ($replay) { match ($replay) {
ReplayType::Pass, ReplayType::Risky => $this->__beginReplay($replay, $tia), ReplayType::Pass, ReplayType::Risky => $this->__beginReplay($replay, $tia),
ReplayType::Skipped => $this->markTestSkipped($status->message()), ReplayType::Skipped => $this->markTestSkipped($status->message()),
@@ -245,12 +317,16 @@ trait Testable
private function __beginReplay(ReplayType $replay, Tia $tia): void private function __beginReplay(ReplayType $replay, Tia $tia): void
{ {
$this->__replay = $replay; $this->__replay = $replay;
$this->__replayAssertions = $tia->getAssertionCount($this->valueObjectForEvents()->id()); $this->__replayAssertions = $tia->getAssertionCount($this::class.'::'.$this->name());
$this->__ran = true; $this->__ran = true;
} }
/**
* Initialize test case properties from TestSuite.
*/
public function __initializeTestCase(): void public function __initializeTestCase(): void
{ {
// Return if the test case has already been initialized
if (isset($this->__test)) { if (isset($this->__test)) {
return; return;
} }
@@ -272,6 +348,9 @@ trait Testable
} }
} }
/**
* Gets executed after the Test Case.
*/
protected function tearDown(...$arguments): void protected function tearDown(...$arguments): void
{ {
if ($this->__replay !== ReplayType::None) { if ($this->__replay !== ReplayType::None) {
@@ -299,6 +378,8 @@ trait Testable
} }
/** /**
* Executes the Test Case current test.
*
* @throws Throwable * @throws Throwable
*/ */
private function __runTest(Closure $closure, ...$args): mixed private function __runTest(Closure $closure, ...$args): mixed
@@ -350,15 +431,10 @@ trait Testable
unset($this->{$property}); unset($this->{$property});
} }
$outputBuffer = Closure::bind(fn () => $this->outputBuffer, $this, TestCase::class)(); $hasOutputExpectation = Closure::bind(fn (): bool => is_string($this->outputExpectedString) || is_string($this->outputExpectedRegex), $this, TestCase::class)();
if ($outputBuffer->hasExpectation()) { if ($hasOutputExpectation) {
ob_clean(); ob_clean();
Closure::bind(function (): void {
$this->expectedString = null;
$this->expectedRegularExpression = null;
}, $outputBuffer, OutputBuffer::class)();
} }
$this->setUp(); $this->setUp();
@@ -369,11 +445,12 @@ trait Testable
throw $lastException; throw $lastException;
} }
/**
* Determines if the given exception matches PHPUnit's expected exception.
*/
private function __isExpectedException(Throwable $e): bool private function __isExpectedException(Throwable $e): bool
{ {
$expectation = Closure::bind(fn () => $this->exceptionExpectation, $this, TestCase::class)(); $read = fn (string $property): mixed => Closure::bind(fn () => $this->{$property}, $this, TestCase::class)();
$read = fn (string $property): mixed => Closure::bind(fn () => $this->{$property}, $expectation, ExceptionExpectation::class)();
$expectedClass = $read('expectedException'); $expectedClass = $read('expectedException');
@@ -381,19 +458,13 @@ trait Testable
return $e instanceof $expectedClass; return $e instanceof $expectedClass;
} }
$expectedMessage = $read('expectedMessage'); $expectedMessage = $read('expectedExceptionMessage');
if ($expectedMessage !== null) { if ($expectedMessage !== null) {
return str_contains($e->getMessage(), (string) $expectedMessage); return str_contains($e->getMessage(), (string) $expectedMessage);
} }
$expectedMessageRegex = $read('expectedMessageRegularExpression'); $expectedCode = $read('expectedExceptionCode');
if ($expectedMessageRegex !== null) {
return preg_match($expectedMessageRegex, $e->getMessage()) === 1;
}
$expectedCode = $read('expectedCode');
if ($expectedCode !== null) { if ($expectedCode !== null) {
return $e->getCode() === $expectedCode; return $e->getCode() === $expectedCode;
@@ -403,6 +474,8 @@ trait Testable
} }
/** /**
* Resolve the passed arguments. Any Closures will be bound to the testcase and resolved.
*
* @throws Throwable * @throws Throwable
*/ */
private function __resolveTestArguments(array $arguments): array private function __resolveTestArguments(array $arguments): array
@@ -410,6 +483,10 @@ trait Testable
$method = TestSuite::getInstance()->tests->get(self::$__filename)->getMethod($this->name()); $method = TestSuite::getInstance()->tests->get(self::$__filename)->getMethod($this->name());
if ($method->repetitions > 1) { if ($method->repetitions > 1) {
// If the test is repeated, the first argument is the iteration number
// we need to move it to the end of the arguments list
// so that the datasets are the first n arguments
// and the iteration number is the last argument
$firstArgument = array_shift($arguments); $firstArgument = array_shift($arguments);
$arguments[] = $firstArgument; $arguments[] = $firstArgument;
} }
@@ -458,6 +535,8 @@ trait Testable
} }
/** /**
* Ensures dataset items count matches underlying test case required parameters
*
* @throws ReflectionException * @throws ReflectionException
* @throws DatasetArgumentsMismatch * @throws DatasetArgumentsMismatch
*/ */
@@ -497,6 +576,9 @@ trait Testable
return ExceptionTrace::ensure(fn (): mixed => call_user_func_array(Closure::bind($closure, $this, $this::class), $arguments)); return ExceptionTrace::ensure(fn (): mixed => call_user_func_array(Closure::bind($closure, $this, $this::class), $arguments));
} }
/**
* Uses the given preset on the test.
*/
public function preset(): Preset public function preset(): Preset
{ {
return new Preset; return new Preset;
@@ -512,21 +594,33 @@ trait Testable
$this->markTestIncomplete(implode('. ', $this->__snapshotChanges)); $this->markTestIncomplete(implode('. ', $this->__snapshotChanges));
} }
/**
* The printable test case name.
*/
public static function getPrintableTestCaseName(): string public static function getPrintableTestCaseName(): string
{ {
return preg_replace('/P\\\/', '', self::class, 1); return preg_replace('/P\\\/', '', self::class, 1);
} }
/**
* The printable test case method name.
*/
public function getPrintableTestCaseMethodName(): string public function getPrintableTestCaseMethodName(): string
{ {
return $this->__description; return $this->__description;
} }
/**
* The latest printable test case method name.
*/
public static function getLatestPrintableTestCaseMethodName(): string public static function getLatestPrintableTestCaseMethodName(): string
{ {
return self::$__latestDescription ?? ''; return self::$__latestDescription ?? '';
} }
/**
* The printable test case method context.
*/
public static function getPrintableContext(): array public static function getPrintableContext(): array
{ {
return [ return [
@@ -537,6 +631,9 @@ trait Testable
]; ];
} }
/**
* Opens a shell for the test case.
*/
public function shell(): void public function shell(): void
{ {
Shell::open(); Shell::open();
+47 -8
View File
@@ -14,19 +14,31 @@ use Pest\PendingCalls\UsesCall;
*/ */
final readonly class Configuration final readonly class Configuration
{ {
/**
* The filename of the configuration.
*/
private string $filename; private string $filename;
/**
* Creates a new configuration instance.
*/
public function __construct( public function __construct(
string $filename, string $filename,
) { ) {
$this->filename = str_ends_with($filename, DIRECTORY_SEPARATOR.'Pest.php') ? dirname($filename) : $filename; $this->filename = str_ends_with($filename, DIRECTORY_SEPARATOR.'Pest.php') ? dirname($filename) : $filename;
} }
/**
* Use the given classes and traits in the given targets.
*/
public function in(string ...$targets): UsesCall public function in(string ...$targets): UsesCall
{ {
return new UsesCall($this->filename, [])->in(...$targets); return (new UsesCall($this->filename, []))->in(...$targets);
} }
/**
* Depending on where is called, it will extend the given classes and traits globally or locally.
*/
public function extend(string ...$classAndTraits): UsesCall public function extend(string ...$classAndTraits): UsesCall
{ {
return new UsesCall( return new UsesCall(
@@ -35,62 +47,89 @@ final readonly class Configuration
); );
} }
/**
* Depending on where is called, it will extend the given classes and traits globally or locally.
*/
public function extends(string ...$classAndTraits): UsesCall public function extends(string ...$classAndTraits): UsesCall
{ {
return $this->extend(...$classAndTraits); return $this->extend(...$classAndTraits);
} }
/**
* Depending on where is called, it will add the given groups globally or locally.
*/
public function group(string ...$groups): UsesCall public function group(string ...$groups): UsesCall
{ {
return new UsesCall($this->filename, [])->group(...$groups); return (new UsesCall($this->filename, []))->group(...$groups);
} }
/**
* Marks all tests in the current file to be run exclusively.
*/
public function only(): void public function only(): void
{ {
new BeforeEachCall(TestSuite::getInstance(), $this->filename)->only(); (new BeforeEachCall(TestSuite::getInstance(), $this->filename))->only();
} }
/**
* Depending on where is called, it will extend the given classes and traits globally or locally.
*/
public function use(string ...$classAndTraits): UsesCall public function use(string ...$classAndTraits): UsesCall
{ {
return $this->extend(...$classAndTraits); return $this->extend(...$classAndTraits);
} }
/**
* Depending on where is called, it will extend the given classes and traits globally or locally.
*/
public function uses(string ...$classAndTraits): UsesCall public function uses(string ...$classAndTraits): UsesCall
{ {
return $this->extends(...$classAndTraits); return $this->extends(...$classAndTraits);
} }
/**
* Gets the printer configuration.
*/
public function printer(): Configuration\Printer public function printer(): Configuration\Printer
{ {
return new Configuration\Printer; return new Configuration\Printer;
} }
/**
* Gets the presets configuration.
*/
public function presets(): Configuration\Presets public function presets(): Configuration\Presets
{ {
return new Configuration\Presets; return new Configuration\Presets;
} }
/**
* Gets the project configuration.
*/
public function project(): Configuration\Project public function project(): Configuration\Project
{ {
return Configuration\Project::getInstance(); return Configuration\Project::getInstance();
} }
/**
* Gets the browser configuration.
*/
public function browser(): Browser\Configuration public function browser(): Browser\Configuration
{ {
return new Browser\Configuration; return new Browser\Configuration;
} }
public function evals(): Evals\Configuration // @phpstan-ignore-line /**
{ * Gets the TIA (Test Impact Analysis) configuration.
return new Evals\Configuration; // @phpstan-ignore-line */
}
public function tia(): Plugins\Tia\Configuration public function tia(): Plugins\Tia\Configuration
{ {
return new Plugins\Tia\Configuration; return new Plugins\Tia\Configuration;
} }
/** /**
* Proxies calls to the uses method.
*
* @param array<array-key, mixed> $arguments * @param array<array-key, mixed> $arguments
*/ */
public function __call(string $name, array $arguments): mixed public function __call(string $name, array $arguments): mixed
+3
View File
@@ -9,6 +9,9 @@ use Pest\Preset;
final class Presets final class Presets
{ {
/**
* Creates a custom preset instance, and adds it to the list of presets.
*/
public function custom(string $name, Closure $execute): void public function custom(string $name, Closure $execute): void
{ {
Preset::custom($name, $execute); Preset::custom($name, $execute);
+3
View File
@@ -11,6 +11,9 @@ use NunoMaduro\Collision\Adapters\Phpunit\Printers\DefaultPrinter;
*/ */
final readonly class Printer final readonly class Printer
{ {
/**
* Sets the theme to compact.
*/
public function compact(): self public function compact(): self
{ {
DefaultPrinter::compact(true); DefaultPrinter::compact(true);
+31 -6
View File
@@ -10,27 +10,42 @@ namespace Pest\Configuration;
final class Project final class Project
{ {
/** /**
* The assignees link.
*
* @internal * @internal
*/ */
public string $assignees = ''; public string $assignees = '';
/** /**
* The issues link.
*
* @internal * @internal
*/ */
public string $issues = ''; public string $issues = '';
/** /**
* The PRs link.
*
* @internal * @internal
*/ */
public string $prs = ''; public string $prs = '';
/**
* The singleton instance.
*/
private static ?self $instance = null; private static ?self $instance = null;
/**
* Creates a new instance of the project.
*/
public static function getInstance(): self public static function getInstance(): self
{ {
return self::$instance ??= new self; return self::$instance ??= new self;
} }
/**
* Sets the test project to GitHub.
*/
public function github(string $project): self public function github(string $project): self
{ {
$this->issues = "https://github.com/{$project}/issues/%s"; $this->issues = "https://github.com/{$project}/issues/%s";
@@ -41,18 +56,22 @@ final class Project
return $this; return $this;
} }
public function gitlab(string $project, string $hostname = 'gitlab.com'): self /**
* Sets the test project to GitLab.
*/
public function gitlab(string $project): self
{ {
$hostname = parse_url($hostname, PHP_URL_HOST) ?? $hostname; $this->issues = "https://gitlab.com/{$project}/issues/%s";
$this->prs = "https://gitlab.com/{$project}/merge_requests/%s";
$this->issues = "https://{$hostname}/{$project}/-/work_items/%s"; $this->assignees = 'https://gitlab.com/%s';
$this->prs = "https://{$hostname}/{$project}/-/merge_requests/%s";
$this->assignees = "https://{$hostname}/%s";
return $this; return $this;
} }
/**
* Sets the test project to Bitbucket.
*/
public function bitbucket(string $project): self public function bitbucket(string $project): self
{ {
$this->issues = "https://bitbucket.org/{$project}/issues/%s"; $this->issues = "https://bitbucket.org/{$project}/issues/%s";
@@ -63,6 +82,9 @@ final class Project
return $this; return $this;
} }
/**
* Sets the test project to Jira.
*/
public function jira(string $namespace, string $project): self public function jira(string $namespace, string $project): self
{ {
$this->issues = "https://{$namespace}.atlassian.net/browse/{$project}-%s"; $this->issues = "https://{$namespace}.atlassian.net/browse/{$project}-%s";
@@ -72,6 +94,9 @@ final class Project
return $this; return $this;
} }
/**
* Sets the test project to custom.
*/
public function custom(string $issues, string $prs, string $assignees): self public function custom(string $issues, string $prs, string $assignees): self
{ {
$this->issues = $issues; $this->issues = $issues;
+9 -1
View File
@@ -12,6 +12,8 @@ use Symfony\Component\Console\Output\OutputInterface;
final readonly class Help final readonly class Help
{ {
/** /**
* The Command messages.
*
* @var array<int, string> * @var array<int, string>
*/ */
private const array HELP_MESSAGES = [ private const array HELP_MESSAGES = [
@@ -22,11 +24,17 @@ final readonly class Help
' <info>--group=<fg=cyan><name></></info> Only runs tests from the specified group(s)', ' <info>--group=<fg=cyan><name></></info> Only runs tests from the specified group(s)',
]; ];
/**
* Creates a new Console Command instance.
*/
public function __construct(private OutputInterface $output) public function __construct(private OutputInterface $output)
{ {
// // ..
} }
/**
* Executes the Console Command.
*/
public function __invoke(): void public function __invoke(): void
{ {
foreach (self::HELP_MESSAGES as $message) { foreach (self::HELP_MESSAGES as $message) {
+9 -1
View File
@@ -18,6 +18,8 @@ use Symfony\Component\Console\Question\ConfirmationQuestion;
final readonly class Thanks final readonly class Thanks
{ {
/** /**
* The support options.
*
* @var array<string, string> * @var array<string, string>
*/ */
private const array FUNDING_MESSAGES = [ private const array FUNDING_MESSAGES = [
@@ -31,13 +33,19 @@ final readonly class Thanks
'Sponsor' => 'https://github.com/sponsors/nunomaduro', 'Sponsor' => 'https://github.com/sponsors/nunomaduro',
]; ];
/**
* Creates a new Console Command instance.
*/
public function __construct( public function __construct(
private InputInterface $input, private InputInterface $input,
private OutputInterface $output private OutputInterface $output
) { ) {
// // ..
} }
/**
* Executes the Console Command.
*/
public function __invoke(): void public function __invoke(): void
{ {
$bootstrapper = new BootView($this->output); $bootstrapper = new BootView($this->output);
+3
View File
@@ -9,5 +9,8 @@ namespace Pest\Contracts;
*/ */
interface Bootstrapper interface Bootstrapper
{ {
/**
* Boots the bootstrapper.
*/
public function boot(): void; public function boot(): void;
} }
+1 -1
View File
@@ -11,5 +11,5 @@ use NunoMaduro\Collision\Contracts\Adapters\Phpunit\HasPrintableTestCaseName as
*/ */
interface HasPrintableTestCaseName extends BaseHasPrintableTestCaseName interface HasPrintableTestCaseName extends BaseHasPrintableTestCaseName
{ {
// // ..
} }
+6
View File
@@ -11,7 +11,13 @@ use Symfony\Component\Console\Output\OutputInterface;
*/ */
interface Panicable interface Panicable
{ {
/**
* Renders the panic on the given output.
*/
public function render(OutputInterface $output): void; public function render(OutputInterface $output): void;
/**
* The exit code to be used.
*/
public function exitCode(): int; public function exitCode(): int;
} }
+3
View File
@@ -9,5 +9,8 @@ namespace Pest\Contracts\Plugins;
*/ */
interface AddsOutput interface AddsOutput
{ {
/**
* Adds output after the Test Suite execution.
*/
public function addOutput(int $exitCode): int; public function addOutput(int $exitCode): int;
} }
+3
View File
@@ -9,5 +9,8 @@ namespace Pest\Contracts\Plugins;
*/ */
interface Bootable interface Bootable
{ {
/**
* Boots the plugin.
*/
public function boot(): void; public function boot(): void;
} }
@@ -10,6 +10,8 @@ namespace Pest\Contracts\Plugins;
interface HandlesArguments interface HandlesArguments
{ {
/** /**
* Adds arguments before the Test Suite execution.
*
* @param array<int, string> $arguments * @param array<int, string> $arguments
* @return array<int, string> * @return array<int, string>
*/ */
@@ -10,6 +10,8 @@ namespace Pest\Contracts\Plugins;
interface HandlesOriginalArguments interface HandlesOriginalArguments
{ {
/** /**
* Adds original arguments before the Test Suite execution.
*
* @param array<int, string> $arguments * @param array<int, string> $arguments
*/ */
public function handleOriginalArguments(array $arguments): void; public function handleOriginalArguments(array $arguments): void;
+3
View File
@@ -9,5 +9,8 @@ namespace Pest\Contracts\Plugins;
*/ */
interface Terminable interface Terminable
{ {
/**
* Terminates the plugin.
*/
public function terminate(): void; public function terminate(): void;
} }
+3
View File
@@ -6,5 +6,8 @@ namespace Pest\Contracts;
interface TestCaseFilter interface TestCaseFilter
{ {
/**
* Whether the test case is accepted.
*/
public function accept(string $testCaseFilename): bool; public function accept(string $testCaseFilename): bool;
} }
+3
View File
@@ -8,5 +8,8 @@ use Pest\Factories\TestCaseMethodFactory;
interface TestCaseMethodFilter interface TestCaseMethodFilter
{ {
/**
* Whether the test case method is accepted.
*/
public function accept(TestCaseMethodFactory $factory): bool; public function accept(TestCaseMethodFactory $factory): bool;
} }
+2
View File
@@ -12,6 +12,8 @@ use Pest\Factories\Attribute;
final class Attributes final class Attributes
{ {
/** /**
* Evaluates the given attributes and returns the code.
*
* @param iterable<int, Attribute> $attributes * @param iterable<int, Attribute> $attributes
*/ */
public static function code(iterable $attributes): string public static function code(iterable $attributes): string
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class AfterAllAlreadyExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class AfterAllAlreadyExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $filename) public function __construct(string $filename)
{ {
parent::__construct(sprintf('The [afterAll] hook is already defined in [%s]. Each test file may only define it once.', $filename)); parent::__construct(sprintf('The afterAll already exists in the filename `%s`.', $filename));
} }
} }
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class AfterAllWithinDescribe extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class AfterAllWithinDescribe extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $filename) public function __construct(string $filename)
{ {
parent::__construct(sprintf('The [afterAll] hook may not be used inside a [describe] block. Please move it to the top level of [%s].', $filename)); parent::__construct(sprintf('The afterAll method can not be used within describe functions. Filename `%s`.', $filename));
} }
} }
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class AfterBeforeTestFunction extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class AfterBeforeTestFunction extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $filename) public function __construct(string $filename)
{ {
parent::__construct(sprintf('The [after] hook may only be chained onto [beforeEach] inside a [describe] block. Please move it inside one in [%s].', $filename)); parent::__construct('After method cannot be used with before the [test|it] functions in the filename `['.$filename.']`.');
} }
} }
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class BeforeAllAlreadyExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class BeforeAllAlreadyExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $filename) public function __construct(string $filename)
{ {
parent::__construct(sprintf('The [beforeAll] hook is already defined in [%s]. Each test file may only define it once.', $filename)); parent::__construct(sprintf('The beforeAll already exists in the filename `%s`.', $filename));
} }
} }
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class BeforeAllWithinDescribe extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class BeforeAllWithinDescribe extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $filename) public function __construct(string $filename)
{ {
parent::__construct(sprintf('The [beforeAll] hook may not be used inside a [describe] block. Please move it to the top level of [%s].', $filename)); parent::__construct(sprintf('The beforeAll method can not be used within describe functions. Filename `%s`.', $filename));
} }
} }
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class DatasetAlreadyExists extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class DatasetAlreadyExists extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $name, string $scope) public function __construct(string $name, string $scope)
{ {
parent::__construct(sprintf('A dataset named [%s] is already registered in [%s]. Please choose a different name.', $name, $scope)); parent::__construct(sprintf('A dataset with the name `%s` already exists in scope [%s].', $name, $scope));
} }
} }
+4 -2
View File
@@ -11,9 +11,11 @@ final class DatasetArgumentsMismatch extends Exception
public function __construct(int $requiredCount, int $suppliedCount) public function __construct(int $requiredCount, int $suppliedCount)
{ {
if ($requiredCount <= $suppliedCount) { if ($requiredCount <= $suppliedCount) {
parent::__construct('The test arguments do not match the dataset keys. Please make sure each argument is named after a key in the dataset.'); parent::__construct('Test argument names and dataset keys do not match');
} else { } else {
parent::__construct(sprintf('The test expects [%d] argument(s), but the dataset only provides [%d].', $requiredCount, $suppliedCount)); parent::__construct(sprintf('Test expects %d arguments but dataset only provides %d', $requiredCount, $suppliedCount));
} }
} }
//
} }
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class DatasetDoesNotExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class DatasetDoesNotExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $name) public function __construct(string $name)
{ {
parent::__construct(sprintf("A dataset named [%s] does not exist. You may create one using `dataset('%s', ['a', 'b']);`.", $name, $name)); parent::__construct(sprintf("A dataset with the name `%s` does not exist. You can create it using `dataset('%s', ['a', 'b']);`.", $name, $name));
} }
} }
+4 -2
View File
@@ -15,16 +15,18 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
final class DatasetMissing extends BadFunctionCallException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class DatasetMissing extends BadFunctionCallException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/** /**
* Creates a new Exception instance.
*
* @param array<string, string> $arguments * @param array<string, string> $arguments
*/ */
public function __construct(string $file, string $name, array $arguments) public function __construct(string $file, string $name, array $arguments)
{ {
parent::__construct(sprintf( parent::__construct(sprintf(
'The test [%s] in [%s] expects [%d] argument(s) ([%s]), but no dataset was provided. Please chain [with()] onto the test to supply one.', 'A test with the description [%s] has [%d] argument(s) ([%s]) and no dataset(s) provided in [%s]',
$name, $name,
$file,
count($arguments), count($arguments),
implode(', ', array_map(static fn (string $arg, string $type): string => sprintf('%s $%s', $type, $arg), array_keys($arguments), $arguments)), implode(', ', array_map(static fn (string $arg, string $type): string => sprintf('%s $%s', $type, $arg), array_keys($arguments), $arguments)),
$file,
)); ));
} }
} }
-19
View File
@@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use RuntimeException;
use Throwable;
/**
* @internal
*/
final class DatasetProviderError extends RuntimeException
{
public function __construct(Throwable $previous)
{
parent::__construct($previous->getMessage(), (int) $previous->getCode(), $previous);
}
}
+4 -1
View File
@@ -11,8 +11,11 @@ use Exception;
*/ */
final class ExpectationNotFound extends Exception final class ExpectationNotFound extends Exception
{ {
/**
* Creates a new ExpectationNotFound instance from the given name.
*/
public static function fromName(string $name): ExpectationNotFound public static function fromName(string $name): ExpectationNotFound
{ {
return new self("The expectation [$name] does not exist. You may register it using [expect()->extend()]."); return new self("Expectation [$name] does not exist.");
} }
} }
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class FileOrFolderNotFound extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class FileOrFolderNotFound extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $filename) public function __construct(string $filename)
{ {
parent::__construct(sprintf('The file or folder [%s] could not be found. Please check the path and try again.', $filename)); parent::__construct(sprintf('The file or folder with the name `%s` could not be found.', $filename));
} }
} }
@@ -14,6 +14,9 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $message) public function __construct(string $message)
{ {
parent::__construct($message, 1); parent::__construct($message, 1);
+1 -1
View File
@@ -21,6 +21,6 @@ final class InvalidExpectation extends LogicException implements ExceptionInterf
*/ */
public static function fromMethods(array $methods): never public static function fromMethods(array $methods): never
{ {
throw new self(sprintf('The expectation [%s] does not exist. Please check the spelling, or register it using [expect()->extend()].', implode('->', $methods))); throw new self(sprintf('Expectation [%s] is not valid.', implode('->', $methods)));
} }
} }
+1 -1
View File
@@ -16,6 +16,6 @@ final class InvalidExpectationValue extends InvalidArgumentException
*/ */
public static function expected(string $type): never public static function expected(string $type): never
{ {
throw new self(sprintf('This expectation may only be used on a value of type [%s].', $type)); throw new self(sprintf('Invalid expectation value type. Expected [%s].', $type));
} }
} }
+3
View File
@@ -14,6 +14,9 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class InvalidOption extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class InvalidOption extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $message) public function __construct(string $message)
{ {
parent::__construct($message, 1); parent::__construct($message, 1);
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class InvalidPestCommand extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class InvalidPestCommand extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct() public function __construct()
{ {
parent::__construct('Pest must be run through its own binary. Please run [./vendor/bin/pest] instead.'); parent::__construct('Please run [./vendor/bin/pest] instead.');
} }
} }
-35
View File
@@ -1,35 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use InvalidArgumentException;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Symfony\Component\Console\Exception\ExceptionInterface;
/**
* @internal
*/
final class InvalidTestClassName extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{
public static function fromClassName(string $filename, string $className): self
{
return new self(sprintf(
'The test file [%s] would create the class [%s], which is not a valid PHP class name. Please rename the file.',
$filename,
$className,
));
}
public static function fromNamespace(string $filename, string $namespace, string $part): self
{
return new self(sprintf(
'The test file [%s] would create the namespace [%s], which is not a valid PHP namespace, because [%s] may not be used as a namespace name. Please rename that folder.',
$filename,
$namespace,
$part,
));
}
}
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class MissingDependency extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class MissingDependency extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $feature, string $dependency) public function __construct(string $feature, string $dependency)
{ {
parent::__construct(sprintf('The [%s] feature requires [%s]. Please install it and try again.', $feature, $dependency)); parent::__construct(sprintf('The feature "%s" requires "%s".', $feature, $dependency));
} }
} }
+6
View File
@@ -16,6 +16,9 @@ use Symfony\Component\Console\Output\OutputInterface;
*/ */
final class NoDirtyTestsFound extends InvalidArgumentException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace final class NoDirtyTestsFound extends InvalidArgumentException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
{ {
/**
* Renders the panic on the given output.
*/
public function render(OutputInterface $output): void public function render(OutputInterface $output): void
{ {
$output->writeln([ $output->writeln([
@@ -25,6 +28,9 @@ final class NoDirtyTestsFound extends InvalidArgumentException implements Except
]); ]);
} }
/**
* The exit code to be used.
*/
public function exitCode(): int public function exitCode(): int
{ {
return 0; return 0;
+7 -1
View File
@@ -12,12 +12,15 @@ use RuntimeException;
*/ */
final class ShouldNotHappen extends RuntimeException final class ShouldNotHappen extends RuntimeException
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(Exception $exception) public function __construct(Exception $exception)
{ {
$message = $exception->getMessage(); $message = $exception->getMessage();
parent::__construct(sprintf(<<<'EOF' parent::__construct(sprintf(<<<'EOF'
This should not have happened. Please report it here: https://github.com/pestphp/pest/issues This should not happen - please create an new issue here: https://github.com/pestphp/pest/issues
Issue: %s Issue: %s
PHP version: %s PHP version: %s
@@ -26,6 +29,9 @@ EOF
, $message, phpversion(), PHP_OS), 1, $exception); , $message, phpversion(), PHP_OS), 1, $exception);
} }
/**
* Creates a new instance of should not happen without a specific exception.
*/
public static function fromMessage(string $message): ShouldNotHappen public static function fromMessage(string $message): ShouldNotHappen
{ {
return new ShouldNotHappen(new Exception($message)); return new ShouldNotHappen(new Exception($message));
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class TestAlreadyExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class TestAlreadyExist extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $fileName, string $description) public function __construct(string $fileName, string $description)
{ {
parent::__construct(sprintf('A test named [%s] already exists in [%s]. Please give this test a different description.', $description, $fileName)); parent::__construct(sprintf('A test with the description `%s` already exists in the filename `%s`.', $description, $fileName));
} }
} }
+4 -1
View File
@@ -14,10 +14,13 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class TestCaseAlreadyInUse extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class TestCaseAlreadyInUse extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $inUse, string $newOne, string $folder) public function __construct(string $inUse, string $newOne, string $folder)
{ {
parent::__construct(sprintf( parent::__construct(sprintf(
'The test case [%s] may not be used here. The folder [%s] is already bound to the test case [%s].', 'Test case [%s] can not be used. The folder [%s] already uses the test case [%s].',
$newOne, $newOne,
$folder, $folder,
$inUse, $inUse,
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class TestCaseClassOrTraitNotFound extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class TestCaseClassOrTraitNotFound extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $testCaseClass) public function __construct(string $testCaseClass)
{ {
parent::__construct(sprintf('The class or trait [%s] could not be found. Please check the name, and make sure it is autoloadable.', $testCaseClass)); parent::__construct(sprintf('The class `%s` was not found.', $testCaseClass));
} }
} }
@@ -15,11 +15,14 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class TestClosureMustNotBeStatic extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class TestClosureMustNotBeStatic extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(TestCaseMethodFactory $method) public function __construct(TestCaseMethodFactory $method)
{ {
parent::__construct( parent::__construct(
sprintf( sprintf(
'Test closures may not be static. Please remove the [static] keyword from the test [%s] in [%s].', 'Test closure must not be static. Please remove the [static] keyword from the [%s] method in [%s].',
$method->description, $method->description,
$method->filename $method->filename
) )
+4 -1
View File
@@ -14,8 +14,11 @@ use Symfony\Component\Console\Exception\ExceptionInterface;
*/ */
final class TestDescriptionMissing extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace final class TestDescriptionMissing extends InvalidArgumentException implements ExceptionInterface, RenderlessEditor, RenderlessTrace
{ {
/**
* Creates a new Exception instance.
*/
public function __construct(string $fileName) public function __construct(string $fileName)
{ {
parent::__construct(sprintf('A test in [%s] is missing its description. Please give every test a description.', $fileName)); parent::__construct(sprintf('Test description is missing in the filename `%s`.', $fileName));
} }
} }
-49
View File
@@ -1,49 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Pest\Contracts\Panicable;
use RuntimeException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class TiaRequiresCommit extends RuntimeException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
{
public function __construct()
{
parent::__construct(
'Tia mode requires a repository with at least one commit, so the baseline it records can be anchored to a revision.',
);
}
public function render(OutputInterface $output): void
{
$output->writeln([
'',
' <fg=white;options=bold;bg=red> ERROR </> Tia mode requires at least one commit.',
'',
' A baseline is anchored to the revision it was recorded at, and this repository',
' has none yet, so there is nothing to record against and nothing to compare a',
' later run to.',
'',
' Commit once, then run again:',
'',
' <fg=yellow>git add . && git commit -m "Initial commit"</>',
'',
' Runs without <fg=yellow>--tia</> are unaffected.',
'',
]);
}
public function exitCode(): int
{
return 1;
}
}
@@ -1,52 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Pest\Contracts\Panicable;
use RuntimeException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class TiaRequiresDefaultBranch extends RuntimeException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
{
public function __construct()
{
parent::__construct(
'Tia mode could not determine the default branch every other branch falls back to reading.',
);
}
public function render(OutputInterface $output): void
{
$output->writeln([
'',
' <fg=white;options=bold;bg=red> ERROR </> Tia mode could not determine the default branch.',
'',
' It is the branch whose baseline every other branch falls back to reading, and',
' nothing in this checkout names it: the repository has a remote, but no',
' <fg=yellow>origin/HEAD</>, and no CI provider stated it either. Guessing would re-run the',
' whole suite on every new branch while reporting it as a cache hit.',
'',
' Name the branch in <fg=yellow>tests/Pest.php</>:',
'',
' <fg=yellow>pest()->tia()->defaultBranch(\'master\');</>',
'',
' Or let git answer, once per clone:',
'',
' <fg=yellow>git remote set-head origin --auto</>',
'',
]);
}
public function exitCode(): int
{
return 1;
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ final class TiaRequiresPestTests extends RuntimeException implements ExceptionIn
public function __construct(private readonly string $className, string $filename) public function __construct(private readonly string $className, string $filename)
{ {
parent::__construct(sprintf( parent::__construct(sprintf(
'Tia mode supports functional Pest tests only, but found the PHPUnit class [%s] in [%s]. Please convert it to a Pest test, or run without Tia.', 'Tia mode requires only functional based Pest tests, but encountered PHPUnit class [%s] in [%s].',
$className, $className,
$filename, $filename,
)); ));
-47
View File
@@ -1,47 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Pest\Contracts\Panicable;
use RuntimeException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class TiaRequiresRemote extends RuntimeException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
{
public function __construct()
{
parent::__construct(
'Tia mode requires a repository with a remote, so the default branch every other branch falls back to reading can be resolved.',
);
}
public function render(OutputInterface $output): void
{
$output->writeln([
'',
' <fg=white;options=bold;bg=red> ERROR </> Tia mode requires a repository with a remote.',
'',
' Without one there is no way to tell which branch is the default — the branch',
' whose baseline every other branch falls back to reading — so the first run on',
' each new branch would silently re-run the whole suite.',
'',
' Add a remote, or name the branch yourself in <fg=yellow>tests/Pest.php</>:',
'',
' <fg=yellow>pest()->tia()->defaultBranch(\'master\');</>',
'',
]);
}
public function exitCode(): int
{
return 1;
}
}
@@ -1,44 +0,0 @@
<?php
declare(strict_types=1);
namespace Pest\Exceptions;
use NunoMaduro\Collision\Contracts\RenderlessEditor;
use NunoMaduro\Collision\Contracts\RenderlessTrace;
use Pest\Contracts\Panicable;
use RuntimeException;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @internal
*/
final class TiaRequiresRepositoryRoot extends RuntimeException implements ExceptionInterface, Panicable, RenderlessEditor, RenderlessTrace
{
public function __construct(private readonly string $subdirectoryPrefix)
{
parent::__construct(sprintf(
'Tia mode requires the project root to be the git repository root, but this project sits in the subdirectory [%s] of a larger repository. Please give it its own repository to use Tia.',
$this->subdirectoryPrefix,
));
}
public function render(OutputInterface $output): void
{
$output->writeln([
'',
' <fg=white;options=bold;bg=red> ERROR </> Tia mode requires the git repository root.',
'',
sprintf(' This project sits in a subdirectory of a larger repo <fg=yellow>%s</>.', $this->subdirectoryPrefix),
'',
' Give the project its own git repository to use Tia.',
'',
]);
}
public function exitCode(): int
{
return 1;
}
}
+230 -31
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest; namespace Pest;
use Attribute;
use BadMethodCallException; use BadMethodCallException;
use Closure; use Closure;
use InvalidArgumentException; use InvalidArgumentException;
@@ -59,15 +60,19 @@ final class Expectation
use Retrievable; use Retrievable;
/** /**
* Creates a new expectation.
*
* @param TValue $value * @param TValue $value
*/ */
public function __construct( public function __construct(
public mixed $value public mixed $value
) { ) {
// // ..
} }
/** /**
* Creates a new expectation.
*
* @template TAndValue * @template TAndValue
* *
* @param TAndValue $value * @param TAndValue $value
@@ -79,6 +84,8 @@ final class Expectation
} }
/** /**
* Creates a new expectation with the decoded JSON value.
*
* @return self<array<int|string, mixed>|bool> * @return self<array<int|string, mixed>|bool>
*/ */
public function json(): Expectation public function json(): Expectation
@@ -96,6 +103,8 @@ final class Expectation
} }
/** /**
* Dump the expectation value.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function dump(mixed ...$arguments): self public function dump(mixed ...$arguments): self
@@ -103,32 +112,31 @@ final class Expectation
if (function_exists('dump')) { if (function_exists('dump')) {
dump($this->value, ...$arguments); dump($this->value, ...$arguments);
} else { } else {
var_dump($this->value, ...$arguments); var_dump($this->value);
} }
return $this; return $this;
} }
public function dd(mixed ...$arguments): never /**
* Dump the expectation value and end the script.
*
* @return never
*/
public function dd(mixed ...$arguments): void
{ {
if (function_exists('dd')) { if (function_exists('dd')) {
dd($this->value, ...$arguments); dd($this->value, ...$arguments);
} }
if (getenv('PARATEST') !== false || isset($_SERVER['COLLISION_PRINTER'])) { var_dump($this->value);
ob_start();
var_dump($this->value, ...$arguments);
$output = ob_get_clean();
throw new ExpectationFailedException($output);
}
var_dump($this->value, ...$arguments);
exit(1); exit(1);
} }
/** /**
* Dump the expectation value when the result of the condition is truthy.
*
* @param (Closure(TValue): bool)|bool $condition * @param (Closure(TValue): bool)|bool $condition
* @return self<TValue> * @return self<TValue>
*/ */
@@ -144,6 +152,8 @@ final class Expectation
} }
/** /**
* Dump the expectation value when the result of the condition is falsy.
*
* @param (Closure(TValue): bool)|bool $condition * @param (Closure(TValue): bool)|bool $condition
* @return self<TValue> * @return self<TValue>
*/ */
@@ -159,6 +169,8 @@ final class Expectation
} }
/** /**
* Send the expectation value to Ray along with all given arguments.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function ray(mixed ...$arguments): self public function ray(mixed ...$arguments): self
@@ -171,6 +183,8 @@ final class Expectation
} }
/** /**
* Creates the opposite expectation for the value.
*
* @return OppositeExpectation<TValue> * @return OppositeExpectation<TValue>
*/ */
public function not(): OppositeExpectation public function not(): OppositeExpectation
@@ -179,6 +193,8 @@ final class Expectation
} }
/** /**
* Creates an expectation on each item of the iterable "value".
*
* @return EachExpectation<TValue> * @return EachExpectation<TValue>
*/ */
public function each(?callable $callback = null): EachExpectation public function each(?callable $callback = null): EachExpectation
@@ -197,6 +213,8 @@ final class Expectation
} }
/** /**
* Allows you to specify a sequential set of expectations for each item in a iterable "value".
*
* @template TSequenceValue * @template TSequenceValue
* *
* @param (callable(self<TValue>, self<string|int>): void)|TSequenceValue ...$callbacks * @param (callable(self<TValue>, self<string|int>): void)|TSequenceValue ...$callbacks
@@ -220,7 +238,7 @@ final class Expectation
if ($callbacks[$index] instanceof Closure) { if ($callbacks[$index] instanceof Closure) {
$callbacks[$index](new self($value), new self($key)); $callbacks[$index](new self($value), new self($key));
} else { } else {
new self($value)->toEqual($callbacks[$index]); (new self($value))->toEqual($callbacks[$index]);
} }
$index = isset($callbacks[$index + 1]) ? $index + 1 : 0; $index = isset($callbacks[$index + 1]) ? $index + 1 : 0;
@@ -234,6 +252,8 @@ final class Expectation
} }
/** /**
* If the subject matches one of the given "expressions", the expression callback will run.
*
* @template TMatchSubject of array-key * @template TMatchSubject of array-key
* *
* @param (callable(): TMatchSubject)|TMatchSubject $subject * @param (callable(): TMatchSubject)|TMatchSubject $subject
@@ -272,6 +292,8 @@ final class Expectation
} }
/** /**
* Apply the callback if the given "condition" is falsy.
*
* @param (callable(): bool)|bool $condition * @param (callable(): bool)|bool $condition
* @param callable(Expectation<TValue>): mixed $callback * @param callable(Expectation<TValue>): mixed $callback
* @return self<TValue> * @return self<TValue>
@@ -286,6 +308,8 @@ final class Expectation
} }
/** /**
* Apply the callback if the given "condition" is truthy.
*
* @param (callable(): bool)|bool $condition * @param (callable(): bool)|bool $condition
* @param callable(self<TValue>): mixed $callback * @param callable(self<TValue>): mixed $callback
* @return self<TValue> * @return self<TValue>
@@ -304,6 +328,8 @@ final class Expectation
} }
/** /**
* Dynamically calls methods on the class or creates a new higher order expectation.
*
* @param array<int, mixed> $parameters * @param array<int, mixed> $parameters
* @return Expectation<TValue>|HigherOrderExpectation<Expectation<TValue>, TValue> * @return Expectation<TValue>|HigherOrderExpectation<Expectation<TValue>, TValue>
*/ */
@@ -318,7 +344,7 @@ final class Expectation
if (! is_object($this->value)) { if (! is_object($this->value)) {
throw new BadMethodCallException(sprintf( throw new BadMethodCallException(sprintf(
'Method [%s] does not exist in [%s].', 'Method "%s" does not exist in %s.',
$method, $method,
gettype($this->value) gettype($this->value)
)); ));
@@ -347,6 +373,8 @@ final class Expectation
} }
/** /**
* Creates a new expectation closure from the given name.
*
* @throws ExpectationNotFound * @throws ExpectationNotFound
*/ */
private function getExpectationClosure(string $name): Closure private function getExpectationClosure(string $name): Closure
@@ -368,6 +396,8 @@ final class Expectation
} }
/** /**
* Dynamically calls methods on the class without any arguments or creates a new higher order expectation.
*
* @return Expectation<TValue>|OppositeExpectation<TValue>|EachExpectation<TValue>|HigherOrderExpectation<Expectation<TValue>, TValue|null>|TValue * @return Expectation<TValue>|OppositeExpectation<TValue>|EachExpectation<TValue>|HigherOrderExpectation<Expectation<TValue>, TValue|null>|TValue
*/ */
public function __get(string $name): mixed public function __get(string $name): mixed
@@ -386,6 +416,9 @@ final class Expectation
return $this->{$name}(); return $this->{$name}();
} }
/**
* Checks if the given expectation method exists.
*/
public static function hasMethod(string $name): bool public static function hasMethod(string $name): bool
{ {
return method_exists(self::class, $name) return method_exists(self::class, $name)
@@ -393,12 +426,17 @@ final class Expectation
|| self::hasExtend($name); || self::hasExtend($name);
} }
/**
* Matches any value.
*/
public function any(): Any public function any(): Any
{ {
return new Any; return new Any;
} }
/** /**
* Asserts that the given expectation target use the given dependencies.
*
* @param array<int, string>|string $targets * @param array<int, string>|string $targets
*/ */
public function toUse(array|string $targets): ArchExpectation public function toUse(array|string $targets): ArchExpectation
@@ -406,6 +444,9 @@ final class Expectation
return ToUse::make($this, $targets); return ToUse::make($this, $targets);
} }
/**
* Asserts that the given expectation target does have the given permissions
*/
public function toHaveFileSystemPermissions(string $permissions): ArchExpectation public function toHaveFileSystemPermissions(string $permissions): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -416,6 +457,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target to have line count less than the given number.
*/
public function toHaveLineCountLessThan(int $lines): ArchExpectation public function toHaveLineCountLessThan(int $lines): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -426,6 +470,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target have all methods documented.
*/
public function toHaveMethodsDocumented(): ArchExpectation public function toHaveMethodsDocumented(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -442,6 +489,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target have all properties documented.
*/
public function toHavePropertiesDocumented(): ArchExpectation public function toHavePropertiesDocumented(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -459,6 +509,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target use the "declare(strict_types=1)" declaration.
*/
public function toUseStrictTypes(): ArchExpectation public function toUseStrictTypes(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -469,6 +522,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target uses strict equality.
*/
public function toUseStrictEquality(): ArchExpectation public function toUseStrictEquality(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -479,6 +535,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target is final.
*/
public function toBeFinal(): ArchExpectation public function toBeFinal(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -489,6 +548,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target is readonly.
*/
public function toBeReadonly(): ArchExpectation public function toBeReadonly(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -499,6 +561,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target is trait.
*/
public function toBeTrait(): ArchExpectation public function toBeTrait(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -509,11 +574,17 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation targets are traits.
*/
public function toBeTraits(): ArchExpectation public function toBeTraits(): ArchExpectation
{ {
return $this->toBeTrait(); return $this->toBeTrait();
} }
/**
* Asserts that the given expectation target is abstract.
*/
public function toBeAbstract(): ArchExpectation public function toBeAbstract(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -525,6 +596,8 @@ final class Expectation
} }
/** /**
* Asserts that the given expectation target has a specific method.
*
* @param array<int, string>|string $method * @param array<int, string>|string $method
*/ */
public function toHaveMethod(array|string $method): ArchExpectation public function toHaveMethod(array|string $method): ArchExpectation
@@ -534,12 +607,14 @@ final class Expectation
return Targeted::make( return Targeted::make(
$this, $this,
fn (ObjectDescription $object): bool => count(array_filter($methods, fn (string $method): bool => isset($object->reflectionClass) && $object->reflectionClass->hasMethod($method))) === count($methods), fn (ObjectDescription $object): bool => count(array_filter($methods, fn (string $method): bool => isset($object->reflectionClass) && $object->reflectionClass->hasMethod($method))) === count($methods),
sprintf('to have method [%s]', implode('], [', $methods)), sprintf("to have method '%s'", implode("', '", $methods)),
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/** /**
* Asserts that the given expectation target has a specific methods.
*
* @param array<int, string> $methods * @param array<int, string> $methods
*/ */
public function toHaveMethods(array $methods): ArchExpectation public function toHaveMethods(array $methods): ArchExpectation
@@ -547,36 +622,57 @@ final class Expectation
return $this->toHaveMethod($methods); return $this->toHaveMethod($methods);
} }
/**
* Not supported.
*/
public function toHavePublicMethodsBesides(): void public function toHavePublicMethodsBesides(): void
{ {
throw InvalidExpectation::fromMethods(['toHavePublicMethodsBesides']); throw InvalidExpectation::fromMethods(['toHavePublicMethodsBesides']);
} }
/**
* Not supported.
*/
public function toHavePublicMethods(): void public function toHavePublicMethods(): void
{ {
throw InvalidExpectation::fromMethods(['toHavePublicMethods']); throw InvalidExpectation::fromMethods(['toHavePublicMethods']);
} }
/**
* Not supported.
*/
public function toHaveProtectedMethodsBesides(): void public function toHaveProtectedMethodsBesides(): void
{ {
throw InvalidExpectation::fromMethods(['toHaveProtectedMethodsBesides']); throw InvalidExpectation::fromMethods(['toHaveProtectedMethodsBesides']);
} }
/**
* Not supported.
*/
public function toHaveProtectedMethods(): void public function toHaveProtectedMethods(): void
{ {
throw InvalidExpectation::fromMethods(['toHaveProtectedMethods']); throw InvalidExpectation::fromMethods(['toHaveProtectedMethods']);
} }
/**
* Not supported.
*/
public function toHavePrivateMethodsBesides(): void public function toHavePrivateMethodsBesides(): void
{ {
throw InvalidExpectation::fromMethods(['toHavePrivateMethodsBesides']); throw InvalidExpectation::fromMethods(['toHavePrivateMethodsBesides']);
} }
/**
* Not supported.
*/
public function toHavePrivateMethods(): void public function toHavePrivateMethods(): void
{ {
throw InvalidExpectation::fromMethods(['toHavePrivateMethods']); throw InvalidExpectation::fromMethods(['toHavePrivateMethods']);
} }
/**
* Asserts that the given expectation target is cased correctly.
*/
public function toBeCasedCorrectly(): ArchExpectation public function toBeCasedCorrectly(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -609,6 +705,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target is enum.
*/
public function toBeEnum(): ArchExpectation public function toBeEnum(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -619,11 +718,17 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation targets are enums.
*/
public function toBeEnums(): ArchExpectation public function toBeEnums(): ArchExpectation
{ {
return $this->toBeEnum(); return $this->toBeEnum();
} }
/**
* Asserts that the given expectation target is a class.
*/
public function toBeClass(): ArchExpectation public function toBeClass(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -634,11 +739,17 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation targets are classes.
*/
public function toBeClasses(): ArchExpectation public function toBeClasses(): ArchExpectation
{ {
return $this->toBeClass(); return $this->toBeClass();
} }
/**
* Asserts that the given expectation target is interface.
*/
public function toBeInterface(): ArchExpectation public function toBeInterface(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -649,21 +760,30 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation targets are interfaces.
*/
public function toBeInterfaces(): ArchExpectation public function toBeInterfaces(): ArchExpectation
{ {
return $this->toBeInterface(); return $this->toBeInterface();
} }
/**
* Asserts that the given expectation target to be subclass of the given class.
*/
public function toExtend(string $class): ArchExpectation public function toExtend(string $class): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
$this, $this,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) && ($class === $object->reflectionClass->getName() || $object->reflectionClass->isSubclassOf($class)), fn (ObjectDescription $object): bool => isset($object->reflectionClass) && ($class === $object->reflectionClass->getName() || $object->reflectionClass->isSubclassOf($class)),
sprintf('to extend [%s]', $class), sprintf("to extend '%s'", $class),
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Asserts that the given expectation target to be have a parent class.
*/
public function toExtendNothing(): ArchExpectation public function toExtendNothing(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -674,12 +794,17 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target to use the given trait.
*/
public function toUseTrait(string $trait): ArchExpectation public function toUseTrait(string $trait): ArchExpectation
{ {
return $this->toUseTraits($trait); return $this->toUseTraits($trait);
} }
/** /**
* Asserts that the given expectation target to use the given traits.
*
* @param array<int, string>|string $traits * @param array<int, string>|string $traits
*/ */
public function toUseTraits(array|string $traits): ArchExpectation public function toUseTraits(array|string $traits): ArchExpectation
@@ -721,6 +846,9 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target to not implement any interfaces.
*/
public function toImplementNothing(): ArchExpectation public function toImplementNothing(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -732,6 +860,8 @@ final class Expectation
} }
/** /**
* Asserts that the given expectation target to only implement the given interfaces.
*
* @param array<int, string>|string $interfaces * @param array<int, string>|string $interfaces
*/ */
public function toOnlyImplement(array|string $interfaces): ArchExpectation public function toOnlyImplement(array|string $interfaces): ArchExpectation
@@ -748,27 +878,35 @@ final class Expectation
); );
} }
/**
* Asserts that the given expectation target to have the given prefix.
*/
public function toHavePrefix(string $prefix): ArchExpectation public function toHavePrefix(string $prefix): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
$this, $this,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) && str_starts_with($object->reflectionClass->getShortName(), $prefix), fn (ObjectDescription $object): bool => isset($object->reflectionClass) && str_starts_with($object->reflectionClass->getShortName(), $prefix),
"to have prefix [{$prefix}]", "to have prefix '{$prefix}'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
);
}
public function toHaveSuffix(string $suffix): ArchExpectation
{
return Targeted::make(
$this,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) && str_ends_with($object->reflectionClass->getName(), $suffix),
"to have suffix [{$suffix}]",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/** /**
* Asserts that the given expectation target to have the given suffix.
*/
public function toHaveSuffix(string $suffix): ArchExpectation
{
return Targeted::make(
$this,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) && str_ends_with($object->reflectionClass->getName(), $suffix),
"to have suffix '{$suffix}'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
);
}
/**
* Asserts that the given expectation target to implement the given interfaces.
*
* @param array<int, string>|string $interfaces * @param array<int, string>|string $interfaces
*/ */
public function toImplement(array|string $interfaces): ArchExpectation public function toImplement(array|string $interfaces): ArchExpectation
@@ -777,13 +915,23 @@ final class Expectation
return Targeted::make( return Targeted::make(
$this, $this,
fn (ObjectDescription $object): bool => array_all($interfaces, fn (string $interface): bool => isset($object->reflectionClass) && $object->reflectionClass->implementsInterface($interface)), function (ObjectDescription $object) use ($interfaces): bool {
foreach ($interfaces as $interface) {
if (! isset($object->reflectionClass) || ! $object->reflectionClass->implementsInterface($interface)) {
return false;
}
}
return true;
},
"to implement '".implode("', '", $interfaces)."'", "to implement '".implode("', '", $interfaces)."'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/** /**
* Asserts that the given expectation target "only" use on the given dependencies.
*
* @param array<int, string>|string $targets * @param array<int, string>|string $targets
*/ */
public function toOnlyUse(array|string $targets): ArchExpectation public function toOnlyUse(array|string $targets): ArchExpectation
@@ -791,22 +939,33 @@ final class Expectation
return ToOnlyUse::make($this, $targets); return ToOnlyUse::make($this, $targets);
} }
/**
* Asserts that the given expectation target does not use any dependencies.
*/
public function toUseNothing(): ArchExpectation public function toUseNothing(): ArchExpectation
{ {
return ToUseNothing::make($this); return ToUseNothing::make($this);
} }
/**
* Asserts that the source code of the given expectation target does not include suspicious characters.
*/
public function toHaveSuspiciousCharacters(): ArchExpectation public function toHaveSuspiciousCharacters(): ArchExpectation
{ {
throw InvalidExpectation::fromMethods(['toHaveSuspiciousCharacters']); throw InvalidExpectation::fromMethods(['toHaveSuspiciousCharacters']);
} }
/**
* Not supported.
*/
public function toBeUsed(): void public function toBeUsed(): void
{ {
throw InvalidExpectation::fromMethods(['toBeUsed']); throw InvalidExpectation::fromMethods(['toBeUsed']);
} }
/** /**
* Asserts that the given expectation dependency is used by the given targets.
*
* @param array<int, string>|string $targets * @param array<int, string>|string $targets
*/ */
public function toBeUsedIn(array|string $targets): ArchExpectation public function toBeUsedIn(array|string $targets): ArchExpectation
@@ -815,6 +974,8 @@ final class Expectation
} }
/** /**
* Asserts that the given expectation dependency is "only" used by the given targets.
*
* @param array<int, string>|string $targets * @param array<int, string>|string $targets
*/ */
public function toOnlyBeUsedIn(array|string $targets): ArchExpectation public function toOnlyBeUsedIn(array|string $targets): ArchExpectation
@@ -822,11 +983,17 @@ final class Expectation
return ToOnlyBeUsedIn::make($this, $targets); return ToOnlyBeUsedIn::make($this, $targets);
} }
/**
* Asserts that the given expectation dependency is not used.
*/
public function toBeUsedInNothing(): ArchExpectation public function toBeUsedInNothing(): ArchExpectation
{ {
return ToBeUsedInNothing::make($this); return ToBeUsedInNothing::make($this);
} }
/**
* Asserts that the given expectation dependency is an invokable class.
*/
public function toBeInvokable(): ArchExpectation public function toBeInvokable(): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
@@ -838,6 +1005,8 @@ final class Expectation
} }
/** /**
* Asserts that the given expectation is iterable and contains snake_case keys.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function toHaveSnakeCaseKeys(string $message = ''): self public function toHaveSnakeCaseKeys(string $message = ''): self
@@ -860,6 +1029,8 @@ final class Expectation
} }
/** /**
* Asserts that the given expectation is iterable and contains kebab-case keys.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function toHaveKebabCaseKeys(string $message = ''): self public function toHaveKebabCaseKeys(string $message = ''): self
@@ -882,6 +1053,8 @@ final class Expectation
} }
/** /**
* Asserts that the given expectation is iterable and contains camelCase keys.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function toHaveCamelCaseKeys(string $message = ''): self public function toHaveCamelCaseKeys(string $message = ''): self
@@ -904,6 +1077,8 @@ final class Expectation
} }
/** /**
* Asserts that the given expectation is iterable and contains StudlyCase keys.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function toHaveStudlyCaseKeys(string $message = ''): self public function toHaveStudlyCaseKeys(string $message = ''): self
@@ -925,54 +1100,78 @@ final class Expectation
return $this; return $this;
} }
/**
* Asserts that the given expectation target to have the given attribute.
*/
public function toHaveAttribute(string $attribute): ArchExpectation public function toHaveAttribute(string $attribute): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
$this, $this,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) && $object->reflectionClass->getAttributes($attribute) !== [], fn (ObjectDescription $object): bool => isset($object->reflectionClass) && $object->reflectionClass->getAttributes($attribute) !== [],
"to have attribute [{$attribute}]", "to have attribute '{$attribute}'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Asserts that the given expectation target has a constructor method.
*/
public function toHaveConstructor(): ArchExpectation public function toHaveConstructor(): ArchExpectation
{ {
return $this->toHaveMethod('__construct'); return $this->toHaveMethod('__construct');
} }
/**
* Asserts that the given expectation target has a destructor method.
*/
public function toHaveDestructor(): ArchExpectation public function toHaveDestructor(): ArchExpectation
{ {
return $this->toHaveMethod('__destruct'); return $this->toHaveMethod('__destruct');
} }
/**
* Asserts that the given expectation target is a backed enum of given type.
*/
private function toBeBackedEnum(string $backingType): ArchExpectation private function toBeBackedEnum(string $backingType): ArchExpectation
{ {
return Targeted::make( return Targeted::make(
$this, $this,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) fn (ObjectDescription $object): bool => isset($object->reflectionClass)
&& $object->reflectionClass->isEnum() && $object->reflectionClass->isEnum()
&& new ReflectionEnum($object->name)->isBacked() // @phpstan-ignore-line && (new ReflectionEnum($object->name))->isBacked() // @phpstan-ignore-line
&& (string) new ReflectionEnum($object->name)->getBackingType() === $backingType, // @phpstan-ignore-line && (string) (new ReflectionEnum($object->name))->getBackingType() === $backingType, // @phpstan-ignore-line
'to be '.$backingType.' backed enum', 'to be '.$backingType.' backed enum',
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Asserts that the given expectation targets are string backed enums.
*/
public function toBeStringBackedEnums(): ArchExpectation public function toBeStringBackedEnums(): ArchExpectation
{ {
return $this->toBeStringBackedEnum(); return $this->toBeStringBackedEnum();
} }
/**
* Asserts that the given expectation targets are int backed enums.
*/
public function toBeIntBackedEnums(): ArchExpectation public function toBeIntBackedEnums(): ArchExpectation
{ {
return $this->toBeIntBackedEnum(); return $this->toBeIntBackedEnum();
} }
/**
* Asserts that the given expectation target is a string backed enum.
*/
public function toBeStringBackedEnum(): ArchExpectation public function toBeStringBackedEnum(): ArchExpectation
{ {
return $this->toBeBackedEnum('string'); return $this->toBeBackedEnum('string');
} }
/**
* Asserts that the given expectation target is an int backed enum.
*/
public function toBeIntBackedEnum(): ArchExpectation public function toBeIntBackedEnum(): ArchExpectation
{ {
return $this->toBeBackedEnum('int'); return $this->toBeBackedEnum('int');
+13
View File
@@ -17,14 +17,21 @@ use function expect;
*/ */
final class EachExpectation final class EachExpectation
{ {
/**
* Indicates if the expectation is the opposite.
*/
private bool $opposite = false; private bool $opposite = false;
/** /**
* Creates an expectation on each item of the iterable "value".
*
* @param Expectation<TValue> $original * @param Expectation<TValue> $original
*/ */
public function __construct(private readonly Expectation $original) {} public function __construct(private readonly Expectation $original) {}
/** /**
* Creates a new expectation.
*
* @template TAndValue * @template TAndValue
* *
* @param TAndValue $value * @param TAndValue $value
@@ -36,6 +43,8 @@ final class EachExpectation
} }
/** /**
* Creates the opposite expectation for the value.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function not(): self public function not(): self
@@ -46,6 +55,8 @@ final class EachExpectation
} }
/** /**
* Dynamically calls methods on the class with the given arguments on each item.
*
* @param array<int|string, mixed> $arguments * @param array<int|string, mixed> $arguments
* @return self<TValue> * @return self<TValue>
*/ */
@@ -62,6 +73,8 @@ final class EachExpectation
} }
/** /**
* Dynamically calls methods on the class without any arguments on each item.
*
* @return self<TValue> * @return self<TValue>
*/ */
public function __get(string $name): self public function __get(string $name): self
+32 -2
View File
@@ -25,11 +25,19 @@ final class HigherOrderExpectation
*/ */
private Expectation|EachExpectation $expectation; private Expectation|EachExpectation $expectation;
/**
* Indicates if the expectation is the opposite.
*/
private bool $opposite = false; private bool $opposite = false;
/**
* Indicates if the expectation should reset the value.
*/
private bool $shouldReset = false; private bool $shouldReset = false;
/** /**
* Creates a new higher order expectation.
*
* @param Expectation<TOriginalValue> $original * @param Expectation<TOriginalValue> $original
* @param TValue $value * @param TValue $value
*/ */
@@ -39,6 +47,8 @@ final class HigherOrderExpectation
} }
/** /**
* Creates the opposite expectation for the value.
*
* @return self<TOriginalValue, TValue> * @return self<TOriginalValue, TValue>
*/ */
public function not(): self public function not(): self
@@ -49,6 +59,8 @@ final class HigherOrderExpectation
} }
/** /**
* Creates a new Expectation.
*
* @template TExpectValue * @template TExpectValue
* *
* @param TExpectValue $value * @param TExpectValue $value
@@ -60,6 +72,8 @@ final class HigherOrderExpectation
} }
/** /**
* Creates a new expectation.
*
* @template TExpectValue * @template TExpectValue
* *
* @param TExpectValue $value * @param TExpectValue $value
@@ -71,6 +85,9 @@ final class HigherOrderExpectation
} }
/** /**
* Scope an expectation callback to the current value in
* the HigherOrderExpectation chain.
*
* @param Closure(Expectation<TValue>): void $expectation * @param Closure(Expectation<TValue>): void $expectation
* @return HigherOrderExpectation<TOriginalValue, TOriginalValue> * @return HigherOrderExpectation<TOriginalValue, TOriginalValue>
*/ */
@@ -82,6 +99,8 @@ final class HigherOrderExpectation
} }
/** /**
* Creates a new expectation with the decoded JSON value.
*
* @return self<TOriginalValue, array<string|int, mixed>|bool> * @return self<TOriginalValue, array<string|int, mixed>|bool>
*/ */
public function json(): self public function json(): self
@@ -90,8 +109,10 @@ final class HigherOrderExpectation
} }
/** /**
* Dynamically calls methods on the class with the given arguments.
*
* @param array<int, mixed> $arguments * @param array<int, mixed> $arguments
* @return self<TOriginalValue, mixed> * @return self<TOriginalValue, mixed>|self<TOriginalValue, TValue>
*/ */
public function __call(string $name, array $arguments): self public function __call(string $name, array $arguments): self
{ {
@@ -104,7 +125,9 @@ final class HigherOrderExpectation
} }
/** /**
* @return self<TOriginalValue, mixed> * Accesses properties in the value or in the expectation.
*
* @return self<TOriginalValue, mixed>|self<TOriginalValue, TValue>
*/ */
public function __get(string $name): self public function __get(string $name): self
{ {
@@ -122,6 +145,9 @@ final class HigherOrderExpectation
return $this->performAssertion($name, []); return $this->performAssertion($name, []);
} }
/**
* Determines if the original expectation has the given method name.
*/
private function expectationHasMethod(string $name): bool private function expectationHasMethod(string $name): bool
{ {
if (method_exists($this->original, $name)) { if (method_exists($this->original, $name)) {
@@ -135,6 +161,8 @@ final class HigherOrderExpectation
} }
/** /**
* Retrieve the applicable value based on the current reset condition.
*
* @return TOriginalValue|TValue * @return TOriginalValue|TValue
*/ */
private function getValue(): mixed private function getValue(): mixed
@@ -143,6 +171,8 @@ final class HigherOrderExpectation
} }
/** /**
* Performs the given assertion with the current expectation.
*
* @param array<int, mixed> $arguments * @param array<int, mixed> $arguments
* @return self<TOriginalValue, TValue> * @return self<TOriginalValue, TValue>
*/ */
+183 -13
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Expectations; namespace Pest\Expectations;
use Attribute;
use Pest\Arch\Contracts\ArchExpectation; use Pest\Arch\Contracts\ArchExpectation;
use Pest\Arch\Expectations\Targeted; use Pest\Arch\Expectations\Targeted;
use Pest\Arch\Expectations\ToBeUsedIn; use Pest\Arch\Expectations\ToBeUsedIn;
@@ -37,11 +38,15 @@ use stdClass;
final readonly class OppositeExpectation final readonly class OppositeExpectation
{ {
/** /**
* Creates a new opposite expectation.
*
* @param Expectation<TValue> $original * @param Expectation<TValue> $original
*/ */
public function __construct(private Expectation $original) {} public function __construct(private Expectation $original) {}
/** /**
* Asserts that the value array not has the provided $keys.
*
* @param array<int, int|string|array<int-string, mixed>> $keys * @param array<int, int|string|array<int-string, mixed>> $keys
* @return Expectation<TValue> * @return Expectation<TValue>
*/ */
@@ -65,6 +70,8 @@ final readonly class OppositeExpectation
} }
/** /**
* Asserts that the given expectation target does not use any of the given dependencies.
*
* @param array<int, string>|string $targets * @param array<int, string>|string $targets
*/ */
public function toUse(array|string $targets): ArchExpectation public function toUse(array|string $targets): ArchExpectation
@@ -77,6 +84,9 @@ final readonly class OppositeExpectation
), is_string($targets) ? [$targets] : $targets)); ), is_string($targets) ? [$targets] : $targets));
} }
/**
* Asserts that the given expectation target does not have the given permissions
*/
public function toHaveFileSystemPermissions(string $permissions): ArchExpectation public function toHaveFileSystemPermissions(string $permissions): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -90,11 +100,17 @@ final readonly class OppositeExpectation
); );
} }
/**
* Not supported.
*/
public function toHaveLineCountLessThan(): ArchExpectation public function toHaveLineCountLessThan(): ArchExpectation
{ {
throw InvalidExpectation::fromMethods(['not', 'toHaveLineCountLessThan']); throw InvalidExpectation::fromMethods(['not', 'toHaveLineCountLessThan']);
} }
/**
* Not supported.
*/
public function toHaveMethodsDocumented(): ArchExpectation public function toHaveMethodsDocumented(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -114,6 +130,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Not supported.
*/
public function toHavePropertiesDocumented(): ArchExpectation public function toHavePropertiesDocumented(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -134,6 +153,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target does not use the "declare(strict_types=1)" declaration.
*/
public function toUseStrictTypes(): ArchExpectation public function toUseStrictTypes(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -147,6 +169,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target does not use the strict equality operator.
*/
public function toUseStrictEquality(): ArchExpectation public function toUseStrictEquality(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -160,6 +185,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target is not final.
*/
public function toBeFinal(): ArchExpectation public function toBeFinal(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -173,6 +201,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target is not readonly.
*/
public function toBeReadonly(): ArchExpectation public function toBeReadonly(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -186,6 +217,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target is not trait.
*/
public function toBeTrait(): ArchExpectation public function toBeTrait(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -199,11 +233,17 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation targets are not traits.
*/
public function toBeTraits(): ArchExpectation public function toBeTraits(): ArchExpectation
{ {
return $this->toBeTrait(); return $this->toBeTrait();
} }
/**
* Asserts that the given expectation target is not abstract.
*/
public function toBeAbstract(): ArchExpectation public function toBeAbstract(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -218,6 +258,8 @@ final readonly class OppositeExpectation
} }
/** /**
* Asserts that the given expectation target does not have a specific method.
*
* @param array<int, string>|string $method * @param array<int, string>|string $method
*/ */
public function toHaveMethod(array|string $method): ArchExpectation public function toHaveMethod(array|string $method): ArchExpectation
@@ -238,6 +280,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target does not have suspicious characters.
*/
public function toHaveSuspiciousCharacters(): ArchExpectation public function toHaveSuspiciousCharacters(): ArchExpectation
{ {
if (! class_exists(Spoofchecker::class)) { if (! class_exists(Spoofchecker::class)) {
@@ -258,6 +303,8 @@ final readonly class OppositeExpectation
} }
/** /**
* Asserts that the given expectation target does not have the given methods.
*
* @param array<int, string> $methods * @param array<int, string> $methods
*/ */
public function toHaveMethods(array $methods): ArchExpectation public function toHaveMethods(array $methods): ArchExpectation
@@ -266,6 +313,8 @@ final readonly class OppositeExpectation
} }
/** /**
* Asserts that the given expectation target not to have the public methods besides the given methods.
*
* @param array<int, string>|string $methods * @param array<int, string>|string $methods
*/ */
public function toHavePublicMethodsBesides(array|string $methods): ArchExpectation public function toHavePublicMethodsBesides(array|string $methods): ArchExpectation
@@ -296,17 +345,22 @@ final readonly class OppositeExpectation
}, },
$methods === [] $methods === []
? 'not to have public methods' ? 'not to have public methods'
: sprintf('not to have public methods besides [%s]', implode('], [', $methods)), : sprintf("not to have public methods besides '%s'", implode("', '", $methods)),
FileLineFinder::where(fn (string $line): bool => str_contains($line, (string) $state->contains)), FileLineFinder::where(fn (string $line): bool => str_contains($line, (string) $state->contains)),
); );
} }
/**
* Asserts that the given expectation target not to have the public methods.
*/
public function toHavePublicMethods(): ArchExpectation public function toHavePublicMethods(): ArchExpectation
{ {
return $this->toHavePublicMethodsBesides([]); return $this->toHavePublicMethodsBesides([]);
} }
/** /**
* Asserts that the given expectation target not to have the protected methods besides the given methods.
*
* @param array<int, string>|string $methods * @param array<int, string>|string $methods
*/ */
public function toHaveProtectedMethodsBesides(array|string $methods): ArchExpectation public function toHaveProtectedMethodsBesides(array|string $methods): ArchExpectation
@@ -337,17 +391,22 @@ final readonly class OppositeExpectation
}, },
$methods === [] $methods === []
? 'not to have protected methods' ? 'not to have protected methods'
: sprintf('not to have protected methods besides [%s]', implode('], [', $methods)), : sprintf("not to have protected methods besides '%s'", implode("', '", $methods)),
FileLineFinder::where(fn (string $line): bool => str_contains($line, (string) $state->contains)), FileLineFinder::where(fn (string $line): bool => str_contains($line, (string) $state->contains)),
); );
} }
/**
* Asserts that the given expectation target not to have the protected methods.
*/
public function toHaveProtectedMethods(): ArchExpectation public function toHaveProtectedMethods(): ArchExpectation
{ {
return $this->toHaveProtectedMethodsBesides([]); return $this->toHaveProtectedMethodsBesides([]);
} }
/** /**
* Asserts that the given expectation target not to have the private methods besides the given methods.
*
* @param array<int, string>|string $methods * @param array<int, string>|string $methods
*/ */
public function toHavePrivateMethodsBesides(array|string $methods): ArchExpectation public function toHavePrivateMethodsBesides(array|string $methods): ArchExpectation
@@ -378,16 +437,22 @@ final readonly class OppositeExpectation
}, },
$methods === [] $methods === []
? 'not to have private methods' ? 'not to have private methods'
: sprintf('not to have private methods besides [%s]', implode('], [', $methods)), : sprintf("not to have private methods besides '%s'", implode("', '", $methods)),
FileLineFinder::where(fn (string $line): bool => str_contains($line, (string) $state->contains)), FileLineFinder::where(fn (string $line): bool => str_contains($line, (string) $state->contains)),
); );
} }
/**
* Asserts that the given expectation target not to have the private methods.
*/
public function toHavePrivateMethods(): ArchExpectation public function toHavePrivateMethods(): ArchExpectation
{ {
return $this->toHavePrivateMethodsBesides([]); return $this->toHavePrivateMethodsBesides([]);
} }
/**
* Asserts that the given expectation target is not enum.
*/
public function toBeEnum(): ArchExpectation public function toBeEnum(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -401,11 +466,17 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation targets are not enums.
*/
public function toBeEnums(): ArchExpectation public function toBeEnums(): ArchExpectation
{ {
return $this->toBeEnum(); return $this->toBeEnum();
} }
/**
* Asserts that the given expectation targets is not class.
*/
public function toBeClass(): ArchExpectation public function toBeClass(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -419,11 +490,17 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation targets are not classes.
*/
public function toBeClasses(): ArchExpectation public function toBeClasses(): ArchExpectation
{ {
return $this->toBeClass(); return $this->toBeClass();
} }
/**
* Asserts that the given expectation target is not interface.
*/
public function toBeInterface(): ArchExpectation public function toBeInterface(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -437,11 +514,17 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation targets are not interfaces.
*/
public function toBeInterfaces(): ArchExpectation public function toBeInterfaces(): ArchExpectation
{ {
return $this->toBeInterface(); return $this->toBeInterface();
} }
/**
* Asserts that the given expectation target to be not subclass of the given class.
*/
public function toExtend(string $class): ArchExpectation public function toExtend(string $class): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -450,11 +533,14 @@ final readonly class OppositeExpectation
return Targeted::make( return Targeted::make(
$original, $original,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || ! $object->reflectionClass->isSubclassOf($class), fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || ! $object->reflectionClass->isSubclassOf($class),
sprintf('not to extend [%s]', $class), sprintf("not to extend '%s'", $class),
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Asserts that the given expectation target to be not have any parent class.
*/
public function toExtendNothing(): ArchExpectation public function toExtendNothing(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -468,12 +554,17 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target not to use the given trait.
*/
public function toUseTrait(string $trait): ArchExpectation public function toUseTrait(string $trait): ArchExpectation
{ {
return $this->toUseTraits($trait); return $this->toUseTraits($trait);
} }
/** /**
* Asserts that the given expectation target not to use the given traits.
*
* @param array<int, string>|string $traits * @param array<int, string>|string $traits
*/ */
public function toUseTraits(array|string $traits): ArchExpectation public function toUseTraits(array|string $traits): ArchExpectation
@@ -485,13 +576,23 @@ final readonly class OppositeExpectation
return Targeted::make( return Targeted::make(
$original, $original,
fn (ObjectDescription $object): bool => array_all($traits, fn (string $trait): bool => ! isset($object->reflectionClass) || ! in_array($trait, $object->reflectionClass->getTraitNames(), true)), function (ObjectDescription $object) use ($traits): bool {
foreach ($traits as $trait) {
if (isset($object->reflectionClass) && in_array($trait, $object->reflectionClass->getTraitNames(), true)) {
return false;
}
}
return true;
},
"not to use traits '".implode("', '", $traits)."'", "not to use traits '".implode("', '", $traits)."'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/** /**
* Asserts that the given expectation target not to implement the given interfaces.
*
* @param array<int, string>|string $interfaces * @param array<int, string>|string $interfaces
*/ */
public function toImplement(array|string $interfaces): ArchExpectation public function toImplement(array|string $interfaces): ArchExpectation
@@ -503,12 +604,23 @@ final readonly class OppositeExpectation
return Targeted::make( return Targeted::make(
$original, $original,
fn (ObjectDescription $object): bool => array_all($interfaces, fn (string $interface): bool => ! isset($object->reflectionClass) || ! $object->reflectionClass->implementsInterface($interface)), function (ObjectDescription $object) use ($interfaces): bool {
foreach ($interfaces as $interface) {
if (isset($object->reflectionClass) && $object->reflectionClass->implementsInterface($interface)) {
return false;
}
}
return true;
},
"not to implement '".implode("', '", $interfaces)."'", "not to implement '".implode("', '", $interfaces)."'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Asserts that the given expectation target to not implement any interfaces.
*/
public function toImplementNothing(): ArchExpectation public function toImplementNothing(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -522,11 +634,17 @@ final readonly class OppositeExpectation
); );
} }
/**
* Not supported.
*/
public function toOnlyImplement(): void public function toOnlyImplement(): void
{ {
throw InvalidExpectation::fromMethods(['not', 'toOnlyImplement']); throw InvalidExpectation::fromMethods(['not', 'toOnlyImplement']);
} }
/**
* Asserts that the given expectation target to not have the given prefix.
*/
public function toHavePrefix(string $prefix): ArchExpectation public function toHavePrefix(string $prefix): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -535,11 +653,14 @@ final readonly class OppositeExpectation
return Targeted::make( return Targeted::make(
$original, $original,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || ! str_starts_with($object->reflectionClass->getShortName(), $prefix), fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || ! str_starts_with($object->reflectionClass->getShortName(), $prefix),
"not to have prefix [{$prefix}]", "not to have prefix '{$prefix}'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Asserts that the given expectation target to not have the given suffix.
*/
public function toHaveSuffix(string $suffix): ArchExpectation public function toHaveSuffix(string $suffix): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -548,21 +669,30 @@ final readonly class OppositeExpectation
return Targeted::make( return Targeted::make(
$original, $original,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || ! str_ends_with($object->reflectionClass->getName(), $suffix), fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || ! str_ends_with($object->reflectionClass->getName(), $suffix),
"not to have suffix [{$suffix}]", "not to have suffix '{$suffix}'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Not supported.
*/
public function toOnlyUse(): void public function toOnlyUse(): void
{ {
throw InvalidExpectation::fromMethods(['not', 'toOnlyUse']); throw InvalidExpectation::fromMethods(['not', 'toOnlyUse']);
} }
/**
* Not supported.
*/
public function toUseNothing(): void public function toUseNothing(): void
{ {
throw InvalidExpectation::fromMethods(['not', 'toUseNothing']); throw InvalidExpectation::fromMethods(['not', 'toUseNothing']);
} }
/**
* Asserts that the given expectation dependency is not used.
*/
public function toBeUsed(): ArchExpectation public function toBeUsed(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -572,6 +702,8 @@ final readonly class OppositeExpectation
} }
/** /**
* Asserts that the given expectation dependency is not used by any of the given targets.
*
* @param array<int, string>|string $targets * @param array<int, string>|string $targets
*/ */
public function toBeUsedIn(array|string $targets): ArchExpectation public function toBeUsedIn(array|string $targets): ArchExpectation
@@ -589,11 +721,17 @@ final readonly class OppositeExpectation
throw InvalidExpectation::fromMethods(['not', 'toOnlyBeUsedIn']); throw InvalidExpectation::fromMethods(['not', 'toOnlyBeUsedIn']);
} }
/**
* Asserts that the given expectation dependency is not used.
*/
public function toBeUsedInNothing(): void public function toBeUsedInNothing(): void
{ {
throw InvalidExpectation::fromMethods(['not', 'toBeUsedInNothing']); throw InvalidExpectation::fromMethods(['not', 'toBeUsedInNothing']);
} }
/**
* Asserts that the given expectation dependency is not an invokable class.
*/
public function toBeInvokable(): ArchExpectation public function toBeInvokable(): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -607,6 +745,9 @@ final readonly class OppositeExpectation
); );
} }
/**
* Asserts that the given expectation target not to have the given attribute.
*/
public function toHaveAttribute(string $attribute): ArchExpectation public function toHaveAttribute(string $attribute): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -615,12 +756,14 @@ final readonly class OppositeExpectation
return Targeted::make( return Targeted::make(
$original, $original,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || $object->reflectionClass->getAttributes($attribute) === [], fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false || $object->reflectionClass->getAttributes($attribute) === [],
"to not have attribute [{$attribute}]", "to not have attribute '{$attribute}'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')) FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class'))
); );
} }
/** /**
* Handle dynamic method calls into the original expectation.
*
* @param array<int, mixed> $arguments * @param array<int, mixed> $arguments
* @return Expectation<TValue>|Expectation<mixed>|never * @return Expectation<TValue>|Expectation<mixed>|never
*/ */
@@ -641,6 +784,8 @@ final readonly class OppositeExpectation
} }
/** /**
* Handle dynamic properties gets into the original expectation.
*
* @return Expectation<TValue>|Expectation<mixed>|never * @return Expectation<TValue>|Expectation<mixed>|never
*/ */
public function __get(string $name): Expectation public function __get(string $name): Expectation
@@ -659,6 +804,8 @@ final readonly class OppositeExpectation
} }
/** /**
* Creates a new expectation failed exception with a nice readable message.
*
* @param array<int, mixed>|string $arguments * @param array<int, mixed>|string $arguments
*/ */
public function throwExpectationFailedException(string $name, array|string $arguments = []): never public function throwExpectationFailedException(string $name, array|string $arguments = []): never
@@ -667,24 +814,35 @@ final readonly class OppositeExpectation
$exporter = Exporter::default(); $exporter = Exporter::default();
$toString = fn (mixed $argument): string => $exporter->shortenedExport($argument);
throw new ExpectationFailedException(sprintf( throw new ExpectationFailedException(sprintf(
'Expecting %s not %s %s.', 'Expecting %s not %s %s.',
$exporter->shortenedExport($this->original->value), $toString($this->original->value),
strtolower((string) preg_replace('/(?<!\ )[A-Z]/', ' $0', $name)), strtolower((string) preg_replace('/(?<!\ )[A-Z]/', ' $0', $name)),
implode(' ', array_map(fn (mixed $argument): string => $exporter->export($argument), $arguments)), implode(' ', array_map(fn (mixed $argument): string => $toString($argument), $arguments)),
)); ));
} }
/**
* Asserts that the given expectation target does not have a constructor method.
*/
public function toHaveConstructor(): ArchExpectation public function toHaveConstructor(): ArchExpectation
{ {
return $this->toHaveMethod('__construct'); return $this->toHaveMethod('__construct');
} }
/**
* Asserts that the given expectation target does not have a destructor method.
*/
public function toHaveDestructor(): ArchExpectation public function toHaveDestructor(): ArchExpectation
{ {
return $this->toHaveMethod('__destruct'); return $this->toHaveMethod('__destruct');
} }
/**
* Asserts that the given expectation target is not a backed enum of given type.
*/
private function toBeBackedEnum(string $backingType): ArchExpectation private function toBeBackedEnum(string $backingType): ArchExpectation
{ {
/** @var Expectation<array<int, string>|string> $original */ /** @var Expectation<array<int, string>|string> $original */
@@ -694,28 +852,40 @@ final readonly class OppositeExpectation
$original, $original,
fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false fn (ObjectDescription $object): bool => isset($object->reflectionClass) === false
|| ! $object->reflectionClass->isEnum() || ! $object->reflectionClass->isEnum()
|| ! new \ReflectionEnum($object->name)->isBacked() // @phpstan-ignore-line || ! (new \ReflectionEnum($object->name))->isBacked() // @phpstan-ignore-line
|| (string) new \ReflectionEnum($object->name)->getBackingType() !== $backingType, // @phpstan-ignore-line || (string) (new \ReflectionEnum($object->name))->getBackingType() !== $backingType, // @phpstan-ignore-line
'not to be '.$backingType.' backed enum', 'not to be '.$backingType.' backed enum',
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')), FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
); );
} }
/**
* Asserts that the given expectation targets are not string backed enums.
*/
public function toBeStringBackedEnums(): ArchExpectation public function toBeStringBackedEnums(): ArchExpectation
{ {
return $this->toBeStringBackedEnum(); return $this->toBeStringBackedEnum();
} }
/**
* Asserts that the given expectation targets are not int backed enums.
*/
public function toBeIntBackedEnums(): ArchExpectation public function toBeIntBackedEnums(): ArchExpectation
{ {
return $this->toBeIntBackedEnum(); return $this->toBeIntBackedEnum();
} }
/**
* Asserts that the given expectation target is not a string backed enum.
*/
public function toBeStringBackedEnum(): ArchExpectation public function toBeStringBackedEnum(): ArchExpectation
{ {
return $this->toBeBackedEnum('string'); return $this->toBeBackedEnum('string');
} }
/**
* Asserts that the given expectation target is not an int backed enum.
*/
public function toBeIntBackedEnum(): ArchExpectation public function toBeIntBackedEnum(): ArchExpectation
{ {
return $this->toBeBackedEnum('int'); return $this->toBeBackedEnum('int');

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