IntegrationTestTraitTest.php 56 KB

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