IntegrationTestTrait.php 40 KB

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