From 7df3863880a45b8fcab02b57e1de0b70da7cc10a Mon Sep 17 00:00:00 2001 From: Mohammad Alavi Date: Mon, 3 Jun 2024 18:56:06 +0330 Subject: [PATCH] test(unit): add repository test --- .../Infrastructure/Doubles/UserRepository.php | 17 +++++ .../Abstracts/Repositories/RepositoryTest.php | 73 +++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 tests/Infrastructure/Doubles/UserRepository.php create mode 100644 tests/Unit/Abstracts/Repositories/RepositoryTest.php diff --git a/tests/Infrastructure/Doubles/UserRepository.php b/tests/Infrastructure/Doubles/UserRepository.php new file mode 100644 index 00000000..f71333db --- /dev/null +++ b/tests/Infrastructure/Doubles/UserRepository.php @@ -0,0 +1,17 @@ + 'ilike', + ]; + + public function model(): string + { + return User::class; + } +} diff --git a/tests/Unit/Abstracts/Repositories/RepositoryTest.php b/tests/Unit/Abstracts/Repositories/RepositoryTest.php new file mode 100644 index 00000000..6d676186 --- /dev/null +++ b/tests/Unit/Abstracts/Repositories/RepositoryTest.php @@ -0,0 +1,73 @@ +set('apiato.requests.params.include', 'include'); + } + + public static function includeDataProvider(): array + { + return [ + 'single relation' => ['parent', ['parent'], ['children']], + 'multiple relations' => ['parent,children', ['parent', 'children'], []], + 'single nested relation' => ['children.parent', ['children'], []], + 'multiple nested relations' => ['parent.children,children', ['parent', 'children'], []], + 'multiple and single nested relations' => ['parent.children,children.parent', ['parent', 'children'], []], + ]; + } + + #[DataProvider('includeDataProvider')] + public function testEagerLoadSingleRelationRequestedViaRequest(string $includes, array $mustLoadRelations, array $mustNotLoadRelations): void + { + request()->offsetSet(config('apiato.requests.params.include'), $includes); + $parent = UserFactory::new()->has( + UserFactory::new()->count(3), + 'children' + )->count(3)->create(); + $repository = app(UserRepository::class); + + // get all children + $result = $repository->all(); + + $result->each(function (User $user) use ($mustLoadRelations, $mustNotLoadRelations) { + foreach ($mustLoadRelations as $relation) { + $this->assertTrue($user->relationLoaded($relation)); + } + foreach ($mustNotLoadRelations as $relation) { + $this->assertFalse($user->relationLoaded($relation)); + } + }); + } + + public function testMultipleEagerLoadAppliesAllEagerLoads(): void + { + $parent = UserFactory::new()->createOne(); + $children = UserFactory::new()->count(3)->create(['parent_id' => $parent->id]); + $repository = app(UserRepository::class); + + /** @var Collection $result */ + $result = $repository->with('parent')->with('children')->all(); + + $result->each(function (User $user) { + $this->assertTrue($user->relationLoaded('parent')); + $this->assertTrue($user->relationLoaded('children')); + }); + } +}