IntegrationTestTrait.php 42 KB

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