-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDispatcherTest.php
More file actions
826 lines (740 loc) · 28.2 KB
/
DispatcherTest.php
File metadata and controls
826 lines (740 loc) · 28.2 KB
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
<?php
declare(strict_types=1);
namespace Firehed\API;
use Exception;
use Firehed\API\Authentication;
use Firehed\API\Authorization;
use Firehed\API\Interfaces\EndpointInterface;
use Firehed\API\Interfaces\HandlesOwnErrorsInterface;
use Firehed\API\Errors\HandlerInterface;
use Firehed\Input\Exceptions\InputException;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;
use Throwable;
use Zend\Diactoros\Request;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\Stream;
/**
* @coversDefaultClass Firehed\API\Dispatcher
* @covers ::<protected>
* @covers ::<private>
*/
class DispatcherTest extends \PHPUnit\Framework\TestCase
{
private $reporting;
public function setUp()
{
$this->reporting = error_reporting();
error_reporting($this->reporting & ~E_USER_DEPRECATED);
}
public function tearDown()
{
error_reporting($this->reporting);
}
public function testConstruct()
{
$this->assertInstanceOf(
'Firehed\API\Dispatcher',
new Dispatcher()
);
}
// ----(Setters)-----------------------------------------------------------
/** @covers ::setContainer */
public function testSetContainerReturnsSelf()
{
$d = new Dispatcher();
$container = $this->getMockContainer([]);
$this->assertSame(
$d,
$d->setContainer($container),
'setContainer did not return $this'
);
}
/** @covers ::setEndpointList */
public function testSetEndpointListReturnsSelf()
{
$d = new Dispatcher();
$this->assertSame(
$d,
$d->setEndpointList('list'),
'setEndpointList did not return $this'
);
}
/** @covers ::setParserList */
public function testSetParserListReturnsSelf()
{
$d = new Dispatcher();
$this->assertSame(
$d,
$d->setParserList('list'),
'setParserList did not return $this'
);
}
/** @covers ::setRequest */
public function testSetRequestReturnsSelf()
{
$d = new Dispatcher();
$req = $this->createMock(ServerRequestInterface::class);
$req->method('getHeaders')->willReturn([]);
$req->method('getBody')->willReturn($this->createMock(StreamInterface::class));
$req->method('getUri')->willReturn($this->createMock(UriInterface::class));
$this->assertSame(
$d,
$d->setRequest($req),
'setRequest did not return $this'
);
}
// ----(Success case)-------------------------------------------------------
/**
* Test successful all-the-way-through controller execution, including both
* URL-provided data (regex captures) and POST body.
*
* @covers ::dispatch
*/
public function testDataReachesEndpoint()
{
// See tests/EndpointFixture
$req = $this->getMockRequestWithUriPath('/user/5', 'POST');
$body = $req->getBody();
$body->write('shortstring=aBcD');
$req = $req->withBody($body);
$req = $req->withHeader('Content-type', 'application/x-www-form-urlencoded');
$response = (new Dispatcher())
->setEndpointList($this->getEndpointListForFixture())
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
$this->checkResponse($response, 200);
$data = json_decode($response->getBody(), true);
$this->assertSame(
[
'id' => 5,
'shortstring' => 'aBcD',
],
$data,
'The data did not reach the endpoint'
);
}
/**
* Test successful all-the-way-through controller execution, focusing on
* accessing $_GET/querystring data
*
* @covers ::dispatch
*/
public function testQueryStringDataReachesEndpoint()
{
// See tests/EndpointFixture
$req = $this->getMockRequestWithUriPath(
'/user/5',
'GET',
['shortstring' => 'aBcD']
);
$response = (new Dispatcher())
->setEndpointList($this->getEndpointListForFixture())
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
$this->checkResponse($response, 200);
$data = json_decode($response->getBody(), true);
$this->assertSame(
[
'id' => 5,
'shortstring' => 'aBcD',
],
$data,
'The data did not reach the endpoint'
);
}
/**
* Default behavior is to directly use the class found in the endpoint
* list. If a value exists in the DI Container (well, really a service
* locator now) at the key of that class name, it should be preferred. This
* allows configuring the class without having to do crazy magic in the
* dispatcher.
*
* @covers ::dispatch
*/
public function testContainerClassIsPrioritized()
{
$endpoint = $this->getMockEndpoint();
$endpoint->expects($this->atLeastOnce())
->method('execute')
->will($this->returnValue(
$this->createMock(ResponseInterface::class)
));
$this->executeMockRequestOnEndpoint($endpoint);
}
/**
* @covers ::addMiddleware
* @covers ::dispatch
* @covers ::handle
*/
public function testPsr15()
{
$request = $this->createMock(ServerRequestInterface::class);
$modifiedRequest = $this->getMockRequestWithUriPath('/c', 'GET', []);
$response = $this->createMock(ResponseInterface::class);
$modifiedResponse = $this->createMock(ResponseInterface::class);
$dispatcher = new Dispatcher();
$mw1 = $this->createMock(MiddlewareInterface::class);
$mw1->expects($this->once())
->method('process')
->willReturnCallback(function ($req, $handler) use ($request, $modifiedRequest, $dispatcher) {
$this->assertSame($req, $request, 'Request mismatch');
$this->assertSame($dispatcher, $handler, 'Handler mismatch');
return $handler->handle($modifiedRequest);
});
$mw2 = $this->createMock(MiddlewareInterface::class);
$mw2->expects($this->once())
->method('process')
->willReturnCallback(function ($req, $handler) use ($modifiedRequest, $response, $modifiedResponse) {
$this->assertSame($req, $modifiedRequest, 'Request mismatch');
$endpointResponse = $handler->handle($req);
$this->assertSame($response, $endpointResponse, 'Response mismatch');
return $modifiedResponse;
});
$endpoint = $this->getMockEndpoint();
$endpoint->expects($this->atLeastOnce())
->method('execute')
->willReturn($response);
$routes = ['GET' => ['/c' => 'EP']];
$res = $dispatcher
->addMiddleware($mw1)
->addMiddleware($mw2)
->setContainer($this->getMockContainer(['EP' => $endpoint]))
->setEndpointList($routes)
->setParserList($this->getDefaultParserList())
->setRequest($request)
->dispatch();
$this->assertSame($modifiedResponse, $res, 'Dispatcher returned different response');
}
/**
* Ensure that if an exception is thrown during execute() and another (or
* the same) exception is thrown during the subsequent call. Basically, we
* *want* the error-handling exception to leak, because
* a) trying to supress it will probably result in undefined behavior, and
* b) something is deeply broken in the application, which you should know
*
* @covers ::dispatch
*/
public function testErrorInResponseHandler()
{
$execute = new Exception('Execute error');
$error = new Exception('Exception handler error');
$endpoint = $this->getMockEndpoint(HandlesOwnErrorsInterface::class);
$endpoint->expects($this->once())
->method('execute')
->will($this->throwException($execute));
$endpoint->expects($this->once())
->method('handleException')
->with($execute)
->will($this->throwException($error));
$req = $this->getMockRequestWithUriPath('/cb', 'GET');
$list = [
'GET' => [
'/cb' => 'CBClass',
],
];
try {
$ret = (new Dispatcher())
->setContainer($this->getMockContainer(['CBClass' => $endpoint]))
->setEndpointList($list)
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
$this->fail(
"The exception thrown from the error handler's failure should ".
"have made it through"
);
} catch (Throwable $e) {
$this->assertSame(
$error,
$e,
"Some exception other than the one from the exception handler ".
"was thrown"
);
}
}
// ----(Error cases)--------------------------------------------------------
/**
* @covers ::dispatch
* @expectedException BadMethodCallException
* @expectedExceptionCode 500
*/
public function testDispatchThrowsWhenMissingData()
{
$d = new Dispatcher();
$ret = $d->dispatch();
}
/**
* @covers ::dispatch
* @expectedException OutOfBoundsException
* @expectedExceptionCode 404
*/
public function testNoRouteMatchReturns404()
{
$req = $this->getMockRequestWithUriPath('/');
$ret = (new Dispatcher())
->setRequest($req)
->setEndpointList([]) // No routes
->setParserList([])
->dispatch();
}
/** @covers ::dispatch */
public function testFailedInputValidationCanReachErrorHandlers()
{
// See tests/EndpointFixture
$req = $this->getMockRequestWithUriPath('/user/5', 'POST');
$body = $req->getBody();
$body->write('shortstring=thisistoolong');
$req = $req->withBody($body);
$req = $req->withHeader('Content-type', 'application/x-www-form-urlencoded');
try {
$response = (new Dispatcher())
->setEndpointList($this->getEndpointListForFixture())
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
$this->fail('An exception should have been thrown');
} catch (Throwable $e) {
$this->assertInstanceOf(InputException::class, $e);
}
}
/** @covers ::dispatch */
public function testUnsupportedContentTypeCanReachErrorHandlers()
{
$req = $this->getMockRequestWithUriPath('/user/5', 'POST');
$req = $req->withHeader('Content-type', 'application/x-test-failure');
try {
$response = (new Dispatcher())
->setEndpointList($this->getEndpointListForFixture())
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
$this->fail('An exception should have been thrown');
} catch (Throwable $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(415, $e->getCode());
}
}
/** @covers ::dispatch */
public function testMethodNotAllowed()
{
$req = $this->getMockRequestWithUriPath('/user/1', 'PUT');
try {
$response = (new Dispatcher())
->setEndpointList($this->getEndpointListForFixture())
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
$this->fail('An exception should have been thrown');
} catch (Throwable $e) {
$this->assertInstanceOf(RuntimeException::class, $e);
$this->assertSame(405, $e->getCode());
}
}
/**
* @covers ::dispatch
*/
public function testMatchingContentTypeWithDirectives()
{
$contentType = 'application/json; charset=utf-8';
$req = $this->getMockRequestWithUriPath('/user/5', 'POST');
$req = $req->withHeader('Content-type', $contentType);
$response = (new Dispatcher())
->setEndpointList($this->getEndpointListForFixture())
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
$this->checkResponse($response, 200);
}
/** @covers ::dispatch */
public function testFailedEndpointExecutionReachesEndpointErrorHandler()
{
$e = new Exception('This should reach the error handler');
$endpoint = $this->getMockEndpoint(HandlesOwnErrorsInterface::class);
$endpoint->method('execute')
->will($this->throwException($e));
$endpoint->expects($this->once())
->method('handleException')
->with($e);
$this->executeMockRequestOnEndpoint($endpoint);
}
/** @covers ::dispatch */
public function testScalarResponseFromEndpointReachesErrorHandler()
{
$endpoint = $this->getMockEndpoint(HandlesOwnErrorsInterface::class);
$endpoint->expects($this->atLeastOnce())
->method('execute')
->will($this->returnValue(false)); // Trigger a bad return value
$endpoint->expects($this->once())
->method('handleException');
$this->executeMockRequestOnEndpoint($endpoint);
}
/** @covers ::dispatch */
public function testInvalidTypeResponseFromEndpointReachesErrorHandler()
{
$endpoint = $this->getMockEndpoint(HandlesOwnErrorsInterface::class);
$endpoint->expects($this->atLeastOnce())
->method('execute')
->will($this->returnValue(new \DateTime())); // Trigger a bad return value
$endpoint->expects($this->once())
->method('handleException');
$this->executeMockRequestOnEndpoint($endpoint);
}
/**
* @covers ::dispatch
* @covers ::setErrorHandler
*/
public function testExceptionsReachDefaultErrorHandlerWhenSet()
{
$first = new Exception('This is the initially thrown exception');
$second = new Exception('This should reach the main error handler');
$res = $this->createMock(ResponseInterface::class);
$cb = function ($req, $ex) use ($second, $res) {
$this->assertSame($second, $ex, 'A different exception reached the handler');
return $res;
};
$handler = $this->createMock(HandlerInterface::class);
$handler->expects($this->once())
->method('handle')
->will($this->returnCallback($cb));
$dispatcher = new Dispatcher();
$this->assertSame(
$dispatcher,
$dispatcher->setErrorHandler($handler),
'setErrorHandler should return $this'
);
$endpoint = $this->getMockEndpoint(HandlesOwnErrorsInterface::class);
$endpoint->method('execute')
->will($this->throwException($first));
$endpoint->expects($this->once())
->method('handleException')
->with($first)
->will($this->throwException($second));
$this->executeMockRequestOnEndpoint($endpoint, $dispatcher);
}
/** @covers ::dispatch */
public function testExceptionsLeakWhenNoErrorHandler()
{
$e = new Exception('This should reach the top level');
$endpoint = $this->getMockEndpoint();
$endpoint->method('execute')
->will($this->throwException($e));
try {
$this->executeMockRequestOnEndpoint($endpoint);
$this->fail('An exception should have been thrown');
} catch (Throwable $t) {
$this->assertSame($e, $t, 'A different exception was thrown');
}
}
/** @covers ::setAuthProviders */
public function testSetAuthProviders()
{
$dispatcher = new Dispatcher();
$this->assertSame(
$dispatcher,
$dispatcher->setAuthProviders(
$this->createMock(Authentication\ProviderInterface::class),
$this->createMock(Authorization\ProviderInterface::class)
),
'Dispacher did not return $this'
);
}
/**
* @covers ::setAuthProviders
* @covers ::setContainer
* @covers ::dispatch
*/
public function testAuthComponentsAreAutoDetected()
{
$authn = $this->createMock(Authentication\ProviderInterface::class);
$authn->expects($this->once())
->method('authenticate')
->willReturn($this->createMock(ContainerInterface::class));
$authz = $this->createMock(Authorization\ProviderInterface::class);
$authz->expects($this->once())
->method('authorize')
->willReturn(new Authorization\Ok());
$req = $this->getMockRequestWithUriPath('/c', 'GET', []);
$routes = ['GET' => ['/c' => 'ClassThatDoesNotExist']];
$endpoint = $this->createMock(Interfaces\AuthenticatedEndpointInterface::class);
$container = $this->getMockContainer([
Authentication\ProviderInterface::class => $authn,
Authorization\ProviderInterface::class => $authz,
'ClassThatDoesNotExist' => $endpoint,
]);
$dispatcher = new Dispatcher();
$dispatcher->setContainer($container)
->setEndpointList($routes)
->setParserList($this->getDefaultParserList())
->setRequest($req);
$dispatcher->dispatch();
}
/**
* @covers ::setContainer
* @covers ::setErrorHandler
* @covers ::dispatch
*/
public function testErrorHandlerIsAutoDetected()
{
$ex = new Exception('execute');
$eh = $this->createMock(HandlerInterface::class);
$eh->expects($this->once())
->method('handle')
->will($this->returnCallback(function ($sri, $caught) use ($ex) {
$this->assertSame($ex, $caught);
return $this->createMock(ResponseInterface::class);
}));
$ep = $this->createMock(EndpointInterface::class);
$ep->method('execute')
->will($this->throwException($ex));
$container = $this->getMockContainer([
HandlerInterface::class => $eh,
'ClassThatDoesNotExist' => $ep,
]);
$req = $this->getMockRequestWithUriPath('/c', 'GET', []);
$routes = ['GET' => ['/c' => 'ClassThatDoesNotExist']];
$dispatcher = new Dispatcher();
$dispatcher->setContainer($container)
->setEndpointList($routes)
->setParserList($this->getDefaultParserList())
->setRequest($req);
$dispatcher->dispatch();
}
/**
* @covers ::setAuthProviders
* @covers ::setContainer
* @covers ::dispatch
*/
public function testAutoDetectedAuthComponentsDoNotOverrideExplicit()
{
// explicitly provided should run
$authn1 = $this->createMock(Authentication\ProviderInterface::class);
$authn1->expects($this->once())
->method('authenticate')
->willReturn($this->createMock(ContainerInterface::class));
$authz1 = $this->createMock(Authorization\ProviderInterface::class);
$authz1->expects($this->once())
->method('authorize')
->willReturn(new Authorization\Ok());
// implicit from container should not
$authn2 = $this->createMock(Authentication\ProviderInterface::class);
$authn2->expects($this->never())
->method('authenticate');
$authz2 = $this->createMock(Authorization\ProviderInterface::class);
$authz2->expects($this->never())
->method('authorize');
$req = $this->getMockRequestWithUriPath('/c', 'GET', []);
$routes = ['GET' => ['/c' => 'ClassThatDoesNotExist']];
$endpoint = $this->createMock(Interfaces\AuthenticatedEndpointInterface::class);
$container = $this->getMockContainer([
Authentication\ProviderInterface::class => $authn2,
Authorization\ProviderInterface::class => $authz2,
'ClassThatDoesNotExist' => $endpoint,
]);
$dispatcher = new Dispatcher();
$dispatcher->setContainer($container)
->setAuthProviders($authn1, $authz1)
->setEndpointList($routes)
->setParserList($this->getDefaultParserList())
->setRequest($req);
$dispatcher->dispatch();
}
/** @covers ::dispatch */
public function testAuthHappensWhenProvided()
{
$authContainer = $this->createMock(ContainerInterface::class);
$authn = $this->createMock(Authentication\ProviderInterface::class);
$authn->expects($this->once())
->method('authenticate')
->willReturn($authContainer);
$response = $this->createMock(ResponseInterface::class);
$endpoint = $this->createMock(Interfaces\AuthenticatedEndpointInterface::class);
$endpoint->expects($this->once())
->method('setAuthentication')
->with($authContainer);
$endpoint->expects($this->once())
->method('execute')
->willReturn($response);
$authz = $this->createMock(Authorization\ProviderInterface::class);
$authz->expects($this->once())
->method('authorize')
->with($endpoint, $authContainer)
->willReturn(new Authorization\Ok());
$dispatcher = new Dispatcher();
$dispatcher->setAuthProviders($authn, $authz);
$res = $this->executeMockRequestOnEndpoint($endpoint, $dispatcher);
$this->assertSame($response, $res);
}
/** @covers ::dispatch */
public function testExecuteIsNotCalledWhenAuthzFails()
{
$authContainer = $this->createMock(ContainerInterface::class);
$authn = $this->createMock(Authentication\ProviderInterface::class);
$authn->expects($this->once())
->method('authenticate')
->willReturn($authContainer);
$authzEx = new Authorization\Exception();
$endpoint = $this->createMock(Interfaces\AuthenticatedEndpointInterface::class);
$endpoint->expects($this->never())
->method('execute');
$authz = $this->createMock(Authorization\ProviderInterface::class);
$authz->expects($this->once())
->method('authorize')
->with($endpoint, $authContainer)
->will($this->throwException($authzEx));
$dispatcher = new Dispatcher();
$dispatcher->setAuthProviders($authn, $authz);
try {
$this->executeMockRequestOnEndpoint($endpoint, $dispatcher);
$this->fail('An authorization exception should have been thrown');
} catch (Authorization\Exception $e) {
$this->assertSame($authzEx, $e);
}
}
/** @covers ::dispatch */
public function testExecuteIsNotCalledWhenAuthnFails()
{
$authnEx = new Authentication\Exception();
$authn = $this->createMock(Authentication\ProviderInterface::class);
$authn->expects($this->once())
->method('authenticate')
->will($this->throwException($authnEx));
$endpoint = $this->createMock(Interfaces\AuthenticatedEndpointInterface::class);
$endpoint->expects($this->never())
->method('execute');
$authz = $this->createMock(Authorization\ProviderInterface::class);
$authz->expects($this->never())
->method('authorize');
$dispatcher = new Dispatcher();
$dispatcher->setAuthProviders($authn, $authz);
try {
$this->executeMockRequestOnEndpoint($endpoint, $dispatcher);
$this->fail('An exception should have been thrown');
} catch (Authentication\Exception $e) {
$this->assertSame($authnEx, $e);
}
}
// ----(Helper methods)----------------------------------------------------
/**
* @param ResponseInterface $response response to test
* @param int $expected_code HTTP status code to check for
*/
private function checkResponse(ResponseInterface $response, int $expected_code)
{
$this->assertSame(
$expected_code,
$response->getStatusCode(),
'Incorrect status code in response'
);
}
/**
* Convenience method to get a mock PSR-7 Request that will itself support
* returning a mock PSR-7 URI with the provided path, and the HTTP method
* if provided
*
* @param string $uri path component of URI
* @param string $method optional HTTP method
* @param array $query_data optional raw, unescaped query string data
* @return ServerRequestInterface
*/
private function getMockRequestWithUriPath(
string $uri,
string $method = 'GET',
array $query_data = []
): ServerRequestInterface {
$uri .= '?' . http_build_query($query_data);
$request = new ServerRequest(
[],
[],
$uri,
$method,
'php://memory'
);
return $request;
}
/**
* Convenience method for mocking an endpoint. The mock has no required or
* optional inputs.
*
* @return EndpointInterface | \PHPUnit\Framework\MockObject\MockObject
*/
private function getMockEndpoint(string ...$additionalInterfaces): EndpointInterface
{
if ($additionalInterfaces) {
/** @var EndpointInterface | \PHPUnit\Framework\MockObject\MockObject */
$endpoint = $this->createMock(array_merge([EndpointInterface::class], $additionalInterfaces));
} else {
$endpoint = $this->createMock(EndpointInterface::class);
}
$endpoint->method('getRequiredInputs')
->will($this->returnValue([]));
$endpoint->method('getOptionalInputs')
->will($this->returnValue([]));
return $endpoint;
}
/**
* Run the endpointwith an empty request
*
* @param EndpointInterface $endpoint the endpoint to test
* @param ?Dispatcher $dispatcher a configured dispatcher
* @return ResponseInterface the endpoint response
*/
private function executeMockRequestOnEndpoint(
EndpointInterface $endpoint,
Dispatcher $dispatcher = null
): ResponseInterface {
$req = $this->getMockRequestWithUriPath('/container', 'GET', []);
$list = [
'GET' => [
'/container' => 'ClassThatDoesNotExist',
],
];
if (!$dispatcher) {
$dispatcher = new Dispatcher();
}
$response = $dispatcher
->setContainer($this->getMockContainer(['ClassThatDoesNotExist' => $endpoint]))
->setEndpointList($list)
->setParserList($this->getDefaultParserList())
->setRequest($req)
->dispatch();
return $response;
}
private function getEndpointListForFixture(): array
{
return [
'GET' => [
'/user/(?P<id>[1-9]\d*)' => __NAMESPACE__.'\EndpointFixture'
],
'POST' => [
'/user/(?P<id>[1-9]\d*)' => __NAMESPACE__.'\EndpointFixture'
],
];
}
private function getDefaultParserList(): string
{
// This could also be dynamically built
return dirname(__DIR__).'/vendor/firehed/input/src/Parsers/__parser_list__.json';
}
private function getMockContainer(array $values): ContainerInterface
{
$container = $this->createMock(ContainerInterface::class);
$container->method('has')
->willReturnCallback(function ($id) use ($values) {
return array_key_exists($id, $values);
});
$container->method('get')
->willReturnCallback(function ($id) use ($values) {
return $values[$id];
});
return $container;
}
}