IntegrationTestCase.php 29 KB

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