Update dependencies
Composer: Laravel 13.43, Octane 2.25, Fortify 1.43 and Pest 5.3.7, with the packages they bring (70 in all). This fixes the advisories in Laravel and the Symfony components. npm: Vite 8.3.8 with Rolldown 1.2.19, Playwright 1.65.1 and chokidar 6. The asset build, CI and the dev container use Node.js 26. The dev image also has git for Composer. Both audits are clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
# Assertions
|
||||
|
||||
## Arrange, Act, Assert
|
||||
## Arrange, act, assert
|
||||
|
||||
Write each test in three parts: setup, one action, and assertions. Put one blank line between them so readers can identify each part without comments.
|
||||
|
||||
Keep each test self-contained. Do not use values created by another test.
|
||||
|
||||
## How to Find the Correct Assertion
|
||||
## How to find the correct assertion
|
||||
|
||||
First identify the subject of the check, then find an assertion designed for it. A subject-specific assertion identifies the incorrect value when the test fails.
|
||||
|
||||
@@ -28,17 +28,17 @@ Use a PHPUnit assertion only if no Pest expectation and no Laravel assertion exi
|
||||
|
||||
Assert each fact once, but status and content are separate facts. `assertSee` passes on an error page that contains the text, so keep `assertOk()` alongside it when the status is part of the behavior.
|
||||
|
||||
## Named Response Assertions
|
||||
## Named response assertions
|
||||
|
||||
Use a named response assertion, such as `assertNotFound()`, rather than `assertStatus(404)`. A failure then identifies the broken contract. Laravel provides named assertions for commonly tested status codes.
|
||||
|
||||
Keep one `expect()` chain on one subject. Start a new chain when the subject changes, or when the chain is difficult to read.
|
||||
|
||||
## Format Expectations
|
||||
## Format expectations
|
||||
|
||||
Use Pest's format expectations rather than regular expressions because they provide clearer failure messages. Pest covers email addresses, URLs, UUIDs, IP addresses, and other common formats, and each expectation supports `not` for the negative case.
|
||||
|
||||
## Assert a Known Value
|
||||
## Assert a known value
|
||||
|
||||
Write the expected value in the test, or calculate the expected value by a different method. Do not calculate the expected value with the logic of the implementation, because the test then passes when that logic is wrong.
|
||||
|
||||
@@ -52,7 +52,7 @@ travelTo('2025-01-01 00:00:00');
|
||||
expect($from)->toBe('2024-12-31T00:00:00.000000Z');
|
||||
```
|
||||
|
||||
## Assert the Complete Result
|
||||
## Assert the complete result
|
||||
|
||||
A status code is not the complete result of a write operation. Assert each of the following if the operation changes it:
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Endpoint Tests
|
||||
# Endpoint tests
|
||||
|
||||
## How to Write the Test
|
||||
## How to write the test
|
||||
|
||||
Fetch `https://laravel.com/framework/docs/http-tests` for the request helpers, the authentication helpers, and the response assertions. Confirm the name before you use it, and do not guess an assertion.
|
||||
|
||||
Choose an assertion based on the subject of the check: the status, a header, a redirect, the JSON body, the session, a validation error, or the view. Laravel provides a named assertion for each subject that identifies the incorrect value.
|
||||
|
||||
## Endpoint Coverage
|
||||
## Endpoint coverage
|
||||
|
||||
Write a test for each applicable case:
|
||||
|
||||
@@ -19,27 +19,27 @@ Write a test for each applicable case:
|
||||
|
||||
Assert the application's actual behavior rather than a generic status code. An API returns `401` for a missing or invalid token, while a browser endpoint redirects to the sign-in route.
|
||||
|
||||
## Tenant Isolation
|
||||
## Tenant isolation
|
||||
|
||||
Assert the status code returned for a cross-tenant request. Use `404` rather than `403` when one tenant must not learn that another tenant's record exists, because `403` confirms its existence.
|
||||
|
||||
## Test Authorization at the Policy Level
|
||||
## Test authorization at the policy level
|
||||
|
||||
An HTTP test shows that the endpoint performs authorization. It cannot identify which mechanism refused the request because middleware, a policy, and a call to `abort()` can all return `403`.
|
||||
|
||||
- Assert the complete matrix of the permissions against the policy or the gate. A failure then names the rule that is not correct.
|
||||
- Write one HTTP test for one refused role, which shows that the endpoint calls the authorization.
|
||||
- Use the helper of the project that asserts the ability and the arguments of the gate, if such a helper exists.
|
||||
- If the project has a helper that asserts the ability and the arguments of the gate, use that helper.
|
||||
|
||||
## Browser Tests
|
||||
## Browser tests
|
||||
|
||||
Write a browser test only for JavaScript behavior that an HTTP test cannot reach, such as modal interaction, drag-and-drop, live search, or client-side validation. Browser tests are slower than HTTP tests and can fail for reasons unrelated to the code under test.
|
||||
|
||||
- Assert the state that the user can see, and assert the state in the database that the interaction saves.
|
||||
- Wait until the test reaches the required state. Do not wait for a fixed number of seconds, which can fail on a slower machine.
|
||||
- Wait until the test reaches the required state. Do not wait for a fixed number of seconds. A fixed wait can fail on a slower machine.
|
||||
- Call `assertNoJavaScriptErrors()` in each browser test. An error in the console is a defect.
|
||||
|
||||
### Where a Browser Test Lives and How to Run It
|
||||
### Where a browser test lives and how to run it
|
||||
|
||||
The plugin runs browser tests as normal Pest tests, so they need no separate suite. Put them in `tests/Browser` to separate them from faster tests and run the directory with one command.
|
||||
|
||||
@@ -49,15 +49,15 @@ The plugin runs browser tests as normal Pest tests, so they need no separate sui
|
||||
- The run needs Playwright and a browser on the machine. Follow the plugin documentation for local and CI installation commands.
|
||||
- Fetch `https://pestphp.com/docs/browser-testing` for the interactions, the assertions, and the devices that the plugin gives.
|
||||
|
||||
### Browser Test Pitfalls
|
||||
### Browser test pitfalls
|
||||
|
||||
- The plugin waits five seconds for an element. Raise the value with `pest()->browser()->timeout(10000)` in `Pest.php` for a page that is slower, and do not add a wait for a number of seconds to the test.
|
||||
- The plugin waits five seconds for an element. For a slower page, raise the value with `pest()->browser()->timeout(10000)` in `Pest.php`. Do not add a wait for a number of seconds to the test.
|
||||
- Apply `RefreshDatabase` to the browser tests in `Pest.php`. A browser test hits the application through a real request, and the records that it leaves break the next test.
|
||||
- Add `tests/Browser/Screenshots` to `.gitignore`. A failure writes a screenshot, and the file is not part of the repository.
|
||||
- Give `withKeyDown()` a key code, such as `KeyA`. A letter such as `'a'` gives the lowercase character, whatever modifier the test holds.
|
||||
- Interact inside the callback of `withinFrame()`. An interaction outside the callback does not reach the frame.
|
||||
|
||||
## Testing Validation
|
||||
## Testing validation
|
||||
|
||||
- Write one test for each validation rule when each failure represents a separate contract.
|
||||
- Write one test with an empty payload to assert several required fields together.
|
||||
@@ -66,7 +66,7 @@ The plugin runs browser tests as normal Pest tests, so they need no separate sui
|
||||
|
||||
Send an input value that is not valid through the application, and assert the error. Do not assert that an array of rules contains a string, because that assertion tests the declaration and not the behavior. Use such an assertion only for a rule that no request can reach, and write the reason in the test.
|
||||
|
||||
### Which Layer Owns Which Case
|
||||
### Which layer owns which case
|
||||
|
||||
The rule-class test owns the matrix of values that pass and fail. The endpoint test proves that the endpoint applies the rule and that the user receives the message.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# How to Find Test Framework Features
|
||||
# How to find test framework features
|
||||
|
||||
Pest adds features faster than this skill can list them. Find an existing feature before implementing the behavior by hand.
|
||||
|
||||
@@ -22,11 +22,11 @@ Search for a feature in this table before you write the code by hand.
|
||||
| Assert that a value has a known format | validation expectations |
|
||||
| Run one test while you debug | filtering, `--bail`, `--dirty` |
|
||||
|
||||
## Built-in Laravel Assertion Methods
|
||||
## Built-in Laravel assertion methods
|
||||
|
||||
Laravel provides assertions for each part of the framework. Fetch `https://laravel.com/framework/docs/testing` for the complete list, and search for an assertion before building a check by hand. Examples include `assertDatabaseHas()`, `assertModelExists()`, `assertSoftDeleted()`, response assertions such as `assertRedirectToRoute()` and `assertJsonPath()`, and fake assertions such as `Queue::assertPushed()` and `Notification::assertSentTo()`.
|
||||
Laravel provides assertions for each part of the framework. Fetch `https://laravel.com/framework/docs/testing` for the complete list, and search for an assertion before you build a check by hand. Examples include `assertDatabaseHas()`, `assertModelExists()`, `assertSoftDeleted()`, response assertions such as `assertRedirectToRoute()` and `assertJsonPath()`, and fake assertions such as `Queue::assertPushed()` and `Notification::assertSentTo()`.
|
||||
|
||||
A hand-built check fails with `false is not true`, which identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure indicates what to fix.
|
||||
A hand-built check fails with `false is not true`. That message identifies nothing. A framework assertion names the incorrect table, value, or response, so the failure shows what to fix.
|
||||
|
||||
```php
|
||||
// The failure says that false is not true. Instead of this...
|
||||
|
||||
@@ -1,52 +1,52 @@
|
||||
# Fakes, Mocks, and Determinism
|
||||
# Fakes, mocks, and determinism
|
||||
|
||||
Tests that depend on actual time, randomness, sleeping, or network calls can fail for reasons unrelated to the code under test. Control all four.
|
||||
|
||||
## How to Isolate a Dependency
|
||||
## How to isolate a dependency
|
||||
|
||||
Fetch `https://laravel.com/framework/docs/mocking` for Laravel's fakes, facade doubles, and fake assertions. Confirm each name before using it.
|
||||
|
||||
Identify the dependency, then choose the first applicable option. A framework fake preserves the real code path, while a mock replaces the dependency.
|
||||
Identify the dependency, then choose the first option that applies. A framework fake preserves the real code path, while a mock replaces the dependency.
|
||||
|
||||
1. Always use framework fakes for facades such as events, queues, mail, notifications, storage, the HTTP client, time, and sleep.
|
||||
2. Use a developer-defined fake implementation of a service if the application provides one.
|
||||
3. Use a mock for a container-resolved contract only when the real implementation leaves the process or is nondeterministic.
|
||||
4. Use the real implementation for everything else, including the database.
|
||||
|
||||
## Framework Fakes
|
||||
## Framework fakes
|
||||
|
||||
- Create each fake inside the test that needs it. Do not create fakes in a file-level `beforeEach()`.
|
||||
- Pass class names to `Event::fake()` and `Queue::fake()` when you know which classes the code dispatches. A fake without class names can hide an unexpected dispatch.
|
||||
- Use a fake without class names only when the test asserts the complete result, including a call to `assertNothingPushed()`.
|
||||
- Write one assertion for each fake. The assertion states that the code dispatches the item, or that the code does not dispatch the item.
|
||||
- Assert the data of a job or of an event if that data is part of the behavior.
|
||||
- If the data of a job or an event is part of the behavior, assert that data.
|
||||
- Use `Exceptions::fake()` to assert that the application reports the correct exception. Do not use `withoutExceptionHandling()`, because it changes the response under test.
|
||||
|
||||
Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID, and a fake without class names suppresses those events and can produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.
|
||||
Create prerequisite factory records before calling `Event::fake()`. Factories use model events, such as a `creating` hook that generates a UUID. A fake without class names suppresses those events, and the factory can then produce an invalid model. Call the fake first only when a factory event is under test, and pass that event's class name.
|
||||
|
||||
## Mocking
|
||||
|
||||
Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. Use `Mockery::on()` or `withArgs()` if an equality check cannot state the expected argument, such as a check of one field of a value object.
|
||||
Use `shouldReceive()` before the action to declare an expectation. Use `shouldHaveReceived()` after the action for a spy. If an equality check cannot state the expected argument, such as a check of one field of a value object, use `Mockery::on()` or `withArgs()`.
|
||||
|
||||
Import the mock function before you use it: `use function Pest\Laravel\mock;`.
|
||||
|
||||
## Outbound HTTP Testing
|
||||
## Outbound HTTP testing
|
||||
|
||||
Call `Http::preventStrayRequests()`. Any request without a matching fake then fails without reaching the network.
|
||||
|
||||
Fake the exact endpoint used by each test. Do not call `Http::fake()` without an endpoint because it accepts unexpected requests and can hide defects.
|
||||
Fake the exact endpoint that each test calls. Do not call `Http::fake()` without an endpoint, because a fake without an endpoint accepts unexpected requests and can hide defects.
|
||||
|
||||
## Time and Randomness
|
||||
## Time and randomness
|
||||
|
||||
- Freeze the time or move the time in each test that depends on a date, a period, or a timestamp.
|
||||
- Use the framework helpers `freezeTime()`, `travelTo()`, `travel()`, and `travelBack()`. Do not call `Carbon::setTestNow()`.
|
||||
- Use `Str::createRandomStringsUsing()` to fix a generated string, if the test asserts an identifier or a slug.
|
||||
- If the test asserts an identifier or a slug, use `Str::createRandomStringsUsing()` to fix the generated string.
|
||||
- Use `Sleep::fake()` instead of a real sleep, and assert the sleeps that the code requests.
|
||||
- Restore the time and the randomness after each test, if the suite does not restore them for every test.
|
||||
- If the suite does not restore the time and the randomness for every test, restore them after each test.
|
||||
|
||||
## Database
|
||||
|
||||
- Run real queries against the real records in the test database. Do not mock the query builder, because the test then asserts the mock.
|
||||
- Assert the exact keys of `toArray()` if the shape of the serialized model is a contract. The test then fails when the model exposes a new attribute.
|
||||
- If the shape of the serialized model is a contract, assert the exact keys of `toArray()`. The test then fails when the model exposes a new attribute.
|
||||
- Test application behavior caused by the schema, such as deleting dependent records through a cascade. Do not test the database engine's cascade implementation.
|
||||
- Use `LazilyRefreshDatabase` instead of `RefreshDatabase`. A test that does not use the database then does not run the migrations.
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
# Naming and Structure
|
||||
# Naming and structure
|
||||
|
||||
## File Layout
|
||||
## File layout
|
||||
|
||||
- Name each test file `{ClassName}Test.php`.
|
||||
- Place each test file at the same relative path as the class under test. The class `app/Actions/DeleteTeam.php` gets the test `tests/Unit/Actions/DeleteTeamTest.php`.
|
||||
- Follow the project's convention for fixture files. If none exists, put fixtures in `tests/Fixtures/` and load them by path.
|
||||
- Move large literal values out of the test body and into fixture files.
|
||||
|
||||
## Test Function
|
||||
## Test function
|
||||
|
||||
Use the test function used by other files in the same directory. If no neighboring test files exist:
|
||||
Use the test function that other files in the same directory use. If no neighboring test files exist:
|
||||
|
||||
- Use `it()` for the behavior of the code, and write the name as a verb phrase.
|
||||
- Use `test()` for a declarative fact, such as a grant in a policy, the labels of an enum, or the shape of a serialized model.
|
||||
|
||||
Use one Pest declaration style in each file. Use either `it()` or `test()` consistently.
|
||||
|
||||
## Naming Tests
|
||||
## Naming tests
|
||||
|
||||
The name of a test is a specification. State the user-visible result and the condition that causes it.
|
||||
|
||||
- Name the behavior, and not the method under test. The file name already gives the class.
|
||||
- Name the behavior, not the method under test. The file name already gives the class.
|
||||
- Give the exact status code in the name of a test for an API error.
|
||||
- Do not write `Given`, `When`, or `Then` in the name.
|
||||
|
||||
@@ -32,11 +32,11 @@ it('falls back to the default region when none is configured', function () { ...
|
||||
|
||||
Use a verb that describes a result, such as `returns`, `renders`, `creates`, `dispatches`, `rejects`, `forbids`, `falls back`, or `does not`.
|
||||
|
||||
Do not write `it('works correctly')` or `it('returns data')`, because neither specifies a meaningful result. Do not write `it('handleMethod creates record')`, because it names a method rather than behavior.
|
||||
Do not write `it('works correctly')` or `it('returns data')`, because neither names a result. Do not write `it('handleMethod creates record')`, because that name gives a method rather than a behavior.
|
||||
|
||||
## Grouping
|
||||
|
||||
Use `describe()` if one file covers separate actions in a lifecycle. An example is a controller with the actions `index`, `show`, `store`, `update`, and `destroy`.
|
||||
If one file covers separate actions in a lifecycle, use `describe()`. An example is a controller with the actions `index`, `show`, `store`, `update`, and `destroy`.
|
||||
|
||||
Do not use `describe()` in these cases:
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Test Suite Performance
|
||||
# Test suite performance
|
||||
|
||||
These settings apply to the project and CI, not to individual tests. Read `rules/isolation.md` for choices within a test.
|
||||
|
||||
@@ -7,52 +7,52 @@ Verify each flag in the documentation before adding it to CI.
|
||||
|
||||
Measure before changing a setting. Find the slow test first, and apply a project-wide setting only after identifying the costly work.
|
||||
|
||||
## Test Environment
|
||||
## Test environment
|
||||
|
||||
- Set `BCRYPT_ROUNDS=4` in `.env.testing` or in `phpunit.xml`. The default value is 12, and the hash then takes most of the time of each test that signs a user in.
|
||||
- Disable XDebug. Disable pcov also, unless the run needs the coverage.
|
||||
- Disable Xdebug. Unless the run needs coverage, disable pcov too.
|
||||
- Disable packages that perform work on every request in the test environment. Examples are Pulse, Telescope, and Nightwatch.
|
||||
- Use the `WithCachedConfig` and `WithCachedRoutes` traits, so the run does not parse the configuration and the routes for every test.
|
||||
- Call `withoutVite()`, or `withoutMix()`, so the framework does not resolve a built asset.
|
||||
|
||||
## Global Fakes
|
||||
## Global fakes
|
||||
|
||||
Put these three calls in the base `Pest.php` of the project:
|
||||
|
||||
- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. This catches requests made through Laravel's HTTP client. Check direct Guzzle and cURL usage separately.
|
||||
- `Http::preventStrayRequests()`, because one request that reaches the network can slow the suite. It catches requests that go through Laravel's HTTP client. Check direct Guzzle and cURL usage separately.
|
||||
- `Sleep::fake(syncWithCarbon: true)`, so a retry and a backoff do not sleep.
|
||||
- `Exceptions::fake()`, so the suite does not report an exception to an external service.
|
||||
|
||||
## How to Run the Suite in Parallel
|
||||
## How to run the suite in parallel
|
||||
|
||||
Run `vendor/bin/pest --parallel` to spread tests across the machine's CPU cores. Add `--processes=N` if the default count is unsuitable for the machine or CI.
|
||||
Run `vendor/bin/pest --parallel` to spread tests across the machine's CPU cores. If the default count does not suit the machine or CI, add `--processes=N`.
|
||||
|
||||
A parallel run gives each process a separate database. Tests must meet these conditions; a test that fails only in parallel breaks one of them:
|
||||
A parallel run gives each process a separate database. Each test must meet the conditions below. A test that fails only in parallel breaks one of them.
|
||||
|
||||
- The test creates each record that it reads. It does not read a record that another test creates.
|
||||
- The test does not depend on the order of the run.
|
||||
- The test does not share a file, a cache key, or a queue with another test. Give each process a separate name for such a resource.
|
||||
|
||||
## How to Run Fewer Tests
|
||||
## How to run fewer tests
|
||||
|
||||
Run `vendor/bin/pest --parallel --tia` to run only the tests that the recent changes affect. Pest replays the cached result of each other test.
|
||||
|
||||
Pest replays cached results rather than skipping unaffected tests. The cache includes each produced value and the covered lines and branches. Pest finds affected Laravel, Symfony, Livewire, and Inertia tests without configuration.
|
||||
|
||||
## How to Split Tests Across CI
|
||||
## How to split tests across CI
|
||||
|
||||
Run `vendor/bin/pest --update-shards` to measure the time of each test. Run `vendor/bin/pest --shard=1/4` in each CI job, and change the first number for each job.
|
||||
|
||||
Commit `tests/.pest/shards.json` so each CI job gets the same shard and the shards remain balanced by runtime rather than test count.
|
||||
|
||||
## How to Find a Slow Test
|
||||
## How to find a slow test
|
||||
|
||||
Run `vendor/bin/pest --profile` to list the slowest tests. Start with the ten slowest tests, because the same cause often applies to the complete suite.
|
||||
|
||||
If the cause of a slow test is unclear, add an event listener or temporary log entry to identify its work.
|
||||
If the cause of a slow test is unclear, add an event listener or temporary log entry to identify the work the test does.
|
||||
|
||||
## Common Errors
|
||||
## Common errors
|
||||
|
||||
- The run loads XDebug for a test that does not need it.
|
||||
- The run loads Xdebug for a test that does not need it.
|
||||
- `BCRYPT_ROUNDS` keeps the default value, because the project has no `.env.testing`.
|
||||
- The code under test calls the real `sleep()`, and `Sleep::fake()` then does not help.
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
# Reviewing Tests
|
||||
# Reviewing tests
|
||||
|
||||
Check every item in this file. A passing test may still provide no value. For each test, identify the defect it would catch.
|
||||
Check every item in this file. A test can pass and still provide no value. For each test, identify the defect it would catch.
|
||||
|
||||
Report each finding. Do not delete or rewrite a test without the user's approval. When an issue appears throughout the suite as a convention, report the pattern once rather than every affected file.
|
||||
Report each finding. Do not delete or rewrite a test without the user's approval. If an issue appears throughout the suite as a convention, report the pattern once rather than once for each affected file.
|
||||
|
||||
## Test Value
|
||||
## Test value
|
||||
|
||||
Apply this section to behavioral tests. An architecture test states a convention for a directory, so these items do not apply to it.
|
||||
|
||||
- [ ] Each test covers observable behavior or an application contract, and passes after a change to the implementation that keeps the behavior.
|
||||
- [ ] Each tested declaration is exercised through behavior, and no test asserts the behavior of the framework. A test of what this project configures, such as a relation with a constraint, a cast, or a scope, belongs to this project.
|
||||
- [ ] Each test detects a distinct defect that no other test covers. A duplicate shrinks at the higher layer to the one case that proves the wiring.
|
||||
- [ ] Each test detects a distinct defect that no other test covers. Reduce a duplicate at the higher layer to the one case that proves the wiring.
|
||||
- [ ] Every changed decision and each applicable high-value failure mode has coverage.
|
||||
|
||||
## Names and Structure
|
||||
## Names and structure
|
||||
|
||||
- [ ] Each file has the name `{ClassName}Test.php` and the relative path of the class under test.
|
||||
- [ ] Each name states a result, the condition that causes it, and the status code for an API error.
|
||||
@@ -24,16 +24,16 @@ Apply this section to behavioral tests. An architecture test states a convention
|
||||
- [ ] HTTP tests cover authentication, authorization, role, scope, and validation when applicable.
|
||||
- [ ] A request for a record of a different tenant gets a status code that does not confirm that the record exists.
|
||||
- [ ] The complete permission matrix belongs in policy tests, not controller tests.
|
||||
- [ ] Each validation rule has one test that asserts the user-visible message. When a unit test owns a matrix, reduce duplicate higher-level coverage to one case rather than deleting it.
|
||||
- [ ] Each validation rule has one test that asserts the user-visible message. If a unit test covers a matrix, reduce the duplicate higher-level coverage to one case rather than deleting it.
|
||||
- [ ] Rendered user input and each dynamic part of a query have a security test.
|
||||
|
||||
## Data and Determinism
|
||||
## Data and determinism
|
||||
|
||||
- [ ] Each test creates its mutable records directly or through a helper that it calls, and every created record arranges the behavior or supports an assertion.
|
||||
- [ ] Each `beforeEach()` holds configuration only.
|
||||
- [ ] Each factory state and each relationship gives the meaning of the data.
|
||||
- [ ] Each call to `make()` is in a test that does not need the database.
|
||||
- [ ] Time, randomness, sleep, and outbound HTTP are controlled.
|
||||
- [ ] Each test controls time, randomness, sleep, and outbound HTTP.
|
||||
- [ ] Each test passes alone, and passes in the complete suite in any order.
|
||||
|
||||
## Assertions
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# Security Tests
|
||||
# Security tests
|
||||
|
||||
Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary can be difficult to detect because the feature may continue to work.
|
||||
Test each security boundary where user input affects authorization, rendered output, or query construction. A defect at such a boundary is hard to detect, because the feature can keep working.
|
||||
|
||||
Write a test for each of these cases:
|
||||
|
||||
- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for why the response should possibly be `404` rather than `403`.
|
||||
- **Cross-tenant access.** Request a record of a different tenant, team, or organization. Read `rules/endpoint-tests.md` for when the response should be `404` rather than `403`.
|
||||
- **Each unprivileged role.** Use a dataset over the roles that the endpoint must refuse.
|
||||
- **Escaping user-provided content.** Test escaping in HTML and mail. Include names and every free-text field a template renders. Assert that dangerous characters are escaped and the raw value is absent. Do not assert an exact entity for a quote, because Markdown and mail CSS inliners may decode it.
|
||||
- **Escaping user-provided content.** Test escaping in HTML and mail. Include names and every free-text field a template renders. Assert that dangerous characters are escaped and the raw value is absent. Do not assert an exact entity for a quote, because Markdown and mail CSS inliners can decode it.
|
||||
- **Injection into dynamic query components.** Examples include sort columns, filter fields, and sort directions.
|
||||
- **An unexpected key** in a payload or configuration array. A merge that accepts every key can set an attribute the user must not control.
|
||||
|
||||
@@ -24,4 +24,4 @@ it('escapes dangerous content in the notification', function () {
|
||||
});
|
||||
```
|
||||
|
||||
Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the appropriate defense to each attribute, route, and template.
|
||||
Laravel provides defenses against mass assignment, unauthorized access, and unescaped output. Test that the application applies the correct defense to each attribute, route, and template.
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
# Factories and Test Data
|
||||
# Factories and test data
|
||||
|
||||
## Each Test Makes Its Own Data
|
||||
## Each test makes its own data
|
||||
|
||||
Create mutable records inside the test that uses them. This keeps setup visible and lets each test select its factory state.
|
||||
Create mutable records inside the test that uses them. The setup then stays visible, and each test can select its factory state.
|
||||
|
||||
Use `beforeEach()` only for configuration that applies to every test in the file. Do not create records in it.
|
||||
|
||||
## Record Construction
|
||||
## Record construction
|
||||
|
||||
- Use `create()` if the test needs the record in the database.
|
||||
- Use `make()` only if the test does not need the database. Examples include rendering a notification and testing a value object's behavior.
|
||||
- Use a named factory state instead of a raw attribute. `User::factory()->unverified()->create()` gives the state meaning; `create(['email_verified_at' => null])` gives only its value.
|
||||
- Use a named factory state instead of a raw attribute. `User::factory()->unverified()->create()` gives the state meaning. `create(['email_verified_at' => null])` gives only its value.
|
||||
- Use `for()` or the relationship helper of the project to declare the owner of a record.
|
||||
- Use `recycle()` if several records must share one parent record.
|
||||
- Use `sequence()` if several records need different attributes.
|
||||
- If several records must share one parent record, use `recycle()`.
|
||||
- If several records need different attributes, use `sequence()`.
|
||||
|
||||
```php
|
||||
$organization = Organization::factory()->onPlan(BillingPlan::PRO)->create();
|
||||
@@ -51,6 +51,6 @@ Use parameterized tests for:
|
||||
- input values that are invalid in the same way
|
||||
- input and output value pairs
|
||||
|
||||
Write separate tests if the cases need a different setup, a different behavior, or different assertions. One test function with a branch in the body is two tests in one function.
|
||||
If the cases need a different setup, a different behavior, or different assertions, write separate tests. One test function with a branch in the body is two tests in one function.
|
||||
|
||||
Give each dataset case a name that states the difference. A failure then identifies the case without requiring you to count positions.
|
||||
|
||||
Reference in New Issue
Block a user