IntegrationTestCaseTest.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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. }