IntegrationTestTrait.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @since 3.7.0
  12. * @license https://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\Http\ServerRequest;
  18. use Cake\Http\Session;
  19. use Cake\Routing\Router;
  20. use Cake\TestSuite\Constraint\Response\BodyContains;
  21. use Cake\TestSuite\Constraint\Response\BodyEmpty;
  22. use Cake\TestSuite\Constraint\Response\BodyEquals;
  23. use Cake\TestSuite\Constraint\Response\BodyNotContains;
  24. use Cake\TestSuite\Constraint\Response\BodyNotEmpty;
  25. use Cake\TestSuite\Constraint\Response\BodyNotEquals;
  26. use Cake\TestSuite\Constraint\Response\BodyNotRegExp;
  27. use Cake\TestSuite\Constraint\Response\BodyRegExp;
  28. use Cake\TestSuite\Constraint\Response\ContentType;
  29. use Cake\TestSuite\Constraint\Response\CookieEncryptedEquals;
  30. use Cake\TestSuite\Constraint\Response\CookieEquals;
  31. use Cake\TestSuite\Constraint\Response\CookieNotSet;
  32. use Cake\TestSuite\Constraint\Response\CookieSet;
  33. use Cake\TestSuite\Constraint\Response\FileSent;
  34. use Cake\TestSuite\Constraint\Response\FileSentAs;
  35. use Cake\TestSuite\Constraint\Response\HeaderContains;
  36. use Cake\TestSuite\Constraint\Response\HeaderEquals;
  37. use Cake\TestSuite\Constraint\Response\HeaderNotContains;
  38. use Cake\TestSuite\Constraint\Response\HeaderNotSet;
  39. use Cake\TestSuite\Constraint\Response\HeaderSet;
  40. use Cake\TestSuite\Constraint\Response\StatusCode;
  41. use Cake\TestSuite\Constraint\Response\StatusError;
  42. use Cake\TestSuite\Constraint\Response\StatusFailure;
  43. use Cake\TestSuite\Constraint\Response\StatusOk;
  44. use Cake\TestSuite\Constraint\Response\StatusSuccess;
  45. use Cake\TestSuite\Constraint\Session\FlashParamEquals;
  46. use Cake\TestSuite\Constraint\Session\SessionEquals;
  47. use Cake\TestSuite\Constraint\View\LayoutFileEquals;
  48. use Cake\TestSuite\Constraint\View\TemplateFileEquals;
  49. use Cake\TestSuite\Stub\TestExceptionRenderer;
  50. use Cake\Utility\CookieCryptTrait;
  51. use Cake\Utility\Hash;
  52. use Cake\Utility\Security;
  53. use Cake\Utility\Text;
  54. use Cake\View\Helper\SecureFieldTokenTrait;
  55. use Exception;
  56. use LogicException;
  57. use PHPUnit\Exception as PhpunitException;
  58. use Zend\Diactoros\Uri;
  59. /**
  60. * A trait intended to make integration tests of your controllers easier.
  61. *
  62. * This test class provides a number of helper methods and features
  63. * that make dispatching requests and checking their responses simpler.
  64. * It favours full integration tests over mock objects as you can test
  65. * more of your code easily and avoid some of the maintenance pitfalls
  66. * that mock objects create.
  67. */
  68. trait IntegrationTestTrait
  69. {
  70. use CookieCryptTrait;
  71. use SecureFieldTokenTrait;
  72. /**
  73. * Track whether or not tests are run against
  74. * the PSR7 HTTP stack.
  75. *
  76. * @var bool
  77. */
  78. protected $_useHttpServer = false;
  79. /**
  80. * The customized application class name.
  81. *
  82. * @var string|null
  83. */
  84. protected $_appClass;
  85. /**
  86. * The customized application constructor arguments.
  87. *
  88. * @var array|null
  89. */
  90. protected $_appArgs;
  91. /**
  92. * The data used to build the next request.
  93. *
  94. * @var array
  95. */
  96. protected $_request = [];
  97. /**
  98. * The response for the most recent request.
  99. *
  100. * @var \Cake\Http\Response|null
  101. */
  102. protected $_response;
  103. /**
  104. * The exception being thrown if the case.
  105. *
  106. * @var \Exception|null
  107. */
  108. protected $_exception;
  109. /**
  110. * Session data to use in the next request.
  111. *
  112. * @var array
  113. */
  114. protected $_session = [];
  115. /**
  116. * Cookie data to use in the next request.
  117. *
  118. * @var array
  119. */
  120. protected $_cookie = [];
  121. /**
  122. * The controller used in the last request.
  123. *
  124. * @var \Cake\Controller\Controller|null
  125. */
  126. protected $_controller;
  127. /**
  128. * The last rendered view
  129. *
  130. * @var string|null
  131. */
  132. protected $_viewName;
  133. /**
  134. * The last rendered layout
  135. *
  136. * @var string|null
  137. */
  138. protected $_layoutName;
  139. /**
  140. * The session instance from the last request
  141. *
  142. * @var \Cake\Http\Session|null
  143. */
  144. protected $_requestSession;
  145. /**
  146. * Boolean flag for whether or not the request should have
  147. * a SecurityComponent token added.
  148. *
  149. * @var bool
  150. */
  151. protected $_securityToken = false;
  152. /**
  153. * Boolean flag for whether or not the request should have
  154. * a CSRF token added.
  155. *
  156. * @var bool
  157. */
  158. protected $_csrfToken = false;
  159. /**
  160. * Boolean flag for whether or not the request should re-store
  161. * flash messages
  162. *
  163. * @var bool
  164. */
  165. protected $_retainFlashMessages = false;
  166. /**
  167. * Stored flash messages before render
  168. *
  169. * @var array|null
  170. */
  171. protected $_flashMessages;
  172. /**
  173. *
  174. * @var string|null
  175. */
  176. protected $_cookieEncryptionKey;
  177. /**
  178. * List of fields that are excluded from field validation.
  179. *
  180. * @var string[]
  181. */
  182. protected $_unlockedFields = [];
  183. /**
  184. * Auto-detect if the HTTP middleware stack should be used.
  185. *
  186. * @before
  187. * @return void
  188. */
  189. public function setupServer()
  190. {
  191. $namespace = Configure::read('App.namespace');
  192. $this->_useHttpServer = class_exists($namespace . '\Application');
  193. }
  194. /**
  195. * Clears the state used for requests.
  196. *
  197. * @after
  198. * @return void
  199. */
  200. public function cleanup()
  201. {
  202. $this->_request = [];
  203. $this->_session = [];
  204. $this->_cookie = [];
  205. $this->_response = null;
  206. $this->_exception = null;
  207. $this->_controller = null;
  208. $this->_viewName = null;
  209. $this->_layoutName = null;
  210. $this->_requestSession = null;
  211. $this->_appClass = null;
  212. $this->_appArgs = null;
  213. $this->_securityToken = false;
  214. $this->_csrfToken = false;
  215. $this->_retainFlashMessages = false;
  216. $this->_useHttpServer = false;
  217. }
  218. /**
  219. * Toggle whether or not you want to use the HTTP Server stack.
  220. *
  221. * @param bool $enable Enable/disable the usage of the HTTP Stack.
  222. * @return void
  223. */
  224. public function useHttpServer($enable)
  225. {
  226. $this->_useHttpServer = (bool)$enable;
  227. }
  228. /**
  229. * Configure the application class to use in integration tests.
  230. *
  231. * Combined with `useHttpServer()` to customize the class name and constructor arguments
  232. * of your application class.
  233. *
  234. * @param string $class The application class name.
  235. * @param array|null $constructorArgs The constructor arguments for your application class.
  236. * @return void
  237. */
  238. public function configApplication($class, $constructorArgs)
  239. {
  240. $this->_appClass = $class;
  241. $this->_appArgs = $constructorArgs;
  242. }
  243. /**
  244. * Calling this method will enable a SecurityComponent
  245. * compatible token to be added to request data. This
  246. * lets you easily test actions protected by SecurityComponent.
  247. *
  248. * @return void
  249. */
  250. public function enableSecurityToken()
  251. {
  252. $this->_securityToken = true;
  253. }
  254. /**
  255. * Set list of fields that are excluded from field validation.
  256. *
  257. * @param string[] $unlockedFields List of fields that are excluded from field validation.
  258. * @return void
  259. */
  260. public function setUnlockedFields(array $unlockedFields = [])
  261. {
  262. $this->_unlockedFields = $unlockedFields;
  263. }
  264. /**
  265. * Calling this method will add a CSRF token to the request.
  266. *
  267. * Both the POST data and cookie will be populated when this option
  268. * is enabled. The default parameter names will be used.
  269. *
  270. * @return void
  271. */
  272. public function enableCsrfToken()
  273. {
  274. $this->_csrfToken = true;
  275. }
  276. /**
  277. * Calling this method will re-store flash messages into the test session
  278. * after being removed by the FlashHelper
  279. *
  280. * @return void
  281. */
  282. public function enableRetainFlashMessages()
  283. {
  284. $this->_retainFlashMessages = true;
  285. }
  286. /**
  287. * Configures the data for the *next* request.
  288. *
  289. * This data is cleared in the tearDown() method.
  290. *
  291. * You can call this method multiple times to append into
  292. * the current state.
  293. *
  294. * @param array $data The request data to use.
  295. * @return void
  296. */
  297. public function configRequest(array $data)
  298. {
  299. $this->_request = $data + $this->_request;
  300. }
  301. /**
  302. * Sets session data.
  303. *
  304. * This method lets you configure the session data
  305. * you want to be used for requests that follow. The session
  306. * state is reset in each tearDown().
  307. *
  308. * You can call this method multiple times to append into
  309. * the current state.
  310. *
  311. * @param array $data The session data to use.
  312. * @return void
  313. */
  314. public function session(array $data)
  315. {
  316. $this->_session = $data + $this->_session;
  317. }
  318. /**
  319. * Sets a request cookie for future requests.
  320. *
  321. * This method lets you configure the session data
  322. * you want to be used for requests that follow. The session
  323. * state is reset in each tearDown().
  324. *
  325. * You can call this method multiple times to append into
  326. * the current state.
  327. *
  328. * @param string $name The cookie name to use.
  329. * @param mixed $value The value of the cookie.
  330. * @return void
  331. */
  332. public function cookie($name, $value)
  333. {
  334. $this->_cookie[$name] = $value;
  335. }
  336. /**
  337. * Returns the encryption key to be used.
  338. *
  339. * @return string
  340. */
  341. protected function _getCookieEncryptionKey()
  342. {
  343. if (isset($this->_cookieEncryptionKey)) {
  344. return $this->_cookieEncryptionKey;
  345. }
  346. return Security::getSalt();
  347. }
  348. /**
  349. * Sets a encrypted request cookie for future requests.
  350. *
  351. * The difference from cookie() is this encrypts the cookie
  352. * value like the CookieComponent.
  353. *
  354. * @param string $name The cookie name to use.
  355. * @param mixed $value The value of the cookie.
  356. * @param string|bool $encrypt Encryption mode to use.
  357. * @param string|null $key Encryption key used. Defaults
  358. * to Security.salt.
  359. * @return void
  360. * @see \Cake\Utility\CookieCryptTrait::_encrypt()
  361. */
  362. public function cookieEncrypted($name, $value, $encrypt = 'aes', $key = null)
  363. {
  364. $this->_cookieEncryptionKey = $key;
  365. $this->_cookie[$name] = $this->_encrypt($value, $encrypt);
  366. }
  367. /**
  368. * Performs a GET request using the current request data.
  369. *
  370. * The response of the dispatched request will be stored as
  371. * a property. You can use various assert methods to check the
  372. * response.
  373. *
  374. * @param string|array $url The URL to request.
  375. * @return void
  376. * @throws \PHPUnit\Exception
  377. */
  378. public function get($url)
  379. {
  380. $this->_sendRequest($url, 'GET');
  381. }
  382. /**
  383. * Performs a POST request using the current request data.
  384. *
  385. * The response of the dispatched request will be stored as
  386. * a property. You can use various assert methods to check the
  387. * response.
  388. *
  389. * @param string|array $url The URL to request.
  390. * @param string|array|null $data The data for the request.
  391. * @return void
  392. * @throws \PHPUnit\Exception
  393. */
  394. public function post($url, $data = [])
  395. {
  396. $this->_sendRequest($url, 'POST', $data);
  397. }
  398. /**
  399. * Performs a PATCH request using the current request data.
  400. *
  401. * The response of the dispatched request will be stored as
  402. * a property. You can use various assert methods to check the
  403. * response.
  404. *
  405. * @param string|array $url The URL to request.
  406. * @param string|array|null $data The data for the request.
  407. * @return void
  408. * @throws \PHPUnit\Exception
  409. */
  410. public function patch($url, $data = [])
  411. {
  412. $this->_sendRequest($url, 'PATCH', $data);
  413. }
  414. /**
  415. * Performs a PUT request using the current request data.
  416. *
  417. * The response of the dispatched request will be stored as
  418. * a property. You can use various assert methods to check the
  419. * response.
  420. *
  421. * @param string|array $url The URL to request.
  422. * @param string|array|null $data The data for the request.
  423. * @return void
  424. * @throws \PHPUnit\Exception
  425. */
  426. public function put($url, $data = [])
  427. {
  428. $this->_sendRequest($url, 'PUT', $data);
  429. }
  430. /**
  431. * Performs a DELETE request using the current request data.
  432. *
  433. * The response of the dispatched request will be stored as
  434. * a property. You can use various assert methods to check the
  435. * response.
  436. *
  437. * @param string|array $url The URL to request.
  438. * @return void
  439. * @throws \PHPUnit\Exception
  440. */
  441. public function delete($url)
  442. {
  443. $this->_sendRequest($url, 'DELETE');
  444. }
  445. /**
  446. * Performs a HEAD request using the current request data.
  447. *
  448. * The response of the dispatched request will be stored as
  449. * a property. You can use various assert methods to check the
  450. * response.
  451. *
  452. * @param string|array $url The URL to request.
  453. * @return void
  454. * @throws \PHPUnit\Exception
  455. */
  456. public function head($url)
  457. {
  458. $this->_sendRequest($url, 'HEAD');
  459. }
  460. /**
  461. * Performs an OPTIONS request using the current request data.
  462. *
  463. * The response of the dispatched request will be stored as
  464. * a property. You can use various assert methods to check the
  465. * response.
  466. *
  467. * @param string|array $url The URL to request.
  468. * @return void
  469. * @throws \PHPUnit\Exception
  470. */
  471. public function options($url)
  472. {
  473. $this->_sendRequest($url, 'OPTIONS');
  474. }
  475. /**
  476. * Creates and send the request into a Dispatcher instance.
  477. *
  478. * Receives and stores the response for future inspection.
  479. *
  480. * @param string|array $url The URL
  481. * @param string $method The HTTP method
  482. * @param string|array|null $data The request data.
  483. * @return void
  484. * @throws \PHPUnit\Exception
  485. */
  486. protected function _sendRequest($url, $method, $data = [])
  487. {
  488. $dispatcher = $this->_makeDispatcher();
  489. $url = $dispatcher->resolveUrl($url);
  490. try {
  491. $request = $this->_buildRequest($url, $method, $data);
  492. $response = $dispatcher->execute($request);
  493. $this->_requestSession = $request['session'];
  494. if ($this->_retainFlashMessages && $this->_flashMessages) {
  495. $this->_requestSession->write('Flash', $this->_flashMessages);
  496. }
  497. $this->_response = $response;
  498. } catch (PhpUnitException $e) {
  499. throw $e;
  500. } catch (DatabaseException $e) {
  501. throw $e;
  502. } catch (LogicException $e) {
  503. throw $e;
  504. } catch (Exception $e) {
  505. $this->_exception = $e;
  506. // Simulate the global exception handler being invoked.
  507. $this->_handleError($e);
  508. }
  509. }
  510. /**
  511. * Get the correct dispatcher instance.
  512. *
  513. * @return \Cake\TestSuite\MiddlewareDispatcher|\Cake\TestSuite\LegacyRequestDispatcher A dispatcher instance
  514. */
  515. protected function _makeDispatcher()
  516. {
  517. if ($this->_useHttpServer) {
  518. return new MiddlewareDispatcher($this, $this->_appClass, $this->_appArgs);
  519. }
  520. return new LegacyRequestDispatcher($this);
  521. }
  522. /**
  523. * Adds additional event spies to the controller/view event manager.
  524. *
  525. * @param \Cake\Event\Event $event A dispatcher event.
  526. * @param \Cake\Controller\Controller|null $controller Controller instance.
  527. * @return void
  528. */
  529. public function controllerSpy($event, $controller = null)
  530. {
  531. if (!$controller) {
  532. /** @var \Cake\Controller\Controller $controller */
  533. $controller = $event->getSubject();
  534. }
  535. $this->_controller = $controller;
  536. $events = $controller->getEventManager();
  537. $events->on('View.beforeRender', function ($event, $viewFile) use ($controller) {
  538. if (!$this->_viewName) {
  539. $this->_viewName = $viewFile;
  540. }
  541. if ($this->_retainFlashMessages) {
  542. $this->_flashMessages = $controller->getRequest()->getSession()->read('Flash');
  543. }
  544. });
  545. $events->on('View.beforeLayout', function ($event, $viewFile) {
  546. $this->_layoutName = $viewFile;
  547. });
  548. }
  549. /**
  550. * Attempts to render an error response for a given exception.
  551. *
  552. * This method will attempt to use the configured exception renderer.
  553. * If that class does not exist, the built-in renderer will be used.
  554. *
  555. * @param \Exception $exception Exception to handle.
  556. * @return void
  557. * @throws \Exception
  558. */
  559. protected function _handleError($exception)
  560. {
  561. $class = Configure::read('Error.exceptionRenderer');
  562. if (empty($class) || !class_exists($class)) {
  563. $class = 'Cake\Error\ExceptionRenderer';
  564. }
  565. /** @var \Cake\Error\ExceptionRenderer $instance */
  566. $instance = new $class($exception);
  567. $this->_response = $instance->render();
  568. }
  569. /**
  570. * Creates a request object with the configured options and parameters.
  571. *
  572. * @param string|array $url The URL
  573. * @param string $method The HTTP method
  574. * @param string|array|null $data The request data.
  575. * @return array The request context
  576. */
  577. protected function _buildRequest($url, $method, $data)
  578. {
  579. $sessionConfig = (array)Configure::read('Session') + [
  580. 'defaults' => 'php',
  581. ];
  582. $session = Session::create($sessionConfig);
  583. $session->write($this->_session);
  584. list($url, $query, $hostInfo) = $this->_url($url);
  585. $tokenUrl = $url;
  586. if ($query) {
  587. $tokenUrl .= '?' . $query;
  588. }
  589. parse_str($query, $queryData);
  590. $props = [
  591. 'url' => $url,
  592. 'session' => $session,
  593. 'query' => $queryData,
  594. 'files' => [],
  595. ];
  596. if (is_string($data)) {
  597. $props['input'] = $data;
  598. }
  599. if (!isset($props['input'])) {
  600. $data = $this->_addTokens($tokenUrl, $data);
  601. $props['post'] = $this->_castToString($data);
  602. }
  603. $props['cookies'] = $this->_cookie;
  604. $env = [
  605. 'REQUEST_METHOD' => $method,
  606. 'QUERY_STRING' => $query,
  607. 'REQUEST_URI' => $url,
  608. ];
  609. if (!empty($hostInfo['ssl'])) {
  610. $env['HTTPS'] = 'on';
  611. }
  612. if (isset($hostInfo['host'])) {
  613. $env['HTTP_HOST'] = $hostInfo['host'];
  614. }
  615. if (isset($this->_request['headers'])) {
  616. foreach ($this->_request['headers'] as $k => $v) {
  617. $name = strtoupper(str_replace('-', '_', $k));
  618. if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
  619. $name = 'HTTP_' . $name;
  620. }
  621. $env[$name] = $v;
  622. }
  623. unset($this->_request['headers']);
  624. }
  625. $props['environment'] = $env;
  626. $props = Hash::merge($props, $this->_request);
  627. return $props;
  628. }
  629. /**
  630. * Add the CSRF and Security Component tokens if necessary.
  631. *
  632. * @param string $url The URL the form is being submitted on.
  633. * @param array $data The request body data.
  634. * @return array The request body with tokens added.
  635. */
  636. protected function _addTokens($url, $data)
  637. {
  638. if ($this->_securityToken === true) {
  639. $fields = array_diff_key($data, array_flip($this->_unlockedFields));
  640. $keys = array_map(function ($field) {
  641. return preg_replace('/(\.\d+)+$/', '', $field);
  642. }, array_keys(Hash::flatten($fields)));
  643. $tokenData = $this->_buildFieldToken($url, array_unique($keys), $this->_unlockedFields);
  644. $data['_Token'] = $tokenData;
  645. $data['_Token']['debug'] = 'SecurityComponent debug data would be added here';
  646. }
  647. if ($this->_csrfToken === true) {
  648. if (!isset($this->_cookie['csrfToken'])) {
  649. $this->_cookie['csrfToken'] = Text::uuid();
  650. }
  651. if (!isset($data['_csrfToken'])) {
  652. $data['_csrfToken'] = $this->_cookie['csrfToken'];
  653. }
  654. }
  655. return $data;
  656. }
  657. /**
  658. * Recursively casts all data to string as that is how data would be POSTed in
  659. * the real world
  660. *
  661. * @param array $data POST data
  662. * @return array
  663. */
  664. protected function _castToString($data)
  665. {
  666. foreach ($data as $key => $value) {
  667. if (is_scalar($value)) {
  668. $data[$key] = $value === false ? '0' : (string)$value;
  669. continue;
  670. }
  671. if (is_array($value)) {
  672. $looksLikeFile = isset($value['error'], $value['tmp_name'], $value['size']);
  673. if ($looksLikeFile) {
  674. continue;
  675. }
  676. $data[$key] = $this->_castToString($value);
  677. }
  678. }
  679. return $data;
  680. }
  681. /**
  682. * Creates a valid request url and parameter array more like Request::_url()
  683. *
  684. * @param string|array $url The URL
  685. * @return array Qualified URL, the query parameters, and host data
  686. */
  687. protected function _url($url)
  688. {
  689. $uri = new Uri($url);
  690. $path = $uri->getPath();
  691. $query = $uri->getQuery();
  692. $hostData = [];
  693. if ($uri->getHost()) {
  694. $hostData['host'] = $uri->getHost();
  695. }
  696. if ($uri->getScheme()) {
  697. $hostData['ssl'] = $uri->getScheme() === 'https';
  698. }
  699. return [$path, $query, $hostData];
  700. }
  701. /**
  702. * Get the response body as string
  703. *
  704. * @return string The response body.
  705. */
  706. protected function _getBodyAsString()
  707. {
  708. if (!$this->_response) {
  709. $this->fail('No response set, cannot assert content.');
  710. }
  711. return (string)$this->_response->getBody();
  712. }
  713. /**
  714. * Fetches a view variable by name.
  715. *
  716. * If the view variable does not exist, null will be returned.
  717. *
  718. * @param string $name The view variable to get.
  719. * @return mixed The view variable if set.
  720. */
  721. public function viewVariable($name)
  722. {
  723. if (empty($this->_controller->viewVars)) {
  724. $this->fail('There are no view variables, perhaps you need to run a request?');
  725. }
  726. if (isset($this->_controller->viewVars[$name])) {
  727. return $this->_controller->viewVars[$name];
  728. }
  729. return null;
  730. }
  731. /**
  732. * Asserts that the response status code is in the 2xx range.
  733. *
  734. * @param string $message Custom message for failure.
  735. * @return void
  736. */
  737. public function assertResponseOk($message = null)
  738. {
  739. $verboseMessage = $this->extractVerboseMessage($message);
  740. $this->assertThat(null, new StatusOk($this->_response), $verboseMessage);
  741. }
  742. /**
  743. * Asserts that the response status code is in the 2xx/3xx range.
  744. *
  745. * @param string $message Custom message for failure.
  746. * @return void
  747. */
  748. public function assertResponseSuccess($message = null)
  749. {
  750. $verboseMessage = $this->extractVerboseMessage($message);
  751. $this->assertThat(null, new StatusSuccess($this->_response), $verboseMessage);
  752. }
  753. /**
  754. * Asserts that the response status code is in the 4xx range.
  755. *
  756. * @param string $message Custom message for failure.
  757. * @return void
  758. */
  759. public function assertResponseError($message = null)
  760. {
  761. $this->assertThat(null, new StatusError($this->_response), $message);
  762. }
  763. /**
  764. * Asserts that the response status code is in the 5xx range.
  765. *
  766. * @param string $message Custom message for failure.
  767. * @return void
  768. */
  769. public function assertResponseFailure($message = null)
  770. {
  771. $this->assertThat(null, new StatusFailure($this->_response), $message);
  772. }
  773. /**
  774. * Asserts a specific response status code.
  775. *
  776. * @param int $code Status code to assert.
  777. * @param string $message Custom message for failure.
  778. * @return void
  779. */
  780. public function assertResponseCode($code, $message = null)
  781. {
  782. $this->assertThat($code, new StatusCode($this->_response), $message);
  783. }
  784. /**
  785. * Asserts that the Location header is correct. Comparison is made against a full URL.
  786. *
  787. * @param string|array|null $url The URL you expected the client to go to. This
  788. * can either be a string URL or an array compatible with Router::url(). Use null to
  789. * simply check for the existence of this header.
  790. * @param string $message The failure message that will be appended to the generated message.
  791. * @return void
  792. */
  793. public function assertRedirect($url = null, $message = '')
  794. {
  795. $verboseMessage = $this->extractVerboseMessage($message);
  796. $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $verboseMessage);
  797. if ($url) {
  798. $this->assertThat(Router::url($url, ['_full' => true]), new HeaderEquals($this->_response, 'Location'), $verboseMessage);
  799. }
  800. }
  801. /**
  802. * Asserts that the Location header is correct. Comparison is made against exactly the URL provided.
  803. *
  804. * @param string|array|null $url The URL you expected the client to go to. This
  805. * can either be a string URL or an array compatible with Router::url(). Use null to
  806. * simply check for the existence of this header.
  807. * @param string $message The failure message that will be appended to the generated message.
  808. * @return void
  809. */
  810. public function assertRedirectEquals($url = null, $message = '')
  811. {
  812. $verboseMessage = $this->extractVerboseMessage($message);
  813. $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $verboseMessage);
  814. if ($url) {
  815. $this->assertThat(Router::url($url), new HeaderEquals($this->_response, 'Location'), $verboseMessage);
  816. }
  817. }
  818. /**
  819. * Asserts that the Location header contains a substring
  820. *
  821. * @param string $url The URL you expected the client to go to.
  822. * @param string $message The failure message that will be appended to the generated message.
  823. * @return void
  824. */
  825. public function assertRedirectContains($url, $message = '')
  826. {
  827. $verboseMessage = $this->extractVerboseMessage($message);
  828. $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $verboseMessage);
  829. $this->assertThat($url, new HeaderContains($this->_response, 'Location'), $verboseMessage);
  830. }
  831. /**
  832. * Asserts that the Location header does not contain a substring
  833. *
  834. * @param string $url The URL you expected the client to go to.
  835. * @param string $message The failure message that will be appended to the generated message.
  836. * @return void
  837. */
  838. public function assertRedirectNotContains($url, $message = '')
  839. {
  840. $verboseMessage = $this->extractVerboseMessage($message);
  841. $this->assertThat(null, new HeaderSet($this->_response, 'Location'), $verboseMessage);
  842. $this->assertThat($url, new HeaderNotContains($this->_response, 'Location'), $verboseMessage);
  843. }
  844. /**
  845. * Asserts that the Location header is not set.
  846. *
  847. * @param string $message The failure message that will be appended to the generated message.
  848. * @return void
  849. */
  850. public function assertNoRedirect($message = '')
  851. {
  852. $verboseMessage = $this->extractVerboseMessage($message);
  853. $this->assertThat(null, new HeaderNotSet($this->_response, 'Location'), $verboseMessage);
  854. }
  855. /**
  856. * Asserts response headers
  857. *
  858. * @param string $header The header to check
  859. * @param string $content The content to check for.
  860. * @param string $message The failure message that will be appended to the generated message.
  861. * @return void
  862. */
  863. public function assertHeader($header, $content, $message = '')
  864. {
  865. $verboseMessage = $this->extractVerboseMessage($message);
  866. $this->assertThat(null, new HeaderSet($this->_response, $header), $verboseMessage);
  867. $this->assertThat($content, new HeaderEquals($this->_response, $header), $verboseMessage);
  868. }
  869. /**
  870. * Asserts response header contains a string
  871. *
  872. * @param string $header The header to check
  873. * @param string $content The content to check for.
  874. * @param string $message The failure message that will be appended to the generated message.
  875. * @return void
  876. */
  877. public function assertHeaderContains($header, $content, $message = '')
  878. {
  879. $verboseMessage = $this->extractVerboseMessage($message);
  880. $this->assertThat(null, new HeaderSet($this->_response, $header), $verboseMessage);
  881. $this->assertThat($content, new HeaderContains($this->_response, $header), $verboseMessage);
  882. }
  883. /**
  884. * Asserts response header does not contain a string
  885. *
  886. * @param string $header The header to check
  887. * @param string $content The content to check for.
  888. * @param string $message The failure message that will be appended to the generated message.
  889. * @return void
  890. */
  891. public function assertHeaderNotContains($header, $content, $message = '')
  892. {
  893. $verboseMessage = $this->extractVerboseMessage($message);
  894. $this->assertThat(null, new HeaderSet($this->_response, $header), $verboseMessage);
  895. $this->assertThat($content, new HeaderNotContains($this->_response, $header), $verboseMessage);
  896. }
  897. /**
  898. * Asserts content type
  899. *
  900. * @param string $type The content-type to check for.
  901. * @param string $message The failure message that will be appended to the generated message.
  902. * @return void
  903. */
  904. public function assertContentType($type, $message = '')
  905. {
  906. $verboseMessage = $this->extractVerboseMessage($message);
  907. $this->assertThat($type, new ContentType($this->_response), $verboseMessage);
  908. }
  909. /**
  910. * Asserts content in the response body equals.
  911. *
  912. * @param mixed $content The content to check for.
  913. * @param string $message The failure message that will be appended to the generated message.
  914. * @return void
  915. */
  916. public function assertResponseEquals($content, $message = '')
  917. {
  918. $verboseMessage = $this->extractVerboseMessage($message);
  919. $this->assertThat($content, new BodyEquals($this->_response), $verboseMessage);
  920. }
  921. /**
  922. * Asserts content in the response body not equals.
  923. *
  924. * @param mixed $content The content to check for.
  925. * @param string $message The failure message that will be appended to the generated message.
  926. * @return void
  927. */
  928. public function assertResponseNotEquals($content, $message = '')
  929. {
  930. $verboseMessage = $this->extractVerboseMessage($message);
  931. $this->assertThat($content, new BodyNotEquals($this->_response), $verboseMessage);
  932. }
  933. /**
  934. * Asserts content exists in the response body.
  935. *
  936. * @param string $content The content to check for.
  937. * @param string $message The failure message that will be appended to the generated message.
  938. * @param bool $ignoreCase A flag to check whether we should ignore case or not.
  939. * @return void
  940. */
  941. public function assertResponseContains($content, $message = '', $ignoreCase = false)
  942. {
  943. $verboseMessage = $this->extractVerboseMessage($message);
  944. $this->assertThat($content, new BodyContains($this->_response, $ignoreCase), $verboseMessage);
  945. }
  946. /**
  947. * Asserts content does not exist in the response body.
  948. *
  949. * @param string $content The content to check for.
  950. * @param string $message The failure message that will be appended to the generated message.
  951. * @param bool $ignoreCase A flag to check whether we should ignore case or not.
  952. * @return void
  953. */
  954. public function assertResponseNotContains($content, $message = '', $ignoreCase = false)
  955. {
  956. $verboseMessage = $this->extractVerboseMessage($message);
  957. $this->assertThat($content, new BodyNotContains($this->_response, $ignoreCase), $verboseMessage);
  958. }
  959. /**
  960. * Asserts that the response body matches a given regular expression.
  961. *
  962. * @param string $pattern The pattern to compare against.
  963. * @param string $message The failure message that will be appended to the generated message.
  964. * @return void
  965. */
  966. public function assertResponseRegExp($pattern, $message = '')
  967. {
  968. $verboseMessage = $this->extractVerboseMessage($message);
  969. $this->assertThat($pattern, new BodyRegExp($this->_response), $verboseMessage);
  970. }
  971. /**
  972. * Asserts that the response body does not match a given regular expression.
  973. *
  974. * @param string $pattern The pattern to compare against.
  975. * @param string $message The failure message that will be appended to the generated message.
  976. * @return void
  977. */
  978. public function assertResponseNotRegExp($pattern, $message = '')
  979. {
  980. $verboseMessage = $this->extractVerboseMessage($message);
  981. $this->assertThat($pattern, new BodyNotRegExp($this->_response), $verboseMessage);
  982. }
  983. /**
  984. * Assert response content is not empty.
  985. *
  986. * @param string $message The failure message that will be appended to the generated message.
  987. * @return void
  988. */
  989. public function assertResponseNotEmpty($message = '')
  990. {
  991. $this->assertThat(null, new BodyNotEmpty($this->_response), $message);
  992. }
  993. /**
  994. * Assert response content is empty.
  995. *
  996. * @param string $message The failure message that will be appended to the generated message.
  997. * @return void
  998. */
  999. public function assertResponseEmpty($message = '')
  1000. {
  1001. $this->assertThat(null, new BodyEmpty($this->_response), $message);
  1002. }
  1003. /**
  1004. * Asserts that the search string was in the template name.
  1005. *
  1006. * @param string $content The content to check for.
  1007. * @param string $message The failure message that will be appended to the generated message.
  1008. * @return void
  1009. */
  1010. public function assertTemplate($content, $message = '')
  1011. {
  1012. $verboseMessage = $this->extractVerboseMessage($message);
  1013. $this->assertThat($content, new TemplateFileEquals($this->_viewName), $verboseMessage);
  1014. }
  1015. /**
  1016. * Asserts that the search string was in the layout name.
  1017. *
  1018. * @param string $content The content to check for.
  1019. * @param string $message The failure message that will be appended to the generated message.
  1020. * @return void
  1021. */
  1022. public function assertLayout($content, $message = '')
  1023. {
  1024. $verboseMessage = $this->extractVerboseMessage($message);
  1025. $this->assertThat($content, new LayoutFileEquals($this->_layoutName), $verboseMessage);
  1026. }
  1027. /**
  1028. * Asserts session contents
  1029. *
  1030. * @param string $expected The expected contents.
  1031. * @param string $path The session data path. Uses Hash::get() compatible notation
  1032. * @param string $message The failure message that will be appended to the generated message.
  1033. * @return void
  1034. */
  1035. public function assertSession($expected, $path, $message = '')
  1036. {
  1037. $verboseMessage = $this->extractVerboseMessage($message);
  1038. $this->assertThat($expected, new SessionEquals($this->_requestSession, $path), $verboseMessage);
  1039. }
  1040. /**
  1041. * Asserts a flash message was set
  1042. *
  1043. * @param string $expected Expected message
  1044. * @param string $key Flash key
  1045. * @param string $message Assertion failure message
  1046. * @return void
  1047. */
  1048. public function assertFlashMessage($expected, $key = 'flash', $message = '')
  1049. {
  1050. $verboseMessage = $this->extractVerboseMessage($message);
  1051. $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'message'), $verboseMessage);
  1052. }
  1053. /**
  1054. * Asserts a flash message was set at a certain index
  1055. *
  1056. * @param int $at Flash index
  1057. * @param string $expected Expected message
  1058. * @param string $key Flash key
  1059. * @param string $message Assertion failure message
  1060. * @return void
  1061. */
  1062. public function assertFlashMessageAt($at, $expected, $key = 'flash', $message = '')
  1063. {
  1064. $verboseMessage = $this->extractVerboseMessage($message);
  1065. $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'message', $at), $verboseMessage);
  1066. }
  1067. /**
  1068. * Asserts a flash element was set
  1069. *
  1070. * @param string $expected Expected element name
  1071. * @param string $key Flash key
  1072. * @param string $message Assertion failure message
  1073. * @return void
  1074. */
  1075. public function assertFlashElement($expected, $key = 'flash', $message = '')
  1076. {
  1077. $verboseMessage = $this->extractVerboseMessage($message);
  1078. $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'element'), $verboseMessage);
  1079. }
  1080. /**
  1081. * Asserts a flash element was set at a certain index
  1082. *
  1083. * @param int $at Flash index
  1084. * @param string $expected Expected element name
  1085. * @param string $key Flash key
  1086. * @param string $message Assertion failure message
  1087. * @return void
  1088. */
  1089. public function assertFlashElementAt($at, $expected, $key = 'flash', $message = '')
  1090. {
  1091. $verboseMessage = $this->extractVerboseMessage($message);
  1092. $this->assertThat($expected, new FlashParamEquals($this->_requestSession, $key, 'element', $at), $verboseMessage);
  1093. }
  1094. /**
  1095. * Asserts cookie values
  1096. *
  1097. * @param string $expected The expected contents.
  1098. * @param string $name The cookie name.
  1099. * @param string $message The failure message that will be appended to the generated message.
  1100. * @return void
  1101. */
  1102. public function assertCookie($expected, $name, $message = '')
  1103. {
  1104. $verboseMessage = $this->extractVerboseMessage($message);
  1105. $this->assertThat($name, new CookieSet($this->_response), $verboseMessage);
  1106. $this->assertThat($expected, new CookieEquals($this->_response, $name), $verboseMessage);
  1107. }
  1108. /**
  1109. * Asserts a cookie has not been set in the response
  1110. *
  1111. * @param string $cookie The cookie name to check
  1112. * @param string $message The failure message that will be appended to the generated message.
  1113. * @return void
  1114. */
  1115. public function assertCookieNotSet($cookie, $message = '')
  1116. {
  1117. $verboseMessage = $this->extractVerboseMessage($message);
  1118. $this->assertThat($cookie, new CookieNotSet($this->_response), $verboseMessage);
  1119. }
  1120. /**
  1121. * Disable the error handler middleware.
  1122. *
  1123. * By using this function, exceptions are no longer caught by the ErrorHandlerMiddleware
  1124. * and are instead re-thrown by the TestExceptionRenderer. This can be helpful
  1125. * when trying to diagnose/debug unexpected failures in test cases.
  1126. *
  1127. * @return void
  1128. */
  1129. public function disableErrorHandlerMiddleware()
  1130. {
  1131. Configure::write('Error.exceptionRenderer', TestExceptionRenderer::class);
  1132. }
  1133. /**
  1134. * Asserts cookie values which are encrypted by the
  1135. * CookieComponent.
  1136. *
  1137. * The difference from assertCookie() is this decrypts the cookie
  1138. * value like the CookieComponent for this assertion.
  1139. *
  1140. * @param string $expected The expected contents.
  1141. * @param string $name The cookie name.
  1142. * @param string|bool $encrypt Encryption mode to use.
  1143. * @param string|null $key Encryption key used. Defaults
  1144. * to Security.salt.
  1145. * @param string $message The failure message that will be appended to the generated message.
  1146. * @return void
  1147. * @see \Cake\Utility\CookieCryptTrait::_encrypt()
  1148. */
  1149. public function assertCookieEncrypted($expected, $name, $encrypt = 'aes', $key = null, $message = '')
  1150. {
  1151. $verboseMessage = $this->extractVerboseMessage($message);
  1152. $this->assertThat($name, new CookieSet($this->_response), $verboseMessage);
  1153. $this->_cookieEncryptionKey = $key;
  1154. $this->assertThat($expected, new CookieEncryptedEquals($this->_response, $name, $encrypt, $this->_getCookieEncryptionKey()));
  1155. }
  1156. /**
  1157. * Asserts that a file with the given name was sent in the response
  1158. *
  1159. * @param string $expected The absolute file path that should be sent in the response.
  1160. * @param string $message The failure message that will be appended to the generated message.
  1161. * @return void
  1162. */
  1163. public function assertFileResponse($expected, $message = '')
  1164. {
  1165. $verboseMessage = $this->extractVerboseMessage($message);
  1166. $this->assertThat(null, new FileSent($this->_response), $verboseMessage);
  1167. $this->assertThat($expected, new FileSentAs($this->_response), $verboseMessage);
  1168. }
  1169. /**
  1170. * Inspect controller to extract possible causes of the failed assertion
  1171. *
  1172. * @param string $message Original message to use as a base
  1173. * @return string|null
  1174. */
  1175. protected function extractVerboseMessage($message = null)
  1176. {
  1177. if ($this->_exception instanceof \Exception) {
  1178. $message .= $this->extractExceptionMessage($this->_exception);
  1179. }
  1180. if ($this->_controller === null) {
  1181. return $message;
  1182. }
  1183. $error = Hash::get($this->_controller->viewVars, 'error');
  1184. if ($error instanceof \Exception) {
  1185. $message .= $this->extractExceptionMessage($this->viewVariable('error'));
  1186. }
  1187. return $message;
  1188. }
  1189. /**
  1190. * Extract verbose message for existing exception
  1191. *
  1192. * @param \Exception $exception Exception to extract
  1193. * @return string
  1194. */
  1195. protected function extractExceptionMessage(\Exception $exception)
  1196. {
  1197. return PHP_EOL .
  1198. sprintf('Possibly related to %s: "%s" ', get_class($exception), $exception->getMessage()) .
  1199. PHP_EOL .
  1200. $exception->getTraceAsString();
  1201. }
  1202. }