From 177808c3a50284ca1ff8ab116225d83fe8fd5439 Mon Sep 17 00:00:00 2001 From: kenjis Date: Thu, 2 Jun 2022 15:12:58 +0900 Subject: [PATCH 1/3] refactor: add return type --- src/Auth.php | 2 +- src/Authentication/Actions/Email2FA.php | 2 +- .../AuthenticationException.php | 8 +--- src/Authentication/Authenticators/Session.php | 2 +- .../Passwords/NothingPersonalValidator.php | 14 ++----- src/Models/RememberModel.php | 4 +- tests/Authentication/AccessTokenTest.php | 12 +++--- tests/Authentication/AuthHelperTest.php | 10 ++--- tests/Authentication/AuthenticationTest.php | 4 +- .../AccessTokenAuthenticatorTest.php | 22 +++++------ .../SessionAuthenticatorTest.php | 38 +++++++++---------- .../Filters/ChainFilterTest.php | 6 +-- .../Filters/SessionFilterTest.php | 10 ++--- .../Filters/TokenFilterTest.php | 10 ++--- tests/Authentication/HasAccessTokensTest.php | 20 +++++----- tests/Authentication/MagicLinkTest.php | 14 +++---- tests/Authorization/AuthorizableTest.php | 30 +++++++-------- tests/Authorization/GroupTest.php | 10 ++--- tests/Authorization/GroupsTest.php | 10 ++--- tests/Collectors/AuthTest.php | 10 ++--- tests/Controllers/ActionsTest.php | 24 ++++++------ tests/Controllers/LoginTest.php | 10 ++--- tests/Controllers/RegisterTest.php | 14 +++---- tests/Unit/AuthRoutesTest.php | 4 +- tests/Unit/CompositionValidatorTest.php | 6 +-- tests/Unit/DictionaryValidatorTest.php | 4 +- tests/Unit/LoginModelTest.php | 2 +- tests/Unit/NothingPersonalValidatorTest.php | 14 +++---- tests/Unit/PasswordsTest.php | 2 +- tests/Unit/PwnedValidatorTest.php | 8 ++-- tests/Unit/UserIdentityModelTest.php | 4 +- tests/Unit/UserTest.php | 16 ++++---- 32 files changed, 166 insertions(+), 180 deletions(-) diff --git a/src/Auth.php b/src/Auth.php index d3abf1d02..2d9b92705 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -102,7 +102,7 @@ public function routes(RouteCollection &$routes, array $config = []): void { $authRoutes = config('AuthRoutes')->routes; - $routes->group('/', ['namespace' => 'CodeIgniter\Shield\Controllers'], static function (RouteCollection $routes) use ($authRoutes, $config) { + $routes->group('/', ['namespace' => 'CodeIgniter\Shield\Controllers'], static function (RouteCollection $routes) use ($authRoutes, $config): void { foreach ($authRoutes as $name => $row) { if (! isset($config['except']) || (isset($config['except']) && ! in_array($name, $config['except'], true))) { foreach ($row as $params) { diff --git a/src/Authentication/Actions/Email2FA.php b/src/Authentication/Actions/Email2FA.php index 7f61dd289..7c781f285 100644 --- a/src/Authentication/Actions/Email2FA.php +++ b/src/Authentication/Actions/Email2FA.php @@ -115,7 +115,7 @@ public function afterLogin(User $user): void $this->createIdentity($user); } - private function createIdentity(User $user) + private function createIdentity(User $user): void { /** @var UserIdentityModel $identityModel */ $identityModel = model(UserIdentityModel::class); diff --git a/src/Authentication/AuthenticationException.php b/src/Authentication/AuthenticationException.php index cb8636b3e..d1311a039 100644 --- a/src/Authentication/AuthenticationException.php +++ b/src/Authentication/AuthenticationException.php @@ -35,10 +35,8 @@ public static function forNoEntityProvided(): self /** * Fires when no minimumPasswordLength has been set * in the Auth config file. - * - * @return self */ - public static function forUnsetPasswordLength() + public static function forUnsetPasswordLength(): self { return new self(lang('Auth.unsetPasswordLength'), 500); } @@ -46,10 +44,8 @@ public static function forUnsetPasswordLength() /** * When the cURL request (to Have I Been Pwned) in PwnedValidator * throws a HTTPException it is re-thrown as this one - * - * @return self */ - public static function forHIBPCurlFail(HTTPException $e) + public static function forHIBPCurlFail(HTTPException $e): self { return new self($e->getMessage(), $e->getCode(), $e); } diff --git a/src/Authentication/Authenticators/Session.php b/src/Authentication/Authenticators/Session.php index f2cc38b27..0840dbec9 100644 --- a/src/Authentication/Authenticators/Session.php +++ b/src/Authentication/Authenticators/Session.php @@ -810,7 +810,7 @@ private function hashValidator(string $validator): string return hash('sha256', $validator); } - private function refreshRememberMeToken(stdClass $token) + private function refreshRememberMeToken(stdClass $token): void { // Update validator. $validator = bin2hex(random_bytes(20)); diff --git a/src/Authentication/Passwords/NothingPersonalValidator.php b/src/Authentication/Passwords/NothingPersonalValidator.php index d5fa510f6..0523a7bdd 100644 --- a/src/Authentication/Passwords/NothingPersonalValidator.php +++ b/src/Authentication/Passwords/NothingPersonalValidator.php @@ -49,10 +49,8 @@ public function check(string $password, ?User $user = null): Result * * isNotPersonal() returns true if no personal information can be found, or false * if such info is found. - * - * @return bool */ - protected function isNotPersonal(string $password, ?User $user) + protected function isNotPersonal(string $password, ?User $user): bool { $userName = \strtolower($user->username); $email = \strtolower($user->email); @@ -150,10 +148,8 @@ protected function isNotPersonal(string $password, ?User $user) * * A $maxSimilarity value of 0 (zero) returns true without making a comparison. * In other words, 0 (zero) turns off similarity testing. - * - * @return bool */ - protected function isNotSimilar(string $password, ?User $user) + protected function isNotSimilar(string $password, ?User $user): bool { $maxSimilarity = (float) $this->config->maxSimilarity; // sanity checking - working range 1-100, 0 is off @@ -183,12 +179,8 @@ protected function isNotSimilar(string $password, ?User $user) * * Replaces all non-word characters and underscores in $str with a space. * Then it explodes that result using the space for a delimiter. - * - * @param string $str - * - * @return array */ - protected function strip_explode($str) + protected function strip_explode(string $str): array { $stripped = \preg_replace('/[\W_]+/', ' ', $str); $parts = \explode(' ', \trim($stripped)); diff --git a/src/Models/RememberModel.php b/src/Models/RememberModel.php index d36dc3f30..b3f05a0f4 100644 --- a/src/Models/RememberModel.php +++ b/src/Models/RememberModel.php @@ -42,10 +42,8 @@ public function rememberUser(User $user, string $selector, string $hashedValidat /** * Returns the remember-me token info for a given selector. - * - * @return stdClass|null */ - public function getRememberToken(string $selector) + public function getRememberToken(string $selector): ?stdClass { return $this->where('selector', $selector) ->get() diff --git a/tests/Authentication/AccessTokenTest.php b/tests/Authentication/AccessTokenTest.php index 60ee28c02..ff14cf53d 100644 --- a/tests/Authentication/AccessTokenTest.php +++ b/tests/Authentication/AccessTokenTest.php @@ -10,14 +10,14 @@ */ final class AccessTokenTest extends DatabaseTestCase { - public function testCanNoScopes() + public function testCanNoScopes(): void { $token = new AccessToken(); $this->assertFalse($token->can('foo')); } - public function testCanWildcard() + public function testCanWildcard(): void { $token = new AccessToken([ 'extra' => ['*'], @@ -27,7 +27,7 @@ public function testCanWildcard() $this->assertTrue($token->can('bar')); } - public function testCanSuccess() + public function testCanSuccess(): void { $token = new AccessToken([ 'extra' => ['foo'], @@ -37,14 +37,14 @@ public function testCanSuccess() $this->assertFalse($token->can('bar')); } - public function testCantNoScopes() + public function testCantNoScopes(): void { $token = new AccessToken(); $this->assertTrue($token->cant('foo')); } - public function testCantWildcard() + public function testCantWildcard(): void { $token = new AccessToken([ 'extra' => ['*'], @@ -54,7 +54,7 @@ public function testCantWildcard() $this->assertFalse($token->cant('bar')); } - public function testCantSuccess() + public function testCantSuccess(): void { $token = new AccessToken([ 'extra' => ['foo'], diff --git a/tests/Authentication/AuthHelperTest.php b/tests/Authentication/AuthHelperTest.php index 44ed3ab6e..3c0481179 100644 --- a/tests/Authentication/AuthHelperTest.php +++ b/tests/Authentication/AuthHelperTest.php @@ -31,21 +31,21 @@ protected function setUp(): void $this->setPrivateProperty(auth(), 'alias', null); } - public function testAuthReturnsDefaultAuthenticator() + public function testAuthReturnsDefaultAuthenticator(): void { $authenticatorClassname = config('Auth')->authenticators[config('Auth')->defaultAuthenticator]; $this->assertInstanceOf($authenticatorClassname, auth()->getAuthenticator()); } - public function testAuthReturnsSpecifiedAuthenticator() + public function testAuthReturnsSpecifiedAuthenticator(): void { $authenticatorClassname = config('Auth')->authenticators['tokens']; $this->assertInstanceOf($authenticatorClassname, auth('tokens')->getAuthenticator()); } - public function testAuthThrowsWithInvalidAuthenticator() + public function testAuthThrowsWithInvalidAuthenticator(): void { $this->expectException(AuthenticationException::class); $this->expectExceptionMessage(lang('Auth.unknownAuthenticator', ['foo'])); @@ -53,13 +53,13 @@ public function testAuthThrowsWithInvalidAuthenticator() auth('foo')->user(); } - public function testUserIdReturnsNull() + public function testUserIdReturnsNull(): void { $this->assertFalse(auth()->loggedIn()); $this->assertNull(user_id()); } - public function testUserIdReturnsId() + public function testUserIdReturnsId(): void { $user = fake(UserModel::class, ['id' => 1]); $this->setPrivateProperty(auth()->getAuthenticator(), 'user', $user); diff --git a/tests/Authentication/AuthenticationTest.php b/tests/Authentication/AuthenticationTest.php index 3ce0c69a9..c4563b87f 100644 --- a/tests/Authentication/AuthenticationTest.php +++ b/tests/Authentication/AuthenticationTest.php @@ -25,7 +25,7 @@ protected function setUp(): void $this->auth->setProvider(new UserModel()); } - public function testThrowsOnUnknownAuthenticator() + public function testThrowsOnUnknownAuthenticator(): void { $this->expectException(AuthenticationException::class); $this->expectExceptionMessage(lang('Auth.unknownAuthenticator', ['foo'])); @@ -33,7 +33,7 @@ public function testThrowsOnUnknownAuthenticator() $this->auth->factory('foo'); } - public function testFactoryLoadsDefault() + public function testFactoryLoadsDefault(): void { $shield1 = $this->auth->factory(); $shield2 = $this->auth->factory('session'); diff --git a/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php b/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php index 6bb8afded..d3ec2046d 100644 --- a/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/AccessTokenAuthenticatorTest.php @@ -37,7 +37,7 @@ protected function setUp(): void Services::injectMock('events', new MockEvents()); } - public function testLogin() + public function testLogin(): void { $user = fake(UserModel::class); @@ -48,7 +48,7 @@ public function testLogin() $this->assertSame($user->id, $this->auth->getUser()->id); } - public function testLogout() + public function testLogout(): void { // this one's a little odd since it's stateless, but roll with it... $user = fake(UserModel::class); @@ -60,7 +60,7 @@ public function testLogout() $this->assertNull($this->auth->getUser()); } - public function testLoginByIdNoToken() + public function testLoginByIdNoToken(): void { $user = fake(UserModel::class); @@ -72,7 +72,7 @@ public function testLoginByIdNoToken() $this->assertNull($this->auth->getUser()->currentAccessToken()); } - public function testLoginByIdWithToken() + public function testLoginByIdWithToken(): void { /** @var User $user */ $user = fake(UserModel::class); @@ -87,7 +87,7 @@ public function testLoginByIdWithToken() $this->assertSame($token->id, $this->auth->getUser()->currentAccessToken()->id); } - public function testLoginByIdWithMultipleTokens() + public function testLoginByIdWithMultipleTokens(): void { /** @var User $user */ $user = fake(UserModel::class); @@ -103,7 +103,7 @@ public function testLoginByIdWithMultipleTokens() $this->assertSame($token1->id, $this->auth->getUser()->currentAccessToken()->id); } - public function testCheckNoToken() + public function testCheckNoToken(): void { $result = $this->auth->check([]); @@ -111,7 +111,7 @@ public function testCheckNoToken() $this->assertSame(lang('Auth.noToken'), $result->reason()); } - public function testCheckBadToken() + public function testCheckBadToken(): void { $result = $this->auth->check(['token' => 'abc123']); @@ -135,7 +135,7 @@ public function testCheckOldToken() $this->assertSame(lang('Auth.oldToken'), $result->reason()); } - public function testCheckSuccess() + public function testCheckSuccess(): void { /** @var User $user */ $user = fake(UserModel::class); @@ -157,7 +157,7 @@ public function testCheckSuccess() $this->assertNotEmpty($updatedToken->last_used_at); } - public function testAttemptCannotFindUser() + public function testAttemptCannotFindUser(): void { $result = $this->auth->attempt([ 'token' => 'abc123', @@ -175,7 +175,7 @@ public function testAttemptCannotFindUser() ]); } - public function testAttemptSuccess() + public function testAttemptSuccess(): void { /** @var User $user */ $user = fake(UserModel::class); @@ -203,7 +203,7 @@ public function testAttemptSuccess() ]); } - protected function setRequestHeader(string $token) + protected function setRequestHeader(string $token): void { $request = service('request'); $request->setHeader('Authorization', 'Bearer ' . $token); diff --git a/tests/Authentication/Authenticators/SessionAuthenticatorTest.php b/tests/Authentication/Authenticators/SessionAuthenticatorTest.php index ec75ad0ca..848b22fd1 100644 --- a/tests/Authentication/Authenticators/SessionAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/SessionAuthenticatorTest.php @@ -46,12 +46,12 @@ protected function setUp(): void $this->db->table('auth_identities')->truncate(); } - public function testLoggedInFalse() + public function testLoggedInFalse(): void { $this->assertFalse($this->auth->loggedIn()); } - public function testLoggedInTrue() + public function testLoggedInTrue(): void { $_SESSION['user']['id'] = $this->user->id; @@ -62,7 +62,7 @@ public function testLoggedInTrue() $this->assertSame($this->user->id, $authUser->id); } - public function testLoggedInWithRememberCookie() + public function testLoggedInWithRememberCookie(): void { unset($_SESSION['user']); @@ -88,7 +88,7 @@ public function testLoggedInWithRememberCookie() $this->assertSame($this->user->id, $authUser->id); } - public function testLoginNoRemember() + public function testLoginNoRemember(): void { $this->user->createEmailIdentity(['email' => 'foo@example.com', 'password' => 'secret']); @@ -101,7 +101,7 @@ public function testLoginNoRemember() ]); } - public function testLoginWithRemember() + public function testLoginWithRemember(): void { $this->user->createEmailIdentity(['email' => 'foo@example.com', 'password' => 'secret']); @@ -118,7 +118,7 @@ public function testLoginWithRemember() $this->assertNotNull($response->getCookie('remember')); } - public function testLogout() + public function testLogout(): void { $this->user->createEmailIdentity(['email' => 'foo@example.com', 'password' => 'secret']); $this->auth->remember()->login($this->user); @@ -131,7 +131,7 @@ public function testLogout() $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); } - public function testLoginByIdBadUser() + public function testLoginByIdBadUser(): void { $this->expectException(AuthenticationException::class); $this->expectExceptionMessage(lang('Auth.invalidUser')); @@ -139,7 +139,7 @@ public function testLoginByIdBadUser() $this->auth->loginById(123); } - public function testLoginById() + public function testLoginById(): void { $this->user->createEmailIdentity(['email' => 'foo@example.com', 'password' => 'secret']); @@ -150,7 +150,7 @@ public function testLoginById() $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); } - public function testLoginByIdRemember() + public function testLoginByIdRemember(): void { $this->user->createEmailIdentity(['email' => 'foo@example.com', 'password' => 'secret']); @@ -161,7 +161,7 @@ public function testLoginByIdRemember() $this->seeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); } - public function testForgetCurrentUser() + public function testForgetCurrentUser(): void { $this->user->createEmailIdentity(['email' => 'foo@example.com', 'password' => 'secret']); $this->auth->remember()->loginById($this->user->id); @@ -174,7 +174,7 @@ public function testForgetCurrentUser() $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); } - public function testForgetAnotherUser() + public function testForgetAnotherUser(): void { fake(RememberModel::class, ['user_id' => $this->user->id]); @@ -185,7 +185,7 @@ public function testForgetAnotherUser() $this->dontSeeInDatabase('auth_remember_tokens', ['user_id' => $this->user->id]); } - public function testCheckNoPassword() + public function testCheckNoPassword(): void { $result = $this->auth->check([ 'email' => 'johnsmith@example.com', @@ -196,7 +196,7 @@ public function testCheckNoPassword() $this->assertSame(lang('Auth.badAttempt'), $result->reason()); } - public function testCheckCannotFindUser() + public function testCheckCannotFindUser(): void { $result = $this->auth->check([ 'email' => 'johnsmith@example.com', @@ -208,7 +208,7 @@ public function testCheckCannotFindUser() $this->assertSame(lang('Auth.badAttempt'), $result->reason()); } - public function testCheckBadPassword() + public function testCheckBadPassword(): void { $this->user->createEmailIdentity([ 'email' => 'foo@example.com', @@ -225,7 +225,7 @@ public function testCheckBadPassword() $this->assertSame(lang('Auth.invalidPassword'), $result->reason()); } - public function testCheckSuccess() + public function testCheckSuccess(): void { $this->user->createEmailIdentity([ 'email' => 'foo@example.com', @@ -244,7 +244,7 @@ public function testCheckSuccess() $this->assertSame($this->user->id, $foundUser->id); } - public function testAttemptCannotFindUser() + public function testAttemptCannotFindUser(): void { $result = $this->auth->attempt([ 'email' => 'johnsmith@example.com', @@ -262,7 +262,7 @@ public function testAttemptCannotFindUser() ]); } - public function testAttemptSuccess() + public function testAttemptSuccess(): void { $this->user->createEmailIdentity([ 'email' => 'foo@example.com', @@ -292,7 +292,7 @@ public function testAttemptSuccess() ]); } - public function testAttemptCaseInsensitive() + public function testAttemptCaseInsensitive(): void { $this->user->createEmailIdentity([ 'email' => 'FOO@example.com', @@ -322,7 +322,7 @@ public function testAttemptCaseInsensitive() ]); } - public function testAttemptUsernameOnly() + public function testAttemptUsernameOnly(): void { /** @var User $user */ $user = fake(UserModel::class, ['username' => 'foorog']); diff --git a/tests/Authentication/Filters/ChainFilterTest.php b/tests/Authentication/Filters/ChainFilterTest.php index c583152c0..e61d3f3a0 100644 --- a/tests/Authentication/Filters/ChainFilterTest.php +++ b/tests/Authentication/Filters/ChainFilterTest.php @@ -49,7 +49,7 @@ protected function setUp(): void Services::injectMock('routes', $routes); } - public function testFilterNotAuthorized() + public function testFilterNotAuthorized(): void { $result = $this->call('get', 'protected-route'); @@ -60,7 +60,7 @@ public function testFilterNotAuthorized() $result->assertSee('Open'); } - public function testFilterSuccessSeession() + public function testFilterSuccessSeession(): void { $_SESSION['user']['id'] = $this->user->id; @@ -74,7 +74,7 @@ public function testFilterSuccessSeession() $this->assertSame($this->user->id, auth()->user()->id); } - public function testFilterSuccessTokens() + public function testFilterSuccessTokens(): void { $token = $this->user->generateAccessToken('foo'); diff --git a/tests/Authentication/Filters/SessionFilterTest.php b/tests/Authentication/Filters/SessionFilterTest.php index 2e9b9966a..7e94d3fd4 100644 --- a/tests/Authentication/Filters/SessionFilterTest.php +++ b/tests/Authentication/Filters/SessionFilterTest.php @@ -33,19 +33,19 @@ protected function setUp(): void // Add a test route that we can visit to trigger. $routes = service('routes'); - $routes->group('/', ['filter' => 'sessionAuth'], static function ($routes) { - $routes->get('protected-route', static function () { + $routes->group('/', ['filter' => 'sessionAuth'], static function ($routes): void { + $routes->get('protected-route', static function (): void { echo 'Protected'; }); }); - $routes->get('open-route', static function () { + $routes->get('open-route', static function (): void { echo 'Open'; }); $routes->get('login', 'AuthController::login', ['as' => 'login']); Services::injectMock('routes', $routes); } - public function testFilterNotAuthorized() + public function testFilterNotAuthorized(): void { $result = $this->call('get', 'protected-route'); @@ -56,7 +56,7 @@ public function testFilterNotAuthorized() $result->assertSee('Open'); } - public function testFilterSuccess() + public function testFilterSuccess(): void { $user = fake(UserModel::class); $_SESSION['user']['id'] = $user->id; diff --git a/tests/Authentication/Filters/TokenFilterTest.php b/tests/Authentication/Filters/TokenFilterTest.php index 42ef583df..4426176e6 100644 --- a/tests/Authentication/Filters/TokenFilterTest.php +++ b/tests/Authentication/Filters/TokenFilterTest.php @@ -35,19 +35,19 @@ protected function setUp(): void // Add a test route that we can visit to trigger. $routes = service('routes'); - $routes->group('/', ['filter' => 'tokenAuth'], static function ($routes) { - $routes->get('protected-route', static function () { + $routes->group('/', ['filter' => 'tokenAuth'], static function ($routes): void { + $routes->get('protected-route', static function (): void { echo 'Protected'; }); }); - $routes->get('open-route', static function () { + $routes->get('open-route', static function (): void { echo 'Open'; }); $routes->get('login', 'AuthController::login', ['as' => 'login']); Services::injectMock('routes', $routes); } - public function testFilterNotAuthorized() + public function testFilterNotAuthorized(): void { $result = $this->call('get', 'protected-route'); @@ -58,7 +58,7 @@ public function testFilterNotAuthorized() $result->assertSee('Open'); } - public function testFilterSuccess() + public function testFilterSuccess(): void { /** @var User $user */ $user = fake(UserModel::class); diff --git a/tests/Authentication/HasAccessTokensTest.php b/tests/Authentication/HasAccessTokensTest.php index 0ea8c2437..c59d0aee3 100644 --- a/tests/Authentication/HasAccessTokensTest.php +++ b/tests/Authentication/HasAccessTokensTest.php @@ -23,7 +23,7 @@ protected function setUp(): void $this->db->table('auth_identities')->truncate(); } - public function testGenerateToken() + public function testGenerateToken(): void { $token = $this->user->generateAccessToken('foo'); @@ -40,7 +40,7 @@ public function testGenerateToken() $this->assertSame(['*'], $token->scopes); } - public function testAccessTokens() + public function testAccessTokens(): void { // Should return empty array when none exist $this->assertSame([], $this->user->accessTokens()); @@ -63,7 +63,7 @@ public function testAccessTokens() $this->assertSame($token2->id, $tokens[1]->id); } - public function testGetAccessToken() + public function testGetAccessToken(): void { // Should return null when not found $this->assertNull($this->user->getAccessToken('foo')); @@ -76,7 +76,7 @@ public function testGetAccessToken() $this->assertSame($token->id, $found->id); } - public function testGetAccessTokenById() + public function testGetAccessTokenById(): void { // Should return null when not found $this->assertNull($this->user->getAccessTokenById(123)); @@ -88,7 +88,7 @@ public function testGetAccessTokenById() $this->assertSame($token->id, $found->id); } - public function testRevokeAccessToken() + public function testRevokeAccessToken(): void { $token = $this->user->generateAccessToken('foo'); @@ -99,7 +99,7 @@ public function testRevokeAccessToken() $this->assertCount(0, $this->user->accessTokens()); } - public function testRevokeAllAccessTokens() + public function testRevokeAllAccessTokens(): void { $this->user->generateAccessToken('foo'); $this->user->generateAccessToken('foo'); @@ -111,12 +111,12 @@ public function testRevokeAllAccessTokens() $this->assertCount(0, $this->user->accessTokens()); } - public function testTokenCanNoTokenSet() + public function testTokenCanNoTokenSet(): void { $this->assertFalse($this->user->tokenCan('foo')); } - public function testTokenCanBasics() + public function testTokenCanBasics(): void { $token = $this->user->generateAccessToken('foo', ['foo:bar']); $this->user->setAccessToken($token); @@ -125,12 +125,12 @@ public function testTokenCanBasics() $this->assertFalse($this->user->tokenCan('foo:baz')); } - public function testTokenCantNoTokenSet() + public function testTokenCantNoTokenSet(): void { $this->assertTrue($this->user->tokenCant('foo')); } - public function testTokenCant() + public function testTokenCant(): void { $token = $this->user->generateAccessToken('foo', ['foo:bar']); $this->user->setAccessToken($token); diff --git a/tests/Authentication/MagicLinkTest.php b/tests/Authentication/MagicLinkTest.php index 43c14caf2..93602625d 100644 --- a/tests/Authentication/MagicLinkTest.php +++ b/tests/Authentication/MagicLinkTest.php @@ -35,7 +35,7 @@ protected function setUp(): void Services::injectMock('routes', $routeCollection); } - public function testCanSeeMagicLinkForm() + public function testCanSeeMagicLinkForm(): void { $result = $this->get(route_to('magic-link')); @@ -43,7 +43,7 @@ public function testCanSeeMagicLinkForm() $result->assertSee(lang('Auth.useMagicLink')); } - public function testMagicLinkSubmitNoEmail() + public function testMagicLinkSubmitNoEmail(): void { $result = $this->post(route_to('magic-link'), [ 'email' => '', @@ -53,7 +53,7 @@ public function testMagicLinkSubmitNoEmail() $result->assertSessionHas('error', lang('Auth.invalidEmail')); } - public function testMagicLinkSubmitBadEmail() + public function testMagicLinkSubmitBadEmail(): void { $result = $this->post(route_to('magic-link'), [ 'email' => 'foo@example.com', @@ -63,7 +63,7 @@ public function testMagicLinkSubmitBadEmail() $result->assertSessionHas('error', lang('Auth.invalidEmail')); } - public function testMagicLinkSubmitSuccess() + public function testMagicLinkSubmitSuccess(): void { /** * @phpstan-var User @@ -84,7 +84,7 @@ public function testMagicLinkSubmitSuccess() ]); } - public function testMagicLinkVerifyNoToken() + public function testMagicLinkVerifyNoToken(): void { $result = $this->get(route_to('verify-magic-link')); @@ -92,7 +92,7 @@ public function testMagicLinkVerifyNoToken() $result->assertSessionHas('error', lang('Auth.magicTokenNotFound')); } - public function testMagicLinkVerifyExpired() + public function testMagicLinkVerifyExpired(): void { $identities = new UserIdentityModel(); /** @@ -113,7 +113,7 @@ public function testMagicLinkVerifyExpired() $result->assertSessionHas('error', lang('Auth.magicLinkExpired')); } - public function testMagicLinkVerifySuccess() + public function testMagicLinkVerifySuccess(): void { $identities = new UserIdentityModel(); /** @var User $user */ diff --git a/tests/Authorization/AuthorizableTest.php b/tests/Authorization/AuthorizableTest.php index 1a9a52573..34ed87a63 100644 --- a/tests/Authorization/AuthorizableTest.php +++ b/tests/Authorization/AuthorizableTest.php @@ -32,7 +32,7 @@ protected function setUp(): void db_connect()->table('auth_permissions_users')->truncate(); } - public function testAddGroupWithNoExistingGroups() + public function testAddGroupWithNoExistingGroups(): void { $this->user->addGroup('admin', 'beta'); // Make sure it doesn't record duplicates @@ -52,7 +52,7 @@ public function testAddGroupWithNoExistingGroups() $this->assertFalse($this->user->inGroup('user')); } - public function testAddGroupWithExistingGroups() + public function testAddGroupWithExistingGroups(): void { $this->hasInDatabase('auth_groups_users', [ 'user_id' => $this->user->id, @@ -87,19 +87,19 @@ public function testAddGroupWithExistingGroups() $this->assertFalse($this->user->inGroup('user')); } - public function testAddGroupWithUnknownGroup() + public function testAddGroupWithUnknownGroup(): void { $this->expectException(AuthorizationException::class); $this->user->addGroup('admin', 'foo'); } - public function testRemoveGroupNoGroups() + public function testRemoveGroupNoGroups(): void { $this->assertSame($this->user, $this->user->removeGroup('admin')); } - public function testRemoveGroupExistingGroup() + public function testRemoveGroupExistingGroup(): void { $this->hasInDatabase('auth_groups_users', [ 'user_id' => $this->user->id, @@ -128,7 +128,7 @@ public function testRemoveGroupExistingGroup() ]); } - public function testSyncGroups() + public function testSyncGroups(): void { $this->hasInDatabase('auth_groups_users', [ 'user_id' => $this->user->id, @@ -153,7 +153,7 @@ public function testSyncGroups() ]); } - public function testAddPermissionWithNoExistingPermissions() + public function testAddPermissionWithNoExistingPermissions(): void { $this->user->addPermission('admin.access', 'beta.access'); // Make sure it doesn't record duplicates @@ -173,7 +173,7 @@ public function testAddPermissionWithNoExistingPermissions() $this->assertFalse($this->user->can('user.manage')); } - public function testAddPermissionWithExistingPermissions() + public function testAddPermissionWithExistingPermissions(): void { $this->hasInDatabase('auth_permissions_users', [ 'user_id' => $this->user->id, @@ -208,19 +208,19 @@ public function testAddPermissionWithExistingPermissions() $this->assertTrue($this->user->can('users.manage')); } - public function testAddPermissionsWithUnknownPermission() + public function testAddPermissionsWithUnknownPermission(): void { $this->expectException(AuthorizationException::class); $this->user->addPermission('admin.access', 'foo'); } - public function testRemovePermissionNoPermissions() + public function testRemovePermissionNoPermissions(): void { $this->assertSame($this->user, $this->user->removePermission('Admin.access')); } - public function testRemovePermissionExistingPermissions() + public function testRemovePermissionExistingPermissions(): void { $this->hasInDatabase('auth_permissions_users', [ 'user_id' => $this->user->id, @@ -249,7 +249,7 @@ public function testRemovePermissionExistingPermissions() ]); } - public function testSyncPermissions() + public function testSyncPermissions(): void { $this->hasInDatabase('auth_permissions_users', [ 'user_id' => $this->user->id, @@ -274,7 +274,7 @@ public function testSyncPermissions() ]); } - public function testHasPermission() + public function testHasPermission(): void { $this->user->addPermission('admin.access'); @@ -282,14 +282,14 @@ public function testHasPermission() $this->assertFalse($this->user->hasPermission('beta.access')); } - public function testCanCascadesToGroupsSimple() + public function testCanCascadesToGroupsSimple(): void { $this->user->addGroup('admin'); $this->assertTrue($this->user->can('admin.access')); } - public function testCanCascadesToGroupsWithWildcards() + public function testCanCascadesToGroupsWithWildcards(): void { $this->user->addGroup('superadmin'); diff --git a/tests/Authorization/GroupTest.php b/tests/Authorization/GroupTest.php index 5ed1441ec..0585dfb41 100644 --- a/tests/Authorization/GroupTest.php +++ b/tests/Authorization/GroupTest.php @@ -24,7 +24,7 @@ protected function setUp(): void $this->groups = new Groups(); } - public function testPermissions() + public function testPermissions(): void { $group = $this->groups->info('admin'); @@ -34,7 +34,7 @@ public function testPermissions() $this->assertContains('users.create', $permissions); } - public function testSavePermissions() + public function testSavePermissions(): void { $group = $this->groups->info('admin'); @@ -47,7 +47,7 @@ public function testSavePermissions() $this->assertNotContains('users.create', $permissions); } - public function testAddPermission() + public function testAddPermission(): void { $group = $this->groups->info('admin'); @@ -57,7 +57,7 @@ public function testAddPermission() $this->assertContains('foo.bar', $permissions); } - public function testRemovePermission() + public function testRemovePermission(): void { $group = $this->groups->info('admin'); @@ -67,7 +67,7 @@ public function testRemovePermission() $this->assertNotContains('users.edit', $permissions); } - public function testCan() + public function testCan(): void { $group = $this->groups->info('admin'); diff --git a/tests/Authorization/GroupsTest.php b/tests/Authorization/GroupsTest.php index 89a2830e3..62791eddc 100644 --- a/tests/Authorization/GroupsTest.php +++ b/tests/Authorization/GroupsTest.php @@ -30,12 +30,12 @@ protected function setUp(): void $this->groups = new Groups(); } - public function testGroupInfoBadName() + public function testGroupInfoBadName(): void { $this->assertNull($this->groups->info('foo')); } - public function testGroupInfo() + public function testGroupInfo(): void { $group = $this->groups->info('admin'); @@ -45,7 +45,7 @@ public function testGroupInfo() $this->assertSame('admin', $group->alias); } - public function testSaveGroupCreatesNew() + public function testSaveGroupCreatesNew(): void { $group = new Group([ 'alias' => 'foo', @@ -58,7 +58,7 @@ public function testSaveGroupCreatesNew() $this->assertInstanceOf(Group::class, $this->groups->info('foo')); } - public function testSaveGroupCreatesNewMakesAlias() + public function testSaveGroupCreatesNewMakesAlias(): void { $group = new Group([ 'title' => 'Foo Dog', @@ -70,7 +70,7 @@ public function testSaveGroupCreatesNewMakesAlias() $this->assertInstanceOf(Group::class, $this->groups->info('foo-dog')); } - public function testSaveGroupThrowsOnMissingTitle() + public function testSaveGroupThrowsOnMissingTitle(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage(lang('Auth.missingTitle')); diff --git a/tests/Collectors/AuthTest.php b/tests/Collectors/AuthTest.php index 3c725a3e6..1d30aa375 100644 --- a/tests/Collectors/AuthTest.php +++ b/tests/Collectors/AuthTest.php @@ -30,17 +30,17 @@ protected function setUp(): void $this->collector = new Auth(); } - public function testDisplayNotLoggedIn() + public function testDisplayNotLoggedIn(): void { $output = $this->collector->display(); $this->assertStringContainsString('Not logged in', $output); } - public function testtestDisplayLoggedIn() + public function testtestDisplayLoggedIn(): void { - /** @var Session $authenticator */ $authenticator = service('auth')->getAuthenticator(); + assert($authenticator instanceof Session); $authenticator->login($this->user); $this->user->addGroup('admin', 'beta'); @@ -51,14 +51,14 @@ public function testtestDisplayLoggedIn() $this->assertStringContainsString('Groupsadmin, beta', $output); } - public function testGetTitleDetails() + public function testGetTitleDetails(): void { $output = $this->collector->getTitleDetails(); $this->assertStringContainsString(Session::class, $output); } - public function testGetBadgeValueReturnsUserId() + public function testGetBadgeValueReturnsUserId(): void { /** @var Session $authenticator */ $authenticator = service('auth')->getAuthenticator(); diff --git a/tests/Controllers/ActionsTest.php b/tests/Controllers/ActionsTest.php index b50f56ef4..002ce6d25 100644 --- a/tests/Controllers/ActionsTest.php +++ b/tests/Controllers/ActionsTest.php @@ -49,7 +49,7 @@ protected function setUp(): void $this->user->createEmailIdentity(['email' => 'johnsmith@example.com', 'password' => 'secret123']); } - public function testActionShowNoneAvailable() + public function testActionShowNoneAvailable(): void { $this->expectException(PageNotFoundException::class); @@ -59,7 +59,7 @@ public function testActionShowNoneAvailable() $result->assertStatus(404); } - public function testEmail2FAShow() + public function testEmail2FAShow(): void { $this->insertIdentityEmal2FA(); @@ -82,7 +82,7 @@ private function getSessionUserInfo(string $class = Email2FA::class): array ]; } - public function testEmail2FAHandleInvalidEmail() + public function testEmail2FAHandleInvalidEmail(): void { $this->insertIdentityEmal2FA(); @@ -97,7 +97,7 @@ public function testEmail2FAHandleInvalidEmail() $result->assertSessionHas('error', lang('Auth.invalidEmail')); } - private function insertIdentityEmal2FA() + private function insertIdentityEmal2FA(): void { // An identity with 2FA info would have been stored previously $identities = model(UserIdentityModel::class); @@ -110,7 +110,7 @@ private function insertIdentityEmal2FA() ]); } - public function testEmail2FAHandleSendsEmail() + public function testEmail2FAHandleSendsEmail(): void { $this->insertIdentityEmal2FA(); @@ -127,7 +127,7 @@ public function testEmail2FAHandleSendsEmail() $this->assertStringContainsString('Your authentication code is:', service('email')->archive['body']); } - public function testEmail2FAVerifyFails() + public function testEmail2FAVerifyFails(): void { $this->insertIdentityEmal2FA(); @@ -141,7 +141,7 @@ public function testEmail2FAVerifyFails() $result->assertSee(lang('Auth.invalid2FAToken')); } - public function testEmail2FAVerify() + public function testEmail2FAVerify(): void { $this->insertIdentityEmal2FA(); @@ -164,7 +164,7 @@ public function testEmail2FAVerify() $result->assertSessionMissing('auth_action'); } - public function testShowEmail2FACreatesIdentity() + public function testShowEmail2FACreatesIdentity(): void { $this->insertIdentityEmal2FA(); @@ -181,7 +181,7 @@ public function testShowEmail2FACreatesIdentity() ]); } - public function testEmail2FACannotBeBypassed() + public function testEmail2FACannotBeBypassed(): void { // Ensure filter is enabled for all routes $config = config('Filters'); @@ -220,7 +220,7 @@ private function insertIdentityEmailActivate(): void ]); } - public function testEmailActivateShow() + public function testEmailActivateShow(): void { $this->insertIdentityEmailActivate(); @@ -241,7 +241,7 @@ public function testEmailActivateShow() ); } - public function testEmailActivateVerify() + public function testEmailActivateVerify(): void { $this->insertIdentityEmailActivate(); @@ -274,7 +274,7 @@ public function testEmailActivateVerify() ]); } - public function testEmailActivateCannotBeBypassed() + public function testEmailActivateCannotBeBypassed(): void { // Ensure filter is enabled for all routes $config = config('Filters'); diff --git a/tests/Controllers/LoginTest.php b/tests/Controllers/LoginTest.php index 33cfe061f..d2716e346 100644 --- a/tests/Controllers/LoginTest.php +++ b/tests/Controllers/LoginTest.php @@ -34,7 +34,7 @@ protected function setUp(): void Services::injectMock('routes', $routes); } - public function testLoginBadEmail() + public function testLoginBadEmail(): void { $this->user->createEmailIdentity([ 'email' => 'foo@example.com', @@ -61,7 +61,7 @@ public function testLoginBadEmail() $this->assertSame(lang('Auth.badAttempt'), session('error')); } - public function testLoginActionEmailSuccess() + public function testLoginActionEmailSuccess(): void { $this->user->createEmailIdentity([ 'email' => 'foo@example.com', @@ -91,7 +91,7 @@ public function testLoginActionEmailSuccess() $this->assertSame($this->user->id, session('user')['id']); } - public function testLoginActionUsernameSuccess() + public function testLoginActionUsernameSuccess(): void { $this->user->createEmailIdentity([ 'email' => 'foo@example.com', @@ -121,7 +121,7 @@ public function testLoginActionUsernameSuccess() $this->assertSame($this->user->id, session('user')['id']); } - public function testLogoutAction() + public function testLogoutAction(): void { // log them in session()->set('user', ['id' => $this->user->id]); @@ -134,7 +134,7 @@ public function testLogoutAction() $this->assertNull(session('user')); } - public function testLoginRedirectsToActionIfDefined() + public function testLoginRedirectsToActionIfDefined(): void { // Ensure our action is defined $config = config('Auth'); diff --git a/tests/Controllers/RegisterTest.php b/tests/Controllers/RegisterTest.php index 220845747..515e6197e 100644 --- a/tests/Controllers/RegisterTest.php +++ b/tests/Controllers/RegisterTest.php @@ -41,7 +41,7 @@ protected function setUp(): void Factories::injectMock('config', 'Validation', $config); } - public function testRegisterActionSuccess() + public function testRegisterActionSuccess(): void { $result = $this->withSession()->post('/register', [ 'username' => 'JohnDoe', @@ -75,7 +75,7 @@ public function testRegisterActionSuccess() $this->assertTrue($user->active); } - public function testRegisterDisplaysForm() + public function testRegisterDisplaysForm(): void { $result = $this->withSession()->get('/register'); @@ -83,7 +83,7 @@ public function testRegisterDisplaysForm() $result->assertSee(lang('Auth.register')); } - public function testRegisterRedirectsIfNotAllowed() + public function testRegisterRedirectsIfNotAllowed(): void { $config = config('Auth'); $config->allowRegistration = false; @@ -95,7 +95,7 @@ public function testRegisterRedirectsIfNotAllowed() $result->assertRedirect(); } - public function testRegisterActionRedirectsIfNotAllowed() + public function testRegisterActionRedirectsIfNotAllowed(): void { $config = config('Auth'); $config->allowRegistration = false; @@ -107,7 +107,7 @@ public function testRegisterActionRedirectsIfNotAllowed() $result->assertRedirect(); } - public function testRegisterActionInvalidData() + public function testRegisterActionInvalidData(): void { $result = $this->withSession()->post('/register'); @@ -115,7 +115,7 @@ public function testRegisterActionInvalidData() $this->assertCount(4, session('errors')); } - public function testRegisterRedirectsToActionIfDefined() + public function testRegisterRedirectsToActionIfDefined(): void { // Ensure our action is defined $config = config('Auth'); @@ -139,7 +139,7 @@ public function testRegisterRedirectsToActionIfDefined() ]); } - protected function setupConfig() + protected function setupConfig(): void { $config = config('Validation'); $config->ruleSets[] = ValidationRules::class; diff --git a/tests/Unit/AuthRoutesTest.php b/tests/Unit/AuthRoutesTest.php index 1f4743318..24ba72f2c 100644 --- a/tests/Unit/AuthRoutesTest.php +++ b/tests/Unit/AuthRoutesTest.php @@ -9,7 +9,7 @@ */ final class AuthRoutesTest extends TestCase { - public function testRoutes() + public function testRoutes(): void { $collection = single_service('routes'); $auth = service('auth'); @@ -25,7 +25,7 @@ public function testRoutes() $this->assertArrayHasKey('auth/a/show', $routes); } - public function testRoutesExcept() + public function testRoutesExcept(): void { $collection = single_service('routes'); $auth = service('auth'); diff --git a/tests/Unit/CompositionValidatorTest.php b/tests/Unit/CompositionValidatorTest.php index c0b7db5de..d3747d955 100644 --- a/tests/Unit/CompositionValidatorTest.php +++ b/tests/Unit/CompositionValidatorTest.php @@ -25,7 +25,7 @@ protected function setUp(): void $this->validator = new CompositionValidator($this->config); } - public function testCheckThrowsException() + public function testCheckThrowsException(): void { $this->expectException(AuthenticationException::class); $this->expectExceptionMessage(lang('Auth.unsetPasswordLength')); @@ -36,7 +36,7 @@ public function testCheckThrowsException() $this->validator->check($password); } - public function testCheckFalse() + public function testCheckFalse(): void { $password = '1234'; @@ -46,7 +46,7 @@ public function testCheckFalse() $this->assertSame(lang('Auth.errorPasswordLength', [$this->config->minimumPasswordLength]), $result->reason()); } - public function testCheckTrue() + public function testCheckTrue(): void { $password = '1234567890'; diff --git a/tests/Unit/DictionaryValidatorTest.php b/tests/Unit/DictionaryValidatorTest.php index 20f62a9c0..6965f22c0 100644 --- a/tests/Unit/DictionaryValidatorTest.php +++ b/tests/Unit/DictionaryValidatorTest.php @@ -22,7 +22,7 @@ protected function setUp(): void $this->validator = new DictionaryValidator($config); } - public function testCheckFalseOnFoundPassword() + public function testCheckFalseOnFoundPassword(): void { $password = '!!!gerard!!!'; @@ -31,7 +31,7 @@ public function testCheckFalseOnFoundPassword() $this->assertFalse($result->isOK()); } - public function testCheckTrueOnNotFound() + public function testCheckTrueOnNotFound(): void { $password = '!!!gerard!!!abootylicious'; diff --git a/tests/Unit/LoginModelTest.php b/tests/Unit/LoginModelTest.php index 5ae46c01d..2292327e1 100644 --- a/tests/Unit/LoginModelTest.php +++ b/tests/Unit/LoginModelTest.php @@ -22,7 +22,7 @@ private function createLoginModel(): LoginModel return new LoginModel(); } - public function testRecordLoginAttemptThrowsException() + public function testRecordLoginAttemptThrowsException(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage( diff --git a/tests/Unit/NothingPersonalValidatorTest.php b/tests/Unit/NothingPersonalValidatorTest.php index eec5d810d..f3638a34b 100644 --- a/tests/Unit/NothingPersonalValidatorTest.php +++ b/tests/Unit/NothingPersonalValidatorTest.php @@ -22,7 +22,7 @@ protected function setUp(): void $this->validator = new NothingPersonalValidator($config); } - public function testFalseOnPasswordIsEmail() + public function testFalseOnPasswordIsEmail(): void { $user = new User([ 'email' => 'JoeSmith@example.com', @@ -38,7 +38,7 @@ public function testFalseOnPasswordIsEmail() $this->assertSame(lang('Auth.suggestPasswordPersonal'), $result->extraInfo()); } - public function testFalseOnPasswordIsUsernameBackwards() + public function testFalseOnPasswordIsUsernameBackwards(): void { $user = new User([ 'email' => 'JoeSmith@example.com', @@ -54,7 +54,7 @@ public function testFalseOnPasswordIsUsernameBackwards() $this->assertSame(lang('Auth.suggestPasswordPersonal'), $result->extraInfo()); } - public function testFalseOnPasswordAndUsernameTheSame() + public function testFalseOnPasswordAndUsernameTheSame(): void { $user = new User([ 'email' => 'vampire@example.com', @@ -70,7 +70,7 @@ public function testFalseOnPasswordAndUsernameTheSame() $this->assertSame(lang('Auth.suggestPasswordPersonal'), $result->extraInfo()); } - public function testTrueWhenPasswordHasNothingPersonal() + public function testTrueWhenPasswordHasNothingPersonal(): void { $config = new Auth(); $config->maxSimilarity = 50; @@ -109,7 +109,7 @@ public function testTrueWhenPasswordHasNothingPersonal() * * @param mixed $password */ - public function testIsNotPersonalFalsePositivesCaughtByIsNotSimilar($password) + public function testIsNotPersonalFalsePositivesCaughtByIsNotSimilar($password): void { new User([ 'username' => 'CaptainJoe', @@ -148,7 +148,7 @@ public function passwordProvider() * @param mixed $lastName * @param mixed $expected */ - public function testConfigPersonalFieldsValues($firstName, $lastName, $expected) + public function testConfigPersonalFieldsValues($firstName, $lastName, $expected): void { $config = new Auth(); $config->maxSimilarity = 66; @@ -204,7 +204,7 @@ public function firstLastNameProvider() * @param mixed $maxSimilarity * @param mixed $expected */ - public function testMaxSimilarityZeroTurnsOffSimilarityCalculation($maxSimilarity, $expected) + public function testMaxSimilarityZeroTurnsOffSimilarityCalculation($maxSimilarity, $expected): void { $config = new Auth(); $config->maxSimilarity = $maxSimilarity; diff --git a/tests/Unit/PasswordsTest.php b/tests/Unit/PasswordsTest.php index 3a433827d..3a708206f 100644 --- a/tests/Unit/PasswordsTest.php +++ b/tests/Unit/PasswordsTest.php @@ -12,7 +12,7 @@ */ final class PasswordsTest extends CIUnitTestCase { - public function testEmptyPassword() + public function testEmptyPassword(): void { $passwords = new Passwords(new AuthConfig()); diff --git a/tests/Unit/PwnedValidatorTest.php b/tests/Unit/PwnedValidatorTest.php index 6893bd885..9d0689fca 100644 --- a/tests/Unit/PwnedValidatorTest.php +++ b/tests/Unit/PwnedValidatorTest.php @@ -30,7 +30,7 @@ protected function setUp(): void $this->validator = new PwnedValidator(new AuthConfig()); } - public function testCheckFalseOnPwnedPassword() + public function testCheckFalseOnPwnedPassword(): void { $body = implode( "\r\n", @@ -62,7 +62,7 @@ public function testCheckFalseOnPwnedPassword() $this->assertFalse($result->isOK()); } - public function testCheckFalseOnPwnedLastInRange() + public function testCheckFalseOnPwnedLastInRange(): void { $body = "81102569463BE3512984154C66C098B92C5:1\r\n53623B121FD34EE5426C792E5C33AF8C227:22\r\nC528C1B79D1BB387A30C33C5C35B4AC5137:333\r\n621B377E1F35302585D82F1604DF01FE106:1\r\n8371797B4241EBAA28F6A746C4EB2EEDFA3:55555"; @@ -84,7 +84,7 @@ public function testCheckFalseOnPwnedLastInRange() $this->assertFalse($result->isOK()); } - public function testCheckTrueOnNotFound() + public function testCheckTrueOnNotFound(): void { $body = implode( "\r\n", @@ -116,7 +116,7 @@ public function testCheckTrueOnNotFound() $this->assertTrue($result->isOK()); } - public function testCheckCatchesAndRethrowsCurlExceptionAsAuthException() + public function testCheckCatchesAndRethrowsCurlExceptionAsAuthException(): void { $curlrequest = $this->getMockBuilder('CodeIgniter\HTTP\CURLRequest') ->disableOriginalConstructor() diff --git a/tests/Unit/UserIdentityModelTest.php b/tests/Unit/UserIdentityModelTest.php index 9c0d0951b..9b3c619e6 100644 --- a/tests/Unit/UserIdentityModelTest.php +++ b/tests/Unit/UserIdentityModelTest.php @@ -25,7 +25,7 @@ private function createUserIdentityModel(): UserIdentityModel return new UserIdentityModel(); } - public function testCreateDuplicateRecordThrowsException() + public function testCreateDuplicateRecordThrowsException(): void { $this->expectException(DatabaseException::class); @@ -48,7 +48,7 @@ public function testCreateDuplicateRecordThrowsException() ]); } - public function testCreateCodeIdentityThrowsExceptionIfUniqueCodeIsNotGot() + public function testCreateCodeIdentityThrowsExceptionIfUniqueCodeIsNotGot(): void { $this->expectException(DatabaseException::class); diff --git a/tests/Unit/UserTest.php b/tests/Unit/UserTest.php index 62185f68c..bc32558d6 100644 --- a/tests/Unit/UserTest.php +++ b/tests/Unit/UserTest.php @@ -24,13 +24,13 @@ final class UserTest extends TestCase protected $namespace; protected $refresh = true; - public function testGetIdentitiesNone() + public function testGetIdentitiesNone(): void { // when none, returns empty array $this->assertEmpty($this->user->identities); } - public function testGetIdentitiesSome() + public function testGetIdentitiesSome(): void { fake(UserIdentityModel::class, ['user_id' => $this->user->id, 'type' => 'password']); fake(UserIdentityModel::class, ['user_id' => $this->user->id, 'type' => 'access_token']); @@ -40,7 +40,7 @@ public function testGetIdentitiesSome() $this->assertCount(2, $identities); } - public function testGetIdentitiesByType() + public function testGetIdentitiesByType(): void { fake(UserIdentityModel::class, ['user_id' => $this->user->id, 'type' => 'password']); fake(UserIdentityModel::class, ['user_id' => $this->user->id, 'type' => 'access_token']); @@ -53,7 +53,7 @@ public function testGetIdentitiesByType() $this->assertEmpty($this->user->getIdentities('foo')); } - public function testModelWithIdentities() + public function testModelWithIdentities(): void { fake(UserModel::class); fake(UserIdentityModel::class, ['user_id' => $this->user->id, 'type' => 'password']); @@ -67,7 +67,7 @@ public function testModelWithIdentities() $this->assertCount(2, $identities); } - public function testLastLogin() + public function testLastLogin(): void { fake( UserIdentityModel::class, @@ -105,7 +105,7 @@ public function testLastLogin() /** * @see https://github.com/codeigniter4/shield/issues/103 */ - public function testUpdateEmail() + public function testUpdateEmail(): void { // Update user's email $this->user->email = 'foo@bar.com'; @@ -126,7 +126,7 @@ public function testUpdateEmail() /** * @see https://github.com/codeigniter4/shield/issues/103 */ - public function testUpdatePassword() + public function testUpdatePassword(): void { // Update user's email $this->user->email = 'foo@bar.com'; @@ -144,7 +144,7 @@ public function testUpdatePassword() /** * @see https://github.com/codeigniter4/shield/issues/103 */ - public function testUpdatePasswordHash() + public function testUpdatePasswordHash(): void { // Update user's email $hash = service('passwords')->hash('foobar'); From c440e2f24caa4b01b0706f082e80e5c47aefdd8e Mon Sep 17 00:00:00 2001 From: kenjis Date: Thu, 2 Jun 2022 15:31:26 +0900 Subject: [PATCH 2/3] test: extract method --- .../Filters/ChainFilterTest.php | 18 +++++++++++++-- .../Filters/SessionFilterTest.php | 21 ++++++++++++++---- .../Filters/TokenFilterTest.php | 22 +++++++++++++++---- 3 files changed, 51 insertions(+), 10 deletions(-) diff --git a/tests/Authentication/Filters/ChainFilterTest.php b/tests/Authentication/Filters/ChainFilterTest.php index e61d3f3a0..443ce3a1e 100644 --- a/tests/Authentication/Filters/ChainFilterTest.php +++ b/tests/Authentication/Filters/ChainFilterTest.php @@ -31,12 +31,25 @@ protected function setUp(): void $_SESSION = []; // Register our filter - $filterConfig = config('Filters'); + $this->registerFilter(); + + // Add a test route that we can visit to trigger. + $this->addRoutes(); + } + + private function registerFilter(): void + { + $filterConfig = config('Filters'); + $filterConfig->aliases['chain'] = ChainAuth::class; + Factories::injectMock('filters', 'filters', $filterConfig); + } - // Add a test route that we can visit to trigger. + private function addRoutes(): void + { $routes = service('routes'); + $routes->group('/', ['filter' => 'chain'], static function ($routes) { $routes->get('protected-route', static function () { echo 'Protected'; @@ -46,6 +59,7 @@ protected function setUp(): void echo 'Open'; }); $routes->get('login', 'AuthController::login', ['as' => 'login']); + Services::injectMock('routes', $routes); } diff --git a/tests/Authentication/Filters/SessionFilterTest.php b/tests/Authentication/Filters/SessionFilterTest.php index 7e94d3fd4..1e007eed4 100644 --- a/tests/Authentication/Filters/SessionFilterTest.php +++ b/tests/Authentication/Filters/SessionFilterTest.php @@ -20,19 +20,32 @@ final class SessionFilterTest extends DatabaseTestCase protected function setUp(): void { + $_SESSION = []; + Services::reset(true); parent::setUp(); - $_SESSION = []; - // Register our filter - $filterConfig = config('Filters'); + $this->registerFilter(); + + // Add a test route that we can visit to trigger. + $this->addRoutes(); + } + + private function registerFilter(): void + { + $filterConfig = config('Filters'); + $filterConfig->aliases['sessionAuth'] = SessionAuth::class; + Factories::injectMock('filters', 'filters', $filterConfig); + } - // Add a test route that we can visit to trigger. + private function addRoutes(): void + { $routes = service('routes'); + $routes->group('/', ['filter' => 'sessionAuth'], static function ($routes): void { $routes->get('protected-route', static function (): void { echo 'Protected'; diff --git a/tests/Authentication/Filters/TokenFilterTest.php b/tests/Authentication/Filters/TokenFilterTest.php index 4426176e6..1c3cabb09 100644 --- a/tests/Authentication/Filters/TokenFilterTest.php +++ b/tests/Authentication/Filters/TokenFilterTest.php @@ -22,19 +22,32 @@ final class TokenFilterTest extends DatabaseTestCase protected function setUp(): void { + $_SESSION = []; + Services::reset(true); parent::setUp(); - $_SESSION = []; - // Register our filter - $filterConfig = config('Filters'); + $this->registerFilter(); + + // Add a test route that we can visit to trigger. + $this->addRoutes(); + } + + private function registerFilter(): void + { + $filterConfig = config('Filters'); + $filterConfig->aliases['tokenAuth'] = TokenAuth::class; + Factories::injectMock('filters', 'filters', $filterConfig); + } - // Add a test route that we can visit to trigger. + private function addRoutes(): void + { $routes = service('routes'); + $routes->group('/', ['filter' => 'tokenAuth'], static function ($routes): void { $routes->get('protected-route', static function (): void { echo 'Protected'; @@ -44,6 +57,7 @@ protected function setUp(): void echo 'Open'; }); $routes->get('login', 'AuthController::login', ['as' => 'login']); + Services::injectMock('routes', $routes); } From baf204e7527cc84d08fc91220657fccc08fa6a1f Mon Sep 17 00:00:00 2001 From: kenjis Date: Thu, 2 Jun 2022 15:52:31 +0900 Subject: [PATCH 3/3] test: extract AbstractFilterTest --- .../Filters/AbstractFilterTest.php | 65 +++++++++++++++++++ .../Filters/ChainFilterTest.php | 51 +-------------- .../Filters/SessionFilterTest.php | 52 ++------------- .../Filters/TokenFilterTest.php | 53 ++------------- 4 files changed, 78 insertions(+), 143 deletions(-) create mode 100644 tests/Authentication/Filters/AbstractFilterTest.php diff --git a/tests/Authentication/Filters/AbstractFilterTest.php b/tests/Authentication/Filters/AbstractFilterTest.php new file mode 100644 index 000000000..e747e7359 --- /dev/null +++ b/tests/Authentication/Filters/AbstractFilterTest.php @@ -0,0 +1,65 @@ +registerFilter(); + + // Add a test route that we can visit to trigger. + $this->addRoutes(); + } + + private function registerFilter(): void + { + $filterConfig = config('Filters'); + + $filterConfig->aliases[$this->alias] = $this->classname; + + Factories::injectMock('filters', 'filters', $filterConfig); + } + + private function addRoutes(): void + { + $routes = service('routes'); + + $routes->group( + '/', + ['filter' => $this->alias], + static function ($routes): void { + $routes->get('protected-route', static function (): void { + echo 'Protected'; + }); + } + ); + $routes->get('open-route', static function (): void { + echo 'Open'; + }); + $routes->get('login', 'AuthController::login', ['as' => 'login']); + + Services::injectMock('routes', $routes); + } +} diff --git a/tests/Authentication/Filters/ChainFilterTest.php b/tests/Authentication/Filters/ChainFilterTest.php index 443ce3a1e..5f5b8c1ab 100644 --- a/tests/Authentication/Filters/ChainFilterTest.php +++ b/tests/Authentication/Filters/ChainFilterTest.php @@ -2,66 +2,21 @@ namespace Tests\Authentication\Filters; -use CodeIgniter\Config\Factories; use CodeIgniter\Shield\Entities\AccessToken; use CodeIgniter\Shield\Filters\ChainAuth; use CodeIgniter\Test\DatabaseTestTrait; -use CodeIgniter\Test\FeatureTestTrait; -use Config\Services; use Tests\Support\FakeUser; -use Tests\Support\TestCase; /** * @internal */ -final class ChainFilterTest extends TestCase +final class ChainFilterTest extends AbstractFilterTest { use DatabaseTestTrait; - use FeatureTestTrait; use FakeUser; - protected $namespace; - - protected function setUp(): void - { - Services::reset(true); - - parent::setUp(); - - $_SESSION = []; - - // Register our filter - $this->registerFilter(); - - // Add a test route that we can visit to trigger. - $this->addRoutes(); - } - - private function registerFilter(): void - { - $filterConfig = config('Filters'); - - $filterConfig->aliases['chain'] = ChainAuth::class; - - Factories::injectMock('filters', 'filters', $filterConfig); - } - - private function addRoutes(): void - { - $routes = service('routes'); - - $routes->group('/', ['filter' => 'chain'], static function ($routes) { - $routes->get('protected-route', static function () { - echo 'Protected'; - }); - }); - $routes->get('open-route', static function () { - echo 'Open'; - }); - $routes->get('login', 'AuthController::login', ['as' => 'login']); - - Services::injectMock('routes', $routes); - } + protected string $alias = 'chain'; + protected string $classname = ChainAuth::class; public function testFilterNotAuthorized(): void { diff --git a/tests/Authentication/Filters/SessionFilterTest.php b/tests/Authentication/Filters/SessionFilterTest.php index 1e007eed4..ddc37a44d 100644 --- a/tests/Authentication/Filters/SessionFilterTest.php +++ b/tests/Authentication/Filters/SessionFilterTest.php @@ -2,61 +2,19 @@ namespace Tests\Authentication\Filters; -use CodeIgniter\Config\Factories; use CodeIgniter\Shield\Filters\SessionAuth; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Test\FeatureTestTrait; -use Config\Services; -use Tests\Support\DatabaseTestCase; +use CodeIgniter\Test\DatabaseTestTrait; /** * @internal */ -final class SessionFilterTest extends DatabaseTestCase +final class SessionFilterTest extends AbstractFilterTest { - use FeatureTestTrait; + use DatabaseTestTrait; - protected $namespace; - - protected function setUp(): void - { - $_SESSION = []; - - Services::reset(true); - - parent::setUp(); - - // Register our filter - $this->registerFilter(); - - // Add a test route that we can visit to trigger. - $this->addRoutes(); - } - - private function registerFilter(): void - { - $filterConfig = config('Filters'); - - $filterConfig->aliases['sessionAuth'] = SessionAuth::class; - - Factories::injectMock('filters', 'filters', $filterConfig); - } - - private function addRoutes(): void - { - $routes = service('routes'); - - $routes->group('/', ['filter' => 'sessionAuth'], static function ($routes): void { - $routes->get('protected-route', static function (): void { - echo 'Protected'; - }); - }); - $routes->get('open-route', static function (): void { - echo 'Open'; - }); - $routes->get('login', 'AuthController::login', ['as' => 'login']); - Services::injectMock('routes', $routes); - } + protected string $alias = 'sessionAuth'; + protected string $classname = SessionAuth::class; public function testFilterNotAuthorized(): void { diff --git a/tests/Authentication/Filters/TokenFilterTest.php b/tests/Authentication/Filters/TokenFilterTest.php index 1c3cabb09..71a1d0f15 100644 --- a/tests/Authentication/Filters/TokenFilterTest.php +++ b/tests/Authentication/Filters/TokenFilterTest.php @@ -2,64 +2,21 @@ namespace Tests\Authentication\Filters; -use CodeIgniter\Config\Factories; use CodeIgniter\Shield\Entities\AccessToken; use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Filters\TokenAuth; use CodeIgniter\Shield\Models\UserModel; -use CodeIgniter\Test\FeatureTestTrait; -use Config\Services; -use Tests\Support\DatabaseTestCase; +use CodeIgniter\Test\DatabaseTestTrait; /** * @internal */ -final class TokenFilterTest extends DatabaseTestCase +final class TokenFilterTest extends AbstractFilterTest { - use FeatureTestTrait; + use DatabaseTestTrait; - protected $namespace; - - protected function setUp(): void - { - $_SESSION = []; - - Services::reset(true); - - parent::setUp(); - - // Register our filter - $this->registerFilter(); - - // Add a test route that we can visit to trigger. - $this->addRoutes(); - } - - private function registerFilter(): void - { - $filterConfig = config('Filters'); - - $filterConfig->aliases['tokenAuth'] = TokenAuth::class; - - Factories::injectMock('filters', 'filters', $filterConfig); - } - - private function addRoutes(): void - { - $routes = service('routes'); - - $routes->group('/', ['filter' => 'tokenAuth'], static function ($routes): void { - $routes->get('protected-route', static function (): void { - echo 'Protected'; - }); - }); - $routes->get('open-route', static function (): void { - echo 'Open'; - }); - $routes->get('login', 'AuthController::login', ['as' => 'login']); - - Services::injectMock('routes', $routes); - } + protected string $alias = 'tokenAuth'; + protected string $classname = TokenAuth::class; public function testFilterNotAuthorized(): void {