IntegrationTestTraitTest.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  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::$initailized === 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 URLs with an empty router.
  624. *
  625. * @return void
  626. */
  627. public function testArrayUrlsEmptyRouter()
  628. {
  629. Router::reload();
  630. $this->assertFalse(Router::$initialized);
  631. $this->post(['controller' => 'Posts', 'action' => 'index']);
  632. $this->assertResponseOk();
  633. $this->assertEquals('value', $this->viewVariable('test'));
  634. }
  635. /**
  636. * Test flash and cookie assertions
  637. *
  638. * @return void
  639. */
  640. public function testFlashSessionAndCookieAsserts()
  641. {
  642. $this->post('/posts/index');
  643. $this->assertSession('An error message', 'Flash.flash.0.message');
  644. $this->assertCookie(1, 'remember_me');
  645. $this->assertCookieNotSet('user_id');
  646. }
  647. /**
  648. * Test flash and cookie assertions
  649. *
  650. * @return void
  651. */
  652. public function testFlashSessionAndCookieAssertsHttpServer()
  653. {
  654. $this->post('/posts/index');
  655. $this->assertSession('An error message', 'Flash.flash.0.message');
  656. $this->assertCookieNotSet('user_id');
  657. $this->assertCookie(1, 'remember_me');
  658. }
  659. /**
  660. * Test flash assertions stored with enableRememberFlashMessages() after they
  661. * are rendered
  662. *
  663. * @return void
  664. */
  665. public function testFlashAssertionsAfterRender()
  666. {
  667. $this->enableRetainFlashMessages();
  668. $this->get('/posts/index/with_flash');
  669. $this->assertSession('An error message', 'Flash.flash.0.message');
  670. }
  671. /**
  672. * Test flash assertions stored with enableRememberFlashMessages() even if
  673. * no view is rendered
  674. *
  675. * @return void
  676. */
  677. public function testFlashAssertionsWithNoRender()
  678. {
  679. $this->enableRetainFlashMessages();
  680. $this->get('/posts/flashNoRender');
  681. $this->assertRedirect();
  682. $this->assertSession('An error message', 'Flash.flash.0.message');
  683. }
  684. /**
  685. * Tests assertCookieNotSet assertion
  686. *
  687. * @return void
  688. */
  689. public function testAssertCookieNotSet()
  690. {
  691. $this->cookie('test', 'value');
  692. $this->get('/cookie_component_test/remove_cookie/test');
  693. $this->assertCookieNotSet('test');
  694. }
  695. /**
  696. * Tests the failure message for assertCookieNotSet
  697. *
  698. * @return void
  699. */
  700. public function testCookieNotSetFailure()
  701. {
  702. $this->expectException(AssertionFailedError::class);
  703. $this->expectExceptionMessage('Failed asserting that \'remember_me\' cookie was not set');
  704. $this->post('/posts/index');
  705. $this->assertCookieNotSet('remember_me');
  706. }
  707. /**
  708. * Tests the failure message for assertCookieNotSet when no
  709. * response whas generated
  710. *
  711. * @return void
  712. */
  713. public function testCookieNotSetFailureNoResponse()
  714. {
  715. $this->expectException(AssertionFailedError::class);
  716. $this->expectExceptionMessage('No response set, cannot assert content.');
  717. $this->assertCookieNotSet('remember_me');
  718. }
  719. /**
  720. * Test error handling and error page rendering.
  721. *
  722. * @return void
  723. */
  724. public function testPostAndErrorHandling()
  725. {
  726. $this->post('/request_action/error_method');
  727. $this->assertResponseNotEmpty();
  728. $this->assertResponseContains('Not there or here');
  729. $this->assertResponseContains('<!DOCTYPE html>');
  730. }
  731. /**
  732. * Test posting to a secured form action.
  733. *
  734. * @return void
  735. */
  736. public function testPostSecuredForm()
  737. {
  738. $this->enableSecurityToken();
  739. $data = [
  740. 'title' => 'Some title',
  741. 'body' => 'Some text'
  742. ];
  743. $this->post('/posts/securePost', $data);
  744. $this->assertResponseOk();
  745. $this->assertResponseContains('Request was accepted');
  746. }
  747. /**
  748. * Test posting to a secured form action with nested data.
  749. *
  750. * @return void
  751. */
  752. public function testPostSecuredFormNestedData()
  753. {
  754. $this->enableSecurityToken();
  755. $data = [
  756. 'title' => 'New post',
  757. 'comments' => [
  758. ['comment' => 'A new comment']
  759. ],
  760. 'tags' => ['_ids' => [1, 2, 3, 4]]
  761. ];
  762. $this->post('/posts/securePost', $data);
  763. $this->assertResponseOk();
  764. $this->assertResponseContains('Request was accepted');
  765. }
  766. /**
  767. * Test posting to a secured form action.
  768. *
  769. * @return void
  770. */
  771. public function testPostSecuredFormWithQuery()
  772. {
  773. $this->enableSecurityToken();
  774. $data = [
  775. 'title' => 'Some title',
  776. 'body' => 'Some text'
  777. ];
  778. $this->post('/posts/securePost?foo=bar', $data);
  779. $this->assertResponseOk();
  780. $this->assertResponseContains('Request was accepted');
  781. }
  782. /**
  783. * Test posting to a secured form action with a query that has a part that
  784. * will be encoded by the security component
  785. *
  786. * @return void
  787. */
  788. public function testPostSecuredFormWithUnencodedQuery()
  789. {
  790. $this->enableSecurityToken();
  791. $data = [
  792. 'title' => 'Some title',
  793. 'body' => 'Some text'
  794. ];
  795. $this->post('/posts/securePost?foo=/', $data);
  796. $this->assertResponseOk();
  797. $this->assertResponseContains('Request was accepted');
  798. }
  799. /**
  800. * Test posting to a secured form action action.
  801. *
  802. * @return void
  803. */
  804. public function testPostSecuredFormFailure()
  805. {
  806. $data = [
  807. 'title' => 'Some title',
  808. 'body' => 'Some text'
  809. ];
  810. $this->post('/posts/securePost', $data);
  811. $this->assertResponseError();
  812. }
  813. /**
  814. * Test that exceptions being thrown are handled correctly.
  815. *
  816. * @return void
  817. */
  818. public function testWithExpectedException()
  819. {
  820. $this->get('/tests_apps/throw_exception');
  821. $this->assertResponseCode(500);
  822. }
  823. /**
  824. * Test that exceptions being thrown are handled correctly by the psr7 stack.
  825. *
  826. * @return void
  827. */
  828. public function testWithExpectedExceptionHttpServer()
  829. {
  830. DispatcherFactory::clear();
  831. $this->get('/tests_apps/throw_exception');
  832. $this->assertResponseCode(500);
  833. }
  834. /**
  835. * Test that exceptions being thrown are handled correctly.
  836. *
  837. * @return void
  838. */
  839. public function testWithUnexpectedException()
  840. {
  841. $this->expectException(AssertionFailedError::class);
  842. $this->get('/tests_apps/throw_exception');
  843. $this->assertResponseCode(501);
  844. }
  845. /**
  846. * Test redirecting and integration tests.
  847. *
  848. * @return void
  849. */
  850. public function testRedirect()
  851. {
  852. $this->post('/tests_apps/redirect_to');
  853. $this->assertResponseSuccess();
  854. $this->assertResponseCode(302);
  855. }
  856. /**
  857. * Test redirecting and psr7 stack
  858. *
  859. * @return void
  860. */
  861. public function testRedirectHttpServer()
  862. {
  863. DispatcherFactory::clear();
  864. $this->post('/tests_apps/redirect_to');
  865. $this->assertResponseCode(302);
  866. $this->assertHeader('X-Middleware', 'true');
  867. }
  868. /**
  869. * Test redirecting and integration tests.
  870. *
  871. * @return void
  872. */
  873. public function testRedirectPermanent()
  874. {
  875. $this->post('/tests_apps/redirect_to_permanent');
  876. $this->assertResponseSuccess();
  877. $this->assertResponseCode(301);
  878. }
  879. /**
  880. * Test the responseOk status assertion
  881. *
  882. * @return void
  883. */
  884. public function testAssertResponseStatusCodes()
  885. {
  886. $this->_response = new Response();
  887. $this->_response = $this->_response->withStatus(200);
  888. $this->assertResponseOk();
  889. $this->_response = $this->_response->withStatus(201);
  890. $this->assertResponseOk();
  891. $this->_response = $this->_response->withStatus(204);
  892. $this->assertResponseOk();
  893. $this->_response = $this->_response->withStatus(202);
  894. $this->assertResponseSuccess();
  895. $this->_response = $this->_response->withStatus(302);
  896. $this->assertResponseSuccess();
  897. $this->_response = $this->_response->withStatus(400);
  898. $this->assertResponseError();
  899. $this->_response = $this->_response->withStatus(417);
  900. $this->assertResponseError();
  901. $this->_response = $this->_response->withStatus(500);
  902. $this->assertResponseFailure();
  903. $this->_response = $this->_response->withStatus(505);
  904. $this->assertResponseFailure();
  905. $this->_response = $this->_response->withStatus(301);
  906. $this->assertResponseCode(301);
  907. }
  908. /**
  909. * Test the location header assertion.
  910. *
  911. * @return void
  912. */
  913. public function testAssertRedirect()
  914. {
  915. $this->_response = new Response();
  916. $this->_response = $this->_response->withHeader('Location', 'http://localhost/get/tasks/index');
  917. $this->assertRedirect();
  918. $this->assertRedirect('/get/tasks/index');
  919. $this->assertRedirect(['controller' => 'Tasks', 'action' => 'index']);
  920. $this->assertResponseEmpty();
  921. }
  922. /**
  923. * Test the location header assertion string not contains
  924. *
  925. * @return void
  926. */
  927. public function testAssertRedirectNotContains()
  928. {
  929. $this->_response = new Response();
  930. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  931. $this->assertRedirectNotContains('test');
  932. }
  933. /**
  934. * Test the location header assertion.
  935. *
  936. * @return void
  937. */
  938. public function testAssertNoRedirect()
  939. {
  940. $this->_response = new Response();
  941. $this->assertNoRedirect();
  942. }
  943. /**
  944. * Test the location header assertion.
  945. *
  946. * @return void
  947. */
  948. public function testAssertNoRedirectFail()
  949. {
  950. $test = new AssertIntegrationTestCase('testBadAssertNoRedirect');
  951. $result = $test->run();
  952. $this->assertFalse($result->wasSuccessful());
  953. $this->assertEquals(1, $result->failureCount());
  954. }
  955. /**
  956. * Test the location header assertion string contains
  957. *
  958. * @return void
  959. */
  960. public function testAssertRedirectContains()
  961. {
  962. $this->_response = new Response();
  963. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  964. $this->assertRedirectContains('/tasks/index');
  965. }
  966. /**
  967. * Test the header assertion.
  968. *
  969. * @return void
  970. */
  971. public function testAssertHeader()
  972. {
  973. $this->_response = new Response();
  974. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  975. $this->assertHeader('Etag', 'abc123');
  976. }
  977. /**
  978. * Test the header contains assertion.
  979. *
  980. * @return void
  981. */
  982. public function testAssertHeaderContains()
  983. {
  984. $this->_response = new Response();
  985. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  986. $this->assertHeaderContains('Etag', 'abc');
  987. }
  988. /**
  989. * Test the header not contains assertion.
  990. *
  991. * @return void
  992. */
  993. public function testAssertHeaderNotContains()
  994. {
  995. $this->_response = new Response();
  996. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  997. $this->assertHeaderNotContains('Etag', 'xyz');
  998. }
  999. /**
  1000. * Test the content type assertion.
  1001. *
  1002. * @return void
  1003. */
  1004. public function testAssertContentType()
  1005. {
  1006. $this->_response = new Response();
  1007. $this->_response = $this->_response->withType('json');
  1008. $this->assertContentType('json');
  1009. $this->assertContentType('application/json');
  1010. }
  1011. /**
  1012. * Test that type() in an action sets the content-type header.
  1013. *
  1014. * @return void
  1015. */
  1016. public function testContentTypeInAction()
  1017. {
  1018. $this->get('/tests_apps/set_type');
  1019. $this->assertHeader('Content-Type', 'application/json');
  1020. $this->assertContentType('json');
  1021. $this->assertContentType('application/json');
  1022. }
  1023. /**
  1024. * Test the content assertion.
  1025. *
  1026. * @return void
  1027. */
  1028. public function testAssertResponseEquals()
  1029. {
  1030. $this->_response = new Response();
  1031. $this->_response = $this->_response->withStringBody('Some content');
  1032. $this->assertResponseEquals('Some content');
  1033. }
  1034. /**
  1035. * Test the negated content assertion.
  1036. *
  1037. * @return void
  1038. */
  1039. public function testAssertResponseNotEquals()
  1040. {
  1041. $this->_response = new Response();
  1042. $this->_response = $this->_response->withStringBody('Some content');
  1043. $this->assertResponseNotEquals('Some Content');
  1044. }
  1045. /**
  1046. * Test the content assertion.
  1047. *
  1048. * @return void
  1049. */
  1050. public function testAssertResponseContains()
  1051. {
  1052. $this->_response = new Response();
  1053. $this->_response = $this->_response->withStringBody('Some content');
  1054. $this->assertResponseContains('content');
  1055. }
  1056. /**
  1057. * Test the content assertion with no case sensitivity.
  1058. *
  1059. * @return void
  1060. */
  1061. public function testAssertResponseContainsWithIgnoreCaseFlag()
  1062. {
  1063. $this->_response = new Response();
  1064. $this->_response = $this->_response->withStringBody('Some content');
  1065. $this->assertResponseContains('some', 'Failed asserting that the body contains given content', true);
  1066. }
  1067. /**
  1068. * Test the negated content assertion.
  1069. *
  1070. * @return void
  1071. */
  1072. public function testAssertResponseNotContains()
  1073. {
  1074. $this->_response = new Response();
  1075. $this->_response = $this->_response->withStringBody('Some content');
  1076. $this->assertResponseNotContains('contents');
  1077. }
  1078. /**
  1079. * Test the content regexp assertion.
  1080. *
  1081. * @return void
  1082. */
  1083. public function testAssertResponseRegExp()
  1084. {
  1085. $this->_response = new Response();
  1086. $this->_response = $this->_response->withStringBody('Some content');
  1087. $this->assertResponseRegExp('/cont/');
  1088. }
  1089. /**
  1090. * Test the content regexp assertion failing
  1091. *
  1092. * @return void
  1093. */
  1094. public function testAssertResponseRegExpNoResponse()
  1095. {
  1096. $this->expectException(AssertionFailedError::class);
  1097. $this->expectExceptionMessage('No response set');
  1098. $this->assertResponseRegExp('/cont/');
  1099. }
  1100. /**
  1101. * Test the negated content regexp assertion.
  1102. *
  1103. * @return void
  1104. */
  1105. public function testAssertResponseNotRegExp()
  1106. {
  1107. $this->_response = new Response();
  1108. $this->_response = $this->_response->withStringBody('Some content');
  1109. $this->assertResponseNotRegExp('/cant/');
  1110. }
  1111. /**
  1112. * Test negated content regexp assertion failing
  1113. *
  1114. * @return void
  1115. */
  1116. public function testAssertResponseNotRegExpNoResponse()
  1117. {
  1118. $this->expectException(AssertionFailedError::class);
  1119. $this->expectExceptionMessage('No response set');
  1120. $this->assertResponseNotRegExp('/cont/');
  1121. }
  1122. /**
  1123. * Test that works in tandem with testEventManagerReset2 to
  1124. * test the EventManager reset.
  1125. *
  1126. * The return value is passed to testEventManagerReset2 as
  1127. * an arguments.
  1128. *
  1129. * @return \Cake\Event\EventManager
  1130. */
  1131. public function testEventManagerReset1()
  1132. {
  1133. $eventManager = EventManager::instance();
  1134. $this->assertInstanceOf('Cake\Event\EventManager', $eventManager);
  1135. return $eventManager;
  1136. }
  1137. /**
  1138. * Test if the EventManager is reset between tests.
  1139. *
  1140. * @depends testEventManagerReset1
  1141. * @return void
  1142. */
  1143. public function testEventManagerReset2($prevEventManager)
  1144. {
  1145. $this->assertInstanceOf('Cake\Event\EventManager', $prevEventManager);
  1146. $this->assertNotSame($prevEventManager, EventManager::instance());
  1147. }
  1148. /**
  1149. * Test sending file in requests.
  1150. *
  1151. * @return void
  1152. */
  1153. public function testSendFile()
  1154. {
  1155. $this->get('/posts/file');
  1156. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  1157. }
  1158. /**
  1159. * Test sending file with psr7 stack
  1160. *
  1161. * @return void
  1162. */
  1163. public function testSendFileHttpServer()
  1164. {
  1165. $this->get('/posts/file');
  1166. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  1167. }
  1168. /**
  1169. * Test that assertFile requires a response
  1170. *
  1171. * @return void
  1172. */
  1173. public function testAssertFileNoResponse()
  1174. {
  1175. $this->expectException(AssertionFailedError::class);
  1176. $this->expectExceptionMessage('No response set, cannot assert content');
  1177. $this->assertFileResponse('foo');
  1178. }
  1179. /**
  1180. * Test that assertFile requires a file
  1181. *
  1182. * @return void
  1183. */
  1184. public function testAssertFileNoFile()
  1185. {
  1186. $this->expectException(AssertionFailedError::class);
  1187. $this->expectExceptionMessage('Failed asserting that file was sent.');
  1188. $this->get('/posts/get');
  1189. $this->assertFileResponse('foo');
  1190. }
  1191. /**
  1192. * Test disabling the error handler middleware.
  1193. *
  1194. * @return void
  1195. */
  1196. public function testDisableErrorHandlerMiddleware()
  1197. {
  1198. $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
  1199. $this->expectExceptionMessage('A route matching "/foo" could not be found.');
  1200. $this->disableErrorHandlerMiddleware();
  1201. $this->get('/foo');
  1202. }
  1203. /**
  1204. * tests getting a secure action while passing a query string
  1205. *
  1206. * @return void
  1207. * @dataProvider methodsProvider
  1208. */
  1209. public function testSecureWithQueryString($method)
  1210. {
  1211. $this->enableSecurityToken();
  1212. $this->{$method}('/posts/securePost/?ids[]=1&ids[]=2');
  1213. $this->assertResponseOk();
  1214. }
  1215. /**
  1216. * Tests flash assertions
  1217. *
  1218. * @return void
  1219. * @throws \PHPUnit\Exception
  1220. */
  1221. public function testAssertFlashMessage()
  1222. {
  1223. $this->get('/posts/stacked_flash');
  1224. $this->assertFlashElement('Flash/error');
  1225. $this->assertFlashElement('Flash/success', 'custom');
  1226. $this->assertFlashMessage('Error 1');
  1227. $this->assertFlashMessageAt(0, 'Error 1');
  1228. $this->assertFlashElementAt(0, 'Flash/error');
  1229. $this->assertFlashMessage('Error 2');
  1230. $this->assertFlashMessageAt(1, 'Error 2');
  1231. $this->assertFlashElementAt(1, 'Flash/error');
  1232. $this->assertFlashMessage('Success 1', 'custom');
  1233. $this->assertFlashMessageAt(0, 'Success 1', 'custom');
  1234. $this->assertFlashElementAt(0, 'Flash/success', 'custom');
  1235. $this->assertFlashMessage('Success 2', 'custom');
  1236. $this->assertFlashMessageAt(1, 'Success 2', 'custom');
  1237. $this->assertFlashElementAt(1, 'Flash/success', 'custom');
  1238. }
  1239. /**
  1240. * Tests asserting flash messages without first sending a request
  1241. *
  1242. * @return void
  1243. */
  1244. public function testAssertFlashMessageWithoutSendingRequest()
  1245. {
  1246. $this->expectException(AssertionFailedError::class);
  1247. $message = 'There is no stored session data. Perhaps you need to run a request?';
  1248. $message .= ' Additionally, ensure `$this->enableRetainFlashMessages()` has been enabled for the test.';
  1249. $this->expectExceptionMessage($message);
  1250. $this->assertFlashMessage('Will not work');
  1251. }
  1252. /**
  1253. * tests failure messages for assertions
  1254. *
  1255. * @param string $assertion Assertion method
  1256. * @param string $message Expected failure message
  1257. * @param string $url URL to test
  1258. * @param mixed ...$rest
  1259. * @dataProvider assertionFailureMessagesProvider
  1260. */
  1261. public function testAssertionFailureMessages($assertion, $message, $url, ...$rest)
  1262. {
  1263. $this->expectException(AssertionFailedError::class);
  1264. $this->expectExceptionMessage($message);
  1265. Security::setSalt('abcdabcdabcdabcdabcdabcdabcdabcdabcd');
  1266. $this->get($url);
  1267. call_user_func_array([$this, $assertion], $rest);
  1268. }
  1269. /**
  1270. * data provider for assertion failure messages
  1271. *
  1272. * @return array
  1273. */
  1274. public function assertionFailureMessagesProvider()
  1275. {
  1276. $templateDir = TEST_APP . 'TestApp' . DS . 'Template' . DS;
  1277. return [
  1278. 'assertContentType' => ['assertContentType', 'Failed asserting that \'test\' was set as the Content-Type.', '/posts/index', 'test'],
  1279. 'assertContentTypeVerbose' => ['assertContentType', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'],
  1280. 'assertCookie' => ['assertCookie', 'Failed asserting that \'test\' was in cookie \'remember_me\'.', '/posts/index', 'test', 'remember_me'],
  1281. 'assertCookieVerbose' => ['assertCookie', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test', 'remember_me'],
  1282. 'assertCookieEncrypted' => ['assertCookieEncrypted', 'Failed asserting that \'test\' was encrypted in cookie \'NameOfCookie\'.', '/cookie_component_test/set_cookie', 'test', 'NameOfCookie'],
  1283. 'assertCookieEncryptedVerbose' => ['assertCookieEncrypted', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test', 'NameOfCookie'],
  1284. 'assertCookieNotSet' => ['assertCookieNotSet', 'Failed asserting that \'remember_me\' cookie was not set.', '/posts/index', 'remember_me'],
  1285. 'assertFileResponse' => ['assertFileResponse', 'Failed asserting that \'test\' file was sent.', '/posts/file', 'test'],
  1286. 'assertFileResponseVerbose' => ['assertFileResponse', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'],
  1287. 'assertHeader' => ['assertHeader', 'Failed asserting that \'test\' equals content in header \'X-Cake\'.', '/posts/header', 'X-Cake', 'test'],
  1288. 'assertHeaderContains' => ['assertHeaderContains', 'Failed asserting that \'test\' is in header \'X-Cake\'', '/posts/header', 'X-Cake', 'test'],
  1289. 'assertHeaderContainsVerbose' => ['assertHeaderContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'X-Cake', 'test'],
  1290. 'assertHeaderNotContainsVerbose' => ['assertHeaderNotContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'X-Cake', 'test'],
  1291. 'assertLayout' => ['assertLayout', 'Failed asserting that \'custom_layout\' equals layout file ' . $templateDir . 'Layout' . DS . 'default.ctp.', '/posts/index', 'custom_layout'],
  1292. 'assertLayoutVerbose' => ['assertLayout', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'custom_layout'],
  1293. 'assertRedirect' => ['assertRedirect', 'Failed asserting that \'http://localhost/\' equals content in header \'Location\'.', '/posts/flashNoRender', '/'],
  1294. 'assertRedirectVerbose' => ['assertRedirect', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/'],
  1295. 'assertRedirectContains' => ['assertRedirectContains', 'Failed asserting that \'/posts/somewhere-else\' is in header \'Location\'.', '/posts/flashNoRender', '/posts/somewhere-else'],
  1296. 'assertRedirectContainsVerbose' => ['assertRedirectContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/posts/somewhere-else'],
  1297. 'assertRedirectNotContainsVerbose' => ['assertRedirectNotContains', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/posts/somewhere-else'],
  1298. 'assertResponseCode' => ['assertResponseCode', 'Failed asserting that 302 matches response status code 200.', '/posts/index', 302],
  1299. 'assertResponseContains' => ['assertResponseContains', 'Failed asserting that \'test\' is in response body.', '/posts/index', 'test'],
  1300. 'assertResponseEmpty' => ['assertResponseEmpty', 'Failed asserting that response body is empty.', '/posts/index'],
  1301. 'assertResponseEquals' => ['assertResponseEquals', 'Failed asserting that \'test\' matches response body.', '/posts/index', 'test'],
  1302. 'assertResponseEqualsVerbose' => ['assertResponseEquals', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'test'],
  1303. 'assertResponseError' => ['assertResponseError', 'Failed asserting that 200 is between 400 and 429.', '/posts/index'],
  1304. 'assertResponseFailure' => ['assertResponseFailure', 'Failed asserting that 200 is between 500 and 505.', '/posts/index'],
  1305. 'assertResponseNotContains' => ['assertResponseNotContains', 'Failed asserting that \'index\' is not in response body.', '/posts/index', 'index'],
  1306. 'assertResponseNotEmpty' => ['assertResponseNotEmpty', 'Failed asserting that response body is not empty.', '/posts/empty_response'],
  1307. 'assertResponseNotEquals' => ['assertResponseNotEquals', 'Failed asserting that \'posts index\' does not match response body.', '/posts/index/error', 'posts index'],
  1308. 'assertResponseNotRegExp' => ['assertResponseNotRegExp', 'Failed asserting that /index/ PCRE pattern not found in response body.', '/posts/index/error', '/index/'],
  1309. 'assertResponseNotRegExpVerbose' => ['assertResponseNotRegExp', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', '/index/'],
  1310. 'assertResponseOk' => ['assertResponseOk', 'Failed asserting that 404 is between 200 and 204.', '/posts/missing', '/index/'],
  1311. 'assertResponseRegExp' => ['assertResponseRegExp', 'Failed asserting that /test/ PCRE pattern found in response body.', '/posts/index/error', '/test/'],
  1312. 'assertResponseSuccess' => ['assertResponseSuccess', 'Failed asserting that 404 is between 200 and 308.', '/posts/missing'],
  1313. 'assertResponseSuccessVerbose' => ['assertResponseSuccess', 'Possibly related to Cake\Controller\Exception\MissingActionException: "Action PostsController::missing() could not be found, or is not accessible."', '/posts/missing'],
  1314. 'assertSession' => ['assertSession', 'Failed asserting that \'test\' is in session path \'Missing.path\'.', '/posts/index', 'test', 'Missing.path'],
  1315. 'assertTemplate' => ['assertTemplate', 'Failed asserting that \'custom_template\' equals template file ' . $templateDir . 'Posts' . DS . 'index.ctp.', '/posts/index', 'custom_template'],
  1316. 'assertTemplateVerbose' => ['assertTemplate', 'Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."', '/notfound', 'custom_template'],
  1317. 'assertFlashMessage' => ['assertFlashMessage', 'Failed asserting that \'missing\' was in \'flash\' message.', '/posts/index', 'missing'],
  1318. 'assertFlashMessageWithKey' => ['assertFlashMessage', 'Failed asserting that \'missing\' was in \'auth\' message.', '/posts/index', 'missing', 'auth'],
  1319. 'assertFlashMessageAt' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' was in \'flash\' message #0.', '/posts/index', 0, 'missing'],
  1320. 'assertFlashMessageAtWithKey' => ['assertFlashMessageAt', 'Failed asserting that \'missing\' was in \'auth\' message #0.', '/posts/index', 0, 'missing', 'auth'],
  1321. 'assertFlashElement' => ['assertFlashElement', 'Failed asserting that \'missing\' was in \'flash\' element.', '/posts/index', 'missing'],
  1322. 'assertFlashElementWithKey' => ['assertFlashElement', 'Failed asserting that \'missing\' was in \'auth\' element.', '/posts/index', 'missing', 'auth'],
  1323. 'assertFlashElementAt' => ['assertFlashElementAt', 'Failed asserting that \'missing\' was in \'flash\' element #0.', '/posts/index', 0, 'missing'],
  1324. 'assertFlashElementAtWithKey' => ['assertFlashElementAt', 'Failed asserting that \'missing\' was in \'auth\' element #0.', '/posts/index', 0, 'missing', 'auth'],
  1325. ];
  1326. }
  1327. /**
  1328. * data provider for HTTP methods
  1329. *
  1330. * @return array
  1331. */
  1332. public function methodsProvider()
  1333. {
  1334. return [
  1335. 'GET' => ['get'],
  1336. 'POST' => ['post'],
  1337. 'PATCH' => ['patch'],
  1338. 'PUT' => ['put'],
  1339. 'DELETE' => ['delete'],
  1340. ];
  1341. }
  1342. /**
  1343. * Test assertCookieNotSet is creating a verbose message
  1344. *
  1345. * @return void
  1346. */
  1347. public function testAssertCookieNotSetVerbose()
  1348. {
  1349. $this->expectException(AssertionFailedError::class);
  1350. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1351. $this->get('/notfound');
  1352. $this->_response = $this->_response->withCookie(new Cookie('cookie', 'value'));
  1353. $this->assertCookieNotSet('cookie');
  1354. }
  1355. /**
  1356. * Test assertNoRedirect is creating a verbose message
  1357. *
  1358. * @return void
  1359. */
  1360. public function testAssertNoRedirectVerbose()
  1361. {
  1362. $this->expectException(AssertionFailedError::class);
  1363. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1364. $this->get('/notfound');
  1365. $this->_response = $this->_response->withHeader('Location', '/redirect');
  1366. $this->assertNoRedirect();
  1367. }
  1368. /**
  1369. * Test the header assertion generating a verbose message.
  1370. *
  1371. * @return void
  1372. */
  1373. public function testAssertHeaderVerbose()
  1374. {
  1375. $this->expectException(AssertionFailedError::class);
  1376. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1377. $this->get('/notfound');
  1378. $this->assertHeader('Etag', 'abc123');
  1379. }
  1380. /**
  1381. * Test the assertResponseNotEquals generates a verbose message.
  1382. *
  1383. * @return void
  1384. */
  1385. public function testAssertResponseNotEqualsVerbose()
  1386. {
  1387. $this->expectException(AssertionFailedError::class);
  1388. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1389. $this->get('/notfound');
  1390. $this->_response = $this->_response->withStringBody('body');
  1391. $this->assertResponseNotEquals('body');
  1392. }
  1393. /**
  1394. * Test the assertResponseRegExp generates a verbose message.
  1395. *
  1396. * @return void
  1397. */
  1398. public function testAssertResponseRegExpVerbose()
  1399. {
  1400. $this->expectException(AssertionFailedError::class);
  1401. $this->expectExceptionMessage('Possibly related to Cake\Routing\Exception\MissingRouteException: "A route matching "/notfound" could not be found."');
  1402. $this->get('/notfound');
  1403. $this->_response = $this->_response->withStringBody('body');
  1404. $this->assertResponseRegExp('/patternNotFound/');
  1405. }
  1406. /**
  1407. * Test the assertion generates a verbose message for session related checks.
  1408. *
  1409. * @dataProvider assertionFailureSessionVerboseProvider
  1410. * @return void
  1411. */
  1412. public function testAssertSessionRelatedVerboseMessages($assertMethod, ...$rest)
  1413. {
  1414. $this->expectException(AssertionFailedError::class);
  1415. $this->expectExceptionMessage('Possibly related to OutOfBoundsException: "oh no!"');
  1416. $this->get('/posts/throw_exception');
  1417. $this->_requestSession = new Session();
  1418. call_user_func_array([$this, $assertMethod], $rest);
  1419. }
  1420. /**
  1421. * data provider for assertion verbose session related tests
  1422. *
  1423. * @return array
  1424. */
  1425. public function assertionFailureSessionVerboseProvider()
  1426. {
  1427. return [
  1428. 'assertFlashMessageVerbose' => ['assertFlashMessage', 'notfound'],
  1429. 'assertFlashMessageAtVerbose' => ['assertFlashMessageAt', 2, 'notfound'],
  1430. 'assertFlashElementVerbose' => ['assertFlashElement', 'notfound'],
  1431. 'assertSessionVerbose' => ['assertSession', 'notfound', 'notfound'],
  1432. ];
  1433. }
  1434. /**
  1435. * Test fail case for viewVariable
  1436. *
  1437. * @return void
  1438. */
  1439. public function testViewVariableShouldFailIfNoViewVars()
  1440. {
  1441. $this->expectException(AssertionFailedError::class);
  1442. $this->expectExceptionMessage('There are no view variables, perhaps you need to run a request?');
  1443. $this->viewVariable('shouldFail');
  1444. }
  1445. /**
  1446. * Test viewVariable not found
  1447. *
  1448. * @return void
  1449. */
  1450. public function testViewVariableNotFoundShouldReturnNull()
  1451. {
  1452. $this->_controller = new Controller();
  1453. $this->_controller->viewVars = ['key' => 'value'];
  1454. $this->assertNull($this->viewVariable('notFound'));
  1455. }
  1456. }