From 246c279b3e9044cf4e33fc99b64199d3e1606d5b Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 4 Jan 2025 11:37:32 +0700 Subject: [PATCH] add tests --- tests/system/Security/SecurityTest.php | 44 ++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tests/system/Security/SecurityTest.php b/tests/system/Security/SecurityTest.php index f8799230e056..4886b04f3f8b 100644 --- a/tests/system/Security/SecurityTest.php +++ b/tests/system/Security/SecurityTest.php @@ -25,6 +25,7 @@ use Config\Security as SecurityConfig; use PHPUnit\Framework\Attributes\BackupGlobals; use PHPUnit\Framework\Attributes\Group; +use ReflectionClass; /** * @internal @@ -49,6 +50,16 @@ private function createMockSecurity(?SecurityConfig $config = null): MockSecurit return new MockSecurity($config); } + private function getPostedTokenMethod(): \ReflectionMethod + { + $reflection = new ReflectionClass(Security::class); + $method = $reflection->getMethod('getPostedToken'); + + $method->setAccessible(true); + + return $method; + } + public function testBasicConfigIsSaved(): void { $security = $this->createMockSecurity(); @@ -315,4 +326,37 @@ public function testGetters(): void $this->assertIsString($security->getCookieName()); $this->assertIsBool($security->shouldRedirect()); } + + public function testGetPostedTokenReturnsTokenWhenValid(): void + { + $method = $this->getPostedTokenMethod(); + $security = $this->createMockSecurity(); + + $_POST['csrf_test_name'] = '8b9218a55906f9dcc1dc263dce7f005a'; + $request = $this->createIncomingRequest(); + + $this->assertSame('8b9218a55906f9dcc1dc263dce7f005a', $method->invoke($security, $request)); + } + + public function testGetPostedTokenReturnsNullWhenEmpty(): void + { + $method = $this->getPostedTokenMethod(); + $security = $this->createMockSecurity(); + + $_POST = []; + $request = $this->createIncomingRequest(); + + $this->assertNull($method->invoke($security, $request)); + } + + public function testGetPostedTokenReturnsNullWhenMaliciousData(): void + { + $method = $this->getPostedTokenMethod(); + $security = $this->createMockSecurity(); + + $_POST['csrf_test_name'] = ['malicious' => 'data']; + $request = $this->createIncomingRequest(); + + $this->assertNull($method->invoke($security, $request)); + } }