-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
IntegrationTestCase.php
727 lines (676 loc) · 21.7 KB
/
IntegrationTestCase.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
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
<?php
/**
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\TestSuite;
use Cake\Core\Configure;
use Cake\Event\EventManager;
use Cake\Network\Request;
use Cake\Network\Session;
use Cake\Routing\DispatcherFactory;
use Cake\Routing\Router;
use Cake\TestSuite\Stub\Response;
use Cake\TestSuite\TestCase;
use Cake\Utility\Hash;
/**
* A test case class intended to make integration tests of
* your controllers easier.
*
* This test class provides a number of helper methods and features
* that make dispatching requests and checking their responses simpler.
* It favours full integration tests over mock objects as you can test
* more of your code easily and avoid some of the maintenance pitfalls
* that mock objects create.
*/
abstract class IntegrationTestCase extends TestCase
{
/**
* The data used to build the next request.
*
* @var array
*/
protected $_request = [];
/**
* The response for the most recent request.
*
* @var \Cake\Network\Response
*/
protected $_response;
/**
* The exception being thrown if the case.
*
* @var \Cake\Core\Exception\Exception
*/
protected $_exception;
/**
* Session data to use in the next request.
*
* @var array
*/
protected $_session = [];
/**
* Cookie data to use in the next request.
*
* @var array
*/
protected $_cookie = [];
/**
* The controller used in the last request.
*
* @var \Cake\Controller\Controller
*/
protected $_controller;
/**
* The last rendered view
*
* @var string
*/
protected $_viewName;
/**
* The last rendered layout
*
* @var string
*/
protected $_layoutName;
/**
* The session instance from the last request
*
* @var \Cake\Network\Session
*/
protected $_requestSession;
/**
* Resets the EventManager for before each test.
*
* @return void
*/
public function setUp()
{
parent::setUp();
EventManager::instance(new EventManager());
}
/**
* Clears the state used for requests.
*
* @return void
*/
public function tearDown()
{
parent::tearDown();
$this->_request = [];
$this->_session = [];
$this->_cookie = [];
$this->_response = null;
$this->_exception = null;
$this->_controller = null;
$this->_viewName = null;
$this->_layoutName = null;
$this->_requestSession = null;
}
/**
* Configures the data for the *next* request.
*
* This data is cleared in the tearDown() method.
*
* You can call this method multiple times to append into
* the current state.
*
* @param array $data The request data to use.
* @return void
*/
public function configRequest(array $data)
{
$this->_request = $data + $this->_request;
}
/**
* Sets session data.
*
* This method lets you configure the session data
* you want to be used for requests that follow. The session
* state is reset in each tearDown().
*
* You can call this method multiple times to append into
* the current state.
*
* @param array $data The session data to use.
* @return void
*/
public function session(array $data)
{
$this->_session = $data + $this->_session;
}
/**
* Sets a request cookie for future requests.
*
* This method lets you configure the session data
* you want to be used for requests that follow. The session
* state is reset in each tearDown().
*
* You can call this method multiple times to append into
* the current state.
*
* @param string $name The cookie name to use.
* @param mixed $value The value of the cookie.
* @return void
*/
public function cookie($name, $value)
{
$this->_cookie[$name] = $value;
}
/**
* Performs a GET request using the current request data.
*
* The response of the dispatched request will be stored as
* a property. You can use various assert methods to check the
* response.
*
* @param string|array $url The URL to request.
* @return void
*/
public function get($url)
{
$this->_sendRequest($url, 'GET');
}
/**
* Performs a POST request using the current request data.
*
* The response of the dispatched request will be stored as
* a property. You can use various assert methods to check the
* response.
*
* @param string|array $url The URL to request.
* @param array $data The data for the request.
* @return void
*/
public function post($url, $data = [])
{
$this->_sendRequest($url, 'POST', $data);
}
/**
* Performs a PATCH request using the current request data.
*
* The response of the dispatched request will be stored as
* a property. You can use various assert methods to check the
* response.
*
* @param string|array $url The URL to request.
* @param array $data The data for the request.
* @return void
*/
public function patch($url, $data = [])
{
$this->_sendRequest($url, 'PATCH', $data);
}
/**
* Performs a PUT request using the current request data.
*
* The response of the dispatched request will be stored as
* a property. You can use various assert methods to check the
* response.
*
* @param string|array $url The URL to request.
* @param array $data The data for the request.
* @return void
*/
public function put($url, $data = [])
{
$this->_sendRequest($url, 'PUT', $data);
}
/**
* Performs a DELETE request using the current request data.
*
* The response of the dispatched request will be stored as
* a property. You can use various assert methods to check the
* response.
*
* @param string|array $url The URL to request.
* @return void
*/
public function delete($url)
{
$this->_sendRequest($url, 'DELETE');
}
/**
* Creates and send the request into a Dispatcher instance.
*
* Receives and stores the response for future inspection.
*
* @param string|array $url The URL
* @param string $method The HTTP method
* @param array|null $data The request data.
* @return void
* @throws \Exception
*/
protected function _sendRequest($url, $method, $data = [])
{
$request = $this->_buildRequest($url, $method, $data);
$response = new Response();
$dispatcher = DispatcherFactory::create();
$dispatcher->eventManager()->on(
'Dispatcher.beforeDispatch',
['priority' => 999],
[$this, 'controllerSpy']
);
try {
$dispatcher->dispatch($request, $response);
$this->_requestSession = $request->session();
$this->_response = $response;
} catch (\PHPUnit_Exception $e) {
throw $e;
} catch (\Exception $e) {
$this->_exception = $e;
$this->_handleError($e);
}
}
/**
* Adds additional event spies to the controller/view event manager.
*
* @param \Cake\Event\Event $event A dispatcher event.
* @return void
*/
public function controllerSpy($event)
{
if (empty($event->data['controller'])) {
return;
}
$this->_controller = $event->data['controller'];
$events = $this->_controller->eventManager();
$events->on('View.beforeRender', function ($event, $viewFile) {
$this->_viewName = $viewFile;
});
$events->on('View.beforeLayout', function ($event, $viewFile) {
$this->_layoutName = $viewFile;
});
}
/**
* Attempts to render an error response for a given exception.
*
* This method will attempt to use the configured exception renderer.
* If that class does not exist, the built-in renderer will be used.
*
* @param \Exception $exception Exception to handle.
* @return void
* @throws \Exception
*/
protected function _handleError($exception)
{
$class = Configure::read('Error.exceptionRenderer');
if (empty($class) || !class_exists($class)) {
$class = 'Cake\Error\ExceptionRenderer';
}
$instance = new $class($exception);
$this->_response = $instance->render();
}
/**
* Creates a request object with the configured options and parameters.
*
* @param string|array $url The URL
* @param string $method The HTTP method
* @param array|null $data The request data.
* @return \Cake\Network\Request The built request.
*/
protected function _buildRequest($url, $method, $data)
{
$sessionConfig = (array)Configure::read('Session') + [
'defaults' => 'php',
];
$session = Session::create($sessionConfig);
$session->write($this->_session);
list ($url, $query) = $this->_url($url);
$props = [
'url' => $url,
'post' => $data,
'cookies' => $this->_cookie,
'session' => $session,
'query' => $query
];
$env = [];
if (isset($this->_request['headers'])) {
foreach ($this->_request['headers'] as $k => $v) {
$env['HTTP_' . str_replace('-', '_', strtoupper($k))] = $v;
}
unset($this->_request['headers']);
}
$env['REQUEST_METHOD'] = $method;
$props['environment'] = $env;
$props = Hash::merge($props, $this->_request);
return new Request($props);
}
/**
* Creates a valid request url and parameter array more like Request::_url()
*
* @param string|array $url The URL
* @return array Qualified URL and the query parameters
*/
protected function _url($url)
{
$url = Router::url($url);
$query = [];
if (strpos($url, '?') !== false) {
list($url, $parameters) = explode('?', $url, 2);
parse_str($parameters, $query);
}
return [$url, $query];
}
/**
* Fetches a view variable by name.
*
* If the view variable does not exist, null will be returned.
*
* @param string $name The view variable to get.
* @return mixed The view variable if set.
*/
public function viewVariable($name)
{
if (empty($this->_controller->viewVars)) {
$this->fail('There are no view variables, perhaps you need to run a request?');
}
if (isset($this->_controller->viewVars[$name])) {
return $this->_controller->viewVars[$name];
}
return null;
}
/**
* Asserts that the response status code is in the 2xx range.
*
* @return void
*/
public function assertResponseOk()
{
$this->_assertStatus(200, 204, 'Status code is not between 200 and 204');
}
/**
* Asserts that the response status code is in the 2xx/3xx range.
*
* @return void
*/
public function assertResponseSuccess()
{
$this->_assertStatus(200, 308, 'Status code is not between 200 and 308');
}
/**
* Asserts that the response status code is in the 4xx range.
*
* @return void
*/
public function assertResponseError()
{
$this->_assertStatus(400, 417, 'Status code is not between 400 and 417');
}
/**
* Asserts that the response status code is in the 5xx range.
*
* @return void
*/
public function assertResponseFailure()
{
$this->_assertStatus(500, 505, 'Status code is not between 500 and 505');
}
/**
* Asserts a specific response status code.
*
* @param int $code Status code to assert.
* @return void
*/
public function assertResponseCode($code)
{
$actual = $this->_response->statusCode();
$this->_assertStatus($code, $code, 'Status code is not ' . $code . ' but ' . $actual);
}
/**
* Helper method for status assertions.
*
* @param int $min Min status code.
* @param int $max Max status code.
* @param string $message The error message.
* @return void
*/
protected function _assertStatus($min, $max, $message)
{
if (!$this->_response) {
$this->fail('No response set, cannot assert status code.');
}
$status = $this->_response->statusCode();
if ($this->_exception && ($status < $min || $status > $max)) {
$this->fail($this->_exception);
}
$this->assertGreaterThanOrEqual($min, $status, $message);
$this->assertLessThanOrEqual($max, $status, $message);
}
/**
* Asserts that the Location header is correct.
*
* @param string|array|null $url The URL you expected the client to go to. This
* can either be a string URL or an array compatible with Router::url(). Use null to
* simply check for the existence of this header.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertRedirect($url = null, $message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert location header. ' . $message);
}
$result = $this->_response->header();
if ($url === null) {
$this->assertTrue(!empty($result['Location']), $message);
return;
}
if (empty($result['Location'])) {
$this->fail('No location header set. ' . $message);
}
$this->assertEquals(Router::url($url, ['_full' => true]), $result['Location'], $message);
}
/**
* Asserts that the Location header contains a substring
*
* @param string $url The URL you expected the client to go to.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertRedirectContains($url, $message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert location header. ' . $message);
}
$result = $this->_response->header();
if (empty($result['Location'])) {
$this->fail('No location header set. ' . $message);
}
$this->assertContains($url, $result['Location'], $message);
}
/**
* Asserts that the Location header is not set.
*
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertNoRedirect($message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert location header. ' . $message);
}
$result = $this->_response->header();
if (!$message) {
$message = 'Redirect header set';
}
if (!empty($result['Location'])) {
$message .= ': ' . $result['Location'];
}
$this->assertTrue(empty($result['Location']), $message);
}
/**
* Asserts response headers
*
* @param string $header The header to check
* @param string $content The content to check for.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertHeader($header, $content, $message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert headers. ' . $message);
}
$headers = $this->_response->header();
if (!isset($headers[$header])) {
$this->fail("The '$header' header is not set. " . $message);
}
$this->assertEquals($headers[$header], $content, $message);
}
/**
* Asserts content type
*
* @param string $type The content-type to check for.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertContentType($type, $message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert content-type. ' . $message);
}
$alias = $this->_response->getMimeType($type);
if ($alias !== false) {
$type = $alias;
}
$result = $this->_response->type();
$this->assertEquals($type, $result, $message);
}
/**
* Asserts content exists in the response body.
*
* @param mixed $content The content to check for.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertResponseEquals($content, $message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert content. ' . $message);
}
$this->assertEquals($content, $this->_response->body(), $message);
}
/**
* Asserts content exists in the response body.
*
* @param string $content The content to check for.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertResponseContains($content, $message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert content. ' . $message);
}
$this->assertContains($content, (string)$this->_response->body(), $message);
}
/**
* Asserts content does not exist in the response body.
*
* @param string $content The content to check for.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertResponseNotContains($content, $message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert content. ' . $message);
}
$this->assertNotContains($content, (string)$this->_response->body(), $message);
}
/**
* Assert response content is not empty.
*
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertResponseNotEmpty($message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert content. ' . $message);
}
$this->assertNotEmpty((string)$this->_response->body(), $message);
}
/**
* Assert response content is empty.
*
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertResponseEmpty($message = '')
{
if (!$this->_response) {
$this->fail('No response set, cannot assert content. ' . $message);
}
$this->assertEmpty((string)$this->_response->body(), $message);
}
/**
* Asserts that the search string was in the template name.
*
* @param string $content The content to check for.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertTemplate($content, $message = '')
{
if (!$this->_viewName) {
$this->fail('No view name stored. ' . $message);
}
$this->assertContains($content, $this->_viewName, $message);
}
/**
* Asserts that the search string was in the layout name.
*
* @param string $content The content to check for.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertLayout($content, $message = '')
{
if (!$this->_layoutName) {
$this->fail('No layout name stored. ' . $message);
}
$this->assertContains($content, $this->_layoutName, $message);
}
/**
* Asserts session contents
*
* @param string $expected The expected contents.
* @param string $path The session data path. Uses Hash::get() compatible notation
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertSession($expected, $path, $message = '')
{
if (empty($this->_requestSession)) {
$this->fail('There is no stored session data. Perhaps you need to run a request?');
}
$result = $this->_requestSession->read($path);
$this->assertEquals($expected, $result, 'Session content differs. ' . $message);
}
/**
* Asserts cookie values
*
* @param string $expected The expected contents.
* @param string $name The cookie name.
* @param string $message The failure message that will be appended to the generated message.
* @return void
*/
public function assertCookie($expected, $name, $message = '')
{
if (empty($this->_response)) {
$this->fail('Not response set, cannot assert cookies.');
}
$result = $this->_response->cookie($name);
$this->assertEquals($expected, $result['value'], 'Cookie data differs. ' . $message);
}
}