IntegrationTestCaseTest.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. {
  210. Router::reload();
  211. Router::connect('/json_response/api_get_data', [
  212. 'controller' => 'JsonResponse',
  213. 'action' => 'apiGetData'
  214. ]);
  215. $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithExceptionsInMiddleware', null);
  216. $this->_request['headers'] = [ "Accept" => "application/json" ];
  217. $this->get('/json_response/api_get_data');
  218. $this->assertResponseCode(403);
  219. $this->assertHeader('Content-Type', 'application/json; charset=UTF-8');
  220. $this->assertResponseContains('"message": "Sample Message"');
  221. $this->assertResponseContains('"code": 403');
  222. }
  223. /**
  224. * Test sending head requests.
  225. *
  226. * @return void
  227. */
  228. public function testHead()
  229. {
  230. $this->assertNull($this->_response);
  231. $this->head('/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->head('/head/request_action/test_request_action');
  237. $this->assertResponseSuccess();
  238. }
  239. /**
  240. * Test sending options requests.
  241. *
  242. * @return void
  243. */
  244. public function testOptions()
  245. {
  246. $this->assertNull($this->_response);
  247. $this->options('/request_action/test_request_action');
  248. $this->assertNotEmpty($this->_response);
  249. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  250. $this->assertResponseSuccess();
  251. $this->_response = null;
  252. $this->options('/options/request_action/test_request_action');
  253. $this->assertResponseSuccess();
  254. }
  255. /**
  256. * Test sending get requests sets the request method
  257. *
  258. * @return void
  259. */
  260. public function testGetSpecificRouteLegacy()
  261. {
  262. $this->useLegacyDispatcher();
  263. $this->deprecated(function () {
  264. $this->get('/get/request_action/test_request_action');
  265. $this->assertResponseOk();
  266. $this->assertEquals('This is a test', $this->_response->getBody());
  267. });
  268. }
  269. /**
  270. * Test sending get requests sets the request method
  271. *
  272. * @return void
  273. */
  274. public function testGetSpecificRouteHttpServer()
  275. {
  276. $this->get('/get/request_action/test_request_action');
  277. $this->assertResponseOk();
  278. $this->assertEquals('This is a test', $this->_response->getBody());
  279. }
  280. /**
  281. * Test customizing the app class.
  282. *
  283. * @return void
  284. */
  285. public function testConfigApplication()
  286. {
  287. $this->expectException(\LogicException::class);
  288. $this->expectExceptionMessage('Cannot load "TestApp\MissingApp" for use in integration');
  289. $this->configApplication('TestApp\MissingApp', []);
  290. $this->get('/request_action/test_request_action');
  291. }
  292. /**
  293. * Test sending get requests with Http\Server
  294. *
  295. * @return void
  296. */
  297. public function testGetHttpServer()
  298. {
  299. $this->assertNull($this->_response);
  300. $this->get('/request_action/test_request_action');
  301. $this->assertNotEmpty($this->_response);
  302. $this->assertInstanceOf('Cake\Http\Response', $this->_response);
  303. $this->assertEquals('This is a test', $this->_response->getBody());
  304. $this->assertHeader('X-Middleware', 'true');
  305. }
  306. /**
  307. * Test that the PSR7 requests get query string data
  308. *
  309. * @return void
  310. */
  311. public function testGetQueryStringHttpServer()
  312. {
  313. $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
  314. $this->get('/request_action/params_pass?q=query');
  315. $this->assertResponseOk();
  316. $this->assertResponseContains('"q":"query"');
  317. $this->assertResponseContains('"contentType":"text\/plain"');
  318. $this->assertHeader('X-Middleware', 'true');
  319. $request = $this->_controller->request;
  320. $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
  321. }
  322. /**
  323. * Test that the PSR7 requests get query string data
  324. *
  325. * @group deprecated
  326. * @return void
  327. */
  328. public function testGetQueryStringSetsHere()
  329. {
  330. $this->deprecated(function () {
  331. $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
  332. $this->get('/request_action/params_pass?q=query');
  333. $this->assertResponseOk();
  334. $this->assertResponseContains('"q":"query"');
  335. $this->assertResponseContains('"contentType":"text\/plain"');
  336. $this->assertHeader('X-Middleware', 'true');
  337. $request = $this->_controller->request;
  338. $this->assertContains('/request_action/params_pass?q=query', $request->here());
  339. $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
  340. });
  341. }
  342. /**
  343. * Test that the PSR7 requests get cookies
  344. *
  345. * @return void
  346. */
  347. public function testGetCookiesHttpServer()
  348. {
  349. $this->configRequest(['cookies' => ['split_test' => 'abc']]);
  350. $this->get('/request_action/cookie_pass');
  351. $this->assertResponseOk();
  352. $this->assertResponseContains('"split_test":"abc"');
  353. $this->assertHeader('X-Middleware', 'true');
  354. }
  355. /**
  356. * Test that the PSR7 requests receive post data
  357. *
  358. * @return void
  359. */
  360. public function testPostDataLegacyDispatcher()
  361. {
  362. $this->useLegacyDispatcher();
  363. $this->deprecated(function () {
  364. $this->post('/request_action/post_pass', ['title' => 'value']);
  365. $data = json_decode($this->_response->getBody());
  366. $this->assertEquals('value', $data->title);
  367. });
  368. }
  369. /**
  370. * Test that the PSR7 requests receive post data
  371. *
  372. * @return void
  373. */
  374. public function testPostDataHttpServer()
  375. {
  376. $this->post('/request_action/post_pass', ['title' => 'value']);
  377. $data = json_decode($this->_response->getBody());
  378. $this->assertEquals('value', $data->title);
  379. $this->assertHeader('X-Middleware', 'true');
  380. }
  381. /**
  382. * Test that the PSR7 requests receive encoded data.
  383. *
  384. * @return void
  385. */
  386. public function testInputDataHttpServer()
  387. {
  388. $this->post('/request_action/input_test', '{"hello":"world"}');
  389. if ($this->_response->getBody()->isSeekable()) {
  390. $this->_response->getBody()->rewind();
  391. }
  392. $this->assertSame('world', $this->_response->getBody()->getContents());
  393. $this->assertHeader('X-Middleware', 'true');
  394. }
  395. /**
  396. * Test that the PSR7 requests receive encoded data.
  397. *
  398. * @return void
  399. */
  400. public function testInputDataSecurityToken()
  401. {
  402. $this->enableSecurityToken();
  403. $this->post('/request_action/input_test', '{"hello":"world"}');
  404. $this->assertSame('world', '' . $this->_response->getBody());
  405. $this->assertHeader('X-Middleware', 'true');
  406. }
  407. /**
  408. * Test that the PSR7 requests get cookies
  409. *
  410. * @return void
  411. */
  412. public function testSessionHttpServer()
  413. {
  414. $this->session(['foo' => 'session data']);
  415. $this->get('/request_action/session_test');
  416. $this->assertResponseOk();
  417. $this->assertResponseContains('session data');
  418. $this->assertHeader('X-Middleware', 'true');
  419. }
  420. /**
  421. * Test sending requests stores references to controller/view/layout.
  422. *
  423. * @return void
  424. */
  425. public function testRequestSetsProperties()
  426. {
  427. $this->post('/posts/index');
  428. $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
  429. $this->assertNotEmpty($this->_viewName, 'View name not set');
  430. $this->assertContains('Template' . DS . 'Posts' . DS . 'index.ctp', $this->_viewName);
  431. $this->assertNotEmpty($this->_layoutName, 'Layout name not set');
  432. $this->assertContains('Template' . DS . 'Layout' . DS . 'default.ctp', $this->_layoutName);
  433. $this->assertTemplate('index');
  434. $this->assertLayout('default');
  435. $this->assertEquals('value', $this->viewVariable('test'));
  436. }
  437. /**
  438. * Test PSR7 requests store references to controller/view/layout
  439. *
  440. * @return void
  441. */
  442. public function testRequestSetsPropertiesHttpServer()
  443. {
  444. $this->post('/posts/index');
  445. $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
  446. $this->assertNotEmpty($this->_viewName, 'View name not set');
  447. $this->assertContains('Template' . DS . 'Posts' . DS . 'index.ctp', $this->_viewName);
  448. $this->assertNotEmpty($this->_layoutName, 'Layout name not set');
  449. $this->assertContains('Template' . DS . 'Layout' . DS . 'default.ctp', $this->_layoutName);
  450. $this->assertTemplate('index');
  451. $this->assertLayout('default');
  452. $this->assertEquals('value', $this->viewVariable('test'));
  453. }
  454. /**
  455. * Assert that the stored template doesn't change when cells are rendered.
  456. *
  457. * @return void
  458. */
  459. public function testAssertTemplateAfterCellRender()
  460. {
  461. $this->get('/posts/get');
  462. $this->assertContains('Template' . DS . 'Posts' . DS . 'get.ctp', $this->_viewName);
  463. $this->assertTemplate('get');
  464. $this->assertResponseContains('cellcontent');
  465. }
  466. /**
  467. * Test array URLs
  468. *
  469. * @return void
  470. */
  471. public function testArrayUrls()
  472. {
  473. $this->post(['controller' => 'Posts', 'action' => 'index']);
  474. $this->assertEquals('value', $this->viewVariable('test'));
  475. }
  476. /**
  477. * Test flash and cookie assertions
  478. *
  479. * @return void
  480. */
  481. public function testFlashSessionAndCookieAsserts()
  482. {
  483. $this->post('/posts/index');
  484. $this->assertSession('An error message', 'Flash.flash.0.message');
  485. $this->assertCookie(1, 'remember_me');
  486. $this->assertCookieNotSet('user_id');
  487. }
  488. /**
  489. * Test flash and cookie assertions
  490. *
  491. * @return void
  492. */
  493. public function testFlashSessionAndCookieAssertsHttpServer()
  494. {
  495. $this->post('/posts/index');
  496. $this->assertSession('An error message', 'Flash.flash.0.message');
  497. $this->assertCookieNotSet('user_id');
  498. $this->assertCookie(1, 'remember_me');
  499. }
  500. /**
  501. * Test flash assertions stored with enableRememberFlashMessages() after they
  502. * are rendered
  503. *
  504. * @return void
  505. */
  506. public function testFlashAssertionsAfterRender()
  507. {
  508. $this->enableRetainFlashMessages();
  509. $this->get('/posts/index/with_flash');
  510. $this->assertSession('An error message', 'Flash.flash.0.message');
  511. }
  512. /**
  513. * Test flash assertions stored with enableRememberFlashMessages() even if
  514. * no view is rendered
  515. *
  516. * @return void
  517. */
  518. public function testFlashAssertionsWithNoRender()
  519. {
  520. $this->enableRetainFlashMessages();
  521. $this->get('/posts/flashNoRender');
  522. $this->assertRedirect();
  523. $this->assertSession('An error message', 'Flash.flash.0.message');
  524. }
  525. /**
  526. * Tests the failure message for assertCookieNotSet
  527. *
  528. * @return void
  529. */
  530. public function testCookieNotSetFailure()
  531. {
  532. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  533. $this->expectExceptionMessage('Cookie \'remember_me\' has been set');
  534. $this->post('/posts/index');
  535. $this->assertCookieNotSet('remember_me');
  536. }
  537. /**
  538. * Tests the failure message for assertCookieNotSet when no
  539. * response whas generated
  540. *
  541. * @return void
  542. */
  543. public function testCookieNotSetFailureNoResponse()
  544. {
  545. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  546. $this->expectExceptionMessage('No response set, cannot assert cookies.');
  547. $this->assertCookieNotSet('remember_me');
  548. }
  549. /**
  550. * Test error handling and error page rendering.
  551. *
  552. * @return void
  553. */
  554. public function testPostAndErrorHandling()
  555. {
  556. $this->post('/request_action/error_method');
  557. $this->assertResponseNotEmpty();
  558. $this->assertResponseContains('Not there or here');
  559. $this->assertResponseContains('<!DOCTYPE html>');
  560. }
  561. /**
  562. * Test posting to a secured form action.
  563. *
  564. * @return void
  565. */
  566. public function testPostSecuredForm()
  567. {
  568. $this->enableSecurityToken();
  569. $data = [
  570. 'title' => 'Some title',
  571. 'body' => 'Some text'
  572. ];
  573. $this->post('/posts/securePost', $data);
  574. $this->assertResponseOk();
  575. $this->assertResponseContains('Request was accepted');
  576. }
  577. /**
  578. * Test posting to a secured form action with nested data.
  579. *
  580. * @return void
  581. */
  582. public function testPostSecuredFormNestedData()
  583. {
  584. $this->enableSecurityToken();
  585. $data = [
  586. 'title' => 'New post',
  587. 'comments' => [
  588. ['comment' => 'A new comment']
  589. ],
  590. 'tags' => ['_ids' => [1, 2, 3, 4]]
  591. ];
  592. $this->post('/posts/securePost', $data);
  593. $this->assertResponseOk();
  594. $this->assertResponseContains('Request was accepted');
  595. }
  596. /**
  597. * Test posting to a secured form action.
  598. *
  599. * @return void
  600. */
  601. public function testPostSecuredFormWithQuery()
  602. {
  603. $this->enableSecurityToken();
  604. $data = [
  605. 'title' => 'Some title',
  606. 'body' => 'Some text'
  607. ];
  608. $this->post('/posts/securePost?foo=bar', $data);
  609. $this->assertResponseOk();
  610. $this->assertResponseContains('Request was accepted');
  611. }
  612. /**
  613. * Test posting to a secured form action with a query that has a part that
  614. * will be encoded by the security component
  615. *
  616. * @return void
  617. */
  618. public function testPostSecuredFormWithUnencodedQuery()
  619. {
  620. $this->enableSecurityToken();
  621. $data = [
  622. 'title' => 'Some title',
  623. 'body' => 'Some text'
  624. ];
  625. $this->post('/posts/securePost?foo=/', $data);
  626. $this->assertResponseOk();
  627. $this->assertResponseContains('Request was accepted');
  628. }
  629. /**
  630. * Test posting to a secured form action action.
  631. *
  632. * @return void
  633. */
  634. public function testPostSecuredFormFailure()
  635. {
  636. $data = [
  637. 'title' => 'Some title',
  638. 'body' => 'Some text'
  639. ];
  640. $this->post('/posts/securePost', $data);
  641. $this->assertResponseError();
  642. }
  643. /**
  644. * Test that exceptions being thrown are handled correctly.
  645. *
  646. * @return void
  647. */
  648. public function testWithExpectedException()
  649. {
  650. $this->get('/tests_apps/throw_exception');
  651. $this->assertResponseCode(500);
  652. }
  653. /**
  654. * Test that exceptions being thrown are handled correctly by the psr7 stack.
  655. *
  656. * @return void
  657. */
  658. public function testWithExpectedExceptionHttpServer()
  659. {
  660. DispatcherFactory::clear();
  661. $this->get('/tests_apps/throw_exception');
  662. $this->assertResponseCode(500);
  663. }
  664. /**
  665. * Test that exceptions being thrown are handled correctly.
  666. *
  667. * @return void
  668. */
  669. public function testWithUnexpectedException()
  670. {
  671. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  672. $this->get('/tests_apps/throw_exception');
  673. $this->assertResponseCode(501);
  674. }
  675. /**
  676. * Test redirecting and integration tests.
  677. *
  678. * @return void
  679. */
  680. public function testRedirect()
  681. {
  682. $this->post('/tests_apps/redirect_to');
  683. $this->assertResponseSuccess();
  684. $this->assertResponseCode(302);
  685. }
  686. /**
  687. * Test redirecting and psr7 stack
  688. *
  689. * @return void
  690. */
  691. public function testRedirectHttpServer()
  692. {
  693. DispatcherFactory::clear();
  694. $this->post('/tests_apps/redirect_to');
  695. $this->assertResponseCode(302);
  696. $this->assertHeader('X-Middleware', 'true');
  697. }
  698. /**
  699. * Test redirecting and integration tests.
  700. *
  701. * @return void
  702. */
  703. public function testRedirectPermanent()
  704. {
  705. $this->post('/tests_apps/redirect_to_permanent');
  706. $this->assertResponseSuccess();
  707. $this->assertResponseCode(301);
  708. }
  709. /**
  710. * Test the responseOk status assertion
  711. *
  712. * @return void
  713. */
  714. public function testAssertResponseStatusCodes()
  715. {
  716. $this->_response = new Response();
  717. $this->_response = $this->_response->withStatus(200);
  718. $this->assertResponseOk();
  719. $this->_response = $this->_response->withStatus(201);
  720. $this->assertResponseOk();
  721. $this->_response = $this->_response->withStatus(204);
  722. $this->assertResponseOk();
  723. $this->_response = $this->_response->withStatus(202);
  724. $this->assertResponseSuccess();
  725. $this->_response = $this->_response->withStatus(302);
  726. $this->assertResponseSuccess();
  727. $this->_response = $this->_response->withStatus(400);
  728. $this->assertResponseError();
  729. $this->_response = $this->_response->withStatus(417);
  730. $this->assertResponseError();
  731. $this->_response = $this->_response->withStatus(500);
  732. $this->assertResponseFailure();
  733. $this->_response = $this->_response->withStatus(505);
  734. $this->assertResponseFailure();
  735. $this->_response = $this->_response->withStatus(301);
  736. $this->assertResponseCode(301);
  737. }
  738. /**
  739. * Test the location header assertion.
  740. *
  741. * @return void
  742. */
  743. public function testAssertRedirect()
  744. {
  745. $this->_response = new Response();
  746. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  747. $this->assertRedirect();
  748. $this->assertRedirect('/tasks/index');
  749. $this->assertRedirect(['controller' => 'Tasks', 'action' => 'index']);
  750. $this->assertResponseEmpty();
  751. }
  752. /**
  753. * Test the location header assertion.
  754. *
  755. * @return void
  756. */
  757. public function testAssertNoRedirect()
  758. {
  759. $this->_response = new Response();
  760. $this->assertNoRedirect();
  761. }
  762. /**
  763. * Test the location header assertion.
  764. *
  765. * @return void
  766. */
  767. public function testAssertNoRedirectFail()
  768. {
  769. $test = new AssertIntegrationTestCase('testBadAssertNoRedirect');
  770. $result = $test->run();
  771. $this->assertFalse($result->wasSuccessful());
  772. $this->assertEquals(1, $result->failureCount());
  773. }
  774. /**
  775. * Test the location header assertion string contains
  776. *
  777. * @return void
  778. */
  779. public function testAssertRedirectContains()
  780. {
  781. $this->_response = new Response();
  782. $this->_response = $this->_response->withHeader('Location', 'http://localhost/tasks/index');
  783. $this->assertRedirectContains('/tasks/index');
  784. }
  785. /**
  786. * Test the header assertion.
  787. *
  788. * @return void
  789. */
  790. public function testAssertHeader()
  791. {
  792. $this->_response = new Response();
  793. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  794. $this->assertHeader('Etag', 'abc123');
  795. }
  796. /**
  797. * Test the header contains assertion.
  798. *
  799. * @return void
  800. */
  801. public function testAssertHeaderContains()
  802. {
  803. $this->_response = new Response();
  804. $this->_response = $this->_response->withHeader('Etag', 'abc123');
  805. $this->assertHeaderContains('Etag', 'abc');
  806. }
  807. /**
  808. * Test the content type assertion.
  809. *
  810. * @return void
  811. */
  812. public function testAssertContentType()
  813. {
  814. $this->_response = new Response();
  815. $this->_response = $this->_response->withType('json');
  816. $this->assertContentType('json');
  817. $this->assertContentType('application/json');
  818. }
  819. /**
  820. * Test that type() in an action sets the content-type header.
  821. *
  822. * @return void
  823. */
  824. public function testContentTypeInAction()
  825. {
  826. $this->get('/tests_apps/set_type');
  827. $this->assertHeader('Content-Type', 'application/json; charset=UTF-8');
  828. $this->assertContentType('json');
  829. $this->assertContentType('application/json');
  830. }
  831. /**
  832. * Test the content assertion.
  833. *
  834. * @return void
  835. */
  836. public function testAssertResponseContains()
  837. {
  838. $this->_response = new Response();
  839. $this->_response = $this->_response->withStringBody('Some content');
  840. $this->assertResponseContains('content');
  841. }
  842. /**
  843. * Test the content assertion with no case sensitivity.
  844. *
  845. * @return void
  846. */
  847. public function testAssertResponseContainsWithIgnoreCaseFlag()
  848. {
  849. $this->_response = new Response();
  850. $this->_response = $this->_response->withStringBody('Some content');
  851. $this->assertResponseContains('some', 'Failed asserting that the body contains given content', true);
  852. }
  853. /**
  854. * Test the negated content assertion.
  855. *
  856. * @return void
  857. */
  858. public function testAssertResponseNotContains()
  859. {
  860. $this->_response = new Response();
  861. $this->_response = $this->_response->withStringBody('Some content');
  862. $this->assertResponseNotContains('contents');
  863. }
  864. /**
  865. * Test the content regexp assertion.
  866. *
  867. * @return void
  868. */
  869. public function testAssertResponseRegExp()
  870. {
  871. $this->_response = new Response();
  872. $this->_response = $this->_response->withStringBody('Some content');
  873. $this->assertResponseRegExp('/cont/');
  874. }
  875. /**
  876. * Test the content regexp assertion failing
  877. *
  878. * @return void
  879. */
  880. public function testAssertResponseRegExpNoResponse()
  881. {
  882. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  883. $this->expectExceptionMessage('No response set');
  884. $this->assertResponseRegExp('/cont/');
  885. }
  886. /**
  887. * Test the negated content regexp assertion.
  888. *
  889. * @return void
  890. */
  891. public function testAssertResponseNotRegExp()
  892. {
  893. $this->_response = new Response();
  894. $this->_response = $this->_response->withStringBody('Some content');
  895. $this->assertResponseNotRegExp('/cant/');
  896. }
  897. /**
  898. * Test negated content regexp assertion failing
  899. *
  900. * @return void
  901. */
  902. public function testAssertResponseNotRegExpNoResponse()
  903. {
  904. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  905. $this->expectExceptionMessage('No response set');
  906. $this->assertResponseNotRegExp('/cont/');
  907. }
  908. /**
  909. * Test that works in tandem with testEventManagerReset2 to
  910. * test the EventManager reset.
  911. *
  912. * The return value is passed to testEventManagerReset2 as
  913. * an arguments.
  914. *
  915. * @return \Cake\Event\EventManager
  916. */
  917. public function testEventManagerReset1()
  918. {
  919. $eventManager = EventManager::instance();
  920. $this->assertInstanceOf('Cake\Event\EventManager', $eventManager);
  921. return $eventManager;
  922. }
  923. /**
  924. * Test if the EventManager is reset between tests.
  925. *
  926. * @depends testEventManagerReset1
  927. * @return void
  928. */
  929. public function testEventManagerReset2($prevEventManager)
  930. {
  931. $this->assertInstanceOf('Cake\Event\EventManager', $prevEventManager);
  932. $this->assertNotSame($prevEventManager, EventManager::instance());
  933. }
  934. /**
  935. * Test sending file in requests.
  936. *
  937. * @return void
  938. */
  939. public function testSendFile()
  940. {
  941. $this->get('/posts/file');
  942. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  943. }
  944. /**
  945. * Test sending file with psr7 stack
  946. *
  947. * @return void
  948. */
  949. public function testSendFileHttpServer()
  950. {
  951. $this->get('/posts/file');
  952. $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
  953. }
  954. /**
  955. * Test that assertFile requires a response
  956. *
  957. * @return void
  958. */
  959. public function testAssertFileNoResponse()
  960. {
  961. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  962. $this->expectExceptionMessage('No response set, cannot assert file');
  963. $this->assertFileResponse('foo');
  964. }
  965. /**
  966. * Test that assertFile requires a file
  967. *
  968. * @return void
  969. */
  970. public function testAssertFileNoFile()
  971. {
  972. $this->expectException(\PHPUnit\Framework\AssertionFailedError::class);
  973. $this->expectExceptionMessage('No file was sent in this response');
  974. $this->get('/posts/get');
  975. $this->assertFileResponse('foo');
  976. }
  977. /**
  978. * Test disabling the error handler middleware.
  979. *
  980. * @return void
  981. */
  982. public function testDisableErrorHandlerMiddleware()
  983. {
  984. $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
  985. $this->expectExceptionMessage('A route matching "/foo" could not be found.');
  986. $this->disableErrorHandlerMiddleware();
  987. $this->get('/foo');
  988. }
  989. /**
  990. * tests getting a secure action while passing a query string
  991. *
  992. * @return void
  993. * @dataProvider methodsProvider
  994. */
  995. public function testSecureWithQueryString($method)
  996. {
  997. $this->enableSecurityToken();
  998. $this->{$method}('/posts/securePost/?ids[]=1&ids[]=2');
  999. $this->assertResponseOk();
  1000. }
  1001. /**
  1002. * data provider for HTTP methods
  1003. *
  1004. * @return array
  1005. */
  1006. public function methodsProvider()
  1007. {
  1008. return [
  1009. 'GET' => ['get'],
  1010. 'POST' => ['post'],
  1011. 'PATCH' => ['patch'],
  1012. 'PUT' => ['put'],
  1013. 'DELETE' => ['delete'],
  1014. ];
  1015. }
  1016. }