From 9ddb00e7199ff2cad80cb953ebefea504fc864a3 Mon Sep 17 00:00:00 2001 From: kj Date: Mon, 7 Sep 2026 17:21:47 -0300 Subject: [PATCH] test(request): cover exception-based validation failures --- tests/Unit/RequestTest.php | 138 +++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 tests/Unit/RequestTest.php diff --git a/tests/Unit/RequestTest.php b/tests/Unit/RequestTest.php new file mode 100644 index 0000000..01162d4 --- /dev/null +++ b/tests/Unit/RequestTest.php @@ -0,0 +1,138 @@ +serverBackup = $_SERVER; + $this->getBackup = $_GET; + $this->postBackup = $_POST; + + $_SERVER['REQUEST_METHOD'] = 'GET'; + $_SERVER['REQUEST_URI'] = '/test'; + $_SERVER['DOCUMENT_ROOT'] = '/nonexistent-docroot'; + unset($_SERVER['CONTENT_TYPE'], $_SERVER['HTTP_ACCEPT']); + $_GET = []; + $_POST = []; + } + + protected function tearDown(): void + { + $_SERVER = $this->serverBackup; + $_GET = $this->getBackup; + $_POST = $this->postBackup; + } + + #[Test] + public function failedValidationThrowsWithHttp422Code(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['age' => '5']; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('The age must be at least 18.'); + $this->expectExceptionCode(422); + + new class extends Request { + public function rules(): array + { + return ['age' => 'required|min:18']; + } + }; + } + + #[Test] + public function messagesOverrideWinsForFailedRule(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['age' => '5']; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Way too short'); + + new class extends Request { + public function rules(): array + { + return ['age' => 'required|min:18']; + } + + public function messages(): array + { + return ['age.min' => 'Way too short']; + } + }; + } + + #[Test] + public function attributesRenameTheFieldInDefaultMessage(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['age' => '5']; + + $this->expectException(Exception::class); + $this->expectExceptionMessage('The applicant age must be at least 18.'); + + new class extends Request { + public function rules(): array + { + return ['age' => 'required|min:18']; + } + + public function attributes(): array + { + return ['age' => 'applicant age']; + } + }; + } + + #[Test] + public function getRulesFailureThrowsToo(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('The q field is required.'); + + new class extends Request { + public function getRules(): array + { + return ['q' => 'required']; + } + }; + } + + #[Test] + public function validDataDoesNotThrow(): void + { + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST = ['age' => '20']; + + $request = new class extends Request { + public function rules(): array + { + return ['age' => 'required|min:18']; + } + }; + + $this->assertSame('20', $request->post->age); + $this->assertSame('/test', $request->path); + } +}