IntegrationTestCaseTest.php 32 KB

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