IntegrationTestCaseTest.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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\Core\Configure;
  17. use Cake\Event\EventManager;
  18. use Cake\Http\Response;
  19. use Cake\Routing\DispatcherFactory;
  20. use Cake\Routing\RouteBuilder;
  21. use Cake\Routing\Router;
  22. use Cake\Routing\Route\InflectedRoute;
  23. use Cake\TestSuite\IntegrationTestCase;
  24. use Cake\Test\Fixture\AssertIntegrationTestCase;
  25. use Cake\Utility\Security;
  26. /**
  27. * Self test of the IntegrationTestCase
  28. */
  29. class IntegrationTestCaseTest extends IntegrationTestCase
  30. {
  31. /**
  32. * Setup method
  33. *
  34. * @return void
  35. */
  36. public function setUp()
  37. {
  38. parent::setUp();
  39. static::setAppNamespace();
  40. Router::reload();
  41. Router::scope('/', function ($routes) {
  42. $routes->setRouteClass(InflectedRoute::class);
  43. $routes->get('/get/:controller/:action', []);
  44. $routes->head('/head/:controller/:action', []);
  45. $routes->options('/options/:controller/:action', []);
  46. $routes->connect('/:controller/:action/*', []);
  47. });
  48. Router::$initialized = true;
  49. $this->useHttpServer(true);
  50. DispatcherFactory::clear();
  51. }
  52. /**
  53. * Helper for enabling the legacy stack for backwards compatibility testing.
  54. *
  55. * @return void
  56. */
  57. protected function useLegacyDispatcher()
  58. {
  59. DispatcherFactory::add('Routing');
  60. DispatcherFactory::add('ControllerFactory');
  61. $this->useHttpServer(false);
  62. }
  63. /**
  64. * Test building a request.
  65. *
  66. * @return void
  67. */
  68. public function testRequestBuilding()
  69. {
  70. $this->configRequest([
  71. 'headers' => [
  72. 'X-CSRF-Token' => 'abc123',
  73. 'Content-Type' => 'application/json',
  74. 'Accept' => 'application/json'
  75. ],
  76. 'base' => '',
  77. 'webroot' => '/',
  78. 'environment' => [
  79. 'PHP_AUTH_USER' => 'foo',
  80. 'PHP_AUTH_PW' => 'bar'
  81. ]
  82. ]);
  83. $this->cookie('split_token', 'def345');
  84. $this->session(['User' => ['id' => 1, 'username' => 'mark']]);
  85. $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  86. $this->assertEquals('abc123', $request['environment']['HTTP_X_CSRF_TOKEN']);
  87. $this->assertEquals('application/json', $request['environment']['CONTENT_TYPE']);
  88. $this->assertEquals('/tasks/add', $request['url']);
  89. $this->assertArrayHasKey('split_token', $request['cookies']);
  90. $this->assertEquals('def345', $request['cookies']['split_token']);
  91. $this->assertEquals(['id' => '1', 'username' => 'mark'], $request['session']->read('User'));
  92. $this->assertEquals('foo', $request['environment']['PHP_AUTH_USER']);
  93. $this->assertEquals('bar', $request['environment']['PHP_AUTH_PW']);
  94. }
  95. /**
  96. * Test request building adds csrf tokens
  97. *
  98. * @return void
  99. */
  100. public function testRequestBuildingCsrfTokens()
  101. {
  102. $this->enableCsrfToken();
  103. $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  104. $this->assertArrayHasKey('csrfToken', $request['cookies']);
  105. $this->assertArrayHasKey('_csrfToken', $request['post']);
  106. $this->assertSame($request['cookies']['csrfToken'], $request['post']['_csrfToken']);
  107. $this->cookie('csrfToken', '');
  108. $request = $this->_buildRequest('/tasks/add', 'POST', [
  109. '_csrfToken' => 'fale',
  110. 'title' => 'First post'
  111. ]);
  112. $this->assertSame('', $request['cookies']['csrfToken']);
  113. $this->assertSame('fale', $request['post']['_csrfToken']);
  114. }
  115. /**
  116. * Test multiple actions using CSRF tokens don't fail
  117. *
  118. * @return void
  119. */
  120. public function testEnableCsrfMultipleRequests()
  121. {
  122. $this->enableCsrfToken();
  123. $first = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  124. $second = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'Second post']);
  125. $this->assertSame(
  126. $first['cookies']['csrfToken'],
  127. $second['post']['_csrfToken'],
  128. 'Csrf token should match cookie'
  129. );
  130. $this->assertSame(
  131. $first['post']['_csrfToken'],
  132. $second['post']['_csrfToken'],
  133. 'Tokens should be consistent per test method'
  134. );
  135. }
  136. /**
  137. * Test pre-determined CSRF tokens.
  138. *
  139. * @return void
  140. */
  141. public function testEnableCsrfPredeterminedCookie()
  142. {
  143. $this->enableCsrfToken();
  144. $value = 'I am a teapot';
  145. $this->cookie('csrfToken', $value);
  146. $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
  147. $this->assertSame($value, $request['cookies']['csrfToken'], 'Csrf token should match cookie');
  148. $this->assertSame($value, $request['post']['_csrfToken'], 'Tokens should match');
  149. }
  150. /**
  151. * Test building a request, with query parameters
  152. *
  153. * @return void
  154. */
  155. public function testRequestBuildingQueryParameters()
  156. {
  157. $request = $this->_buildRequest('/tasks/view?archived=yes', 'GET', []);
  158. $this->assertSame('/tasks/view', $request['url']);
  159. $this->assertSame('archived=yes', $request['environment']['QUERY_STRING']);
  160. $this->assertSame('/tasks/view', $request['environment']['REQUEST_URI']);
  161. }
  162. /**
  163. * Test cookie encrypted
  164. *
  165. * @see CookieComponentControllerTest
  166. */
  167. public function testCookieEncrypted()
  168. {
  169. Security::setSalt('abcdabcdabcdabcdabcdabcdabcdabcdabcd');
  170. $this->cookieEncrypted('KeyOfCookie', 'Encrypted with aes by default');
  171. $request = $this->_buildRequest('/tasks/view', 'GET', []);
  172. $this->assertStringStartsWith('Q2FrZQ==.', $request['cookies']['KeyOfCookie']);
  173. }
  174. /**
  175. * Test sending get requests.
  176. *
  177. * @group deprecated
  178. * @return void
  179. */
  180. public function testGetLegacy()
  181. {
  182. $this->useLegacyDispatcher();
  183. $this->deprecated(function () {
  184. $this->assertNull($this->_response);
  185. $this->get('/request_action/test_request_action');
  186. $this->assertNotEmpty($this->_response);
  187. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  188. $this->assertEquals('This is a test', $this->_response->getBody());
  189. $this->_response = null;
  190. $this->get('/get/request_action/test_request_action');
  191. $this->assertEquals('This is a test', $this->_response->getBody());
  192. });
  193. }
  194. /**
  195. * Test sending get request and using default `test_app/config/routes.php`.
  196. *
  197. * @return void
  198. */
  199. public function testGetUsingApplicationWithDefaultRoutes()
  200. {
  201. // first clean routes to have Router::$initailized === false
  202. Router::reload();
  203. $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithDefaultRoutes', null);
  204. $this->get('/some_alias');
  205. $this->assertResponseOk();
  206. $this->assertEquals('5', $this->_getBodyAsString());
  207. }
  208. public function testExceptionsInMiddlewareJsonView(){
  209. Router::reload();
  210. Router::connect('/json_response/api_get_data', [
  211. 'controller' => 'JsonResponse',
  212. 'action' => 'apiGetData'
  213. ] );
  214. $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithExceptionsInMiddleware', null);
  215. $this->_request['headers'] = [ "Accept" => "application/json" ];
  216. $this->get( '/json_response/api_get_data');
  217. $this->assertResponseCode(403);
  218. $this->assertHeader('Content-Type', 'application/json; charset=UTF-8');
  219. $this->assertResponseContains('"message": "Sample Message"');
  220. $this->assertResponseContains('"code": 403');
  221. }
  222. /**
  223. * Test sending head requests.
  224. *
  225. * @return void
  226. */
  227. public function testHead()
  228. {
  229. $this->assertNull($this->_response);
  230. $this->head('/request_action/test_request_action');
  231. $this->assertNotEmpty($this->_response);
  232. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  233. $this->assertResponseSuccess();
  234. $this->_response = null;
  235. $this->head('/head/request_action/test_request_action');
  236. $this->assertResponseSuccess();
  237. }
  238. /**
  239. * Test sending options requests.
  240. *
  241. * @return void
  242. */
  243. public function testOptions()
  244. {
  245. $this->assertNull($this->_response);
  246. $this->options('/request_action/test_request_action');
  247. $this->assertNotEmpty($this->_response);
  248. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  249. $this->assertResponseSuccess();
  250. $this->_response = null;
  251. $this->options('/options/request_action/test_request_action');
  252. $this->assertResponseSuccess();
  253. }
  254. /**
  255. * Test sending get requests sets the request method
  256. *
  257. * @return void
  258. */
  259. public function testGetSpecificRouteLegacy()
  260. {
  261. $this->useLegacyDispatcher();
  262. $this->deprecated(function () {
  263. $this->get('/get/request_action/test_request_action');
  264. $this->assertResponseOk();
  265. $this->assertEquals('This is a test', $this->_response->getBody());
  266. });
  267. }
  268. /**
  269. * Test sending get requests sets the request method
  270. *
  271. * @return void
  272. */
  273. public function testGetSpecificRouteHttpServer()
  274. {
  275. $this->get('/get/request_action/test_request_action');
  276. $this->assertResponseOk();
  277. $this->assertEquals('This is a test', $this->_response->getBody());
  278. }
  279. /**
  280. * Test customizing the app class.
  281. *
  282. * @return void
  283. */
  284. public function testConfigApplication()
  285. {
  286. $this->expectException(\LogicException::class);
  287. $this->expectExceptionMessage('Cannot load "TestApp\MissingApp" for use in integration');
  288. $this->configApplication('TestApp\MissingApp', []);
  289. $this->get('/request_action/test_request_action');
  290. }
  291. /**
  292. * Test sending get requests with Http\Server
  293. *
  294. * @return void
  295. */
  296. public function testGetHttpServer()
  297. {
  298. $this->assertNull($this->_response);
  299. $this->get('/request_action/test_request_action');
  300. $this->assertNotEmpty($this->_response);
  301. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  302. $this->assertEquals('This is a test', $this->_response->getBody());
  303. $this->assertHeader('X-Middleware', 'true');
  304. }
  305. /**
  306. * Test that the PSR7 requests get query string data
  307. *
  308. * @return void
  309. */
  310. public function testGetQueryStringHttpServer()
  311. {
  312. $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
  313. $this->get('/request_action/params_pass?q=query');
  314. $this->assertResponseOk();
  315. $this->assertResponseContains('"q":"query"');
  316. $this->assertResponseContains('"contentType":"text\/plain"');
  317. $this->assertHeader('X-Middleware', 'true');
  318. $request = $this->_controller->request;
  319. $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
  320. }
  321. /**
  322. * Test that the PSR7 requests get query string data
  323. *
  324. * @group deprecated
  325. * @return void
  326. */
  327. public function testGetQueryStringSetsHere()
  328. {
  329. $this->deprecated(function () {
  330. $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
  331. $this->get('/request_action/params_pass?q=query');
  332. $this->assertResponseOk();
  333. $this->assertResponseContains('"q":"query"');
  334. $this->assertResponseContains('"contentType":"text\/plain"');
  335. $this->assertHeader('X-Middleware', 'true');
  336. $request = $this->_controller->request;
  337. $this->assertContains('/request_action/params_pass?q=query', $request->here());
  338. $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
  339. });
  340. }
  341. /**
  342. * Test that the PSR7 requests get cookies
  343. *
  344. * @return void
  345. */
  346. public function testGetCookiesHttpServer()
  347. {
  348. $this->configRequest(['cookies' => ['split_test' => 'abc']]);
  349. $this->get('/request_action/cookie_pass');
  350. $this->assertResponseOk();
  351. $this->assertResponseContains('"split_test":"abc"');
  352. $this->assertHeader('X-Middleware', 'true');
  353. }
  354. /**
  355. * Test that the PSR7 requests receive post data
  356. *
  357. * @return void
  358. */
  359. public function testPostDataLegacyDispatcher()
  360. {
  361. $this->useLegacyDispatcher();
  362. $this->deprecated(function () {
  363. $this->post('/request_action/post_pass', ['title' => 'value']);
  364. $data = json_decode($this->_response->getBody());
  365. $this->assertEquals('value', $data->title);
  366. });
  367. }
  368. /**
  369. * Test that the PSR7 requests receive post data
  370. *
  371. * @return void
  372. */
  373. public function testPostDataHttpServer()
  374. {
  375. $this->post('/request_action/post_pass', ['title' => 'value']);
  376. $data = json_decode($this->_response->getBody());
  377. $this->assertEquals('value', $data->title);
  378. $this->assertHeader('X-Middleware', 'true');
  379. }
  380. /**
  381. * Test that the PSR7 requests receive encoded data.
  382. *
  383. * @return void
  384. */
  385. public function testInputDataHttpServer()
  386. {
  387. $this->post('/request_action/input_test', '{"hello":"world"}');
  388. if ($this->_response->getBody()->isSeekable()) {
  389. $this->_response->getBody()->rewind();
  390. }
  391. $this->assertSame('world', $this->_response->getBody()->getContents());
  392. $this->assertHeader('X-Middleware', 'true');
  393. }
  394. /**
  395. * Test that the PSR7 requests receive encoded data.
  396. *
  397. * @return void
  398. */
  399. public function testInputDataSecurityToken()
  400. {
  401. $this->enableSecurityToken();
  402. $this->post('/request_action/input_test', '{"hello":"world"}');
  403. $this->assertSame('world', '' . $this->_response->getBody());
  404. $this->assertHeader('X-Middleware', 'true');
  405. }
  406. /**
  407. * Test that the PSR7 requests get cookies
  408. *
  409. * @return void
  410. */
  411. public function testSessionHttpServer()
  412. {
  413. $this->session(['foo' => 'session data']);
  414. $this->get('/request_action/session_test');
  415. $this->assertResponseOk();
  416. $this->assertResponseContains('session data');
  417. $this->assertHeader('X-Middleware', 'true');
  418. }
  419. /**
  420. * Test sending requests stores references to controller/view/layout.
  421. *
  422. * @return void
  423. */
  424. public function testRequestSetsProperties()
  425. {
  426. $this->post('/posts/index');
  427. $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
  428. $this->assertNotEmpty($this->_viewName, 'View name not set');
  429. $this->assertContains('Template' . DS . 'Posts' . DS . 'index.ctp', $this->_viewName);
  430. $this->assertNotEmpty($this->_layoutName, 'Layout name not set');
  431. $this->assertContains('Template' . DS . 'Layout' . DS . 'default.ctp', $this->_layoutName);
  432. $this->assertTemplate('index');
  433. $this->assertLayout('default');
  434. $this->assertEquals('value', $this->viewVariable('test'));
  435. }
  436. /**
  437. * Test PSR7 requests store references to controller/view/layout
  438. *
  439. * @return void
  440. */
  441. public function testRequestSetsPropertiesHttpServer()
  442. {
  443. $this->post('/posts/index');
  444. $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
  445. $this->assertNotEmpty($this->_viewName, 'View name not set');
  446. $this->assertContains('Template' . DS . 'Posts' . DS . 'index.ctp', $this->_viewName);
  447. $this->assertNotEmpty($this->_layoutName, 'Layout name not set');
  448. $this->assertContains('Template' . DS . 'Layout' . DS . 'default.ctp', $this->_layoutName);
  449. $this->assertTemplate('index');
  450. $this->assertLayout('default');
  451. $this->assertEquals('value', $this->viewVariable('test'));
  452. }
  453. /**
  454. * Assert that the stored template doesn't change when cells are rendered.
  455. *
  456. * @return void
  457. */
  458. public function testAssertTemplateAfterCellRender()
  459. {
  460. $this->get('/posts/get');
  461. $this->assertContains('Template' . DS . 'Posts' . DS . 'get.ctp', $this->_viewName);
  462. $this->assertTemplate('get');
  463. $this->assertResponseContains('cellcontent');
  464. }
  465. /**
  466. * Test array URLs
  467. *
  468. * @return void
  469. */
  470. public function testArrayUrls()
  471. {
  472. $this->post(['controller' => 'Posts', 'action' => 'index']);
  473. $this->assertEquals('value', $this->viewVariable('test'));
  474. }
  475. /**
  476. * Test flash and cookie assertions
  477. *
  478. * @return void
  479. */
  480. public function testFlashSessionAndCookieAsserts()
  481. {
  482. $this->post('/posts/index');
  483. $this->assertSession('An error message', 'Flash.flash.0.message');
  484. $this->assertCookie(1, 'remember_me');
  485. $this->assertCookieNotSet('user_id');
  486. }
  487. /**
  488. * Test flash and cookie assertions
  489. *
  490. * @return void
  491. */
  492. public function testFlashSessionAndCookieAssertsHttpServer()
  493. {
  494. $this->post('/posts/index');
  495. $this->assertSession('An error message', 'Flash.flash.0.message');
  496. $this->assertCookieNotSet('user_id');
  497. $this->assertCookie(1, 'remember_me');
  498. }
  499. /**
  500. * Test flash assertions stored with enableRememberFlashMessages() after they
  501. * are rendered
  502. *
  503. * @return void
  504. */
  505. public function testFlashAssertionsAfterRender()
  506. {
  507. $this->enableRetainFlashMessages();
  508. $this->get('/posts/index/with_flash');
  509. $this->assertSession('An error message', 'Flash.flash.0.message');
  510. }
  511. /**
  512. * Test flash assertions stored with enableRememberFlashMessages() even if
  513. * no view is rendered
  514. *
  515. * @return void
  516. */
  517. public function testFlashAssertionsWithNoRender()
  518. {
  519. $this->enableRetainFlashMessages();
  520. $this->get('/posts/flashNoRender');
  521. $this->assertRedirect();
  522. $this->assertSession('An error message', 'Flash.flash.0.message');
  523. }
  524. /**
  525. * Tests the failure message for assertCookieNotSet
  526. *
  527. * @return void
  528. */
  529. public function testCookieNotSetFailure()
  530. {
  531. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  532. $this->expectExceptionMessage('Cookie \'remember_me\' has been set');
  533. $this->post('/posts/index');
  534. $this->assertCookieNotSet('remember_me');
  535. }
  536. /**
  537. * Tests the failure message for assertCookieNotSet when no
  538. * response whas generated
  539. *
  540. * @return void
  541. */
  542. public function testCookieNotSetFailureNoResponse()
  543. {
  544. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  545. $this->expectExceptionMessage('No response set, cannot assert cookies.');
  546. $this->assertCookieNotSet('remember_me');
  547. }
  548. /**
  549. * Test error handling and error page rendering.
  550. *
  551. * @return void
  552. */
  553. public function testPostAndErrorHandling()
  554. {
  555. $this->post('/request_action/error_method');
  556. $this->assertResponseNotEmpty();
  557. $this->assertResponseContains('Not there or here');
  558. $this->assertResponseContains('<!DOCTYPE html>');
  559. }
  560. /**
  561. * Test posting to a secured form action.
  562. *
  563. * @return void
  564. */
  565. public function testPostSecuredForm()
  566. {
  567. $this->enableSecurityToken();
  568. $data = [
  569. 'title' => 'Some title',
  570. 'body' => 'Some text'
  571. ];
  572. $this->post('/posts/securePost', $data);
  573. $this->assertResponseOk();
  574. $this->assertResponseContains('Request was accepted');
  575. }
  576. /**
  577. * Test posting to a secured form action with nested data.
  578. *
  579. * @return void
  580. */
  581. public function testPostSecuredFormNestedData()
  582. {
  583. $this->enableSecurityToken();
  584. $data = [
  585. 'title' => 'New post',
  586. 'comments' => [
  587. ['comment' => 'A new comment']
  588. ],
  589. 'tags' => ['_ids' => [1, 2, 3, 4]]
  590. ];
  591. $this->post('/posts/securePost', $data);
  592. $this->assertResponseOk();
  593. $this->assertResponseContains('Request was accepted');
  594. }
  595. /**
  596. * Test posting to a secured form action.
  597. *
  598. * @return void
  599. */
  600. public function testPostSecuredFormWithQuery()
  601. {
  602. $this->enableSecurityToken();
  603. $data = [
  604. 'title' => 'Some title',
  605. 'body' => 'Some text'
  606. ];
  607. $this->post('/posts/securePost?foo=bar', $data);
  608. $this->assertResponseOk();
  609. $this->assertResponseContains('Request was accepted');
  610. }
  611. /**
  612. * Test posting to a secured form action with a query that has a part that
  613. * will be encoded by the security component
  614. *
  615. * @return void
  616. */
  617. public function testPostSecuredFormWithUnencodedQuery()
  618. {
  619. $this->enableSecurityToken();
  620. $data = [
  621. 'title' => 'Some title',
  622. 'body' => 'Some text'
  623. ];
  624. $this->post('/posts/securePost?foo=/', $data);
  625. $this->assertResponseOk();
  626. $this->assertResponseContains('Request was accepted');
  627. }
  628. /**
  629. * Test posting to a secured form action action.
  630. *
  631. * @return void
  632. */
  633. public function testPostSecuredFormFailure()
  634. {
  635. $data = [
  636. 'title' => 'Some title',
  637. 'body' => 'Some text'
  638. ];
  639. $this->post('/posts/securePost', $data);
  640. $this->assertResponseError();
  641. }
  642. /**
  643. * Test that exceptions being thrown are handled correctly.
  644. *
  645. * @return void
  646. */
  647. public function testWithExpectedException()
  648. {
  649. $this->get('/tests_apps/throw_exception');
  650. $this->assertResponseCode(500);
  651. }
  652. /**
  653. * Test that exceptions being thrown are handled correctly by the psr7 stack.
  654. *
  655. * @return void
  656. */
  657. public function testWithExpectedExceptionHttpServer()
  658. {
  659. DispatcherFactory::clear();
  660. $this->get('/tests_apps/throw_exception');
  661. $this->assertResponseCode(500);
  662. }
  663. /**
  664. * Test that exceptions being thrown are handled correctly.
  665. *
  666. * @return void
  667. */
  668. public function testWithUnexpectedException()
  669. {
  670. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  671. $this->get('/tests_apps/throw_exception');
  672. $this->assertResponseCode(501);
  673. }
  674. /**
  675. * Test redirecting and integration tests.
  676. *
  677. * @return void
  678. */
  679. public function testRedirect()
  680. {
  681. $this->post('/tests_apps/redirect_to');
  682. $this->assertResponseSuccess();
  683. $this->assertResponseCode(302);
  684. }
  685. /**
  686. * Test redirecting and psr7 stack
  687. *
  688. * @return void
  689. */
  690. public function testRedirectHttpServer()
  691. {
  692. DispatcherFactory::clear();
  693. $this->post('/tests_apps/redirect_to');
  694. $this->assertResponseCode(302);
  695. $this->assertHeader('X-Middleware', 'true');
  696. }
  697. /**
  698. * Test redirecting and integration tests.
  699. *
  700. * @return void
  701. */
  702. public function testRedirectPermanent()
  703. {
  704. $this->post('/tests_apps/redirect_to_permanent');
  705. $this->assertResponseSuccess();
  706. $this->assertResponseCode(301);
  707. }
  708. /**
  709. * Test the responseOk status assertion
  710. *
  711. * @return void
  712. */
  713. public function testAssertResponseStatusCodes()
  714. {
  715. $this->_response = new Response();
  716. $this->_response = $this->_response->withStatus(200);
  717. $this->assertResponseOk();
  718. $this->_response = $this->_response->withStatus(201);
  719. $this->assertResponseOk();
  720. $this->_response = $this->_response->withStatus(204);
  721. $this->assertResponseOk();
  722. $this->_response = $this->_response->withStatus(202);
  723. $this->assertResponseSuccess();
  724. $this->_response = $this->_response->withStatus(302);
  725. $this->assertResponseSuccess();
  726. $this->_response = $this->_response->withStatus(400);
  727. $this->assertResponseError();
  728. $this->_response = $this->_response->withStatus(417);
  729. $this->assertResponseError();
  730. $this->_response = $this->_response->withStatus(500);
  731. $this->assertResponseFailure();
  732. $this->_response = $this->_response->withStatus(505);
  733. $this->assertResponseFailure();
  734. $this->_response = $this->_response->withStatus(301);
  735. $this->assertResponseCode(301);
  736. }
  737. /**
  738. * Test the location header assertion.
  739. *
  740. * @return void
  741. */
  742. public function testAssertRedirect()
  743. {
  744. $this->_response = new Response();
  745. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  746. $this->assertRedirect();
  747. $this->assertRedirect('/tasks/index');
  748. $this->assertRedirect(['controller' => 'Tasks', 'action' => 'index']);
  749. $this->assertResponseEmpty();
  750. }
  751. /**
  752. * Test the location header assertion.
  753. *
  754. * @return void
  755. */
  756. public function testAssertNoRedirect()
  757. {
  758. $this->_response = new Response();
  759. $this->assertNoRedirect();
  760. }
  761. /**
  762. * Test the location header assertion.
  763. *
  764. * @return void
  765. */
  766. public function testAssertNoRedirectFail()
  767. {
  768. $test = new AssertIntegrationTestCase('testBadAssertNoRedirect');
  769. $result = $test->run();
  770. $this->assertFalse($result->wasSuccessful());
  771. $this->assertEquals(1, $result->failureCount());
  772. }
  773. /**
  774. * Test the location header assertion string contains
  775. *
  776. * @return void
  777. */
  778. public function testAssertRedirectContains()
  779. {
  780. $this->_response = new Response();
  781. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  782. $this->assertRedirectContains('/tasks/index');
  783. }
  784. /**
  785. * Test the header assertion.
  786. *
  787. * @return void
  788. */
  789. public function testAssertHeader()
  790. {
  791. $this->_response = new Response();
  792. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  793. $this->assertHeader('Etag', 'abc123');
  794. }
  795. /**
  796. * Test the header contains assertion.
  797. *
  798. * @return void
  799. */
  800. public function testAssertHeaderContains()
  801. {
  802. $this->_response = new Response();
  803. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  804. $this->assertHeaderContains('Etag', 'abc');
  805. }
  806. /**
  807. * Test the content type assertion.
  808. *
  809. * @return void
  810. */
  811. public function testAssertContentType()
  812. {
  813. $this->_response = new Response();
  814. $this->_response = $this->_response->withType('json');
  815. $this->assertContentType('json');
  816. $this->assertContentType('application/json');
  817. }
  818. /**
  819. * Test that type() in an action sets the content-type header.
  820. *
  821. * @return void
  822. */
  823. public function testContentTypeInAction()
  824. {
  825. $this->get('/tests_apps/set_type');
  826. $this->assertHeader('Content-Type', 'application/json; charset=UTF-8');
  827. $this->assertContentType('json');
  828. $this->assertContentType('application/json');
  829. }
  830. /**
  831. * Test the content assertion.
  832. *
  833. * @return void
  834. */
  835. public function testAssertResponseContains()
  836. {
  837. $this->_response = new Response();
  838. $this->_response = $this->_response->withStringBody('Some content');
  839. $this->assertResponseContains('content');
  840. }
  841. /**
  842. * Test the content assertion with no case sensitivity.
  843. *
  844. * @return void
  845. */
  846. public function testAssertResponseContainsWithIgnoreCaseFlag()
  847. {
  848. $this->_response = new Response();
  849. $this->_response = $this->_response->withStringBody('Some content');
  850. $this->assertResponseContains('some', 'Failed asserting that the body contains given content', true);
  851. }
  852. /**
  853. * Test the negated content assertion.
  854. *
  855. * @return void
  856. */
  857. public function testAssertResponseNotContains()
  858. {
  859. $this->_response = new Response();
  860. $this->_response = $this->_response->withStringBody('Some content');
  861. $this->assertResponseNotContains('contents');
  862. }
  863. /**
  864. * Test the content regexp assertion.
  865. *
  866. * @return void
  867. */
  868. public function testAssertResponseRegExp()
  869. {
  870. $this->_response = new Response();
  871. $this->_response = $this->_response->withStringBody('Some content');
  872. $this->assertResponseRegExp('/cont/');
  873. }
  874. /**
  875. * Test the content regexp assertion failing
  876. *
  877. * @return void
  878. */
  879. public function testAssertResponseRegExpNoResponse()
  880. {
  881. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  882. $this->expectExceptionMessage('No response set');
  883. $this->assertResponseRegExp('/cont/');
  884. }
  885. /**
  886. * Test the negated content regexp assertion.
  887. *
  888. * @return void
  889. */
  890. public function testAssertResponseNotRegExp()
  891. {
  892. $this->_response = new Response();
  893. $this->_response = $this->_response->withStringBody('Some content');
  894. $this->assertResponseNotRegExp('/cant/');
  895. }
  896. /**
  897. * Test negated content regexp assertion failing
  898. *
  899. * @return void
  900. */
  901. public function testAssertResponseNotRegExpNoResponse()
  902. {
  903. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  904. $this->expectExceptionMessage('No response set');
  905. $this->assertResponseNotRegExp('/cont/');
  906. }
  907. /**
  908. * Test that works in tandem with testEventManagerReset2 to
  909. * test the EventManager reset.
  910. *
  911. * The return value is passed to testEventManagerReset2 as
  912. * an arguments.
  913. *
  914. * @return \Cake\Event\EventManager
  915. */
  916. public function testEventManagerReset1()
  917. {
  918. $eventManager = EventManager::instance();
  919. $this->assertInstanceOf('Cake\Event\EventManager', $eventManager);
  920. return $eventManager;
  921. }
  922. /**
  923. * Test if the EventManager is reset between tests.
  924. *
  925. * @depends testEventManagerReset1
  926. * @return void
  927. */
  928. public function testEventManagerReset2($prevEventManager)
  929. {
  930. $this->assertInstanceOf('Cake\Event\EventManager', $prevEventManager);
  931. $this->assertNotSame($prevEventManager, EventManager::instance());
  932. }
  933. /**
  934. * Test sending file in requests.
  935. *
  936. * @return void
  937. */
  938. public function testSendFile()
  939. {
  940. $this->get('/posts/file');
  941. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  942. }
  943. /**
  944. * Test sending file with psr7 stack
  945. *
  946. * @return void
  947. */
  948. public function testSendFileHttpServer()
  949. {
  950. $this->get('/posts/file');
  951. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  952. }
  953. /**
  954. * Test that assertFile requires a response
  955. *
  956. * @return void
  957. */
  958. public function testAssertFileNoResponse()
  959. {
  960. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  961. $this->expectExceptionMessage('No response set, cannot assert file');
  962. $this->assertFileResponse('foo');
  963. }
  964. /**
  965. * Test that assertFile requires a file
  966. *
  967. * @return void
  968. */
  969. public function testAssertFileNoFile()
  970. {
  971. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  972. $this->expectExceptionMessage('No file was sent in this response');
  973. $this->get('/posts/get');
  974. $this->assertFileResponse('foo');
  975. }
  976. /**
  977. * Test disabling the error handler middleware.
  978. *
  979. * @return void
  980. */
  981. public function testDisableErrorHandlerMiddleware()
  982. {
  983. $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
  984. $this->expectExceptionMessage('A route matching "/foo" could not be found.');
  985. $this->disableErrorHandlerMiddleware();
  986. $this->get('/foo');
  987. }
  988. /**
  989. * tests getting a secure action while passing a query string
  990. *
  991. * @return void
  992. * @dataProvider methodsProvider
  993. */
  994. public function testSecureWithQueryString($method)
  995. {
  996. $this->enableSecurityToken();
  997. $this->{$method}('/posts/securePost/?ids[]=1&ids[]=2');
  998. $this->assertResponseOk();
  999. }
  1000. /**
  1001. * data provider for HTTP methods
  1002. *
  1003. * @return array
  1004. */
  1005. public function methodsProvider()
  1006. {
  1007. return [
  1008. 'GET' => ['get'],
  1009. 'POST' => ['post'],
  1010. 'PATCH' => ['patch'],
  1011. 'PUT' => ['put'],
  1012. 'DELETE' => ['delete'],
  1013. ];
  1014. }
  1015. }