From 948d1aa8b0f91ff4562311b67d80a5b0db7df906 Mon Sep 17 00:00:00 2001 From: Mior Muhammad Zaki Date: Thu, 6 Jun 2024 22:19:27 +0800 Subject: [PATCH] [11.x] Test Improvements (#51723) * [11.x] Test Improvements Add tests for `once()` usage on static methods. * wip Signed-off-by: Mior Muhammad Zaki --------- Signed-off-by: Mior Muhammad Zaki --- tests/Integration/Support/OnceHelperTest.php | 88 ++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 tests/Integration/Support/OnceHelperTest.php diff --git a/tests/Integration/Support/OnceHelperTest.php b/tests/Integration/Support/OnceHelperTest.php new file mode 100644 index 000000000000..ef96cda24b01 --- /dev/null +++ b/tests/Integration/Support/OnceHelperTest.php @@ -0,0 +1,88 @@ +times(3)->create(); + UserFactory::new()->times(2)->unverified()->create(); + } + + public function testItCanCacheStaticMethodWithoutParameters() + { + DB::enableQueryLog(); + DB::flushQueryLog(); + + $verifiedUsers = User::verified(); + $unverifiedUsers = User::unverified(); + + $this->assertCount(3, $verifiedUsers); + $this->assertCount(2, $unverifiedUsers); + $this->assertCount(2, DB::getQueryLog()); + + $verifiedUsers2 = User::verified(); + + $this->assertCount(2, DB::getQueryLog()); + + $this->assertSame($verifiedUsers, $verifiedUsers2); + + DB::disableQueryLog(); + } + + public function testItCanCacheStaticMethodWithParameters() + { + DB::enableQueryLog(); + DB::flushQueryLog(); + + $verifiedUsers = User::getByType('verified'); + $unverifiedUsers = User::getByType('unverified'); + + $this->assertCount(3, $verifiedUsers); + $this->assertCount(2, $unverifiedUsers); + $this->assertCount(2, DB::getQueryLog()); + + $verifiedUsers2 = User::getByType('verified'); + + $this->assertCount(2, DB::getQueryLog()); + + $this->assertSame($verifiedUsers, $verifiedUsers2); + + DB::disableQueryLog(); + } +} + +class User extends Authenticatable +{ + public static function verified(): Collection + { + return once(fn () => self::whereNotNull('email_verified_at')->get()); + } + + public static function unverified(): Collection + { + return once(fn () => self::whereNull('email_verified_at')->get()); + } + + public static function getByType(string $type): Collection + { + return once(function () use ($type) { + return match ($type) { + 'verified' => self::whereNotNull('email_verified_at')->get(), + 'unverified' => self::whereNull('email_verified_at')->get() + }; + }); + } +}