IntegrationTestTraitTest.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  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. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\TestSuite;
  17. use Cake\Controller\Controller;
  18. use Cake\Core\Configure;
  19. use Cake\Event\EventManager;
  20. use Cake\Http\Cookie\Cookie;
  21. use Cake\Http\Middleware\EncryptedCookieMiddleware;
  22. use Cake\Http\Response;
  23. use Cake\Http\Session;
  24. use Cake\Routing\Route\InflectedRoute;
  25. use Cake\Routing\RouteBuilder;
  26. use Cake\Routing\Router;
  27. use Cake\Test\Fixture\AssertIntegrationTestCase;
  28. use Cake\TestSuite\IntegrationTestTrait;
  29. use Cake\TestSuite\TestCase;
  30. use Cake\Utility\Security;
  31. use Laminas\Diactoros\UploadedFile;
  32. use PHPUnit\Framework\AssertionFailedError;
  33. /**
  34. * Self test of the IntegrationTestTrait
  35. */
  36. class IntegrationTestTraitTest extends TestCase
  37. {
  38. use IntegrationTestTrait;
  39. /**
  40. * stub encryption key.
  41. *
  42. * @var string
  43. */
  44. protected $key = 'abcdabcdabcdabcdabcdabcdabcdabcdabcd';
  45. /**
  46. * Setup method
  47. *
  48. * @return void
  49. */
  50. public function setUp(): void
  51. {
  52. parent::setUp();
  53. static::setAppNamespace();
  54. Router::reload();
  55. Router::extensions(['json']);
  56. Router::scope('/', function (RouteBuilder $routes) {
  57. $routes->registerMiddleware('cookie', new EncryptedCookieMiddleware(['secrets'], $this->key));
  58. $routes->applyMiddleware('cookie');
  59. $routes->setRouteClass(InflectedRoute::class);
  60. $routes->get('/get/:controller/:action', []);
  61. $routes->head('/head/:controller/:action', []);
  62. $routes->options('/options/:controller/:action', []);
  63. $routes->connect('/:controller/:action/*', []);
  64. });
  65. $this->configApplication(Configure::read('App.namespace') . '\Application', null);
  66. }
  67. /**
  68. * Tests that all data that used by the request is cast to strings
  69. *
  70. * @return void
  71. */
  72. public function testDataCastToString()
  73. {
  74. $data = [
  75. 'title' => 'Blog Post',
  76. 'status' => 1,
  77. 'published' => true,
  78. 'not_published' => false,
  79. 'comments' => [
  80. [
  81. 'body' => 'Comment',
  82. 'status' => 1,
  83. ],
  84. ],
  85. 'file' => [
  86. 'tmp_name' => __FILE__,
  87. 'size' => 42,
  88. 'error' => 0,
  89. 'type' => 'text/plain',
  90. 'name' => 'Uploaded file',
  91. ],
  92. 'pictures' => [
  93. 'name' => [
  94. ['file' => 'a-file.png'],
  95. ['file' => 'a-moose.png'],
  96. ],
  97. 'type' => [
  98. ['file' => 'image/png'],
  99. ['file' => 'image/jpg'],
  100. ],
  101. 'tmp_name' => [
  102. ['file' => __FILE__],
  103. ['file' => __FILE__],
  104. ],
  105. 'error' => [
  106. ['file' => 0],
  107. ['file' => 0],
  108. ],
  109. 'size' => [
  110. ['file' => 17188],
  111. ['file' => 2010],
  112. ],
  113. ],
  114. 'upload' => new UploadedFile(__FILE__, 42, 0),
  115. ];
  116. $request = $this->_buildRequest('/posts/add', 'POST', $data);
  117. $this->assertIsString($request['post']['status']);
  118. $this->assertIsString($request['post']['published']);
  119. $this->assertSame('0', $request['post']['not_published']);
  120. $this->assertIsString($request['post']['comments'][0]['status']);
  121. $this->assertIsInt($request['post']['file']['error']);
  122. $this->assertIsInt($request['post']['file']['size']);
  123. $this->assertIsInt($request['post']['pictures']['error'][0]['file']);
  124. $this->assertIsInt($request['post']['pictures']['error'][1]['file']);
  125. $this->assertIsInt($request['post']['pictures']['size'][0]['file']);
  126. $this->assertIsInt($request['post']['pictures']['size'][1]['file']);
  127. $this->assertInstanceOf(UploadedFile::class, $request['post']['upload']);
  128. }
  129. /**
  130. * Test building a request.
  131. *
  132. * @return void
  133. */
  134. public function testRequestBuilding()
  135. {
  136. $this->configRequest([
  137. 'headers' => [
  138. 'X-CSRF-Token' => 'abc123',
  139. 'Content-Type' => 'application/json',
  140. 'Accept' => 'application/json',
  141. ],
  142. 'base' => '',
  143. 'webroot' => '/',
  144. 'environment' => [
  145. 'PHP_AUTH_USER' => 'foo',
  146. 'PHP_AUTH_PW' => 'bar',
  147. ],
  148. ]);
  149. $this->cookie('split_token', 'def345');
  150. $this->session(['User' => ['id' => '1', 'username' => 'mark']]);
  151. $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  152. $this->assertSame('abc123', $request['environment']['HTTP_X_CSRF_TOKEN']);
  153. $this->assertSame('application/json', $request['environment']['CONTENT_TYPE']);
  154. $this->assertSame('/tasks/add', $request['url']);
  155. $this->assertArrayHasKey('split_token', $request['cookies']);
  156. $this->assertSame('def345', $request['cookies']['split_token']);
  157. $this->assertSame(['id' => '1', 'username' => 'mark'], $request['session']->read('User'));
  158. $this->assertSame('foo', $request['environment']['PHP_AUTH_USER']);
  159. $this->assertSame('bar', $request['environment']['PHP_AUTH_PW']);
  160. }
  161. /**
  162. * Test request building adds csrf tokens
  163. *
  164. * @return void
  165. */
  166. public function testRequestBuildingCsrfTokens()
  167. {
  168. $this->enableCsrfToken();
  169. $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  170. $this->assertArrayHasKey('csrfToken', $request['cookies']);
  171. $this->assertArrayHasKey('_csrfToken', $request['post']);
  172. $this->assertSame($request['cookies']['csrfToken'], $request['post']['_csrfToken']);
  173. $this->cookie('csrfToken', '');
  174. $request = $this->_buildRequest('/tasks/add', 'POST', [
  175. '_csrfToken' => 'fale',
  176. 'title' => 'First post',
  177. ]);
  178. $this->assertSame('', $request['cookies']['csrfToken']);
  179. $this->assertSame('fale', $request['post']['_csrfToken']);
  180. }
  181. /**
  182. * Test multiple actions using CSRF tokens don't fail
  183. *
  184. * @return void
  185. */
  186. public function testEnableCsrfMultipleRequests()
  187. {
  188. $this->enableCsrfToken();
  189. $first = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  190. $second = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'Second post']);
  191. $this->assertSame(
  192. $first['cookies']['csrfToken'],
  193. $second['post']['_csrfToken'],
  194. 'Csrf token should match cookie'
  195. );
  196. $this->assertSame(
  197. $first['post']['_csrfToken'],
  198. $second['post']['_csrfToken'],
  199. 'Tokens should be consistent per test method'
  200. );
  201. }
  202. /**
  203. * Test pre-determined CSRF tokens.
  204. *
  205. * @return void
  206. */
  207. public function testEnableCsrfPredeterminedCookie()
  208. {
  209. $this->enableCsrfToken();
  210. $value = 'I am a teapot';
  211. $this->cookie('csrfToken', $value);
  212. $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  213. $this->assertSame($value, $request['cookies']['csrfToken'], 'Csrf token should match cookie');
  214. $this->assertSame($value, $request['post']['_csrfToken'], 'Tokens should match');
  215. }
  216. /**
  217. * Test building a request, with query parameters
  218. *
  219. * @return void
  220. */
  221. public function testRequestBuildingQueryParameters()
  222. {
  223. $request = $this->_buildRequest('/tasks/view?archived=yes', 'GET', []);
  224. $this->assertSame('/tasks/view', $request['url']);
  225. $this->assertSame('archived=yes', $request['environment']['QUERY_STRING']);
  226. $this->assertSame('/tasks/view', $request['environment']['REQUEST_URI']);
  227. }
  228. /**
  229. * Test cookie encrypted
  230. *
  231. * @see CookieComponentControllerTest
  232. */
  233. public function testCookieEncrypted()
  234. {
  235. Security::setSalt($this->key);
  236. $this->cookieEncrypted('KeyOfCookie', 'Encrypted with aes by default');
  237. $request = $this->_buildRequest('/tasks/view', 'GET', []);
  238. $this->assertStringStartsWith('Q2FrZQ==.', $request['cookies']['KeyOfCookie']);
  239. }
  240. /**
  241. * Test sending get request and using default `test_app/config/routes.php`.
  242. *
  243. * @return void
  244. */
  245. public function testGetUsingApplicationWithPluginRoutes()
  246. {
  247. // first clean routes to have Router::$initailized === false
  248. Router::reload();
  249. $this->clearPlugins();
  250. $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithPluginRoutes', null);
  251. $this->get('/test_plugin');
  252. $this->assertResponseOk();
  253. }
  254. /**
  255. * Test sending get request and using default `test_app/config/routes.php`.
  256. *
  257. * @return void
  258. */
  259. public function testGetUsingApplicationWithDefaultRoutes()
  260. {
  261. // first clean routes to have Router::$initialized === false
  262. Router::reload();
  263. $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithDefaultRoutes', null);
  264. $this->get('/some_alias');
  265. $this->assertResponseOk();
  266. $this->assertSame('5', $this->_getBodyAsString());
  267. }
  268. public function testExceptionsInMiddlewareJsonView()
  269. {
  270. Router::reload();
  271. Router::connect('/json_response/api_get_data', [
  272. 'controller' => 'JsonResponse',
  273. 'action' => 'apiGetData',
  274. ]);
  275. $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithExceptionsInMiddleware', null);
  276. $this->_request['headers'] = [ "Accept" => "application/json" ];
  277. $this->get('/json_response/api_get_data');
  278. $this->assertResponseCode(403);
  279. $this->assertHeader('Content-Type', 'application/json');
  280. $this->assertResponseContains('"message": "Sample Message"');
  281. $this->assertResponseContains('"code": 403');
  282. }
  283. /**
  284. * Test sending head requests.
  285. *
  286. * @return void
  287. */
  288. public function testHead()
  289. {
  290. $this->assertNull($this->_response);
  291. $this->head('/request_action/test_request_action');
  292. $this->assertNotEmpty($this->_response);
  293. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  294. $this->assertResponseSuccess();
  295. }
  296. /**
  297. * Test sending head requests.
  298. *
  299. * @return void
  300. */
  301. public function testHeadMethodRoute()
  302. {
  303. $this->head('/head/request_action/test_request_action');
  304. $this->assertResponseSuccess();
  305. }
  306. /**
  307. * Test sending options requests.
  308. *
  309. * @return void
  310. */
  311. public function testOptions()
  312. {
  313. $this->assertNull($this->_response);
  314. $this->options('/request_action/test_request_action');
  315. $this->assertNotEmpty($this->_response);
  316. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  317. $this->assertResponseSuccess();
  318. }
  319. /**
  320. * Test sending options requests.
  321. *
  322. * @return void
  323. */
  324. public function testOptionsMethodRoute()
  325. {
  326. $this->options('/options/request_action/test_request_action');
  327. $this->assertResponseSuccess();
  328. }
  329. /**
  330. * Test sending get requests sets the request method
  331. *
  332. * @return void
  333. */
  334. public function testGetSpecificRouteHttpServer()
  335. {
  336. $this->get('/get/request_action/test_request_action');
  337. $this->assertResponseOk();
  338. $this->assertSame('This is a test', (string)$this->_response->getBody());
  339. }
  340. /**
  341. * Test customizing the app class.
  342. *
  343. * @return void
  344. */
  345. public function testConfigApplication()
  346. {
  347. $this->expectException(\LogicException::class);
  348. $this->expectExceptionMessage('Cannot load `TestApp\MissingApp` for use in integration');
  349. $this->configApplication('TestApp\MissingApp', []);
  350. $this->get('/request_action/test_request_action');
  351. }
  352. /**
  353. * Test sending get requests with Http\Server
  354. *
  355. * @return void
  356. */
  357. public function testGetHttpServer()
  358. {
  359. $this->assertNull($this->_response);
  360. $this->get('/request_action/test_request_action');
  361. $this->assertNotEmpty($this->_response);
  362. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  363. $this->assertSame('This is a test', (string)$this->_response->getBody());
  364. $this->assertHeader('X-Middleware', 'true');
  365. }
  366. /**
  367. * Test that the PSR7 requests get query string data
  368. *
  369. * @return void
  370. */
  371. public function testGetQueryStringHttpServer()
  372. {
  373. $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
  374. $this->get('/request_action/params_pass?q=query');
  375. $this->assertResponseOk();
  376. $this->assertResponseContains('"q":"query"');
  377. $this->assertResponseContains('"contentType":"text\/plain"');
  378. $this->assertHeader('X-Middleware', 'true');
  379. $request = $this->_controller->getRequest();
  380. $this->assertStringContainsString('/request_action/params_pass?q=query', $request->getRequestTarget());
  381. }
  382. /**
  383. * Test that the PSR7 requests get query string data
  384. *
  385. * @return void
  386. */
  387. public function testGetQueryStringSetsHere()
  388. {
  389. $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
  390. $this->get('/request_action/params_pass?q=query');
  391. $this->assertResponseOk();
  392. $this->assertResponseContains('"q":"query"');
  393. $this->assertResponseContains('"contentType":"text\/plain"');
  394. $this->assertHeader('X-Middleware', 'true');
  395. $request = $this->_controller->getRequest();
  396. $this->assertStringContainsString('/request_action/params_pass?q=query', $request->getRequestTarget());
  397. $this->assertStringContainsString('/request_action/params_pass', $request->getAttribute('here'));
  398. }
  399. /**
  400. * Test that the PSR7 requests get cookies
  401. *
  402. * @return void
  403. */
  404. public function testGetCookiesHttpServer()
  405. {
  406. $this->configRequest(['cookies' => ['split_test' => 'abc']]);
  407. $this->get('/request_action/cookie_pass');
  408. $this->assertResponseOk();
  409. $this->assertResponseContains('"split_test":"abc"');
  410. $this->assertHeader('X-Middleware', 'true');
  411. }
  412. /**
  413. * Test that the PSR7 requests receive post data
  414. *
  415. * @return void
  416. */
  417. public function testPostDataHttpServer()
  418. {
  419. $this->post('/request_action/post_pass', ['title' => 'value']);
  420. $data = json_decode('' . $this->_response->getBody());
  421. $this->assertSame('value', $data->title);
  422. $this->assertHeader('X-Middleware', 'true');
  423. }
  424. /**
  425. * Test that the uploaded files are passed correctly to the request
  426. *
  427. * @return void
  428. */
  429. public function testUploadedFiles()
  430. {
  431. $this->configRequest([
  432. 'files' => [
  433. 'file' => [
  434. 'tmp_name' => __FILE__,
  435. 'size' => 42,
  436. 'error' => 0,
  437. 'type' => 'text/plain',
  438. 'name' => 'Uploaded file',
  439. ],
  440. 'pictures' => [
  441. 'name' => [
  442. ['file' => 'a-file.png'],
  443. ['file' => 'a-moose.png'],
  444. ],
  445. 'type' => [
  446. ['file' => 'image/png'],
  447. ['file' => 'image/jpg'],
  448. ],
  449. 'tmp_name' => [
  450. ['file' => __FILE__],
  451. ['file' => __FILE__],
  452. ],
  453. 'error' => [
  454. ['file' => 0],
  455. ['file' => 0],
  456. ],
  457. 'size' => [
  458. ['file' => 17188],
  459. ['file' => 2010],
  460. ],
  461. ],
  462. 'upload' => new UploadedFile(__FILE__, 42, 0),
  463. ],
  464. ]);
  465. $this->post('/request_action/uploaded_files');
  466. $this->assertHeader('X-Middleware', 'true');
  467. $data = json_decode((string)$this->_response->getBody(), true);
  468. $this->assertSame([
  469. 'file' => 'Uploaded file',
  470. 'pictures.0.file' => 'a-file.png',
  471. 'pictures.1.file' => 'a-moose.png',
  472. 'upload' => null,
  473. ], $data);
  474. }
  475. /**
  476. * Test that the PSR7 requests receive encoded data.
  477. *
  478. * @return void
  479. */
  480. public function testInputDataHttpServer()
  481. {
  482. $this->post('/request_action/input_test', '{"hello":"world"}');
  483. if ($this->_response->getBody()->isSeekable()) {
  484. $this->_response->getBody()->rewind();
  485. }
  486. $this->assertSame('world', $this->_response->getBody()->getContents());
  487. $this->assertHeader('X-Middleware', 'true');
  488. }
  489. /**
  490. * Test that the PSR7 requests receive encoded data.
  491. *
  492. * @return void
  493. */
  494. public function testInputDataSecurityToken()
  495. {
  496. $this->enableSecurityToken();
  497. $this->post('/request_action/input_test', '{"hello":"world"}');
  498. $this->assertSame('world', '' . $this->_response->getBody());
  499. $this->assertHeader('X-Middleware', 'true');
  500. }
  501. /**
  502. * Test that the PSR7 requests get cookies
  503. *
  504. * @return void
  505. */
  506. public function testSessionHttpServer()
  507. {
  508. $this->session(['foo' => 'session data']);
  509. $this->get('/request_action/session_test');
  510. $this->assertResponseOk();
  511. $this->assertResponseContains('session data');
  512. $this->assertHeader('X-Middleware', 'true');
  513. }
  514. /**
  515. * Test sending requests stores references to controller/view/layout.
  516. *
  517. * @return void
  518. */
  519. public function testRequestSetsProperties()
  520. {
  521. $this->post('/posts/index');
  522. $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
  523. $this->assertNotEmpty($this->_viewName, 'View name not set');
  524. $this->assertStringContainsString('templates' . DS . 'Posts' . DS . 'index.php', $this->_viewName);
  525. $this->assertNotEmpty($this->_layoutName, 'Layout name not set');
  526. $this->assertStringContainsString('templates' . DS . 'layout' . DS . 'default.php', $this->_layoutName);
  527. $this->assertTemplate('index');
  528. $this->assertLayout('default');
  529. $this->assertSame('value', $this->viewVariable('test'));
  530. }
  531. /**
  532. * Test PSR7 requests store references to controller/view/layout
  533. *
  534. * @return void
  535. */
  536. public function testRequestSetsPropertiesHttpServer()
  537. {
  538. $this->post('/posts/index');
  539. $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
  540. $this->assertNotEmpty($this->_viewName, 'View name not set');
  541. $this->assertStringContainsString('templates' . DS . 'Posts' . DS . 'index.php', $this->_viewName);
  542. $this->assertNotEmpty($this->_layoutName, 'Layout name not set');
  543. $this->assertStringContainsString('templates' . DS . 'layout' . DS . 'default.php', $this->_layoutName);
  544. $this->assertTemplate('index');
  545. $this->assertLayout('default');
  546. $this->assertSame('value', $this->viewVariable('test'));
  547. }
  548. /**
  549. * Tests URLs containing extensions.
  550. *
  551. * @return void
  552. */
  553. public function testRequestWithExt()
  554. {
  555. $this->get(['controller' => 'Posts', 'action' => 'ajax', '_ext' => 'json']);
  556. $this->assertResponseCode(200);
  557. }
  558. /**
  559. * Assert that the stored template doesn't change when cells are rendered.
  560. *
  561. * @return void
  562. */
  563. public function testAssertTemplateAfterCellRender()
  564. {
  565. $this->get('/posts/get');
  566. $this->assertStringContainsString('templates' . DS . 'Posts' . DS . 'get.php', $this->_viewName);
  567. $this->assertTemplate('get');
  568. $this->assertResponseContains('cellcontent');
  569. }
  570. /**
  571. * Test array URLs
  572. *
  573. * @return void
  574. */
  575. public function testArrayUrls()
  576. {
  577. $this->post(['controller' => 'Posts', 'action' => 'index', '_method' => 'POST']);
  578. $this->assertResponseOk();
  579. $this->assertSame('value', $this->viewVariable('test'));
  580. }
  581. /**
  582. * Test array URL with host
  583. *
  584. * @return void
  585. */
  586. public function testArrayUrlWithHost()
  587. {
  588. $this->get([
  589. 'controller' => 'Posts',
  590. 'action' => 'hostData',
  591. '_host' => 'app.example.org',
  592. '_ssl' => true,
  593. ]);
  594. $this->assertResponseOk();
  595. $this->assertResponseContains('"isSsl":true');
  596. $this->assertResponseContains('"host":"app.example.org"');
  597. }
  598. /**
  599. * Test array URLs with an empty router.
  600. *
  601. * @return void
  602. */
  603. public function testArrayUrlsEmptyRouter()
  604. {
  605. Router::reload();
  606. $this->assertEmpty(Router::getRouteCollection()->routes());
  607. $this->get(['controller' => 'Posts', 'action' => 'index']);
  608. $this->assertResponseOk();
  609. $this->assertSame('value', $this->viewVariable('test'));
  610. }
  611. /**
  612. * Test flash and cookie assertions
  613. *
  614. * @return void
  615. */
  616. public function testFlashSessionAndCookieAsserts()
  617. {
  618. $this->post('/posts/index');
  619. $this->assertSession('An error message', 'Flash.flash.0.message');
  620. $this->assertCookie(1, 'remember_me');
  621. $this->assertCookieNotSet('user_id');
  622. }
  623. /**
  624. * Test flash and cookie assertions
  625. *
  626. * @return void
  627. */
  628. public function testFlashSessionAndCookieAssertsHttpServer()
  629. {
  630. $this->post('/posts/index');
  631. $this->assertSession('An error message', 'Flash.flash.0.message');
  632. $this->assertCookieNotSet('user_id');
  633. $this->assertCookie(1, 'remember_me');
  634. }
  635. /**
  636. * Test flash assertions stored with enableRememberFlashMessages() after they
  637. * are rendered
  638. *
  639. * @return void
  640. */
  641. public function testFlashAssertionsAfterRender()
  642. {
  643. $this->enableRetainFlashMessages();
  644. $this->get('/posts/index/with_flash');
  645. $this->assertSession('An error message', 'Flash.flash.0.message');
  646. }
  647. /**
  648. * Test flash assertions stored with enableRememberFlashMessages() even if
  649. * no view is rendered
  650. *
  651. * @return void
  652. */
  653. public function testFlashAssertionsWithNoRender()
  654. {
  655. $this->enableRetainFlashMessages();
  656. $this->get('/posts/flashNoRender');
  657. $this->assertRedirect();
  658. $this->assertSession('An error message', 'Flash.flash.0.message');
  659. }
  660. /**
  661. * Tests assertCookieNotSet assertion
  662. *
  663. * @return void
  664. */
  665. public function testAssertCookieNotSet()
  666. {
  667. $this->cookie('test', 'value');
  668. $this->get('/cookie_component_test/remove_cookie/test');
  669. $this->assertCookieNotSet('test');
  670. }
  671. /**
  672. * Tests the failure message for assertCookieNotSet
  673. *
  674. * @return void
  675. */
  676. public function testCookieNotSetFailure()
  677. {
  678. $this->expectException(AssertionFailedError::class);
  679. $this->expectExceptionMessage('Failed asserting that \'remember_me\' cookie is not set');
  680. $this->post('/posts/index');
  681. $this->assertCookieNotSet('remember_me');
  682. }
  683. /**
  684. * Tests the failure message for assertCookieNotSet when no
  685. * response whas generated
  686. *
  687. * @return void
  688. */
  689. public function testCookieNotSetFailureNoResponse()
  690. {
  691. $this->expectException(AssertionFailedError::class);
  692. $this->expectExceptionMessage('No response set, cannot assert content.');
  693. $this->assertCookieNotSet('remember_me');
  694. }
  695. /**
  696. * Test error handling and error page rendering.
  697. *
  698. * @return void
  699. */
  700. public function testPostAndErrorHandling()
  701. {
  702. $this->post('/request_action/error_method');
  703. $this->assertResponseNotEmpty();
  704. $this->assertResponseContains('Not there or here');
  705. $this->assertResponseContains('<!DOCTYPE html>');
  706. }
  707. /**
  708. * Test posting to a secured form action.
  709. *
  710. * @return void
  711. */
  712. public function testPostSecuredForm()
  713. {
  714. $this->enableSecurityToken();
  715. $data = [
  716. 'title' => 'Some title',
  717. 'body' => 'Some text',
  718. ];
  719. $this->post('/posts/securePost', $data);
  720. $this->assertResponseOk();
  721. $this->assertResponseContains('Request was accepted');
  722. }
  723. /**
  724. * Test posting to a secured form action with nested data.
  725. *
  726. * @return void
  727. */
  728. public function testPostSecuredFormNestedData()
  729. {
  730. $this->enableSecurityToken();
  731. $data = [
  732. 'title' => 'New post',
  733. 'comments' => [
  734. ['comment' => 'A new comment'],
  735. ],
  736. 'tags' => ['_ids' => [1, 2, 3, 4]],
  737. ];
  738. $this->post('/posts/securePost', $data);
  739. $this->assertResponseOk();
  740. $this->assertResponseContains('Request was accepted');
  741. }
  742. /**
  743. * Test posting to a secured form action with unlocked fields
  744. *
  745. * @return void
  746. */
  747. public function testPostSecuredFormUnlockedFieldsFails()
  748. {
  749. $this->enableSecurityToken();
  750. $data = [
  751. 'title' => 'New post',
  752. 'comments' => [
  753. ['comment' => 'A new comment'],
  754. ],
  755. 'tags' => ['_ids' => [1, 2, 3, 4]],
  756. 'some_unlocked_field' => 'Unlocked data',
  757. ];
  758. $this->post('/posts/securePost', $data);
  759. $this->assertResponseCode(400);
  760. $this->assertResponseContains('Invalid form protection debug token.');
  761. }
  762. /**
  763. * Test posting to a secured form action with unlocked fields
  764. *
  765. * @return void
  766. */
  767. public function testPostSecuredFormUnlockedFieldsWithSet()
  768. {
  769. $this->enableSecurityToken();
  770. $data = [
  771. 'title' => 'New post',
  772. 'comments' => [
  773. ['comment' => 'A new comment'],
  774. ],
  775. 'tags' => ['_ids' => [1, 2, 3, 4]],
  776. 'some_unlocked_field' => 'Unlocked data',
  777. ];
  778. $this->setUnlockedFields(['some_unlocked_field']);
  779. $this->post('/posts/securePost', $data);
  780. $this->assertResponseOk();
  781. $this->assertResponseContains('Request was accepted');
  782. }
  783. /**
  784. * Test posting to a secured form action.
  785. *
  786. * @return void
  787. */
  788. public function testPostSecuredFormWithQuery()
  789. {
  790. $this->enableSecurityToken();
  791. $data = [
  792. 'title' => 'Some title',
  793. 'body' => 'Some text',
  794. ];
  795. $this->post('/posts/securePost?foo=bar', $data);
  796. $this->assertResponseOk();
  797. $this->assertResponseContains('Request was accepted');
  798. }
  799. /**
  800. * Test posting to a secured form action with a query that has a part that
  801. * will be encoded by the security component
  802. *
  803. * @return void
  804. */
  805. public function testPostSecuredFormWithUnencodedQuery()
  806. {
  807. $this->enableSecurityToken();
  808. $data = [
  809. 'title' => 'Some title',
  810. 'body' => 'Some text',
  811. ];
  812. $this->post('/posts/securePost?foo=/', $data);
  813. $this->assertResponseOk();
  814. $this->assertResponseContains('Request was accepted');
  815. }
  816. /**
  817. * Test posting to a secured form action action.
  818. *
  819. * @return void
  820. */
  821. public function testPostSecuredFormFailure()
  822. {
  823. $data = [
  824. 'title' => 'Some title',
  825. 'body' => 'Some text',
  826. ];
  827. $this->post('/posts/securePost', $data);
  828. $this->assertResponseError();
  829. }
  830. /**
  831. * Test that exceptions being thrown are handled correctly.
  832. *
  833. * @return void
  834. */
  835. public function testWithExpectedException()
  836. {
  837. $this->get('/tests_apps/throw_exception');
  838. $this->assertResponseCode(500);
  839. }
  840. /**
  841. * Test that exceptions being thrown are handled correctly by the psr7 stack.
  842. *
  843. * @return void
  844. */
  845. public function testWithExpectedExceptionHttpServer()
  846. {
  847. $this->get('/tests_apps/throw_exception');
  848. $this->assertResponseCode(500);
  849. }
  850. /**
  851. * Test that exceptions being thrown are handled correctly.
  852. *
  853. * @return void
  854. */
  855. public function testWithUnexpectedException()
  856. {
  857. $this->expectException(AssertionFailedError::class);
  858. $this->get('/tests_apps/throw_exception');
  859. $this->assertResponseCode(501);
  860. }
  861. /**
  862. * Test redirecting and integration tests.
  863. *
  864. * @return void
  865. */
  866. public function testRedirect()
  867. {
  868. $this->post('/tests_apps/redirect_to');
  869. $this->assertResponseSuccess();
  870. $this->assertResponseCode(302);
  871. }
  872. /**
  873. * Test redirecting and psr7 stack
  874. *
  875. * @return void
  876. */
  877. public function testRedirectHttpServer()
  878. {
  879. $this->post('/tests_apps/redirect_to');
  880. $this->assertResponseCode(302);
  881. $this->assertHeader('X-Middleware', 'true');
  882. }
  883. /**
  884. * Test redirecting and integration tests.
  885. *
  886. * @return void
  887. */
  888. public function testRedirectPermanent()
  889. {
  890. $this->post('/tests_apps/redirect_to_permanent');
  891. $this->assertResponseSuccess();
  892. $this->assertResponseCode(301);
  893. }
  894. /**
  895. * Test the responseOk status assertion
  896. *
  897. * @return void
  898. */
  899. public function testAssertResponseStatusCodes()
  900. {
  901. $this->_response = new Response();
  902. $this->_response = $this->_response->withStatus(200);
  903. $this->assertResponseOk();
  904. $this->_response = $this->_response->withStatus(201);
  905. $this->assertResponseOk();
  906. $this->_response = $this->_response->withStatus(204);
  907. $this->assertResponseOk();
  908. $this->_response = $this->_response->withStatus(202);
  909. $this->assertResponseSuccess();
  910. $this->_response = $this->_response->withStatus(302);
  911. $this->assertResponseSuccess();
  912. $this->_response = $this->_response->withStatus(400);
  913. $this->assertResponseError();
  914. $this->_response = $this->_response->withStatus(417);
  915. $this->assertResponseError();
  916. $this->_response = $this->_response->withStatus(500);
  917. $this->assertResponseFailure();
  918. $this->_response = $this->_response->withStatus(505);
  919. $this->assertResponseFailure();
  920. $this->_response = $this->_response->withStatus(301);
  921. $this->assertResponseCode(301);
  922. }
  923. /**
  924. * Test the location header assertion.
  925. *
  926. * @return void
  927. */
  928. public function testAssertRedirect()
  929. {
  930. $this->_response = new Response();
  931. $this->_response = $this->_response->withHeader('Location', 'http://localhost/get/tasks/index');
  932. $this->assertRedirect();
  933. $this->assertRedirect('/get/tasks/index');
  934. $this->assertRedirect(['controller' => 'Tasks', 'action' => 'index']);
  935. $this->assertResponseEmpty();
  936. }
  937. /**
  938. * Test the location header assertion.
  939. *
  940. * @return void
  941. */
  942. public function testAssertRedirectEquals()
  943. {
  944. $this->_response = new Response();
  945. $this->_response = $this->_response->withHeader('Location', '/get/tasks/index');
  946. $this->assertRedirect();
  947. $this->assertRedirectEquals('/get/tasks/index');
  948. $this->assertRedirectEquals(['controller' => 'Tasks', 'action' => 'index']);
  949. $this->assertResponseEmpty();
  950. }
  951. /**
  952. * Test the location header assertion string not contains
  953. *
  954. * @return void
  955. */
  956. public function testAssertRedirectNotContains()
  957. {
  958. $this->_response = new Response();
  959. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  960. $this->assertRedirectNotContains('test');
  961. }
  962. /**
  963. * Test the location header assertion.
  964. *
  965. * @return void
  966. */
  967. public function testAssertNoRedirect()
  968. {
  969. $this->_response = new Response();
  970. $this->assertNoRedirect();
  971. }
  972. /**
  973. * Test the location header assertion.
  974. *
  975. * @return void
  976. */
  977. public function testAssertNoRedirectFail()
  978. {
  979. $test = new AssertIntegrationTestCase('testBadAssertNoRedirect');
  980. $result = $test->run();
  981. $this->assertFalse($result->wasSuccessful());
  982. $this->assertSame(1, $result->failureCount());
  983. }
  984. /**
  985. * Test the location header assertion string contains
  986. *
  987. * @return void
  988. */
  989. public function testAssertRedirectContains()
  990. {
  991. $this->_response = new Response();
  992. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  993. $this->assertRedirectContains('/tasks/index');
  994. }
  995. /**
  996. * Test the header assertion.
  997. *
  998. * @return void
  999. */
  1000. public function testAssertHeader()
  1001. {
  1002. $this->_response = new Response();
  1003. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  1004. $this->assertHeader('Etag', 'abc123');
  1005. }
  1006. /**
  1007. * Test the header contains assertion.
  1008. *
  1009. * @return void
  1010. */
  1011. public function testAssertHeaderContains()
  1012. {
  1013. $this->_response = new Response();
  1014. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  1015. $this->assertHeaderContains('Etag', 'abc');
  1016. }
  1017. /**
  1018. * Test the header not contains assertion.
  1019. *
  1020. * @return void
  1021. */
  1022. public function testAssertHeaderNotContains()
  1023. {
  1024. $this->_response = new Response();
  1025. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  1026. $this->assertHeaderNotContains('Etag', 'xyz');
  1027. }
  1028. /**
  1029. * Test the content type assertion.
  1030. *
  1031. * @return void
  1032. */
  1033. public function testAssertContentType()
  1034. {
  1035. $this->_response = new Response();
  1036. $this->_response = $this->_response->withType('json');
  1037. $this->assertContentType('json');
  1038. $this->assertContentType('application/json');
  1039. }
  1040. /**
  1041. * Test that type() in an action sets the content-type header.
  1042. *
  1043. * @return void
  1044. */
  1045. public function testContentTypeInAction()
  1046. {
  1047. $this->get('/tests_apps/set_type');
  1048. $this->assertHeader('Content-Type', 'application/json');
  1049. $this->assertContentType('json');
  1050. $this->assertContentType('application/json');
  1051. }
  1052. /**
  1053. * Test the content assertion.
  1054. *
  1055. * @return void
  1056. */
  1057. public function testAssertResponseEquals()
  1058. {
  1059. $this->_response = new Response();
  1060. $this->_response = $this->_response->withStringBody('Some content');
  1061. $this->assertResponseEquals('Some content');
  1062. }
  1063. /**
  1064. * Test the negated content assertion.
  1065. *
  1066. * @return void
  1067. */
  1068. public function testAssertResponseNotEquals()
  1069. {
  1070. $this->_response = new Response();
  1071. $this->_response = $this->_response->withStringBody('Some content');
  1072. $this->assertResponseNotEquals('Some Content');
  1073. }
  1074. /**
  1075. * Test the content assertion.
  1076. *
  1077. * @return void
  1078. */
  1079. public function testAssertResponseContains()
  1080. {
  1081. $this->_response = new Response();
  1082. $this->_response = $this->_response->withStringBody('Some content');
  1083. $this->assertResponseContains('content');
  1084. }
  1085. /**
  1086. * Test the content assertion with no case sensitivity.
  1087. *
  1088. * @return void
  1089. */
  1090. public function testAssertResponseContainsWithIgnoreCaseFlag()
  1091. {
  1092. $this->_response = new Response();
  1093. $this->_response = $this->_response->withStringBody('Some content');
  1094. $this->assertResponseContains('some', 'Failed asserting that the body contains given content', true);
  1095. }
  1096. /**
  1097. * Test the negated content assertion.
  1098. *
  1099. * @return void
  1100. */
  1101. public function testAssertResponseNotContains()
  1102. {
  1103. $this->_response = new Response();
  1104. $this->_response = $this->_response->withStringBody('Some content');
  1105. $this->assertResponseNotContains('contents');
  1106. }
  1107. /**
  1108. * Test the content regexp assertion.
  1109. *
  1110. * @return void
  1111. */
  1112. public function testAssertResponseRegExp()
  1113. {
  1114. $this->_response = new Response();
  1115. $this->_response = $this->_response->withStringBody('Some content');
  1116. $this->assertResponseRegExp('/cont/');
  1117. }
  1118. /**
  1119. * Test the content regexp assertion failing
  1120. *
  1121. * @return void
  1122. */
  1123. public function testAssertResponseRegExpNoResponse()
  1124. {
  1125. $this->expectException(AssertionFailedError::class);
  1126. $this->expectExceptionMessage('No response set');
  1127. $this->assertResponseRegExp('/cont/');
  1128. }
  1129. /**
  1130. * Test the negated content regexp assertion.
  1131. *
  1132. * @return void
  1133. */
  1134. public function testAssertResponseNotRegExp()
  1135. {
  1136. $this->_response = new Response();
  1137. $this->_response = $this->_response->withStringBody('Some content');
  1138. $this->assertResponseNotRegExp('/cant/');
  1139. }
  1140. /**
  1141. * Test negated content regexp assertion failing
  1142. *
  1143. * @return void
  1144. */
  1145. public function testAssertResponseNotRegExpNoResponse()
  1146. {
  1147. $this->expectException(AssertionFailedError::class);
  1148. $this->expectExceptionMessage('No response set');
  1149. $this->assertResponseNotRegExp('/cont/');
  1150. }
  1151. /**
  1152. * Test that works in tandem with testEventManagerReset2 to
  1153. * test the EventManager reset.
  1154. *
  1155. * The return value is passed to testEventManagerReset2 as
  1156. * an arguments.
  1157. *
  1158. * @return \Cake\Event\EventManager
  1159. */
  1160. public function testEventManagerReset1()
  1161. {
  1162. $eventManager = EventManager::instance();
  1163. $this->assertInstanceOf('Cake\Event\EventManager', $eventManager);
  1164. return $eventManager;
  1165. }
  1166. /**
  1167. * Test if the EventManager is reset between tests.
  1168. *
  1169. * @depends testEventManagerReset1
  1170. * @return void
  1171. */
  1172. public function testEventManagerReset2($prevEventManager)
  1173. {
  1174. $this->assertInstanceOf('Cake\Event\EventManager', $prevEventManager);
  1175. $this->assertNotSame($prevEventManager, EventManager::instance());
  1176. }
  1177. /**
  1178. * Test sending file in requests.
  1179. *
  1180. * @return void
  1181. */
  1182. public function testSendFile()
  1183. {
  1184. $this->get('/posts/file');
  1185. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  1186. }
  1187. /**
  1188. * Test sending file with psr7 stack
  1189. *
  1190. * @return void
  1191. */
  1192. public function testSendFileHttpServer()
  1193. {
  1194. $this->get('/posts/file');
  1195. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  1196. }
  1197. /**
  1198. * Test that assertFile requires a response
  1199. *
  1200. * @return void
  1201. */
  1202. public function testAssertFileNoResponse()
  1203. {
  1204. $this->expectException(AssertionFailedError::class);
  1205. $this->expectExceptionMessage('No response set, cannot assert content');
  1206. $this->assertFileResponse('foo');
  1207. }
  1208. /**
  1209. * Test that assertFile requires a file
  1210. *
  1211. * @return void
  1212. */
  1213. public function testAssertFileNoFile()
  1214. {
  1215. $this->expectException(AssertionFailedError::class);
  1216. $this->expectExceptionMessage('Failed asserting that file was sent.');
  1217. $this->get('/posts/get');
  1218. $this->assertFileResponse('foo');
  1219. }
  1220. /**
  1221. * Test disabling the error handler middleware.
  1222. *
  1223. * @return void
  1224. */
  1225. public function testDisableErrorHandlerMiddleware()
  1226. {
  1227. $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
  1228. $this->expectExceptionMessage('A route matching "/foo" could not be found.');
  1229. $this->disableErrorHandlerMiddleware();
  1230. $this->get('/foo');
  1231. }
  1232. /**
  1233. * tests getting a secure action while passing a query string
  1234. *
  1235. * @return void
  1236. * @dataProvider methodsProvider
  1237. */
  1238. public function testSecureWithQueryString($method)
  1239. {
  1240. $this->enableSecurityToken();
  1241. $this->{$method}('/posts/securePost/?ids[]=1&ids[]=2');
  1242. $this->assertResponseOk();
  1243. }
  1244. /**
  1245. * Tests flash assertions
  1246. *
  1247. * @return void
  1248. * @throws \PHPUnit\Exception
  1249. */
  1250. public function testAssertFlashMessage()
  1251. {
  1252. $this->get('/posts/stacked_flash');
  1253. $this->assertFlashElement('flash/error');
  1254. $this->assertFlashElement('flash/success', 'custom');
  1255. $this->assertFlashMessage('Error 1');
  1256. $this->assertFlashMessageAt(0, 'Error 1');
  1257. $this->assertFlashElementAt(0, 'flash/error');
  1258. $this->assertFlashMessage('Error 2');
  1259. $this->assertFlashMessageAt(1, 'Error 2');
  1260. $this->assertFlashElementAt(1, 'flash/error');
  1261. $this->assertFlashMessage('Success 1', 'custom');
  1262. $this->assertFlashMessageAt(0, 'Success 1', 'custom');
  1263. $this->assertFlashElementAt(0, 'flash/success', 'custom');
  1264. $this->assertFlashMessage('Success 2', 'custom');
  1265. $this->assertFlashMessageAt(1, 'Success 2', 'custom');
  1266. $this->assertFlashElementAt(1, 'flash/success', 'custom');
  1267. }
  1268. /**
  1269. * Tests asserting flash messages without first sending a request
  1270. *
  1271. * @return void
  1272. */
  1273. public function testAssertFlashMessageWithoutSendingRequest()
  1274. {
  1275. $this->expectException(AssertionFailedError::class);
  1276. $message = 'There is no stored session data. Perhaps you need to run a request?';
  1277. $message .= ' Additionally, ensure `$this->enableRetainFlashMessages()` has been enabled for the test.';
  1278. $this->expectExceptionMessage($message);
  1279. $this->assertFlashMessage('Will not work');
  1280. }
  1281. /**
  1282. * tests failure messages for assertions
  1283. *
  1284. * @param string $assertion Assertion method
  1285. * @param string $message Expected failure message
  1286. * @param string $url URL to test
  1287. * @param mixed ...$rest
  1288. * @dataProvider assertionFailureMessagesProvider
  1289. */
  1290. public function testAssertionFailureMessages($assertion, $message, $url, ...$rest)
  1291. {
  1292. $this->expectException(AssertionFailedError::class);
  1293. $this->expectExceptionMessage($message);
  1294. Security::setSalt($this->key);
  1295. $this->get($url);
  1296. call_user_func_array([$this, $assertion], $rest);
  1297. }
  1298. /**
  1299. * data provider for assertion failure messages
  1300. *
  1301. * @return array
  1302. */
  1303. public function assertionFailureMessagesProvider()
  1304. {
  1305. $templateDir = TEST_APP . 'templates' . DS;
  1306. return [
  1307. 'assertContentType' => ['assertContentType', 'Failed asserting that \'test\' is set as the Content-Type (`text/html`).', '/posts/index', 'test'],
  1308. 'assertContentTypeVerbose' => ['assertContentType', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'],
  1309. 'assertCookie' => ['assertCookie', 'Failed asserting that \'test\' is in cookie \'remember_me\'.', '/posts/index', 'test', 'remember_me'],
  1310. 'assertCookieVerbose' => ['assertCookie', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test', 'remember_me'],
  1311. 'assertCookieEncrypted' => ['assertCookieEncrypted', 'Failed asserting that \'test\' is encrypted in cookie \'secrets\'.', '/posts/secretCookie', 'test', 'secrets'],
  1312. 'assertCookieEncryptedVerbose' => ['assertCookieEncrypted', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test', 'NameOfCookie'],
  1313. 'assertCookieNotSet' => ['assertCookieNotSet', 'Failed asserting that \'remember_me\' cookie is not set.', '/posts/index', 'remember_me'],
  1314. 'assertFileResponse' => ['assertFileResponse', 'Failed asserting that \'test\' file was sent.', '/posts/file', 'test'],
  1315. 'assertFileResponseVerbose' => ['assertFileResponse', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'],
  1316. 'assertHeader' => ['assertHeader', 'Failed asserting that \'test\' equals content in header \'X-Cake\' (`custom header`).', '/posts/header', 'X-Cake', 'test'],
  1317. 'assertHeaderContains' => ['assertHeaderContains', 'Failed asserting that \'test\' is in header \'X-Cake\' (`custom header`)', '/posts/header', 'X-Cake', 'test'],
  1318. 'assertHeaderNotContains' => ['assertHeaderNotContains', 'Failed asserting that \'custom header\' is not in header \'X-Cake\' (`custom header`)', '/posts/header', 'X-Cake', 'custom header'],
  1319. 'assertHeaderContainsVerbose' => ['assertHeaderContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'X-Cake', 'test'],
  1320. 'assertHeaderNotContainsVerbose' => ['assertHeaderNotContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'X-Cake', 'test'],
  1321. 'assertLayout' => ['assertLayout', 'Failed asserting that \'custom_layout\' equals layout file `' . $templateDir . 'layout' . DS . 'default.php`.', '/posts/index', 'custom_layout'],
  1322. 'assertLayoutVerbose' => ['assertLayout', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'custom_layout'],
  1323. 'assertRedirect' => ['assertRedirect', 'Failed asserting that \'http://localhost/\' equals content in header \'Location\' (`http://localhost/posts`).', '/posts/flashNoRender', '/'],
  1324. 'assertRedirectVerbose' => ['assertRedirect', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/'],
  1325. 'assertRedirectContains' => ['assertRedirectContains', 'Failed asserting that \'/posts/somewhere-else\' is in header \'Location\' (`http://localhost/posts`).', '/posts/flashNoRender', '/posts/somewhere-else'],
  1326. 'assertRedirectContainsVerbose' => ['assertRedirectContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/posts/somewhere-else'],
  1327. 'assertRedirectNotContainsVerbose' => ['assertRedirectNotContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/posts/somewhere-else'],
  1328. 'assertResponseCode' => ['assertResponseCode', 'Failed asserting that `302` matches response status code `200`.', '/posts/index', 302],
  1329. 'assertResponseContains' => ['assertResponseContains', 'Failed asserting that \'test\' is in response body.', '/posts/index', 'test'],
  1330. 'assertResponseEmpty' => ['assertResponseEmpty', 'Failed asserting that response body is empty.', '/posts/index'],
  1331. 'assertResponseEquals' => ['assertResponseEquals', 'Failed asserting that \'test\' matches response body.', '/posts/index', 'test'],
  1332. 'assertResponseEqualsVerbose' => ['assertResponseEquals', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'],
  1333. 'assertResponseError' => ['assertResponseError', 'Failed asserting that 200 is between 400 and 429.', '/posts/index'],
  1334. 'assertResponseFailure' => ['assertResponseFailure', 'Failed asserting that 200 is between 500 and 505.', '/posts/index'],
  1335. 'assertResponseNotContains' => ['assertResponseNotContains', 'Failed asserting that \'index\' is not in response body.', '/posts/index', 'index'],
  1336. 'assertResponseNotEmpty' => ['assertResponseNotEmpty', 'Failed asserting that response body is not empty.', '/posts/empty_response'],
  1337. 'assertResponseNotEquals' => ['assertResponseNotEquals', 'Failed asserting that \'posts index\' does not match response body.', '/posts/index/error', 'posts index'],
  1338. 'assertResponseNotRegExp' => ['assertResponseNotRegExp', 'Failed asserting that `/index/` PCRE pattern not found in response body.', '/posts/index/error', '/index/'],
  1339. 'assertResponseNotRegExpVerbose' => ['assertResponseNotRegExp', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/index/'],
  1340. 'assertResponseOk' => ['assertResponseOk', 'Failed asserting that 404 is between 200 and 204.', '/posts/missing', '/index/'],
  1341. 'assertResponseRegExp' => ['assertResponseRegExp', 'Failed asserting that `/test/` PCRE pattern found in response body.', '/posts/index/error', '/test/'],
  1342. 'assertResponseSuccess' => ['assertResponseSuccess', 'Failed asserting that 404 is between 200 and 308.', '/posts/missing'],
  1343. 'assertResponseSuccessVerbose' => ['assertResponseSuccess', 'Possibly related to Cake\Controller\Exception\MissingActionException: "Action PostsController::missing() could not be found, or is not accessible."', '/posts/missing'],
  1344. 'assertSession' => ['assertSession', 'Failed asserting that \'test\' is in session path \'Missing.path\'.', '/posts/index', 'test', 'Missing.path'],
  1345. 'assertTemplate' => ['assertTemplate', 'Failed asserting that \'custom_template\' equals template file `' . $templateDir . 'Posts' . DS . 'index.php`.', '/posts/index', 'custom_template'],
  1346. 'assertTemplateVerbose' => ['assertTemplate', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'custom_template'],
  1347. 'assertFlashMessage' => ['assertFlashMessage', 'Failed asserting that \'missing\' is in \'flash\' message.', '/posts/index', 'missing'],
  1348. 'assertFlashMessageWithKey' => ['assertFlashMessage', 'Failed asserting that \'missing\' is in \'auth\' message.', '/posts/index', 'missing', 'auth'],
  1349. 'assertFlashMessageAt' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' is in \'flash\' message #0.', '/posts/index', 0, 'missing'],
  1350. 'assertFlashMessageAtWithKey' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' is in \'auth\' message #0.', '/posts/index', 0, 'missing', 'auth'],
  1351. 'assertFlashElement' => ['assertFlashElement', 'Failed asserting that \'missing\' is in \'flash\' element.', '/posts/index', 'missing'],
  1352. 'assertFlashElementWithKey' => ['assertFlashElement', 'Failed asserting that \'missing\' is in \'auth\' element.', '/posts/index', 'missing', 'auth'],
  1353. 'assertFlashElementAt' => ['assertFlashElementAt', 'Failed asserting that \'missing\' is in \'flash\' element #0.', '/posts/index', 0, 'missing'],
  1354. 'assertFlashElementAtWithKey' => ['assertFlashElementAt', 'Failed asserting that \'missing\' is in \'auth\' element #0.', '/posts/index', 0, 'missing', 'auth'],
  1355. ];
  1356. }
  1357. /**
  1358. * data provider for HTTP methods
  1359. *
  1360. * @return array
  1361. */
  1362. public function methodsProvider()
  1363. {
  1364. return [
  1365. 'GET' => ['get'],
  1366. 'POST' => ['post'],
  1367. 'PATCH' => ['patch'],
  1368. 'PUT' => ['put'],
  1369. 'DELETE' => ['delete'],
  1370. ];
  1371. }
  1372. /**
  1373. * Test assertCookieNotSet is creating a verbose message
  1374. *
  1375. * @return void
  1376. */
  1377. public function testAssertCookieNotSetVerbose()
  1378. {
  1379. $this->expectException(AssertionFailedError::class);
  1380. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1381. $this->get('/notfound');
  1382. $this->_response = $this->_response->withCookie(new Cookie('cookie', 'value'));
  1383. $this->assertCookieNotSet('cookie');
  1384. }
  1385. /**
  1386. * Test assertNoRedirect is creating a verbose message
  1387. *
  1388. * @return void
  1389. */
  1390. public function testAssertNoRedirectVerbose()
  1391. {
  1392. $this->expectException(AssertionFailedError::class);
  1393. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1394. $this->get('/notfound');
  1395. $this->_response = $this->_response->withHeader('Location', '/redirect');
  1396. $this->assertNoRedirect();
  1397. }
  1398. /**
  1399. * Test the header assertion generating a verbose message.
  1400. *
  1401. * @return void
  1402. */
  1403. public function testAssertHeaderVerbose()
  1404. {
  1405. $this->expectException(AssertionFailedError::class);
  1406. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1407. $this->get('/notfound');
  1408. $this->assertHeader('Etag', 'abc123');
  1409. }
  1410. /**
  1411. * Test the assertResponseNotEquals generates a verbose message.
  1412. *
  1413. * @return void
  1414. */
  1415. public function testAssertResponseNotEqualsVerbose()
  1416. {
  1417. $this->expectException(AssertionFailedError::class);
  1418. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1419. $this->get('/notfound');
  1420. $this->_response = $this->_response->withStringBody('body');
  1421. $this->assertResponseNotEquals('body');
  1422. }
  1423. /**
  1424. * Test the assertResponseRegExp generates a verbose message.
  1425. *
  1426. * @return void
  1427. */
  1428. public function testAssertResponseRegExpVerbose()
  1429. {
  1430. $this->expectException(AssertionFailedError::class);
  1431. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1432. $this->get('/notfound');
  1433. $this->_response = $this->_response->withStringBody('body');
  1434. $this->assertResponseRegExp('/patternNotFound/');
  1435. }
  1436. /**
  1437. * Test the assertion generates a verbose message for session related checks.
  1438. *
  1439. * @dataProvider assertionFailureSessionVerboseProvider
  1440. * @return void
  1441. */
  1442. public function testAssertSessionRelatedVerboseMessages($assertMethod, ...$rest)
  1443. {
  1444. $this->expectException(AssertionFailedError::class);
  1445. $this->expectExceptionMessage('Possibly related to OutOfBoundsException: "oh no!"');
  1446. $this->get('/posts/throw_exception');
  1447. $this->_requestSession = new Session();
  1448. call_user_func_array([$this, $assertMethod], $rest);
  1449. }
  1450. /**
  1451. * data provider for assertion verbose session related tests
  1452. *
  1453. * @return array
  1454. */
  1455. public function assertionFailureSessionVerboseProvider()
  1456. {
  1457. return [
  1458. 'assertFlashMessageVerbose' => ['assertFlashMessage', 'notfound'],
  1459. 'assertFlashMessageAtVerbose' => ['assertFlashMessageAt', 2, 'notfound'],
  1460. 'assertFlashElementVerbose' => ['assertFlashElement', 'notfound'],
  1461. 'assertSessionVerbose' => ['assertSession', 'notfound', 'notfound'],
  1462. ];
  1463. }
  1464. /**
  1465. * Test viewVariable not found
  1466. *
  1467. * @return void
  1468. */
  1469. public function testViewVariableNotFoundShouldReturnNull()
  1470. {
  1471. $this->_controller = new Controller();
  1472. $this->assertNull($this->viewVariable('notFound'));
  1473. }
  1474. }