about summary refs log tree commit diff stats
path: root/tests/RouterTest.php
blob: 1c2197c157cf18bad3ff34f2926a91ed28e969c9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
<?php
use PHPUnit\Framework\TestCase;

final class RouterTest extends TestCase
{
	private Router $router;

	protected function setUp(): void
	{
		$this->router = new Router();
		// Ensure clean session state
		$_SESSION = [];
	}

	protected function tearDown(): void
	{
		$_SESSION = [];
	}

	// ── addRoute() ───────────────────────────────────────────────────────────

	public function test_addRoute_stores_handler(): void
	{
		$handler = $this->createMock(RequestHandlerInterface::class);
		$this->router->addRoute('list', $handler);

		$reflection = new ReflectionClass($this->router);
		$routesProp = $reflection->getProperty('routes');
		$routesProp->setAccessible(true);
		$routes = $routesProp->getValue($this->router);

		$this->assertArrayHasKey('list', $routes);
		$this->assertSame($handler, $routes['list']);
	}

	public function test_addRoute_overwrites_existing_handler(): void
	{
		$handler1 = $this->createMock(RequestHandlerInterface::class);
		$handler2 = $this->createMock(RequestHandlerInterface::class);
		$this->router->addRoute('list', $handler1);
		$this->router->addRoute('list', $handler2);

		$reflection = new ReflectionClass($this->router);
		$routesProp = $reflection->getProperty('routes');
		$routesProp->setAccessible(true);
		$routes = $routesProp->getValue($this->router);

		$this->assertCount(1, $routes);
		$this->assertSame($handler2, $routes['list']);
	}

	// ── addMiddleware() ──────────────────────────────────────────────────────

	public function test_addMiddleware_stores_middleware(): void
	{
		$middleware = $this->createMock(MiddlewareInterface::class);
		$this->router->addMiddleware($middleware);

		$reflection = new ReflectionClass($this->router);
		$mwProp = $reflection->getProperty('middleware');
		$mwProp->setAccessible(true);
		$middlewares = $mwProp->getValue($this->router);

		$this->assertCount(1, $middlewares);
		$this->assertSame($middleware, $middlewares[0]);
	}

	public function test_addMiddleware_accumulates(): void
	{
		$mw1 = $this->createMock(MiddlewareInterface::class);
		$mw2 = $this->createMock(MiddlewareInterface::class);
		$this->router->addMiddleware($mw1);
		$this->router->addMiddleware($mw2);

		$reflection = new ReflectionClass($this->router);
		$mwProp = $reflection->getProperty('middleware');
		$mwProp->setAccessible(true);
		$middlewares = $mwProp->getValue($this->router);

		$this->assertCount(2, $middlewares);
		$this->assertSame($mw1, $middlewares[0]);
		$this->assertSame($mw2, $middlewares[1]);
	}

	// ── dispatchResponse() — unknown op ─────────────────────────────────────

	public function test_dispatchResponse_unknown_op_returns_404(): void
	{
		$response = $this->router->dispatchResponse('nonexistent');
		$body = json_decode($response->getBody(), true);
		$this->assertArrayHasKey('error', $body);
		$this->assertEquals('Method not found', $body['error']);
	}

	// ── dispatchResponse() — AuthRequired handler ────────────────────────────

	public function test_dispatchResponse_auth_required_without_session_returns_401(): void
	{
		$handler = new class implements RequestHandlerInterface, AuthRequired {
			public bool $handleCalled = false;
			public function handle(Request $request): Response
			{
				$this->handleCalled = true;
				return new Response();
			}
		};
		$this->router->addRoute('protected', $handler);

		$response = $this->router->dispatchResponse('protected');
		$body = json_decode($response->getBody(), true);

		$this->assertArrayHasKey('error', $body);
		$this->assertEquals('Unauthorized', $body['error']);
		$this->assertFalse($handler->handleCalled);
	}

	public function test_dispatchResponse_auth_required_with_session_calls_handler(): void
	{
		$expectedResponse = new Response();
		$handler = new class($expectedResponse) implements RequestHandlerInterface, AuthRequired {
			public bool $handleCalled = false;
			private readonly Response $expectedResponse;
			public function __construct(Response $expectedResponse)
			{
				$this->expectedResponse = $expectedResponse;
			}
			public function handle(Request $request): Response
			{
				$this->handleCalled = true;
				return $this->expectedResponse;
			}
		};
		$this->router->addRoute('protected', $handler);
		$_SESSION['owner'] = 'testuser';

		$response = $this->router->dispatchResponse('protected');

		$this->assertTrue($handler->handleCalled);
		$this->assertSame($expectedResponse, $response);
	}

	// ── dispatchResponse() — non-AuthRequired handler ────────────────────────

	public function test_dispatchResponse_non_auth_handler_without_session_calls_handler(): void
	{
		// HealthzHandler equivalent: a handler that does NOT implement AuthRequired
		$handler = $this->createMock(RequestHandlerInterface::class);
		$expectedResponse = new Response();
		$handler->expects($this->once())
			->method('handle')
			->willReturn($expectedResponse);
		$this->router->addRoute('healthz', $handler);
		// No session set

		$response = $this->router->dispatchResponse('healthz');

		$this->assertSame($expectedResponse, $response);
	}

	public function test_dispatchResponse_non_auth_handler_with_session_calls_handler(): void
	{
		$handler = $this->createMock(RequestHandlerInterface::class);
		$expectedResponse = new Response();
		$handler->expects($this->once())
			->method('handle')
			->willReturn($expectedResponse);
		$this->router->addRoute('healthz', $handler);
		$_SESSION['owner'] = 'testuser';

		$response = $this->router->dispatchResponse('healthz');

		$this->assertSame($expectedResponse, $response);
	}

	// ── dispatchResponse() — middleware wrapping ─────────────────────────────

	public function test_dispatchResponse_middleware_wraps_handler(): void
	{
		$handler = $this->createMock(RequestHandlerInterface::class);
		$handlerResponse = new Response();
		$handler->expects($this->once())
			->method('handle')
			->willReturn($handlerResponse);

		// Middleware that adds a header
		$middleware = new class implements MiddlewareInterface {
			public bool $wasCalled = false;

			public function process(Request $request, callable $next): Response
			{
				$this->wasCalled = true;
				$response = $next($request);
				return $response->withHeader('X-Middleware', 'applied');
			}
		};

		$this->router->addRoute('test', $handler);
		$this->router->addMiddleware($middleware);

		$response = $this->router->dispatchResponse('test');

		$this->assertTrue($middleware->wasCalled);
		// Middleware response should be returned (handler response was wrapped)
		// The middleware returns its own response with the header
	}

	public function test_dispatchResponse_middleware_last_added_is_outermost(): void
	{
		$handler = $this->createMock(RequestHandlerInterface::class);
		$handlerResponse = new Response();
		$handler->expects($this->once())
			->method('handle')
			->willReturn($handlerResponse);

		// Use a shared array to track execution order
		$tracker = new class {
			/** @var list<string> */
			public array $order = [];
		};

		// Middleware 1: added first → inner
		$mw1 = new class($tracker) implements MiddlewareInterface {
			public function __construct(private readonly object $tracker)
			{
			}

			public function process(Request $request, callable $next): Response
			{
				$this->tracker->order[] = 'mw1_start';
				$response = $next($request);
				$this->tracker->order[] = 'mw1_end';
				return $response;
			}
		};

		// Middleware 2: added second → outer
		$mw2 = new class($tracker) implements MiddlewareInterface {
			public function __construct(private readonly object $tracker)
			{
			}

			public function process(Request $request, callable $next): Response
			{
				$this->tracker->order[] = 'mw2_start';
				$response = $next($request);
				$this->tracker->order[] = 'mw2_end';
				return $response;
			}
		};

		$this->router->addRoute('test', $handler);
		$this->router->addMiddleware($mw1); // added first = inner
		$this->router->addMiddleware($mw2); // added second = outer

		$this->router->dispatchResponse('test');

		// Execution order: first-added middleware is outermost
		// mw1 (added first) wraps mw2 (added second) which wraps handler
		$this->assertEquals([
			'mw1_start',
			'mw2_start',
			'mw2_end',
			'mw1_end',
		], $tracker->order);
	}

	// ── dispatchResponse() — request attribute ───────────────────────────────

	public function test_dispatchResponse_sets_op_attribute_on_request(): void
	{
		// Use a shared tracker object to capture the request
		$tracker = new class {
			public ?Request $request = null;
		};

		$handler = new class($tracker) implements RequestHandlerInterface {
			public function __construct(private readonly object $tracker)
			{
			}

			public function handle(Request $request): Response
			{
				$this->tracker->request = $request;
				return new Response();
			}
		};

		$this->router->addRoute('list', $handler);

		$this->router->dispatchResponse('list');

		$this->assertNotNull($tracker->request);
		$this->assertEquals('list', $tracker->request->getAttribute('op'));
	}

	// ── dispatch() — integration with exit ───────────────────────────────────

	public function test_dispatch_calls_exit_for_unknown_op(): void
	{
		// Since dispatch() calls exit, we can only verify behavior via dispatchResponse
		// which is the extracted testable method
		$response = $this->router->dispatchResponse('unknown');
		$body = json_decode($response->getBody(), true);
		$this->assertEquals('Method not found', $body['error']);
	}

	public function test_dispatch_calls_exit_for_unauthorized(): void
	{
		$handler = new class implements RequestHandlerInterface, AuthRequired {
			public bool $handleCalled = false;
			public function handle(Request $request): Response
			{
				$this->handleCalled = true;
				return new Response();
			}
		};
		$this->router->addRoute('protected', $handler);

		$response = $this->router->dispatchResponse('protected');
		$body = json_decode($response->getBody(), true);
		$this->assertEquals('Unauthorized', $body['error']);
		$this->assertFalse($handler->handleCalled);
	}
}