IntegrationTestTraitTest.php 61 KB

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