IntegrationTestCase.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @since 3.0.0
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\TestSuite;
  15. use Cake\Core\Configure;
  16. use Cake\Database\Exception as DatabaseException;
  17. use Cake\Network\Request;
  18. use Cake\Network\Session;
  19. use Cake\Routing\DispatcherFactory;
  20. use Cake\Routing\Router;
  21. use Cake\TestSuite\Stub\Response;
  22. use Cake\TestSuite\RequestDispatcher;
  23. use Cake\Utility\CookieCryptTrait;
  24. use Cake\Utility\Hash;
  25. use Cake\Utility\Security;
  26. use Cake\Utility\Text;
  27. use Cake\View\Helper\SecureFieldTokenTrait;
  28. use Exception;
  29. use PHPUnit_Exception;
  30. use PHPUnit_Framework_Constraint_IsEqual;
  31. /**
  32. * A test case class intended to make integration tests of
  33. * your controllers easier.
  34. *
  35. * This test class provides a number of helper methods and features
  36. * that make dispatching requests and checking their responses simpler.
  37. * It favours full integration tests over mock objects as you can test
  38. * more of your code easily and avoid some of the maintenance pitfalls
  39. * that mock objects create.
  40. */
  41. abstract class IntegrationTestCase extends TestCase
  42. {
  43. use CookieCryptTrait;
  44. use SecureFieldTokenTrait;
  45. /**
  46. * Track whether or not tests are run against
  47. * the PSR7 HTTP stack.
  48. *
  49. * @var bool
  50. */
  51. protected $_useHttpServer = false;
  52. /**
  53. * The data used to build the next request.
  54. *
  55. * @var array
  56. */
  57. protected $_request = [];
  58. /**
  59. * The response for the most recent request.
  60. *
  61. * @var \Cake\Network\Response
  62. */
  63. protected $_response;
  64. /**
  65. * The exception being thrown if the case.
  66. *
  67. * @var \Cake\Core\Exception\Exception
  68. */
  69. protected $_exception;
  70. /**
  71. * Session data to use in the next request.
  72. *
  73. * @var array
  74. */
  75. protected $_session = [];
  76. /**
  77. * Cookie data to use in the next request.
  78. *
  79. * @var array
  80. */
  81. protected $_cookie = [];
  82. /**
  83. * The controller used in the last request.
  84. *
  85. * @var \Cake\Controller\Controller
  86. */
  87. protected $_controller;
  88. /**
  89. * The last rendered view
  90. *
  91. * @var string
  92. */
  93. protected $_viewName;
  94. /**
  95. * The last rendered layout
  96. *
  97. * @var string
  98. */
  99. protected $_layoutName;
  100. /**
  101. * The session instance from the last request
  102. *
  103. * @var \Cake\Network\Session
  104. */
  105. protected $_requestSession;
  106. /**
  107. * Boolean flag for whether or not the request should have
  108. * a SecurityComponent token added.
  109. *
  110. * @var bool
  111. */
  112. protected $_securityToken = false;
  113. /**
  114. * Boolean flag for whether or not the request should have
  115. * a CSRF token added.
  116. *
  117. * @var bool
  118. */
  119. protected $_csrfToken = false;
  120. /**
  121. *
  122. * @var null|string
  123. */
  124. protected $_cookieEncriptionKey = null;
  125. /**
  126. * Auto-detect if the Http middleware stack should be used.
  127. *
  128. * @return void
  129. */
  130. public function setUp()
  131. {
  132. parent::setUp();
  133. $namespace = Configure::read('App.namespace');
  134. $this->_useHttpServer = class_exists($namespace . '\Application');
  135. }
  136. /**
  137. * Clears the state used for requests.
  138. *
  139. * @return void
  140. */
  141. public function tearDown()
  142. {
  143. parent::tearDown();
  144. $this->_request = [];
  145. $this->_session = [];
  146. $this->_cookie = [];
  147. $this->_response = null;
  148. $this->_exception = null;
  149. $this->_controller = null;
  150. $this->_viewName = null;
  151. $this->_layoutName = null;
  152. $this->_requestSession = null;
  153. $this->_securityToken = false;
  154. $this->_csrfToken = false;
  155. $this->_useHttpServer = false;
  156. }
  157. /**
  158. * Toggle whether or not you want to use the HTTP Server stack.
  159. *
  160. * @param bool $enable Enable/disable the usage of the Http Stack.
  161. * @return void
  162. */
  163. public function useHttpServer($enable)
  164. {
  165. $this->_useHttpServer = (bool)$enable;
  166. }
  167. /**
  168. * Calling this method will enable a SecurityComponent
  169. * compatible token to be added to request data. This
  170. * lets you easily test actions protected by SecurityComponent.
  171. *
  172. * @return void
  173. */
  174. public function enableSecurityToken()
  175. {
  176. $this->_securityToken = true;
  177. }
  178. /**
  179. * Calling this method will add a CSRF token to the request.
  180. *
  181. * Both the POST data and cookie will be populated when this option
  182. * is enabled. The default parameter names will be used.
  183. *
  184. * @return void
  185. */
  186. public function enableCsrfToken()
  187. {
  188. $this->_csrfToken = true;
  189. }
  190. /**
  191. * Configures the data for the *next* request.
  192. *
  193. * This data is cleared in the tearDown() method.
  194. *
  195. * You can call this method multiple times to append into
  196. * the current state.
  197. *
  198. * @param array $data The request data to use.
  199. * @return void
  200. */
  201. public function configRequest(array $data)
  202. {
  203. $this->_request = $data + $this->_request;
  204. }
  205. /**
  206. * Sets session data.
  207. *
  208. * This method lets you configure the session data
  209. * you want to be used for requests that follow. The session
  210. * state is reset in each tearDown().
  211. *
  212. * You can call this method multiple times to append into
  213. * the current state.
  214. *
  215. * @param array $data The session data to use.
  216. * @return void
  217. */
  218. public function session(array $data)
  219. {
  220. $this->_session = $data + $this->_session;
  221. }
  222. /**
  223. * Sets a request cookie for future requests.
  224. *
  225. * This method lets you configure the session data
  226. * you want to be used for requests that follow. The session
  227. * state is reset in each tearDown().
  228. *
  229. * You can call this method multiple times to append into
  230. * the current state.
  231. *
  232. * @param string $name The cookie name to use.
  233. * @param mixed $value The value of the cookie.
  234. * @return void
  235. */
  236. public function cookie($name, $value)
  237. {
  238. $this->_cookie[$name] = $value;
  239. }
  240. /**
  241. * Returns the encryption key to be used.
  242. *
  243. * @return string
  244. */
  245. protected function _getCookieEncryptionKey()
  246. {
  247. if (isset($this->_cookieEncriptionKey)) {
  248. return $this->_cookieEncriptionKey;
  249. }
  250. return Security::salt();
  251. }
  252. /**
  253. * Sets a encrypted request cookie for future requests.
  254. *
  255. * The difference from cookie() is this encrypts the cookie
  256. * value like the CookieComponent.
  257. *
  258. * @param string $name The cookie name to use.
  259. * @param mixed $value The value of the cookie.
  260. * @param string|bool $encrypt Encryption mode to use.
  261. * @param string|null $key Encryption key used. Defaults
  262. * to Security.salt.
  263. * @return void
  264. * @see \Cake\Utility\CookieCryptTrait::_encrypt()
  265. */
  266. public function cookieEncrypted($name, $value, $encrypt = 'aes', $key = null)
  267. {
  268. $this->_cookieEncriptionKey = $key;
  269. $this->_cookie[$name] = $this->_encrypt($value, $encrypt);
  270. }
  271. /**
  272. * Performs a GET request using the current request data.
  273. *
  274. * The response of the dispatched request will be stored as
  275. * a property. You can use various assert methods to check the
  276. * response.
  277. *
  278. * @param string|array $url The URL to request.
  279. * @return void
  280. */
  281. public function get($url)
  282. {
  283. $this->_sendRequest($url, 'GET');
  284. }
  285. /**
  286. * Performs a POST request using the current request data.
  287. *
  288. * The response of the dispatched request will be stored as
  289. * a property. You can use various assert methods to check the
  290. * response.
  291. *
  292. * @param string|array $url The URL to request.
  293. * @param array $data The data for the request.
  294. * @return void
  295. */
  296. public function post($url, $data = [])
  297. {
  298. $this->_sendRequest($url, 'POST', $data);
  299. }
  300. /**
  301. * Performs a PATCH request using the current request data.
  302. *
  303. * The response of the dispatched request will be stored as
  304. * a property. You can use various assert methods to check the
  305. * response.
  306. *
  307. * @param string|array $url The URL to request.
  308. * @param array $data The data for the request.
  309. * @return void
  310. */
  311. public function patch($url, $data = [])
  312. {
  313. $this->_sendRequest($url, 'PATCH', $data);
  314. }
  315. /**
  316. * Performs a PUT request using the current request data.
  317. *
  318. * The response of the dispatched request will be stored as
  319. * a property. You can use various assert methods to check the
  320. * response.
  321. *
  322. * @param string|array $url The URL to request.
  323. * @param array $data The data for the request.
  324. * @return void
  325. */
  326. public function put($url, $data = [])
  327. {
  328. $this->_sendRequest($url, 'PUT', $data);
  329. }
  330. /**
  331. * Performs a DELETE request using the current request data.
  332. *
  333. * The response of the dispatched request will be stored as
  334. * a property. You can use various assert methods to check the
  335. * response.
  336. *
  337. * @param string|array $url The URL to request.
  338. * @return void
  339. */
  340. public function delete($url)
  341. {
  342. $this->_sendRequest($url, 'DELETE');
  343. }
  344. /**
  345. * Creates and send the request into a Dispatcher instance.
  346. *
  347. * Receives and stores the response for future inspection.
  348. *
  349. * @param string|array $url The URL
  350. * @param string $method The HTTP method
  351. * @param array|null $data The request data.
  352. * @return void
  353. * @throws \Exception
  354. */
  355. protected function _sendRequest($url, $method, $data = [])
  356. {
  357. if ($this->_useHttpServer) {
  358. $dispatcher = new MiddlewareDispatcher($this);
  359. } else {
  360. $dispatcher = new RequestDispatcher($this);
  361. }
  362. try {
  363. $request = $this->_buildRequest($url, $method, $data);
  364. $response = $dispatcher->execute($request);
  365. $this->_requestSession = $request['session'];
  366. $this->_response = $response;
  367. } catch (PHPUnit_Exception $e) {
  368. throw $e;
  369. } catch (DatabaseException $e) {
  370. throw $e;
  371. } catch (Exception $e) {
  372. $this->_exception = $e;
  373. $this->_handleError($e);
  374. }
  375. }
  376. /**
  377. * Adds additional event spies to the controller/view event manager.
  378. *
  379. * @param \Cake\Event\Event $event A dispatcher event.
  380. * @param \Cake\Controller\Controller $controller Controller instance.
  381. * @return void
  382. */
  383. public function controllerSpy($event, $controller = null)
  384. {
  385. if (!$controller) {
  386. $controller = $event->subject();
  387. }
  388. $this->_controller = $controller;
  389. $events = $controller->eventManager();
  390. $events->on('View.beforeRender', function ($event, $viewFile) {
  391. if (!$this->_viewName) {
  392. $this->_viewName = $viewFile;
  393. }
  394. });
  395. $events->on('View.beforeLayout', function ($event, $viewFile) {
  396. $this->_layoutName = $viewFile;
  397. });
  398. }
  399. /**
  400. * Attempts to render an error response for a given exception.
  401. *
  402. * This method will attempt to use the configured exception renderer.
  403. * If that class does not exist, the built-in renderer will be used.
  404. *
  405. * @param \Exception $exception Exception to handle.
  406. * @return void
  407. * @throws \Exception
  408. */
  409. protected function _handleError($exception)
  410. {
  411. $class = Configure::read('Error.exceptionRenderer');
  412. if (empty($class) || !class_exists($class)) {
  413. $class = 'Cake\Error\ExceptionRenderer';
  414. }
  415. $instance = new $class($exception);
  416. $this->_response = $instance->render();
  417. }
  418. /**
  419. * Creates a request object with the configured options and parameters.
  420. *
  421. * @param string|array $url The URL
  422. * @param string $method The HTTP method
  423. * @param array|null $data The request data.
  424. * @return array The request context
  425. */
  426. protected function _buildRequest($url, $method, $data)
  427. {
  428. $sessionConfig = (array)Configure::read('Session') + [
  429. 'defaults' => 'php',
  430. ];
  431. $session = Session::create($sessionConfig);
  432. $session->write($this->_session);
  433. list ($url, $query) = $this->_url($url);
  434. $props = [
  435. 'url' => $url,
  436. 'post' => $this->_addTokens($url, $data),
  437. 'cookies' => $this->_cookie,
  438. 'session' => $session,
  439. 'query' => $query
  440. ];
  441. if (is_string($data)) {
  442. $props['input'] = $data;
  443. }
  444. $env = [];
  445. if (isset($this->_request['headers'])) {
  446. foreach ($this->_request['headers'] as $k => $v) {
  447. $env['HTTP_' . str_replace('-', '_', strtoupper($k))] = $v;
  448. }
  449. unset($this->_request['headers']);
  450. }
  451. $env['REQUEST_METHOD'] = $method;
  452. $props['environment'] = $env;
  453. $props = Hash::merge($props, $this->_request);
  454. return $props;
  455. }
  456. /**
  457. * Add the CSRF and Security Component tokens if necessary.
  458. *
  459. * @param string $url The URL the form is being submitted on.
  460. * @param array $data The request body data.
  461. * @return array The request body with tokens added.
  462. */
  463. protected function _addTokens($url, $data)
  464. {
  465. if ($this->_securityToken === true) {
  466. $keys = array_map(function ($field) {
  467. return preg_replace('/(\.\d+)+$/', '', $field);
  468. }, array_keys(Hash::flatten($data)));
  469. $tokenData = $this->_buildFieldToken($url, array_unique($keys));
  470. $data['_Token'] = $tokenData;
  471. $data['_Token']['debug'] = 'SecurityComponent debug data would be added here';
  472. }
  473. if ($this->_csrfToken === true) {
  474. if (!isset($this->_cookie['csrfToken'])) {
  475. $this->_cookie['csrfToken'] = Text::uuid();
  476. }
  477. if (!isset($data['_csrfToken'])) {
  478. $data['_csrfToken'] = $this->_cookie['csrfToken'];
  479. }
  480. }
  481. return $data;
  482. }
  483. /**
  484. * Creates a valid request url and parameter array more like Request::_url()
  485. *
  486. * @param string|array $url The URL
  487. * @return array Qualified URL and the query parameters
  488. */
  489. protected function _url($url)
  490. {
  491. $url = Router::url($url);
  492. $query = [];
  493. if (strpos($url, '?') !== false) {
  494. list($url, $parameters) = explode('?', $url, 2);
  495. parse_str($parameters, $query);
  496. }
  497. return [$url, $query];
  498. }
  499. /**
  500. * Fetches a view variable by name.
  501. *
  502. * If the view variable does not exist, null will be returned.
  503. *
  504. * @param string $name The view variable to get.
  505. * @return mixed The view variable if set.
  506. */
  507. public function viewVariable($name)
  508. {
  509. if (empty($this->_controller->viewVars)) {
  510. $this->fail('There are no view variables, perhaps you need to run a request?');
  511. }
  512. if (isset($this->_controller->viewVars[$name])) {
  513. return $this->_controller->viewVars[$name];
  514. }
  515. return null;
  516. }
  517. /**
  518. * Asserts that the response status code is in the 2xx range.
  519. *
  520. * @return void
  521. */
  522. public function assertResponseOk()
  523. {
  524. $this->_assertStatus(200, 204, 'Status code is not between 200 and 204');
  525. }
  526. /**
  527. * Asserts that the response status code is in the 2xx/3xx range.
  528. *
  529. * @return void
  530. */
  531. public function assertResponseSuccess()
  532. {
  533. $this->_assertStatus(200, 308, 'Status code is not between 200 and 308');
  534. }
  535. /**
  536. * Asserts that the response status code is in the 4xx range.
  537. *
  538. * @return void
  539. */
  540. public function assertResponseError()
  541. {
  542. $this->_assertStatus(400, 429, 'Status code is not between 400 and 429');
  543. }
  544. /**
  545. * Asserts that the response status code is in the 5xx range.
  546. *
  547. * @return void
  548. */
  549. public function assertResponseFailure()
  550. {
  551. $this->_assertStatus(500, 505, 'Status code is not between 500 and 505');
  552. }
  553. /**
  554. * Asserts a specific response status code.
  555. *
  556. * @param int $code Status code to assert.
  557. * @return void
  558. */
  559. public function assertResponseCode($code)
  560. {
  561. $actual = $this->_response->statusCode();
  562. $this->_assertStatus($code, $code, 'Status code is not ' . $code . ' but ' . $actual);
  563. }
  564. /**
  565. * Helper method for status assertions.
  566. *
  567. * @param int $min Min status code.
  568. * @param int $max Max status code.
  569. * @param string $message The error message.
  570. * @return void
  571. */
  572. protected function _assertStatus($min, $max, $message)
  573. {
  574. if (!$this->_response) {
  575. $this->fail('No response set, cannot assert status code.');
  576. }
  577. $status = $this->_response->statusCode();
  578. if ($this->_exception && ($status < $min || $status > $max)) {
  579. $this->fail($this->_exception);
  580. }
  581. $this->assertGreaterThanOrEqual($min, $status, $message);
  582. $this->assertLessThanOrEqual($max, $status, $message);
  583. }
  584. /**
  585. * Asserts that the Location header is correct.
  586. *
  587. * @param string|array|null $url The URL you expected the client to go to. This
  588. * can either be a string URL or an array compatible with Router::url(). Use null to
  589. * simply check for the existence of this header.
  590. * @param string $message The failure message that will be appended to the generated message.
  591. * @return void
  592. */
  593. public function assertRedirect($url = null, $message = '')
  594. {
  595. if (!$this->_response) {
  596. $this->fail('No response set, cannot assert location header. ' . $message);
  597. }
  598. $result = $this->_response->header();
  599. if ($url === null) {
  600. $this->assertTrue(!empty($result['Location']), $message);
  601. return;
  602. }
  603. if (empty($result['Location'])) {
  604. $this->fail('No location header set. ' . $message);
  605. }
  606. $this->assertEquals(Router::url($url, ['_full' => true]), $result['Location'], $message);
  607. }
  608. /**
  609. * Asserts that the Location header contains a substring
  610. *
  611. * @param string $url The URL you expected the client to go to.
  612. * @param string $message The failure message that will be appended to the generated message.
  613. * @return void
  614. */
  615. public function assertRedirectContains($url, $message = '')
  616. {
  617. if (!$this->_response) {
  618. $this->fail('No response set, cannot assert location header. ' . $message);
  619. }
  620. $result = $this->_response->header();
  621. if (empty($result['Location'])) {
  622. $this->fail('No location header set. ' . $message);
  623. }
  624. $this->assertContains($url, $result['Location'], $message);
  625. }
  626. /**
  627. * Asserts that the Location header is not set.
  628. *
  629. * @param string $message The failure message that will be appended to the generated message.
  630. * @return void
  631. */
  632. public function assertNoRedirect($message = '')
  633. {
  634. if (!$this->_response) {
  635. $this->fail('No response set, cannot assert location header. ' . $message);
  636. }
  637. $result = $this->_response->header();
  638. if (!$message) {
  639. $message = 'Redirect header set';
  640. }
  641. if (!empty($result['Location'])) {
  642. $message .= ': ' . $result['Location'];
  643. }
  644. $this->assertTrue(empty($result['Location']), $message);
  645. }
  646. /**
  647. * Asserts response headers
  648. *
  649. * @param string $header The header to check
  650. * @param string $content The content to check for.
  651. * @param string $message The failure message that will be appended to the generated message.
  652. * @return void
  653. */
  654. public function assertHeader($header, $content, $message = '')
  655. {
  656. if (!$this->_response) {
  657. $this->fail('No response set, cannot assert headers. ' . $message);
  658. }
  659. $headers = $this->_response->header();
  660. if (!isset($headers[$header])) {
  661. $this->fail("The '$header' header is not set. " . $message);
  662. }
  663. $this->assertEquals($headers[$header], $content, $message);
  664. }
  665. /**
  666. * Asserts response header contains a string
  667. *
  668. * @param string $header The header to check
  669. * @param string $content The content to check for.
  670. * @param string $message The failure message that will be appended to the generated message.
  671. * @return void
  672. */
  673. public function assertHeaderContains($header, $content, $message = '')
  674. {
  675. if (!$this->_response) {
  676. $this->fail('No response set, cannot assert headers. ' . $message);
  677. }
  678. $headers = $this->_response->header();
  679. if (!isset($headers[$header])) {
  680. $this->fail("The '$header' header is not set. " . $message);
  681. }
  682. $this->assertContains($content, $headers[$header], $message);
  683. }
  684. /**
  685. * Asserts content type
  686. *
  687. * @param string $type The content-type to check for.
  688. * @param string $message The failure message that will be appended to the generated message.
  689. * @return void
  690. */
  691. public function assertContentType($type, $message = '')
  692. {
  693. if (!$this->_response) {
  694. $this->fail('No response set, cannot assert content-type. ' . $message);
  695. }
  696. $alias = $this->_response->getMimeType($type);
  697. if ($alias !== false) {
  698. $type = $alias;
  699. }
  700. $result = $this->_response->type();
  701. $this->assertEquals($type, $result, $message);
  702. }
  703. /**
  704. * Asserts content exists in the response body.
  705. *
  706. * @param mixed $content The content to check for.
  707. * @param string $message The failure message that will be appended to the generated message.
  708. * @return void
  709. */
  710. public function assertResponseEquals($content, $message = '')
  711. {
  712. if (!$this->_response) {
  713. $this->fail('No response set, cannot assert content. ' . $message);
  714. }
  715. $this->assertEquals($content, $this->_response->body(), $message);
  716. }
  717. /**
  718. * Asserts content exists in the response body.
  719. *
  720. * @param string $content The content to check for.
  721. * @param string $message The failure message that will be appended to the generated message.
  722. * @return void
  723. */
  724. public function assertResponseContains($content, $message = '')
  725. {
  726. if (!$this->_response) {
  727. $this->fail('No response set, cannot assert content. ' . $message);
  728. }
  729. $this->assertContains($content, (string)$this->_response->body(), $message);
  730. }
  731. /**
  732. * Asserts content does not exist in the response body.
  733. *
  734. * @param string $content The content to check for.
  735. * @param string $message The failure message that will be appended to the generated message.
  736. * @return void
  737. */
  738. public function assertResponseNotContains($content, $message = '')
  739. {
  740. if (!$this->_response) {
  741. $this->fail('No response set, cannot assert content. ' . $message);
  742. }
  743. $this->assertNotContains($content, (string)$this->_response->body(), $message);
  744. }
  745. /**
  746. * Assert response content is not empty.
  747. *
  748. * @param string $message The failure message that will be appended to the generated message.
  749. * @return void
  750. */
  751. public function assertResponseNotEmpty($message = '')
  752. {
  753. if (!$this->_response) {
  754. $this->fail('No response set, cannot assert content. ' . $message);
  755. }
  756. $this->assertNotEmpty((string)$this->_response->body(), $message);
  757. }
  758. /**
  759. * Assert response content is empty.
  760. *
  761. * @param string $message The failure message that will be appended to the generated message.
  762. * @return void
  763. */
  764. public function assertResponseEmpty($message = '')
  765. {
  766. if (!$this->_response) {
  767. $this->fail('No response set, cannot assert content. ' . $message);
  768. }
  769. $this->assertEmpty((string)$this->_response->body(), $message);
  770. }
  771. /**
  772. * Asserts that the search string was in the template name.
  773. *
  774. * @param string $content The content to check for.
  775. * @param string $message The failure message that will be appended to the generated message.
  776. * @return void
  777. */
  778. public function assertTemplate($content, $message = '')
  779. {
  780. if (!$this->_viewName) {
  781. $this->fail('No view name stored. ' . $message);
  782. }
  783. $this->assertContains($content, $this->_viewName, $message);
  784. }
  785. /**
  786. * Asserts that the search string was in the layout name.
  787. *
  788. * @param string $content The content to check for.
  789. * @param string $message The failure message that will be appended to the generated message.
  790. * @return void
  791. */
  792. public function assertLayout($content, $message = '')
  793. {
  794. if (!$this->_layoutName) {
  795. $this->fail('No layout name stored. ' . $message);
  796. }
  797. $this->assertContains($content, $this->_layoutName, $message);
  798. }
  799. /**
  800. * Asserts session contents
  801. *
  802. * @param string $expected The expected contents.
  803. * @param string $path The session data path. Uses Hash::get() compatible notation
  804. * @param string $message The failure message that will be appended to the generated message.
  805. * @return void
  806. */
  807. public function assertSession($expected, $path, $message = '')
  808. {
  809. if (empty($this->_requestSession)) {
  810. $this->fail('There is no stored session data. Perhaps you need to run a request?');
  811. }
  812. $result = $this->_requestSession->read($path);
  813. $this->assertEquals($expected, $result, 'Session content differs. ' . $message);
  814. }
  815. /**
  816. * Asserts cookie values
  817. *
  818. * @param string $expected The expected contents.
  819. * @param string $name The cookie name.
  820. * @param string $message The failure message that will be appended to the generated message.
  821. * @return void
  822. */
  823. public function assertCookie($expected, $name, $message = '')
  824. {
  825. if (empty($this->_response)) {
  826. $this->fail('Not response set, cannot assert cookies.');
  827. }
  828. $result = $this->_response->cookie($name);
  829. $this->assertEquals($expected, $result['value'], 'Cookie data differs. ' . $message);
  830. }
  831. /**
  832. * Asserts a cookie has not been set in the response
  833. *
  834. * @param string $cookie The cookie name to check
  835. * @param string $message The failure message that will be appended to the generated message.
  836. * @return void
  837. */
  838. public function assertCookieNotSet($cookie, $message = '')
  839. {
  840. if (!$this->_response) {
  841. $this->fail('No response set, cannot assert cookies. ' . $message);
  842. }
  843. $this->assertCookie(null, $cookie, "Cookie '{$cookie}' has been set. " . $message);
  844. }
  845. /**
  846. * Asserts cookie values which are encrypted by the
  847. * CookieComponent.
  848. *
  849. * The difference from assertCookie() is this decrypts the cookie
  850. * value like the CookieComponent for this assertion.
  851. *
  852. * @param string $expected The expected contents.
  853. * @param string $name The cookie name.
  854. * @param string|bool $encrypt Encryption mode to use.
  855. * @param string|null $key Encryption key used. Defaults
  856. * to Security.salt.
  857. * @param string $message The failure message that will be appended to the generated message.
  858. * @return void
  859. * @see \Cake\Utility\CookieCryptTrait::_encrypt()
  860. */
  861. public function assertCookieEncrypted($expected, $name, $encrypt = 'aes', $key = null, $message = '')
  862. {
  863. if (empty($this->_response)) {
  864. $this->fail('No response set, cannot assert cookies.');
  865. }
  866. $result = $this->_response->cookie($name);
  867. $this->_cookieEncriptionKey = $key;
  868. $result['value'] = $this->_decrypt($result['value'], $encrypt);
  869. $this->assertEquals($expected, $result['value'], 'Cookie data differs. ' . $message);
  870. }
  871. /**
  872. * Asserts that a file with the given name was sent in the response
  873. *
  874. * @param string $expected The file name that should be sent in the response
  875. * @param string $message The failure message that will be appended to the generated message.
  876. * @return void
  877. */
  878. public function assertFileResponse($expected, $message = '')
  879. {
  880. if ($this->_response === null) {
  881. $this->fail('No response set, cannot assert file.');
  882. }
  883. $actual = isset($this->_response->getFile()->path) ? $this->_response->getFile()->path : null;
  884. if ($actual === null) {
  885. $this->fail('No file was sent in this response');
  886. }
  887. $this->assertEquals($expected, $actual, $message);
  888. }
  889. }