Testing
namespace Tests\Feature;
use App\Access\Controls\PostControl;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Lomkit\Access\Testing\InteractsWithAccess;
use Tests\TestCase;
class PostControlTest extends TestCase
{
use InteractsWithAccess, RefreshDatabase;
public function test_its_rules_agree(): void
{
// Give each reader the permissions your application gives it.
$admin = User::factory()->create(['client_id' => 1]); // "... all posts"
$manager = User::factory()->create(['client_id' => 1]); // "... client posts"
$author = User::factory()->create(['client_id' => 1]); // "... own posts"
$other = User::factory()->create(['client_id' => 2]); // "... own posts"
Post::factory()->create(['client_id' => 1, 'author_id' => $author->id]);
Post::factory()->create(['client_id' => 1, 'author_id' => $manager->id]);
Post::factory()->create(['client_id' => 2, 'author_id' => $other->id]);
$readers = [$admin, $manager, $author, $other];
foreach ($readers as $reader) {
$this->assertControlAgrees(PostControl::class, $reader, Post::uncontrolled()->get());
}
$this->assertLevelsNest(PostControl::class, readers: $readers);
$this->assertSearchAgrees(PostControl::class, readers: $readers); // with Laravel Scout
}
}
The Lomkit\Access\Testing\InteractsWithAccess trait adds assertions that compare the ways of deciding with each other, for the readers and the rows of your test.
The decisions
assertControlAgrees() checks that every way of deciding gives the same answer, for each ability and each row:
$this->assertControlAgrees(PostControl::class, $reader, Post::uncontrolled()->get());
$this->assertControlAgrees(PostControl::class, $reader, $posts, ['view', 'update', 'approve']);
It compares four paths:
- the Gate, row by row, with no decision kept;
- the Gate after
Access::preload(); - the Gate after
withAbilities(); - whether
controlledFor($reader, $ability)lists the row.
The abilities default to view, update and delete; pass others as the fourth argument. create is compared through the Gate only, since it is judged on drafts, and viewAny too, since it decides without a row. The rows must be saved rows of the control's model.
A failure names the reader, then each row key and ability that disagree, with the answer of each path: granted, a refusal code, or denied without a code when no policy decided. The usual causes:
- a
should()callback or anincludes()hook that describes other rows than itsquery(); - a policy method that adds its own rule, such as an
update()override that refuses some rows: the Gate then grants fewer rows thancontrolled('update')lists. Move the rule into the control, see Policies.
The levels
assertLevelsNest() checks, for each reader and each pair of adjacent levels of every Levels::of() group, that no row of the lower level, inside the boundary, is missing from the upper level:
$this->assertLevelsNest(PostControl::class, readers: [$author, $manager, $admin]);
It reads the rows of the query() callbacks for view, not the allowed() callbacks, and compares them with not exists on the key, so a NULL in a column cannot hide a missing row. Seed the rows that each level reaches. See Levels.
The search
assertSearchAgrees() checks, for each reader, that the rows the search keys find are the rows of the controlled query:
$this->assertSearchAgrees(PostControl::class, readers: [$admin, $manager, $author]);
- It computes the keys of the rows and of the readers from the same declarations as the indexing, without any engine, and compares their digests, as the engine receives them. It proves the logic of your keys, not the behaviour of the engine.
- A failure lists the readable keys of the reader and of each row in disagreement, the first ten of each list.
- A perimeter that applies to the reader without search keys makes it fail: the search would be narrower than the SQL.
The clock check
Before comparing, the assertion checks that each row gets the same keys at any instant, since an index keeps the keys of the instant the row was written. It computes the keys of the rows of the test at the current instant, and again with the clock frozen 400 days earlier and 400 days later, and fails when the keys of a row differ.
- The failure names the row, the field and the key rules: a
rowcallback that reads the clock, or one that gives other keys each time, such asfirst()on a relation without an order. See Rights that depend on the date. - It sees what reads Laravel's clock:
now(),Date::now(),Illuminate\Support\Carbon::now(),Carbon\Carbon::now()andCarbon\CarbonImmutable::now(). It does not see PHP'stime(),date()ornew DateTimeImmutable(), nor a databaseNOW(). - It catches a clock read only when the keys of a test row change between these instants: give the rows of the test a period that starts or ends within 400 days of the instant of the test.
- The clock is set back afterwards, also after a failure: a test that froze it with
travelTo()keeps its instant.
A test that runs controlled searches uses the database engine, not collection, which refuses them:
<env name="SCOUT_DRIVER" value="database"/>
An index of your own
assertIndexKeysAgree() checks the same for an index of your own, on a model with or without ControlledSearchable: for each reader, null included, the rows whose Access::indexKeysOf() values meet the Access::indexReaderKeys() values in each field must be the rows of controlledFor():
$this->assertIndexKeysAgree(PostControl::class, readers: [null, $admin, $manager, $author]);
It runs the same clock check as assertSearchAgrees().
Several brands
assertRowContextAgrees() checks a parent decided in the context of the child row, with decidedInRowContext(). See Row context.
Kept decisions in tests
The tests need no reset trait: the kept decisions live in a scoped instance of the container, so each test starts with none, and every write through a Laravel connection forgets them, attach() and writes under Event::fake() included, as long as the connection was opened before Event::fake(): a connection opened after it sends its events to the fake and forgets nothing.
After a permission changed in memory, such as a Gate::define() between two checks, call Access::forgetDecisions() before the next check:
Gate::define('update own posts', fn (User $user) => false);
Access::forgetDecisions();
$this->assertFalse($author->can('update', $post));
Pure perimeter lists in tests
In tests, the package builds the perimeters of a control again each time it hands it out, and throws ImpurePerimetersException when they differ: see Controls.
With Laravel Scout installed and without access:cache, the first Eloquent write of a test, such as a factory in setUp(), builds the control of every discovered ControlledSearchable model, to know which writes reindex which documents. Set what perimeters() and boundary() read before that first write, or read it in the callbacks.
laravel-rest-api
With laravel-rest-api 3.6+, AccessControlExtension applies your controls to every resource of a controlled model, its text searches and row checks included.
access:check
php artisan access:check builds every control and reports in CI what would throw, open or hide rows, or leave search documents stale.