IntegrationTestTraitTest.php 66 KB

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