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
|
<?php
use Jasny\Controller;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
class ControllerTest extends PHPUnit_Framework_TestCase
{
/**
* Test running controller
*/
public function testInvoke()
{
$controller = $this->getController();
list($request, $response) = $this->getRequests();
$controller->expects($this->once())->method('run')->will($this->returnValue($response));
$result = $controller($request, $response);
$this->assertEquals($response, $result, "Invoking controller should return 'ResponseInterface' instance");
$this->assertEquals($response, $controller->getResponse(), "Can not get 'ResponseInterface' instance from controller");
$this->assertEquals($request, $controller->getRequest(), "Can not get 'ServerRequestInterface' instance from controller");
}
/**
* Test response status functions if response object is not set
*/
public function testResponseStatusEmptyResponse()
{
$controller = $this->getController();
$data = $this->getStatusCodesMap(null);
foreach ($data as $func => $value) {
$this->assertEquals($value, $controller->$func(), "Method '$func' returns incorrect value");
}
}
/**
* Test functions that check response status code
*
* @dataProvider responseStatusProvider
* @param int $statusCode
*/
public function testResponseStatus($code)
{
$controller = $this->getController();
list($request, $response) = $this->getRequests();
$response->method('getStatusCode')->will($this->returnValue($code));
$controller($request, $response);
$data = $this->getStatusCodesMap($code);
foreach ($data as $func => $value) {
$this->assertEquals($value, $controller->$func(), "Method '$func' returns incorrect value");
}
$this->assertEquals($data['isClientError'] || $data['isServerError'], $controller->isError(), "Method 'isError' returns incorrect value");
}
/**
* Provide data for testing status methods
*
* @return array
*/
public function responseStatusProvider()
{
return [
[null], [199],
[200], [201], [299],
[300], [304], [399],
[400], [403], [499],
[500], [503]
];
}
/**
* Test encodeData method, positive tests
*
* @dataProvider encodeDataPositiveProvider
* @param mixed $data
* @param string $format
* @param string $callback Callback name for testing jsonp request
*/
public function testEncodeDataPositive($data, $format, $callback = null)
{
$controller = $this->getController(['getRequest']);
list($request) = $this->getRequests();
if ($callback) {
$request->method('getQueryParams')->will($this->returnValue(['callback' => $callback]));
}
$controller->method('getRequest')->will($this->returnValue($request));
$result = $controller->encodeData($data, $format);
$expect = null;
if ($format === 'json') {
$expect = json_encode($data);
if ($callback) $expect = "$callback($expect)";
} else {
$expect = $data->asXML();
}
$this->assertNotEmpty($result, "Result should not be empty");
$this->assertEquals($expect, $result, "Data was not encoded correctly");
}
/**
* Provide data for testing encodeData method
*
* @return array
*/
public function encodeDataPositiveProvider()
{
$xml = simplexml_load_string(
"<?xml version='1.0'?>
<document>
<tag1>Test tag</tag1>
<tag2>Test</tag2>
</document>"
);
return [
['test_string', 'json'],
[['testKey' => 'testValue'], 'json'],
[['testKey' => 'testValue'], 'json', 'test_callback'],
['', 'json'],
['', 'json', 'test_callback'],
[$xml, 'xml']
];
}
/**
* Test encodeData method, negative tests
*
* @dataProvider encodeDataNegativeProvider
* @param mixed $data
* @param string $format
*/
public function testEncodeDataNegative($data, $format)
{
$controller = $this->getController(['getRequest']);
list($request) = $this->getRequests();
$controller->method('getRequest')->will($this->returnValue($request));
$this->expectException(\InvalidArgumentException::class);
$result = $controller->encodeData($data, $format);
}
/**
* Provide data for testing encodeData method
*
* @return array
*/
public function encodeDataNegativeProvider()
{
return [
['test_string', 'html'],
['test_string', 'jpg']
];
}
/**
* Test output
*
* @dataProvider outputProvider
* @param mixed $data
* @param string $format
* @param string $contentType
* @param string $callback Callback name for testing jsonp request
*/
public function testOutput($data, $format, $contentType, $callback = '')
{
$controller = $this->getController(['getRequest', 'getResponse']);
list($request, $response) = $this->getRequests();
if (is_scalar($data)) {
$content = $data;
} elseif ($format === 'json') {
$content = json_encode($data);
if ($callback) $content = "$callback($content)";
} elseif ($format === 'xml') {
$content = $data->asXML();
}
$this->expectOutput($response, $content, $contentType);
if ($callback) {
$request->method('getQueryParams')->will($this->returnValue(['callback' => $callback]));
}
$controller->method('getRequest')->will($this->returnValue($request));
$controller->method('getResponse')->will($this->returnValue($response));
$result = $controller->output($data, $format);
$this->assertEquals($result, $response, "Output should return response instance");
}
/**
* Provide data for testing output
*
* @return array
*/
public function outputProvider()
{
$xml = simplexml_load_string(
"<?xml version='1.0'?>
<document>
<tag1>Test tag</tag1>
<tag2>Test</tag2>
</document>"
);
return [
['test_string', 'text', 'text/plain'],
['javascript:test_call();', 'js', 'application/javascript'],
['test {}', 'css', 'text/css'],
['test_string', 'json', 'application/json'],
[['testKey' => 'testValue'], 'json', 'application/json'],
[['testKey' => 'testValue'], 'json', 'application/json', 'test_callback'],
['', 'json', 'application/json'],
['', 'json', 'application/json', 'test_callback'],
[$xml, 'xml', 'application/xml']
];
}
/**
* Test functions that deal with error messages
*
* @dataProvider errorMessagesProvider
* @param string $function
* @param int $code
* @param boolean $default Is code default for this function
*/
public function testErrorMessages($function, $code, $default)
{
$message = 'Test message';
$controller = $this->getController(['getResponse']);
list(, $response) = $this->getRequests();
$this->expectErrorMessage($response, $message, $code);
$controller->method('getResponse')->will($this->returnValue($response));
$result = $default ?
$controller->{$function}($message) :
$controller->{$function}($message, $code);
$this->assertEquals($result, $response, "Response object should be returned");
}
/**
* Provide data for testing error messages functions
*
* @return array
*/
public function errorMessagesProvider()
{
return [
['error', 400, true],
['error', 403, false],
['tooManyRequests', 429, true],
['tooManyRequests', 400, false],
['conflict', 409, true],
['conflict', 403, false],
['notFound', 404, true],
['notFound', 400, false],
['forbidden', 403, true],
['forbidden', 409, false],
['badRequest', 400, true],
['badRequest', 403, false]
];
}
/**
* Test responseWith function
*
* @dataProvider responseWithProvider
* @param int|string $code
* @param string $format
* @param int $setCode Actual code that will be set in response
* @param string $contentType
*/
public function testResponseWith($code, $format, $setCode, $contentType)
{
$controller = $this->getController(['getResponse']);
list(, $response) = $this->getRequests();
$this->expectResponseWith($response, $setCode, $contentType);
$controller->method('getResponse')->will($this->returnValue($response));
$result = $controller->responseWith($code, $format);
$this->assertEquals($result, $response, "Response object should be returned");
}
/**
* Test function responseWith
*
* @return array
*/
public function responseWithProvider()
{
return [
[200, 'json', 200, 'application/json'],
[200, 'application/json', 200, 'application/json'],
[204, null, 204, null],
['204 Created', null, 204, null],
['json', null, null, 'application/json']
];
}
/**
* Test functions that are simple wrappers around responseWith function
*
* @dataProvider responseWithWrappersProvider
* @param string $functino
* @param int $code
*/
public function testResponseWithWrappers($function, $code)
{
$controller = $this->getController(['getResponse']);
list(, $response) = $this->getRequests();
$this->expectResponseWith($response, $code);
$controller->method('getResponse')->will($this->returnValue($response));
$result = $controller->{$function}();
$this->assertEquals($result, $response, "Response object should be returned");
}
/**
* Provide data for testing responseWith wrappers
*
* @return array
*/
public function responseWithWrappersProvider()
{
return [
['ok', 200],
['noContent', 204]
];
}
/**
* Test 'created' function
*
* @dataProvider createdProvider
* @param string $location
*/
public function testCreated($location)
{
$controller = $this->getController(['getResponse']);
list(, $response) = $this->getRequests();
$response->expects($this->once())->method('withStatus')->with($this->equalTo(201))->will($this->returnSelf());
if ($location) {
$response->expects($this->once())->method('withHeader')->with($this->equalTo('Location'), $this->equalTo($location))->will($this->returnSelf());
}
$controller->method('getResponse')->will($this->returnValue($response));
$result = $controller->created($location);
$this->assertEquals($result, $response, "Response object should be returned");
}
/**
* Provide data for testing 'created' function
*
* @return array
*/
public function createdProvider()
{
return [
[''], ['/some-path/test']
];
}
/**
* Test 'redirect' function
*
* @dataProvider redirectProvider
* @param string $url
* @param int $code
* @param boolean $default
*/
public function testRedirect($url, $code, $default)
{
$controller = $this->getController(['getResponse']);
list(, $response) = $this->getRequests();
$this->expectRedirect($response, $url, $code);
$controller->method('getResponse')->will($this->returnValue($response));
$result = $default ?
$controller->redirect($url) :
$controller->redirect($url, $code);
$this->assertEquals($result, $response, "Response object should be returned");
}
/**
* Provide data for testing 'redirect' function
*
* @return array
*/
public function redirectProvider()
{
return [
['/test-url', 303, true],
['/test-url', 301, false]
];
}
/**
* Test 'requireLogin' function
*
* @dataProvider requireLoginProvider
* @param string $function
*/
public function testRequireLogin($function)
{
$controller = $this->getController(['getResponse']);
list(, $response) = $this->getRequests();
$this->expectRedirect($response, '/401', 303);
$controller->method('getResponse')->will($this->returnValue($response));
$result = $controller->{$function}();
$this->assertEquals($result, $response, "Response object should be returned");
}
/**
* Provide data for testing 'requireLogon' function
*
* @return array
*/
public function requireLoginProvider()
{
return [
['requireLogin'], ['requireAuth']
];
}
/**
* Test 'getLocalReferer' funtion
*
* @dataProvider localRefererProvider
* @param string $referer
* @param string $host
* @param boolean $local
*/
public function testLocalReferer($referer, $host, $local)
{
$controller = $this->getController(['getRequest']);
list($request) = $this->getRequests();
$this->expectLocalReferer($request, $referer, $host);
$controller->method('getRequest')->will($this->returnValue($request));
$result = $controller->getLocalReferer();
$local ?
$this->assertEquals($referer, $result, "Local referer should be returned") :
$this->assertEquals('', $result, "Local referer should not be returned");
}
/**
* Test 'back' function
*
* @dataProvider localRefererProvider
* @param string $referer
* @param string $host
* @param boolean $local
*/
public function testBack($referer, $host, $local)
{
$controller = $this->getController(['getRequest', 'getResponse']);
list($request, $response) = $this->getRequests();
$this->expectLocalReferer($request, $referer, $host);
$this->expectRedirect($response, $local ? $referer : '/', 303);
$controller->method('getRequest')->will($this->returnValue($request));
$controller->method('getResponse')->will($this->returnValue($response));
$result = $controller->back();
$this->assertEquals($result, $response, "Response object should be returned");
}
/**
* Provide data fot testing 'getLocalReferer' function
*
* @return array
*/
public function localRefererProvider()
{
return [
['http://not-local-host.com/path', 'local-host.com', false],
['http://local-host.com/path', 'local-host.com', true]
];
}
/**
* Expect for 'getLocalReferer' function to work correctly
*
* @param ServerRequestInterface $request
* @param string $referer
* @param string $host
*/
public function expectLocalReferer($request, $referer, $host)
{
$request->expects($this->exactly(2))->method('getHeaderLine')->withConsecutive(
[$this->equalTo('HTTP_REFERER')],
[$this->equalTo('HTTP_HOST')]
)->will($this->returnCallback(function($header) use ($referer, $host) {
return $header === 'HTTP_REFERER' ? $referer : $host;
}));
}
/**
* Expect for redirect
*
* @param ResponseInterface $response
* @param string $url
* @param int $code
*/
public function expectRedirect($response, $url, $code)
{
$stream = $this->createMock(StreamInterface::class);
$stream->expects($this->once())->method('write')->with($this->equalTo('You are being redirected to <a href="' . $url . '">' . $url . '</a>'));
$response->expects($this->once())->method('getBody')->will($this->returnValue($stream));
$response->expects($this->once())->method('withStatus')->with($this->equalTo($code))->will($this->returnSelf());
$response->expects($this->exactly(2))->method('withHeader')->withConsecutive(
[$this->equalTo('Content-Type'), $this->equalTo('text/html')],
[$this->equalTo('Location'), $this->equalTo($url)]
)->will($this->returnSelf());
}
/**
* Expect correct work of responseWith function
*
* @param ResponseInterface $response
* @param int $code
* @param string $contentType
*/
public function expectResponseWith($response, $code, $contentType = null)
{
$code ?
$response->expects($this->once())->method('withStatus')->with($this->equalTo($code))->will($this->returnSelf()) :
$response->expects($this->never())->method('withStatus')->with($this->equalTo($code));
$contentType ?
$response->expects($this->once())->method('withHeader')->with($this->equalTo('Content-Type'), $this->equalTo($contentType))->will($this->returnSelf()) :
$response->expects($this->never())->method('withHeader')->with($this->equalTo('Content-Type'), $this->equalTo($contentType));
}
/**
* Expect for correct work of error message functions
*
* @param ResponseInterface $response
* @param string $message
* @param int $code
*/
public function expectErrorMessage($response, $message, $code)
{
$stream = $this->createMock(StreamInterface::class);
$stream->expects($this->once())->method('write')->with($this->equalTo($message));
$response->expects($this->once())->method('withStatus')->with($this->equalTo($code))->will($this->returnSelf());
$response->expects($this->once())->method('getBody')->will($this->returnValue($stream));
}
/**
* Expects that output will be set to content
*
* @param ResponseInterface $response
* @param string $content
* @param string $contentType
*/
public function expectOutput($response, $content, $contentType)
{
$stream = $this->createMock(StreamInterface::class);
$stream->expects($this->once())->method('write')->with($this->equalTo($content));
$response->expects($this->once())->method('withHeader')->with($this->equalTo('Content-Type'), $this->equalTo($contentType))->will($this->returnSelf());
$response->expects($this->once())->method('getBody')->will($this->returnValue($stream));
}
/**
* Get mock for controller
*
* @param array $methods Methods to mock
* @return Controller
*/
public function getController($methods = [])
{
$builder = $this->getMockBuilder(Controller::class)->disableOriginalConstructor();
if ($methods) {
$builder->setMethods($methods);
}
return $builder->getMockForAbstractClass();
}
/**
* Get map of status codes to states
*
* @param int $code
* @return []
*/
public function getStatusCodesMap($code)
{
return [
'isSuccessful' => !$code || ($code >= 200 && $code < 300),
'isRedirection' => $code >= 300 && $code < 400,
'isClientError' => $code >= 400 && $code < 500,
'isServerError' => $code >= 500
];
}
/**
* Get request and response instances
*
* @return array
*/
public function getRequests()
{
return [
$this->createMock(ServerRequestInterface::class),
$this->createMock(ResponseInterface::class)
];
}
}
|