This repository has been archived by the owner on Jan 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 89
/
RestfulControllerTest.php
561 lines (502 loc) · 22.9 KB
/
RestfulControllerTest.php
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
<?php
/**
* @link http://github.com/zendframework/zend-mvc for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-mvc/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Mvc\Controller;
use PHPUnit\Framework\TestCase;
use ReflectionObject;
use stdClass;
use Zend\EventManager\EventManager;
use Zend\EventManager\SharedEventManager;
use Zend\EventManager\SharedEventManagerInterface;
use Zend\Http\Response;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Mvc\Controller\Plugin\Url;
use Zend\Mvc\InjectApplicationEventInterface;
use Zend\Mvc\MvcEvent;
use Zend\Router\RouteMatch;
use Zend\Stdlib\DispatchableInterface;
use ZendTest\Mvc\Controller\TestAsset\Request;
use ZendTest\Mvc\Controller\TestAsset\RestfulContentTypeTestController;
use ZendTest\Mvc\Controller\TestAsset\RestfulMethodNotAllowedTestController;
use ZendTest\Mvc\Controller\TestAsset\RestfulTestController;
class RestfulControllerTest extends TestCase
{
public $controller;
public $emptyController;
public $request;
public $response;
public $routeMatch;
public $event;
public function setUp()
{
$this->controller = new RestfulTestController();
$this->emptyController = new RestfulMethodNotAllowedTestController();
$this->request = new Request();
$this->response = new Response();
$this->routeMatch = new RouteMatch(['controller' => 'controller-restful']);
$this->event = new MvcEvent;
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->emptyController->setEvent($this->event);
$this->sharedEvents = new SharedEventManager();
$this->events = $this->createEventManager($this->sharedEvents);
$this->controller->setEventManager($this->events);
}
/**
* @param SharedEventManager
* @return EventManager
*/
protected function createEventManager(SharedEventManagerInterface $sharedManager)
{
return new EventManager($sharedManager);
}
public function testDispatchInvokesListWhenNoActionPresentAndNoIdentifierOnGet()
{
$entities = [
new stdClass,
new stdClass,
new stdClass,
];
$this->controller->entities = $entities;
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('entities', $result);
$this->assertEquals($entities, $result['entities']);
$this->assertEquals('getList', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesGetMethodWhenNoActionPresentAndIdentifierPresentOnGet()
{
$entity = new stdClass;
$this->controller->entity = $entity;
$this->routeMatch->setParam('id', 1);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('entity', $result);
$this->assertEquals($entity, $result['entity']);
$this->assertEquals('get', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesCreateMethodWhenNoActionPresentAndPostInvoked()
{
$entity = ['id' => 1, 'name' => __FUNCTION__];
$this->request->setMethod('POST');
$post = $this->request->getPost();
$post->fromArray($entity);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('entity', $result);
$this->assertEquals($entity, $result['entity']);
$this->assertEquals('create', $this->routeMatch->getParam('action'));
}
public function testCanReceiveStringAsRequestContent()
{
$string = "any content";
$this->request->setMethod('PUT');
$this->request->setContent($string);
$this->routeMatch->setParam('id', $id = 1);
$controller = new RestfulContentTypeTestController();
$controller->setEvent($this->event);
$result = $controller->dispatch($this->request, $this->response);
$this->assertEquals($id, $result['id']);
$this->assertEquals($string, $result['data']);
$this->assertEquals('update', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesUpdateMethodWhenNoActionPresentAndPutInvokedWithIdentifier()
{
$entity = ['name' => __FUNCTION__];
$string = http_build_query($entity);
$this->request->setMethod('PUT')
->setContent($string);
$this->routeMatch->setParam('id', 1);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('entity', $result);
$test = $result['entity'];
$this->assertArrayHasKey('id', $test);
$this->assertEquals(1, $test['id']);
$this->assertArrayHasKey('name', $test);
$this->assertEquals(__FUNCTION__, $test['name']);
$this->assertEquals('update', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesReplaceListMethodWhenNoActionPresentAndPutInvokedWithoutIdentifier()
{
$entities = [
['id' => uniqid(), 'name' => __FUNCTION__],
['id' => uniqid(), 'name' => __FUNCTION__],
['id' => uniqid(), 'name' => __FUNCTION__],
];
$string = http_build_query($entities);
$this->request->setMethod('PUT')
->setContent($string);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertEquals($entities, $result);
$this->assertEquals('replaceList', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesPatchListMethodWhenNoActionPresentAndPatchInvokedWithoutIdentifier()
{
$entities = [
['id' => uniqid(), 'name' => __FUNCTION__],
['id' => uniqid(), 'name' => __FUNCTION__],
['id' => uniqid(), 'name' => __FUNCTION__],
];
$string = http_build_query($entities);
$this->request->setMethod('PATCH')
->setContent($string);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertEquals($entities, $result);
$this->assertEquals('patchList', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesDeleteMethodWhenNoActionPresentAndDeleteInvokedWithIdentifier()
{
$entity = ['id' => 1, 'name' => __FUNCTION__];
$this->controller->entity = $entity;
$this->request->setMethod('DELETE');
$this->routeMatch->setParam('id', 1);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertEquals([], $result);
$this->assertEquals([], $this->controller->entity);
$this->assertEquals('delete', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesDeleteListMethodWhenNoActionPresentAndDeleteInvokedWithoutIdentifier()
{
$entities = [
['id' => uniqid(), 'name' => __FUNCTION__],
['id' => uniqid(), 'name' => __FUNCTION__],
['id' => uniqid(), 'name' => __FUNCTION__],
];
$this->controller->entity = $entities;
$string = http_build_query($entities);
$this->request->setMethod('DELETE')
->setContent($string);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertEmpty($this->controller->entity);
$this->assertEquals(204, $result->getStatusCode());
$this->assertTrue($result->getHeaders()->has('X-Deleted'));
$this->assertEquals('deleteList', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesOptionsMethodWhenNoActionPresentAndOptionsInvoked()
{
$this->request->setMethod('OPTIONS');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($this->response, $result);
$this->assertEquals('options', $this->routeMatch->getParam('action'));
$headers = $result->getHeaders();
$this->assertTrue($headers->has('Allow'));
$allow = $headers->get('Allow');
$expected = explode(', ', 'GET, POST, PUT, DELETE, PATCH, HEAD, TRACE');
sort($expected);
$test = explode(', ', $allow->getFieldValue());
sort($test);
$this->assertEquals($expected, $test);
}
public function testDispatchInvokesPatchMethodWhenNoActionPresentAndPatchInvokedWithIdentifier()
{
$entity = new stdClass;
$entity->name = 'foo';
$entity->type = 'standard';
$this->controller->entity = $entity;
$entity = ['name' => __FUNCTION__];
$string = http_build_query($entity);
$this->request->setMethod('PATCH')
->setContent($string);
$this->routeMatch->setParam('id', 1);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('entity', $result);
$test = $result['entity'];
$this->assertArrayHasKey('id', $test);
$this->assertEquals(1, $test['id']);
$this->assertArrayHasKey('name', $test);
$this->assertEquals(__FUNCTION__, $test['name']);
$this->assertArrayHasKey('type', $test);
$this->assertEquals('standard', $test['type']);
$this->assertEquals('patch', $this->routeMatch->getParam('action'));
}
/**
* @group 7086
*/
public function testOnDispatchHonorsStatusCodeWithHeadMethod()
{
$this->controller->headResponse = new Response();
$this->controller->headResponse->setStatusCode(418);
$this->controller->headResponse->getHeaders()->addHeaderLine('Custom-Header', 'Header Value');
$this->routeMatch->setParam('id', 1);
$this->request->setMethod('HEAD');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertEquals(418, $result->getStatusCode());
$this->assertEquals('', $result->getContent());
$this->assertEquals('head', $this->routeMatch->getParam('action'));
$this->assertEquals('Header Value', $result->getHeaders()->get('Custom-Header')->getFieldValue());
}
public function testDispatchInvokesHeadMethodWhenNoActionPresentAndHeadInvokedWithoutIdentifier()
{
$entities = [
new stdClass,
new stdClass,
new stdClass,
];
$this->controller->entities = $entities;
$this->request->setMethod('HEAD');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($this->response, $result);
$content = $result->getContent();
$this->assertEquals('', $content);
$this->assertEquals('head', $this->routeMatch->getParam('action'));
}
public function testDispatchInvokesHeadMethodWhenNoActionPresentAndHeadInvokedWithIdentifier()
{
$entity = new stdClass;
$this->controller->entity = $entity;
$this->routeMatch->setParam('id', 1);
$this->request->setMethod('HEAD');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($this->response, $result);
$content = $result->getContent();
$this->assertEquals('', $content);
$this->assertEquals('head', $this->routeMatch->getParam('action'));
$headers = $this->controller->getResponse()->getHeaders();
$this->assertTrue($headers->has('X-ZF2-Id'));
$header = $headers->get('X-ZF2-Id');
$this->assertEquals(1, $header->getFieldValue());
}
public function testAllowsRegisteringCustomHttpMethodsWithHandlers()
{
$this->controller->addHttpMethodHandler('DESCRIBE', [$this->controller, 'describe']);
$this->request->setMethod('DESCRIBE');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('description', $result);
$this->assertContains('::describe', $result['description']);
}
public function testDispatchCallsActionMethodBasedOnNormalizingAction()
{
$this->routeMatch->setParam('action', 'test.some-strangely_separated.words');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('content', $result);
$this->assertContains('Test Some Strangely Separated Words', $result['content']);
}
public function testDispatchCallsNotFoundActionWhenActionPassedThatCannotBeMatched()
{
$this->routeMatch->setParam('action', 'test-some-made-up-action');
$result = $this->controller->dispatch($this->request, $this->response);
$response = $this->controller->getResponse();
$this->assertEquals(404, $response->getStatusCode());
$this->assertArrayHasKey('content', $result);
$this->assertContains('Page not found', $result['content']);
}
public function testShortCircuitsBeforeActionIfPreDispatchReturnsAResponse()
{
$response = new Response();
$response->setContent('short circuited!');
$this->controller->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, function ($e) use ($response) {
return $response;
}, 10);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($response, $result);
}
public function testPostDispatchEventAllowsReplacingResponse()
{
$response = new Response();
$response->setContent('short circuited!');
$this->controller->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, function ($e) use ($response) {
return $response;
}, -10);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($response, $result);
}
public function testEventManagerListensOnDispatchableInterfaceByDefault()
{
$response = new Response();
$response->setContent('short circuited!');
$this->sharedEvents->attach(
DispatchableInterface::class,
MvcEvent::EVENT_DISPATCH,
function ($e) use ($response) {
return $response;
},
10
);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($response, $result);
}
public function testEventManagerListensOnRestfulControllerClassByDefault()
{
$response = new Response();
$response->setContent('short circuited!');
$this->sharedEvents->attach(
AbstractRestfulController::class,
MvcEvent::EVENT_DISPATCH,
function ($e) use ($response) {
return $response;
},
10
);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($response, $result);
}
public function testEventManagerListensOnClassNameByDefault()
{
$response = new Response();
$response->setContent('short circuited!');
$this->sharedEvents->attach(
get_class($this->controller),
MvcEvent::EVENT_DISPATCH,
function ($e) use ($response) {
return $response;
},
10
);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertSame($response, $result);
}
public function testDispatchInjectsEventIntoController()
{
$this->controller->dispatch($this->request, $this->response);
$event = $this->controller->getEvent();
$this->assertNotNull($event);
$this->assertSame($this->event, $event);
}
public function testControllerIsEventAware()
{
$this->assertInstanceOf(InjectApplicationEventInterface::class, $this->controller);
}
public function testControllerIsPluggable()
{
$this->assertTrue(method_exists($this->controller, 'plugin'));
}
public function testMethodOverloadingShouldReturnPluginWhenFound()
{
$plugin = $this->controller->url();
$this->assertInstanceOf(Url::class, $plugin);
}
public function testMethodOverloadingShouldInvokePluginAsFunctorIfPossible()
{
$model = $this->event->getViewModel();
$this->controller->layout('alternate/layout');
$this->assertEquals('alternate/layout', $model->getTemplate());
}
public function testParsingDataAsJsonWillReturnAsArray()
{
$this->request->setMethod('POST');
$this->request->getHeaders()->addHeaderLine('Content-type', 'application/json');
$this->request->setContent('{"foo":"bar"}');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertInternalType('array', $result);
$this->assertEquals(['entity' => ['foo' => 'bar']], $result);
}
public function matchingContentTypes()
{
return [
'exact-first' => ['application/hal+json'],
'exact-second' => ['application/json'],
'with-charset' => ['application/json; charset=utf-8'],
'with-whitespace' => ['application/json '],
];
}
/**
* @dataProvider matchingContentTypes
*/
public function testRequestingContentTypeReturnsTrueForValidMatches($contentType)
{
$this->request->getHeaders()->addHeaderLine('Content-Type', $contentType);
$this->assertTrue($this->controller->requestHasContentType(
$this->request,
RestfulTestController::CONTENT_TYPE_JSON
));
}
public function nonMatchingContentTypes()
{
return [
'specific-type' => ['application/xml'],
'generic-type' => ['text/json'],
];
}
/**
* @dataProvider nonMatchingContentTypes
*/
public function testRequestingContentTypeReturnsFalseForInvalidMatches($contentType)
{
$this->request->getHeaders()->addHeaderLine('Content-Type', $contentType);
$this->assertFalse($this->controller->requestHasContentType(
$this->request,
RestfulTestController::CONTENT_TYPE_JSON
));
}
public function testDispatchWithUnrecognizedMethodReturns405Response()
{
$this->request->setMethod('PROPFIND');
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertInstanceOf(Response::class, $result);
$this->assertEquals(405, $result->getStatusCode());
}
public function testDispatchInvokesGetMethodWhenNoActionPresentAndZeroIdentifierPresentOnGet()
{
$entity = new stdClass;
$this->controller->entity = $entity;
$this->routeMatch->setParam('id', 0);
$result = $this->controller->dispatch($this->request, $this->response);
$this->assertArrayHasKey('entity', $result);
$this->assertEquals($entity, $result['entity']);
$this->assertEquals('get', $this->routeMatch->getParam('action'));
}
public function testIdentifierNameDefaultsToId()
{
$this->assertEquals('id', $this->controller->getIdentifierName());
}
public function testCanSetIdentifierName()
{
$this->controller->setIdentifierName('name');
$this->assertEquals('name', $this->controller->getIdentifierName());
}
public function testUsesConfiguredIdentifierNameToGetIdentifier()
{
$r = new ReflectionObject($this->controller);
$getIdentifier = $r->getMethod('getIdentifier');
$getIdentifier->setAccessible(true);
$this->controller->setIdentifierName('name');
$this->routeMatch->setParam('name', 'foo');
$result = $getIdentifier->invoke($this->controller, $this->routeMatch, $this->request);
$this->assertEquals('foo', $result);
$this->routeMatch->setParam('name', false);
$this->request->getQuery()->set('name', 'bar');
$result = $getIdentifier->invoke($this->controller, $this->routeMatch, $this->request);
$this->assertEquals('bar', $result);
}
/**
* @dataProvider providerNotImplementedMethodSets504HttpCodeProvider
*/
public function testNotImplementedMethodSets504HttpCode($method, $content, array $routeParams)
{
$this->request->setMethod($method);
if ($content) {
$this->request->setContent($content);
}
foreach ($routeParams as $name => $value) {
$this->routeMatch->setParam($name, $value);
}
$result = $this->emptyController->dispatch($this->request, $this->response);
$response = $this->emptyController->getResponse();
$this->assertEquals(405, $response->getStatusCode());
$this->assertEquals('Method Not Allowed', $this->response->getReasonPhrase());
}
public function providerNotImplementedMethodSets504HttpCodeProvider()
{
return [
['DELETE', [], ['id' => 1]], // AbstractRestfulController::delete()
['DELETE', [], []], // AbstractRestfulController::deleteList()
['GET', [], ['id' => 1]], // AbstractRestfulController::get()
['GET', [], []], // AbstractRestfulController::getList()
['HEAD', [], ['id' => 1]], // AbstractRestfulController::head()
['HEAD', [], []], // AbstractRestfulController::head()
['OPTIONS', [], []], // AbstractRestfulController::options()
['PATCH', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::patch()
['PATCH', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::patch()
['PATCH', http_build_query(['foo' => 1]), []], // AbstractRestfulController::patchList()
['PATCH', json_encode(['foo' => 1]), []], // AbstractRestfulController::patchList()
['POST', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update()
['POST', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update()
['POST', http_build_query(['foo' => 1]), []], // AbstractRestfulController::create()
['POST', json_encode(['foo' => 1]), []], // AbstractRestfulController::create()
['PUT', http_build_query(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update()
['PUT', json_encode(['foo' => 1]), ['id' => 1]], // AbstractRestfulController::update()
['PUT', http_build_query(['foo' => 1]), []], // AbstractRestfulController::replaceList()
['PUT', json_encode(['foo' => 1]), []], // AbstractRestfulController::replaceList()
];
}
}