IntegrationTestTraitTest.php 65 KB

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