IntegrationTestTraitTest.php 57 KB

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