HttpCacheTest.php 62KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Tests\HttpCache;
  11. use Symfony\Component\HttpKernel\HttpCache\HttpCache;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpKernel\HttpKernelInterface;
  15. /**
  16. * @group time-sensitive
  17. */
  18. class HttpCacheTest extends HttpCacheTestCase
  19. {
  20. public function testTerminateDelegatesTerminationOnlyForTerminableInterface()
  21. {
  22. $storeMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\HttpCache\\StoreInterface')
  23. ->disableOriginalConstructor()
  24. ->getMock();
  25. // does not implement TerminableInterface
  26. $kernel = new TestKernel();
  27. $httpCache = new HttpCache($kernel, $storeMock);
  28. $httpCache->terminate(Request::create('/'), new Response());
  29. $this->assertFalse($kernel->terminateCalled, 'terminate() is never called if the kernel class does not implement TerminableInterface');
  30. // implements TerminableInterface
  31. $kernelMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Kernel')
  32. ->disableOriginalConstructor()
  33. ->setMethods(array('terminate', 'registerBundles', 'registerContainerConfiguration'))
  34. ->getMock();
  35. $kernelMock->expects($this->once())
  36. ->method('terminate');
  37. $kernel = new HttpCache($kernelMock, $storeMock);
  38. $kernel->terminate(Request::create('/'), new Response());
  39. }
  40. public function testPassesOnNonGetHeadRequests()
  41. {
  42. $this->setNextResponse(200);
  43. $this->request('POST', '/');
  44. $this->assertHttpKernelIsCalled();
  45. $this->assertResponseOk();
  46. $this->assertTraceContains('pass');
  47. $this->assertFalse($this->response->headers->has('Age'));
  48. }
  49. public function testInvalidatesOnPostPutDeleteRequests()
  50. {
  51. foreach (array('post', 'put', 'delete') as $method) {
  52. $this->setNextResponse(200);
  53. $this->request($method, '/');
  54. $this->assertHttpKernelIsCalled();
  55. $this->assertResponseOk();
  56. $this->assertTraceContains('invalidate');
  57. $this->assertTraceContains('pass');
  58. }
  59. }
  60. public function testDoesNotCacheWithAuthorizationRequestHeaderAndNonPublicResponse()
  61. {
  62. $this->setNextResponse(200, array('ETag' => '"Foo"'));
  63. $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz'));
  64. $this->assertHttpKernelIsCalled();
  65. $this->assertResponseOk();
  66. $this->assertEquals('private', $this->response->headers->get('Cache-Control'));
  67. $this->assertTraceContains('miss');
  68. $this->assertTraceNotContains('store');
  69. $this->assertFalse($this->response->headers->has('Age'));
  70. }
  71. public function testDoesCacheWithAuthorizationRequestHeaderAndPublicResponse()
  72. {
  73. $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"Foo"'));
  74. $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz'));
  75. $this->assertHttpKernelIsCalled();
  76. $this->assertResponseOk();
  77. $this->assertTraceContains('miss');
  78. $this->assertTraceContains('store');
  79. $this->assertTrue($this->response->headers->has('Age'));
  80. $this->assertEquals('public', $this->response->headers->get('Cache-Control'));
  81. }
  82. public function testDoesNotCacheWithCookieHeaderAndNonPublicResponse()
  83. {
  84. $this->setNextResponse(200, array('ETag' => '"Foo"'));
  85. $this->request('GET', '/', array(), array('foo' => 'bar'));
  86. $this->assertHttpKernelIsCalled();
  87. $this->assertResponseOk();
  88. $this->assertEquals('private', $this->response->headers->get('Cache-Control'));
  89. $this->assertTraceContains('miss');
  90. $this->assertTraceNotContains('store');
  91. $this->assertFalse($this->response->headers->has('Age'));
  92. }
  93. public function testDoesNotCacheRequestsWithACookieHeader()
  94. {
  95. $this->setNextResponse(200);
  96. $this->request('GET', '/', array(), array('foo' => 'bar'));
  97. $this->assertHttpKernelIsCalled();
  98. $this->assertResponseOk();
  99. $this->assertEquals('private', $this->response->headers->get('Cache-Control'));
  100. $this->assertTraceContains('miss');
  101. $this->assertTraceNotContains('store');
  102. $this->assertFalse($this->response->headers->has('Age'));
  103. }
  104. public function testRespondsWith304WhenIfModifiedSinceMatchesLastModified()
  105. {
  106. $time = \DateTime::createFromFormat('U', time());
  107. $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822), 'Content-Type' => 'text/plain'), 'Hello World');
  108. $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));
  109. $this->assertHttpKernelIsCalled();
  110. $this->assertEquals(304, $this->response->getStatusCode());
  111. $this->assertEquals('', $this->response->headers->get('Content-Type'));
  112. $this->assertEmpty($this->response->getContent());
  113. $this->assertTraceContains('miss');
  114. $this->assertTraceContains('store');
  115. }
  116. public function testRespondsWith304WhenIfNoneMatchMatchesETag()
  117. {
  118. $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '12345', 'Content-Type' => 'text/plain'), 'Hello World');
  119. $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345'));
  120. $this->assertHttpKernelIsCalled();
  121. $this->assertEquals(304, $this->response->getStatusCode());
  122. $this->assertEquals('', $this->response->headers->get('Content-Type'));
  123. $this->assertTrue($this->response->headers->has('ETag'));
  124. $this->assertEmpty($this->response->getContent());
  125. $this->assertTraceContains('miss');
  126. $this->assertTraceContains('store');
  127. }
  128. public function testRespondsWith304OnlyIfIfNoneMatchAndIfModifiedSinceBothMatch()
  129. {
  130. $time = \DateTime::createFromFormat('U', time());
  131. $this->setNextResponse(200, array(), '', function ($request, $response) use ($time) {
  132. $response->setStatusCode(200);
  133. $response->headers->set('ETag', '12345');
  134. $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
  135. $response->headers->set('Content-Type', 'text/plain');
  136. $response->setContent('Hello World');
  137. });
  138. // only ETag matches
  139. $t = \DateTime::createFromFormat('U', time() - 3600);
  140. $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $t->format(DATE_RFC2822)));
  141. $this->assertHttpKernelIsCalled();
  142. $this->assertEquals(200, $this->response->getStatusCode());
  143. // only Last-Modified matches
  144. $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '1234', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));
  145. $this->assertHttpKernelIsCalled();
  146. $this->assertEquals(200, $this->response->getStatusCode());
  147. // Both matches
  148. $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));
  149. $this->assertHttpKernelIsCalled();
  150. $this->assertEquals(304, $this->response->getStatusCode());
  151. }
  152. public function testIncrementsMaxAgeWhenNoDateIsSpecifiedEventWhenUsingETag()
  153. {
  154. $this->setNextResponse(
  155. 200,
  156. array(
  157. 'ETag' => '1234',
  158. 'Cache-Control' => 'public, s-maxage=60',
  159. )
  160. );
  161. $this->request('GET', '/');
  162. $this->assertHttpKernelIsCalled();
  163. $this->assertEquals(200, $this->response->getStatusCode());
  164. $this->assertTraceContains('miss');
  165. $this->assertTraceContains('store');
  166. sleep(2);
  167. $this->request('GET', '/');
  168. $this->assertHttpKernelIsNotCalled();
  169. $this->assertEquals(200, $this->response->getStatusCode());
  170. $this->assertTraceContains('fresh');
  171. $this->assertEquals(2, $this->response->headers->get('Age'));
  172. }
  173. public function testValidatesPrivateResponsesCachedOnTheClient()
  174. {
  175. $this->setNextResponse(200, array(), '', function ($request, $response) {
  176. $etags = preg_split('/\s*,\s*/', $request->headers->get('IF_NONE_MATCH'));
  177. if ($request->cookies->has('authenticated')) {
  178. $response->headers->set('Cache-Control', 'private, no-store');
  179. $response->setETag('"private tag"');
  180. if (in_array('"private tag"', $etags)) {
  181. $response->setStatusCode(304);
  182. } else {
  183. $response->setStatusCode(200);
  184. $response->headers->set('Content-Type', 'text/plain');
  185. $response->setContent('private data');
  186. }
  187. } else {
  188. $response->headers->set('Cache-Control', 'public');
  189. $response->setETag('"public tag"');
  190. if (in_array('"public tag"', $etags)) {
  191. $response->setStatusCode(304);
  192. } else {
  193. $response->setStatusCode(200);
  194. $response->headers->set('Content-Type', 'text/plain');
  195. $response->setContent('public data');
  196. }
  197. }
  198. });
  199. $this->request('GET', '/');
  200. $this->assertHttpKernelIsCalled();
  201. $this->assertEquals(200, $this->response->getStatusCode());
  202. $this->assertEquals('"public tag"', $this->response->headers->get('ETag'));
  203. $this->assertEquals('public data', $this->response->getContent());
  204. $this->assertTraceContains('miss');
  205. $this->assertTraceContains('store');
  206. $this->request('GET', '/', array(), array('authenticated' => ''));
  207. $this->assertHttpKernelIsCalled();
  208. $this->assertEquals(200, $this->response->getStatusCode());
  209. $this->assertEquals('"private tag"', $this->response->headers->get('ETag'));
  210. $this->assertEquals('private data', $this->response->getContent());
  211. $this->assertTraceContains('stale');
  212. $this->assertTraceContains('invalid');
  213. $this->assertTraceNotContains('store');
  214. }
  215. public function testStoresResponsesWhenNoCacheRequestDirectivePresent()
  216. {
  217. $time = \DateTime::createFromFormat('U', time() + 5);
  218. $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));
  219. $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));
  220. $this->assertHttpKernelIsCalled();
  221. $this->assertTraceContains('store');
  222. $this->assertTrue($this->response->headers->has('Age'));
  223. }
  224. public function testReloadsResponsesWhenCacheHitsButNoCacheRequestDirectivePresentWhenAllowReloadIsSetTrue()
  225. {
  226. $count = 0;
  227. $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) {
  228. ++$count;
  229. $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
  230. });
  231. $this->request('GET', '/');
  232. $this->assertEquals(200, $this->response->getStatusCode());
  233. $this->assertEquals('Hello World', $this->response->getContent());
  234. $this->assertTraceContains('store');
  235. $this->request('GET', '/');
  236. $this->assertEquals(200, $this->response->getStatusCode());
  237. $this->assertEquals('Hello World', $this->response->getContent());
  238. $this->assertTraceContains('fresh');
  239. $this->cacheConfig['allow_reload'] = true;
  240. $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));
  241. $this->assertEquals(200, $this->response->getStatusCode());
  242. $this->assertEquals('Goodbye World', $this->response->getContent());
  243. $this->assertTraceContains('reload');
  244. $this->assertTraceContains('store');
  245. }
  246. public function testDoesNotReloadResponsesWhenAllowReloadIsSetFalseDefault()
  247. {
  248. $count = 0;
  249. $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) {
  250. ++$count;
  251. $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
  252. });
  253. $this->request('GET', '/');
  254. $this->assertEquals(200, $this->response->getStatusCode());
  255. $this->assertEquals('Hello World', $this->response->getContent());
  256. $this->assertTraceContains('store');
  257. $this->request('GET', '/');
  258. $this->assertEquals(200, $this->response->getStatusCode());
  259. $this->assertEquals('Hello World', $this->response->getContent());
  260. $this->assertTraceContains('fresh');
  261. $this->cacheConfig['allow_reload'] = false;
  262. $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));
  263. $this->assertEquals(200, $this->response->getStatusCode());
  264. $this->assertEquals('Hello World', $this->response->getContent());
  265. $this->assertTraceNotContains('reload');
  266. $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));
  267. $this->assertEquals(200, $this->response->getStatusCode());
  268. $this->assertEquals('Hello World', $this->response->getContent());
  269. $this->assertTraceNotContains('reload');
  270. }
  271. public function testRevalidatesFreshCacheEntryWhenMaxAgeRequestDirectiveIsExceededWhenAllowRevalidateOptionIsSetTrue()
  272. {
  273. $count = 0;
  274. $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) {
  275. ++$count;
  276. $response->headers->set('Cache-Control', 'public, max-age=10000');
  277. $response->setETag($count);
  278. $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
  279. });
  280. $this->request('GET', '/');
  281. $this->assertEquals(200, $this->response->getStatusCode());
  282. $this->assertEquals('Hello World', $this->response->getContent());
  283. $this->assertTraceContains('store');
  284. $this->request('GET', '/');
  285. $this->assertEquals(200, $this->response->getStatusCode());
  286. $this->assertEquals('Hello World', $this->response->getContent());
  287. $this->assertTraceContains('fresh');
  288. $this->cacheConfig['allow_revalidate'] = true;
  289. $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0'));
  290. $this->assertEquals(200, $this->response->getStatusCode());
  291. $this->assertEquals('Goodbye World', $this->response->getContent());
  292. $this->assertTraceContains('stale');
  293. $this->assertTraceContains('invalid');
  294. $this->assertTraceContains('store');
  295. }
  296. public function testDoesNotRevalidateFreshCacheEntryWhenEnableRevalidateOptionIsSetFalseDefault()
  297. {
  298. $count = 0;
  299. $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) {
  300. ++$count;
  301. $response->headers->set('Cache-Control', 'public, max-age=10000');
  302. $response->setETag($count);
  303. $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
  304. });
  305. $this->request('GET', '/');
  306. $this->assertEquals(200, $this->response->getStatusCode());
  307. $this->assertEquals('Hello World', $this->response->getContent());
  308. $this->assertTraceContains('store');
  309. $this->request('GET', '/');
  310. $this->assertEquals(200, $this->response->getStatusCode());
  311. $this->assertEquals('Hello World', $this->response->getContent());
  312. $this->assertTraceContains('fresh');
  313. $this->cacheConfig['allow_revalidate'] = false;
  314. $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0'));
  315. $this->assertEquals(200, $this->response->getStatusCode());
  316. $this->assertEquals('Hello World', $this->response->getContent());
  317. $this->assertTraceNotContains('stale');
  318. $this->assertTraceNotContains('invalid');
  319. $this->assertTraceContains('fresh');
  320. $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0'));
  321. $this->assertEquals(200, $this->response->getStatusCode());
  322. $this->assertEquals('Hello World', $this->response->getContent());
  323. $this->assertTraceNotContains('stale');
  324. $this->assertTraceNotContains('invalid');
  325. $this->assertTraceContains('fresh');
  326. }
  327. public function testFetchesResponseFromBackendWhenCacheMisses()
  328. {
  329. $time = \DateTime::createFromFormat('U', time() + 5);
  330. $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));
  331. $this->request('GET', '/');
  332. $this->assertEquals(200, $this->response->getStatusCode());
  333. $this->assertTraceContains('miss');
  334. $this->assertTrue($this->response->headers->has('Age'));
  335. }
  336. public function testDoesNotCacheSomeStatusCodeResponses()
  337. {
  338. foreach (array_merge(range(201, 202), range(204, 206), range(303, 305), range(400, 403), range(405, 409), range(411, 417), range(500, 505)) as $code) {
  339. $time = \DateTime::createFromFormat('U', time() + 5);
  340. $this->setNextResponse($code, array('Expires' => $time->format(DATE_RFC2822)));
  341. $this->request('GET', '/');
  342. $this->assertEquals($code, $this->response->getStatusCode());
  343. $this->assertTraceNotContains('store');
  344. $this->assertFalse($this->response->headers->has('Age'));
  345. }
  346. }
  347. public function testDoesNotCacheResponsesWithExplicitNoStoreDirective()
  348. {
  349. $time = \DateTime::createFromFormat('U', time() + 5);
  350. $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'no-store'));
  351. $this->request('GET', '/');
  352. $this->assertTraceNotContains('store');
  353. $this->assertFalse($this->response->headers->has('Age'));
  354. }
  355. public function testDoesNotCacheResponsesWithoutFreshnessInformationOrAValidator()
  356. {
  357. $this->setNextResponse();
  358. $this->request('GET', '/');
  359. $this->assertEquals(200, $this->response->getStatusCode());
  360. $this->assertTraceNotContains('store');
  361. }
  362. public function testCachesResponsesWithExplicitNoCacheDirective()
  363. {
  364. $time = \DateTime::createFromFormat('U', time() + 5);
  365. $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, no-cache'));
  366. $this->request('GET', '/');
  367. $this->assertTraceContains('store');
  368. $this->assertTrue($this->response->headers->has('Age'));
  369. }
  370. public function testCachesResponsesWithAnExpirationHeader()
  371. {
  372. $time = \DateTime::createFromFormat('U', time() + 5);
  373. $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));
  374. $this->request('GET', '/');
  375. $this->assertEquals(200, $this->response->getStatusCode());
  376. $this->assertEquals('Hello World', $this->response->getContent());
  377. $this->assertNotNull($this->response->headers->get('Date'));
  378. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  379. $this->assertTraceContains('miss');
  380. $this->assertTraceContains('store');
  381. $values = $this->getMetaStorageValues();
  382. $this->assertCount(1, $values);
  383. }
  384. public function testCachesResponsesWithAMaxAgeDirective()
  385. {
  386. $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=5'));
  387. $this->request('GET', '/');
  388. $this->assertEquals(200, $this->response->getStatusCode());
  389. $this->assertEquals('Hello World', $this->response->getContent());
  390. $this->assertNotNull($this->response->headers->get('Date'));
  391. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  392. $this->assertTraceContains('miss');
  393. $this->assertTraceContains('store');
  394. $values = $this->getMetaStorageValues();
  395. $this->assertCount(1, $values);
  396. }
  397. public function testCachesResponsesWithASMaxAgeDirective()
  398. {
  399. $this->setNextResponse(200, array('Cache-Control' => 's-maxage=5'));
  400. $this->request('GET', '/');
  401. $this->assertEquals(200, $this->response->getStatusCode());
  402. $this->assertEquals('Hello World', $this->response->getContent());
  403. $this->assertNotNull($this->response->headers->get('Date'));
  404. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  405. $this->assertTraceContains('miss');
  406. $this->assertTraceContains('store');
  407. $values = $this->getMetaStorageValues();
  408. $this->assertCount(1, $values);
  409. }
  410. public function testCachesResponsesWithALastModifiedValidatorButNoFreshnessInformation()
  411. {
  412. $time = \DateTime::createFromFormat('U', time());
  413. $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822)));
  414. $this->request('GET', '/');
  415. $this->assertEquals(200, $this->response->getStatusCode());
  416. $this->assertEquals('Hello World', $this->response->getContent());
  417. $this->assertTraceContains('miss');
  418. $this->assertTraceContains('store');
  419. }
  420. public function testCachesResponsesWithAnETagValidatorButNoFreshnessInformation()
  421. {
  422. $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"123456"'));
  423. $this->request('GET', '/');
  424. $this->assertEquals(200, $this->response->getStatusCode());
  425. $this->assertEquals('Hello World', $this->response->getContent());
  426. $this->assertTraceContains('miss');
  427. $this->assertTraceContains('store');
  428. }
  429. public function testHitsCachedResponsesWithExpiresHeader()
  430. {
  431. $time1 = \DateTime::createFromFormat('U', time() - 5);
  432. $time2 = \DateTime::createFromFormat('U', time() + 5);
  433. $this->setNextResponse(200, array('Cache-Control' => 'public', 'Date' => $time1->format(DATE_RFC2822), 'Expires' => $time2->format(DATE_RFC2822)));
  434. $this->request('GET', '/');
  435. $this->assertHttpKernelIsCalled();
  436. $this->assertEquals(200, $this->response->getStatusCode());
  437. $this->assertNotNull($this->response->headers->get('Date'));
  438. $this->assertTraceContains('miss');
  439. $this->assertTraceContains('store');
  440. $this->assertEquals('Hello World', $this->response->getContent());
  441. $this->request('GET', '/');
  442. $this->assertHttpKernelIsNotCalled();
  443. $this->assertEquals(200, $this->response->getStatusCode());
  444. $this->assertLessThan(2, strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')));
  445. $this->assertGreaterThan(0, $this->response->headers->get('Age'));
  446. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  447. $this->assertTraceContains('fresh');
  448. $this->assertTraceNotContains('store');
  449. $this->assertEquals('Hello World', $this->response->getContent());
  450. }
  451. public function testHitsCachedResponseWithMaxAgeDirective()
  452. {
  453. $time = \DateTime::createFromFormat('U', time() - 5);
  454. $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, max-age=10'));
  455. $this->request('GET', '/');
  456. $this->assertHttpKernelIsCalled();
  457. $this->assertEquals(200, $this->response->getStatusCode());
  458. $this->assertNotNull($this->response->headers->get('Date'));
  459. $this->assertTraceContains('miss');
  460. $this->assertTraceContains('store');
  461. $this->assertEquals('Hello World', $this->response->getContent());
  462. $this->request('GET', '/');
  463. $this->assertHttpKernelIsNotCalled();
  464. $this->assertEquals(200, $this->response->getStatusCode());
  465. $this->assertLessThan(2, strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')));
  466. $this->assertGreaterThan(0, $this->response->headers->get('Age'));
  467. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  468. $this->assertTraceContains('fresh');
  469. $this->assertTraceNotContains('store');
  470. $this->assertEquals('Hello World', $this->response->getContent());
  471. }
  472. public function testDegradationWhenCacheLocked()
  473. {
  474. if ('\\' === DIRECTORY_SEPARATOR) {
  475. $this->markTestSkipped('Skips on windows to avoid permissions issues.');
  476. }
  477. $this->cacheConfig['stale_while_revalidate'] = 10;
  478. // The prescence of Last-Modified makes this cacheable (because Response::isValidateable() then).
  479. $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=5', 'Last-Modified' => 'some while ago'), 'Old response');
  480. $this->request('GET', '/'); // warm the cache
  481. // Now, lock the cache
  482. $concurrentRequest = Request::create('/', 'GET');
  483. $this->store->lock($concurrentRequest);
  484. /*
  485. * After 10s, the cached response has become stale. Yet, we're still within the "stale_while_revalidate"
  486. * timeout so we may serve the stale response.
  487. */
  488. sleep(10);
  489. $this->request('GET', '/');
  490. $this->assertHttpKernelIsNotCalled();
  491. $this->assertEquals(200, $this->response->getStatusCode());
  492. $this->assertTraceContains('stale-while-revalidate');
  493. $this->assertEquals('Old response', $this->response->getContent());
  494. /*
  495. * Another 10s later, stale_while_revalidate is over. Resort to serving the old response, but
  496. * do so with a "server unavailable" message.
  497. */
  498. sleep(10);
  499. $this->request('GET', '/');
  500. $this->assertHttpKernelIsNotCalled();
  501. $this->assertEquals(503, $this->response->getStatusCode());
  502. $this->assertEquals('Old response', $this->response->getContent());
  503. }
  504. public function testHitsCachedResponseWithSMaxAgeDirective()
  505. {
  506. $time = \DateTime::createFromFormat('U', time() - 5);
  507. $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 's-maxage=10, max-age=0'));
  508. $this->request('GET', '/');
  509. $this->assertHttpKernelIsCalled();
  510. $this->assertEquals(200, $this->response->getStatusCode());
  511. $this->assertNotNull($this->response->headers->get('Date'));
  512. $this->assertTraceContains('miss');
  513. $this->assertTraceContains('store');
  514. $this->assertEquals('Hello World', $this->response->getContent());
  515. $this->request('GET', '/');
  516. $this->assertHttpKernelIsNotCalled();
  517. $this->assertEquals(200, $this->response->getStatusCode());
  518. $this->assertLessThan(2, strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')));
  519. $this->assertGreaterThan(0, $this->response->headers->get('Age'));
  520. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  521. $this->assertTraceContains('fresh');
  522. $this->assertTraceNotContains('store');
  523. $this->assertEquals('Hello World', $this->response->getContent());
  524. }
  525. public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformation()
  526. {
  527. $this->setNextResponse();
  528. $this->cacheConfig['default_ttl'] = 10;
  529. $this->request('GET', '/');
  530. $this->assertHttpKernelIsCalled();
  531. $this->assertTraceContains('miss');
  532. $this->assertTraceContains('store');
  533. $this->assertEquals('Hello World', $this->response->getContent());
  534. $this->assertRegExp('/s-maxage=10/', $this->response->headers->get('Cache-Control'));
  535. $this->cacheConfig['default_ttl'] = 10;
  536. $this->request('GET', '/');
  537. $this->assertHttpKernelIsNotCalled();
  538. $this->assertEquals(200, $this->response->getStatusCode());
  539. $this->assertTraceContains('fresh');
  540. $this->assertTraceNotContains('store');
  541. $this->assertEquals('Hello World', $this->response->getContent());
  542. $this->assertRegExp('/s-maxage=10/', $this->response->headers->get('Cache-Control'));
  543. }
  544. public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformationAndAfterTtlWasExpired()
  545. {
  546. $this->setNextResponse();
  547. $this->cacheConfig['default_ttl'] = 2;
  548. $this->request('GET', '/');
  549. $this->assertHttpKernelIsCalled();
  550. $this->assertTraceContains('miss');
  551. $this->assertTraceContains('store');
  552. $this->assertEquals('Hello World', $this->response->getContent());
  553. $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control'));
  554. $this->request('GET', '/');
  555. $this->assertHttpKernelIsNotCalled();
  556. $this->assertEquals(200, $this->response->getStatusCode());
  557. $this->assertTraceContains('fresh');
  558. $this->assertTraceNotContains('store');
  559. $this->assertEquals('Hello World', $this->response->getContent());
  560. $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control'));
  561. // expires the cache
  562. $values = $this->getMetaStorageValues();
  563. $this->assertCount(1, $values);
  564. $tmp = unserialize($values[0]);
  565. $time = \DateTime::createFromFormat('U', time() - 5);
  566. $tmp[0][1]['date'] = $time->format(DATE_RFC2822);
  567. $r = new \ReflectionObject($this->store);
  568. $m = $r->getMethod('save');
  569. $m->setAccessible(true);
  570. $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp));
  571. $this->request('GET', '/');
  572. $this->assertHttpKernelIsCalled();
  573. $this->assertEquals(200, $this->response->getStatusCode());
  574. $this->assertTraceContains('stale');
  575. $this->assertTraceContains('invalid');
  576. $this->assertTraceContains('store');
  577. $this->assertEquals('Hello World', $this->response->getContent());
  578. $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control'));
  579. $this->setNextResponse();
  580. $this->request('GET', '/');
  581. $this->assertHttpKernelIsNotCalled();
  582. $this->assertEquals(200, $this->response->getStatusCode());
  583. $this->assertTraceContains('fresh');
  584. $this->assertTraceNotContains('store');
  585. $this->assertEquals('Hello World', $this->response->getContent());
  586. $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control'));
  587. }
  588. public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformationAndAfterTtlWasExpiredWithStatus304()
  589. {
  590. $this->setNextResponse();
  591. $this->cacheConfig['default_ttl'] = 2;
  592. $this->request('GET', '/');
  593. $this->assertHttpKernelIsCalled();
  594. $this->assertTraceContains('miss');
  595. $this->assertTraceContains('store');
  596. $this->assertEquals('Hello World', $this->response->getContent());
  597. $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control'));
  598. $this->request('GET', '/');
  599. $this->assertHttpKernelIsNotCalled();
  600. $this->assertEquals(200, $this->response->getStatusCode());
  601. $this->assertTraceContains('fresh');
  602. $this->assertTraceNotContains('store');
  603. $this->assertEquals('Hello World', $this->response->getContent());
  604. // expires the cache
  605. $values = $this->getMetaStorageValues();
  606. $this->assertCount(1, $values);
  607. $tmp = unserialize($values[0]);
  608. $time = \DateTime::createFromFormat('U', time() - 5);
  609. $tmp[0][1]['date'] = $time->format(DATE_RFC2822);
  610. $r = new \ReflectionObject($this->store);
  611. $m = $r->getMethod('save');
  612. $m->setAccessible(true);
  613. $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp));
  614. $this->request('GET', '/');
  615. $this->assertHttpKernelIsCalled();
  616. $this->assertEquals(200, $this->response->getStatusCode());
  617. $this->assertTraceContains('stale');
  618. $this->assertTraceContains('valid');
  619. $this->assertTraceContains('store');
  620. $this->assertTraceNotContains('miss');
  621. $this->assertEquals('Hello World', $this->response->getContent());
  622. $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control'));
  623. $this->request('GET', '/');
  624. $this->assertHttpKernelIsNotCalled();
  625. $this->assertEquals(200, $this->response->getStatusCode());
  626. $this->assertTraceContains('fresh');
  627. $this->assertTraceNotContains('store');
  628. $this->assertEquals('Hello World', $this->response->getContent());
  629. $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control'));
  630. }
  631. public function testDoesNotAssignDefaultTtlWhenResponseHasMustRevalidateDirective()
  632. {
  633. $this->setNextResponse(200, array('Cache-Control' => 'must-revalidate'));
  634. $this->cacheConfig['default_ttl'] = 10;
  635. $this->request('GET', '/');
  636. $this->assertHttpKernelIsCalled();
  637. $this->assertEquals(200, $this->response->getStatusCode());
  638. $this->assertTraceContains('miss');
  639. $this->assertTraceNotContains('store');
  640. $this->assertNotRegExp('/s-maxage/', $this->response->headers->get('Cache-Control'));
  641. $this->assertEquals('Hello World', $this->response->getContent());
  642. }
  643. public function testFetchesFullResponseWhenCacheStaleAndNoValidatorsPresent()
  644. {
  645. $time = \DateTime::createFromFormat('U', time() + 5);
  646. $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));
  647. // build initial request
  648. $this->request('GET', '/');
  649. $this->assertHttpKernelIsCalled();
  650. $this->assertEquals(200, $this->response->getStatusCode());
  651. $this->assertNotNull($this->response->headers->get('Date'));
  652. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  653. $this->assertNotNull($this->response->headers->get('Age'));
  654. $this->assertTraceContains('miss');
  655. $this->assertTraceContains('store');
  656. $this->assertEquals('Hello World', $this->response->getContent());
  657. // go in and play around with the cached metadata directly ...
  658. $values = $this->getMetaStorageValues();
  659. $this->assertCount(1, $values);
  660. $tmp = unserialize($values[0]);
  661. $time = \DateTime::createFromFormat('U', time());
  662. $tmp[0][1]['expires'] = $time->format(DATE_RFC2822);
  663. $r = new \ReflectionObject($this->store);
  664. $m = $r->getMethod('save');
  665. $m->setAccessible(true);
  666. $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp));
  667. // build subsequent request; should be found but miss due to freshness
  668. $this->request('GET', '/');
  669. $this->assertHttpKernelIsCalled();
  670. $this->assertEquals(200, $this->response->getStatusCode());
  671. $this->assertLessThanOrEqual(1, $this->response->headers->get('Age'));
  672. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  673. $this->assertTraceContains('stale');
  674. $this->assertTraceNotContains('fresh');
  675. $this->assertTraceNotContains('miss');
  676. $this->assertTraceContains('store');
  677. $this->assertEquals('Hello World', $this->response->getContent());
  678. }
  679. public function testValidatesCachedResponsesWithLastModifiedAndNoFreshnessInformation()
  680. {
  681. $time = \DateTime::createFromFormat('U', time());
  682. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time) {
  683. $response->headers->set('Cache-Control', 'public');
  684. $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
  685. if ($time->format(DATE_RFC2822) == $request->headers->get('IF_MODIFIED_SINCE')) {
  686. $response->setStatusCode(304);
  687. $response->setContent('');
  688. }
  689. });
  690. // build initial request
  691. $this->request('GET', '/');
  692. $this->assertHttpKernelIsCalled();
  693. $this->assertEquals(200, $this->response->getStatusCode());
  694. $this->assertNotNull($this->response->headers->get('Last-Modified'));
  695. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  696. $this->assertEquals('Hello World', $this->response->getContent());
  697. $this->assertTraceContains('miss');
  698. $this->assertTraceContains('store');
  699. $this->assertTraceNotContains('stale');
  700. // build subsequent request; should be found but miss due to freshness
  701. $this->request('GET', '/');
  702. $this->assertHttpKernelIsCalled();
  703. $this->assertEquals(200, $this->response->getStatusCode());
  704. $this->assertNotNull($this->response->headers->get('Last-Modified'));
  705. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  706. $this->assertLessThanOrEqual(1, $this->response->headers->get('Age'));
  707. $this->assertEquals('Hello World', $this->response->getContent());
  708. $this->assertTraceContains('stale');
  709. $this->assertTraceContains('valid');
  710. $this->assertTraceContains('store');
  711. $this->assertTraceNotContains('miss');
  712. }
  713. public function testValidatesCachedResponsesUseSameHttpMethod()
  714. {
  715. $test = $this;
  716. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($test) {
  717. $test->assertSame('OPTIONS', $request->getMethod());
  718. });
  719. // build initial request
  720. $this->request('OPTIONS', '/');
  721. // build subsequent request
  722. $this->request('OPTIONS', '/');
  723. }
  724. public function testValidatesCachedResponsesWithETagAndNoFreshnessInformation()
  725. {
  726. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) {
  727. $response->headers->set('Cache-Control', 'public');
  728. $response->headers->set('ETag', '"12345"');
  729. if ($response->getETag() == $request->headers->get('IF_NONE_MATCH')) {
  730. $response->setStatusCode(304);
  731. $response->setContent('');
  732. }
  733. });
  734. // build initial request
  735. $this->request('GET', '/');
  736. $this->assertHttpKernelIsCalled();
  737. $this->assertEquals(200, $this->response->getStatusCode());
  738. $this->assertNotNull($this->response->headers->get('ETag'));
  739. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  740. $this->assertEquals('Hello World', $this->response->getContent());
  741. $this->assertTraceContains('miss');
  742. $this->assertTraceContains('store');
  743. // build subsequent request; should be found but miss due to freshness
  744. $this->request('GET', '/');
  745. $this->assertHttpKernelIsCalled();
  746. $this->assertEquals(200, $this->response->getStatusCode());
  747. $this->assertNotNull($this->response->headers->get('ETag'));
  748. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  749. $this->assertLessThanOrEqual(1, $this->response->headers->get('Age'));
  750. $this->assertEquals('Hello World', $this->response->getContent());
  751. $this->assertTraceContains('stale');
  752. $this->assertTraceContains('valid');
  753. $this->assertTraceContains('store');
  754. $this->assertTraceNotContains('miss');
  755. }
  756. public function testServesResponseWhileFreshAndRevalidatesWithLastModifiedInformation()
  757. {
  758. $time = \DateTime::createFromFormat('U', time());
  759. $this->setNextResponse(200, array(), 'Hello World', function (Request $request, Response $response) use ($time) {
  760. $response->setSharedMaxAge(10);
  761. $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
  762. });
  763. // prime the cache
  764. $this->request('GET', '/');
  765. // next request before s-maxage has expired: Serve from cache
  766. // without hitting the backend
  767. $this->request('GET', '/');
  768. $this->assertHttpKernelIsNotCalled();
  769. $this->assertEquals(200, $this->response->getStatusCode());
  770. $this->assertEquals('Hello World', $this->response->getContent());
  771. $this->assertTraceContains('fresh');
  772. sleep(15); // expire the cache
  773. $this->setNextResponse(304, array(), '', function (Request $request, Response $response) use ($time) {
  774. $this->assertEquals($time->format(DATE_RFC2822), $request->headers->get('IF_MODIFIED_SINCE'));
  775. });
  776. $this->request('GET', '/');
  777. $this->assertHttpKernelIsCalled();
  778. $this->assertEquals(200, $this->response->getStatusCode());
  779. $this->assertEquals('Hello World', $this->response->getContent());
  780. $this->assertTraceContains('stale');
  781. $this->assertTraceContains('valid');
  782. }
  783. public function testReplacesCachedResponsesWhenValidationResultsInNon304Response()
  784. {
  785. $time = \DateTime::createFromFormat('U', time());
  786. $count = 0;
  787. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time, &$count) {
  788. $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
  789. $response->headers->set('Cache-Control', 'public');
  790. switch (++$count) {
  791. case 1:
  792. $response->setContent('first response');
  793. break;
  794. case 2:
  795. $response->setContent('second response');
  796. break;
  797. case 3:
  798. $response->setContent('');
  799. $response->setStatusCode(304);
  800. break;
  801. }
  802. });
  803. // first request should fetch from backend and store in cache
  804. $this->request('GET', '/');
  805. $this->assertEquals(200, $this->response->getStatusCode());
  806. $this->assertEquals('first response', $this->response->getContent());
  807. // second request is validated, is invalid, and replaces cached entry
  808. $this->request('GET', '/');
  809. $this->assertEquals(200, $this->response->getStatusCode());
  810. $this->assertEquals('second response', $this->response->getContent());
  811. // third response is validated, valid, and returns cached entry
  812. $this->request('GET', '/');
  813. $this->assertEquals(200, $this->response->getStatusCode());
  814. $this->assertEquals('second response', $this->response->getContent());
  815. $this->assertEquals(3, $count);
  816. }
  817. public function testPassesHeadRequestsThroughDirectlyOnPass()
  818. {
  819. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) {
  820. $response->setContent('');
  821. $response->setStatusCode(200);
  822. $this->assertEquals('HEAD', $request->getMethod());
  823. });
  824. $this->request('HEAD', '/', array('HTTP_EXPECT' => 'something ...'));
  825. $this->assertHttpKernelIsCalled();
  826. $this->assertEquals('', $this->response->getContent());
  827. }
  828. public function testUsesCacheToRespondToHeadRequestsWhenFresh()
  829. {
  830. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) {
  831. $response->headers->set('Cache-Control', 'public, max-age=10');
  832. $response->setContent('Hello World');
  833. $response->setStatusCode(200);
  834. $this->assertNotEquals('HEAD', $request->getMethod());
  835. });
  836. $this->request('GET', '/');
  837. $this->assertHttpKernelIsCalled();
  838. $this->assertEquals('Hello World', $this->response->getContent());
  839. $this->request('HEAD', '/');
  840. $this->assertHttpKernelIsNotCalled();
  841. $this->assertEquals(200, $this->response->getStatusCode());
  842. $this->assertEquals('', $this->response->getContent());
  843. $this->assertEquals(strlen('Hello World'), $this->response->headers->get('Content-Length'));
  844. }
  845. public function testSendsNoContentWhenFresh()
  846. {
  847. $time = \DateTime::createFromFormat('U', time());
  848. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time) {
  849. $response->headers->set('Cache-Control', 'public, max-age=10');
  850. $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
  851. });
  852. $this->request('GET', '/');
  853. $this->assertHttpKernelIsCalled();
  854. $this->assertEquals('Hello World', $this->response->getContent());
  855. $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));
  856. $this->assertHttpKernelIsNotCalled();
  857. $this->assertEquals(304, $this->response->getStatusCode());
  858. $this->assertEquals('', $this->response->getContent());
  859. }
  860. public function testInvalidatesCachedResponsesOnPost()
  861. {
  862. $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) {
  863. if ('GET' == $request->getMethod()) {
  864. $response->setStatusCode(200);
  865. $response->headers->set('Cache-Control', 'public, max-age=500');
  866. $response->setContent('Hello World');
  867. } elseif ('POST' == $request->getMethod()) {
  868. $response->setStatusCode(303);
  869. $response->headers->set('Location', '/');
  870. $response->headers->remove('Cache-Control');
  871. $response->setContent('');
  872. }
  873. });
  874. // build initial request to enter into the cache
  875. $this->request('GET', '/');
  876. $this->assertHttpKernelIsCalled();
  877. $this->assertEquals(200, $this->response->getStatusCode());
  878. $this->assertEquals('Hello World', $this->response->getContent());
  879. $this->assertTraceContains('miss');
  880. $this->assertTraceContains('store');
  881. // make sure it is valid
  882. $this->request('GET', '/');
  883. $this->assertHttpKernelIsNotCalled();
  884. $this->assertEquals(200, $this->response->getStatusCode());
  885. $this->assertEquals('Hello World', $this->response->getContent());
  886. $this->assertTraceContains('fresh');
  887. // now POST to same URL
  888. $this->request('POST', '/helloworld');
  889. $this->assertHttpKernelIsCalled();
  890. $this->assertEquals('/', $this->response->headers->get('Location'));
  891. $this->assertTraceContains('invalidate');
  892. $this->assertTraceContains('pass');
  893. $this->assertEquals('', $this->response->getContent());
  894. // now make sure it was actually invalidated
  895. $this->request('GET', '/');
  896. $this->assertHttpKernelIsCalled();
  897. $this->assertEquals(200, $this->response->getStatusCode());
  898. $this->assertEquals('Hello World', $this->response->getContent());
  899. $this->assertTraceContains('stale');
  900. $this->assertTraceContains('invalid');
  901. $this->assertTraceContains('store');
  902. }
  903. public function testServesFromCacheWhenHeadersMatch()
  904. {
  905. $count = 0;
  906. $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) {
  907. $response->headers->set('Vary', 'Accept User-Agent Foo');
  908. $response->headers->set('Cache-Control', 'public, max-age=10');
  909. $response->headers->set('X-Response-Count', ++$count);
  910. $response->setContent($request->headers->get('USER_AGENT'));
  911. });
  912. $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
  913. $this->assertEquals(200, $this->response->getStatusCode());
  914. $this->assertEquals('Bob/1.0', $this->response->getContent());
  915. $this->assertTraceContains('miss');
  916. $this->assertTraceContains('store');
  917. $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
  918. $this->assertEquals(200, $this->response->getStatusCode());
  919. $this->assertEquals('Bob/1.0', $this->response->getContent());
  920. $this->assertTraceContains('fresh');
  921. $this->assertTraceNotContains('store');
  922. $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
  923. }
  924. public function testStoresMultipleResponsesWhenHeadersDiffer()
  925. {
  926. $count = 0;
  927. $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) {
  928. $response->headers->set('Vary', 'Accept User-Agent Foo');
  929. $response->headers->set('Cache-Control', 'public, max-age=10');
  930. $response->headers->set('X-Response-Count', ++$count);
  931. $response->setContent($request->headers->get('USER_AGENT'));
  932. });
  933. $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
  934. $this->assertEquals(200, $this->response->getStatusCode());
  935. $this->assertEquals('Bob/1.0', $this->response->getContent());
  936. $this->assertEquals(1, $this->response->headers->get('X-Response-Count'));
  937. $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0'));
  938. $this->assertEquals(200, $this->response->getStatusCode());
  939. $this->assertTraceContains('miss');
  940. $this->assertTraceContains('store');
  941. $this->assertEquals('Bob/2.0', $this->response->getContent());
  942. $this->assertEquals(2, $this->response->headers->get('X-Response-Count'));
  943. $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
  944. $this->assertTraceContains('fresh');
  945. $this->assertEquals('Bob/1.0', $this->response->getContent());
  946. $this->assertEquals(1, $this->response->headers->get('X-Response-Count'));
  947. $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0'));
  948. $this->assertTraceContains('fresh');
  949. $this->assertEquals('Bob/2.0', $this->response->getContent());
  950. $this->assertEquals(2, $this->response->headers->get('X-Response-Count'));
  951. $this->request('GET', '/', array('HTTP_USER_AGENT' => 'Bob/2.0'));
  952. $this->assertTraceContains('miss');
  953. $this->assertEquals('Bob/2.0', $this->response->getContent());
  954. $this->assertEquals(3, $this->response->headers->get('X-Response-Count'));
  955. }
  956. public function testShouldCatchExceptions()
  957. {
  958. $this->catchExceptions();
  959. $this->setNextResponse();
  960. $this->request('GET', '/');
  961. $this->assertExceptionsAreCaught();
  962. }
  963. public function testShouldCatchExceptionsWhenReloadingAndNoCacheRequest()
  964. {
  965. $this->catchExceptions();
  966. $this->setNextResponse();
  967. $this->cacheConfig['allow_reload'] = true;
  968. $this->request('GET', '/', array(), array(), false, array('Pragma' => 'no-cache'));
  969. $this->assertExceptionsAreCaught();
  970. }
  971. public function testShouldNotCatchExceptions()
  972. {
  973. $this->catchExceptions(false);
  974. $this->setNextResponse();
  975. $this->request('GET', '/');
  976. $this->assertExceptionsAreNotCaught();
  977. }
  978. public function testEsiCacheSendsTheLowestTtl()
  979. {
  980. $responses = array(
  981. array(
  982. 'status' => 200,
  983. 'body' => '<esi:include src="/foo" /> <esi:include src="/bar" />',
  984. 'headers' => array(
  985. 'Cache-Control' => 's-maxage=300',
  986. 'Surrogate-Control' => 'content="ESI/1.0"',
  987. ),
  988. ),
  989. array(
  990. 'status' => 200,
  991. 'body' => 'Hello World!',
  992. 'headers' => array('Cache-Control' => 's-maxage=200'),
  993. ),
  994. array(
  995. 'status' => 200,
  996. 'body' => 'My name is Bobby.',
  997. 'headers' => array('Cache-Control' => 's-maxage=100'),
  998. ),
  999. );
  1000. $this->setNextResponses($responses);
  1001. $this->request('GET', '/', array(), array(), true);
  1002. $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent());
  1003. $this->assertEquals(100, $this->response->getTtl());
  1004. }
  1005. public function testEsiCacheSendsTheLowestTtlForHeadRequests()
  1006. {
  1007. $responses = array(
  1008. array(
  1009. 'status' => 200,
  1010. 'body' => 'I am a long-lived master response, but I embed a short-lived resource: <esi:include src="/foo" />',
  1011. 'headers' => array(
  1012. 'Cache-Control' => 's-maxage=300',
  1013. 'Surrogate-Control' => 'content="ESI/1.0"',
  1014. ),
  1015. ),
  1016. array(
  1017. 'status' => 200,
  1018. 'body' => 'I am a short-lived resource',
  1019. 'headers' => array('Cache-Control' => 's-maxage=100'),
  1020. ),
  1021. );
  1022. $this->setNextResponses($responses);
  1023. $this->request('HEAD', '/', array(), array(), true);
  1024. $this->assertEmpty($this->response->getContent());
  1025. $this->assertEquals(100, $this->response->getTtl());
  1026. }
  1027. public function testEsiCacheForceValidation()
  1028. {
  1029. $responses = array(
  1030. array(
  1031. 'status' => 200,
  1032. 'body' => '<esi:include src="/foo" /> <esi:include src="/bar" />',
  1033. 'headers' => array(
  1034. 'Cache-Control' => 's-maxage=300',
  1035. 'Surrogate-Control' => 'content="ESI/1.0"',
  1036. ),
  1037. ),
  1038. array(
  1039. 'status' => 200,
  1040. 'body' => 'Hello World!',
  1041. 'headers' => array('ETag' => 'foobar'),
  1042. ),
  1043. array(
  1044. 'status' => 200,
  1045. 'body' => 'My name is Bobby.',
  1046. 'headers' => array('Cache-Control' => 's-maxage=100'),
  1047. ),
  1048. );
  1049. $this->setNextResponses($responses);
  1050. $this->request('GET', '/', array(), array(), true);
  1051. $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent());
  1052. $this->assertNull($this->response->getTtl());
  1053. $this->assertTrue($this->response->mustRevalidate());
  1054. $this->assertTrue($this->response->headers->hasCacheControlDirective('private'));
  1055. $this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache'));
  1056. }
  1057. public function testEsiCacheForceValidationForHeadRequests()
  1058. {
  1059. $responses = array(
  1060. array(
  1061. 'status' => 200,
  1062. 'body' => 'I am the master response and use expiration caching, but I embed another resource: <esi:include src="/foo" />',
  1063. 'headers' => array(
  1064. 'Cache-Control' => 's-maxage=300',
  1065. 'Surrogate-Control' => 'content="ESI/1.0"',
  1066. ),
  1067. ),
  1068. array(
  1069. 'status' => 200,
  1070. 'body' => 'I am the embedded resource and use validation caching',
  1071. 'headers' => array('ETag' => 'foobar'),
  1072. ),
  1073. );
  1074. $this->setNextResponses($responses);
  1075. $this->request('HEAD', '/', array(), array(), true);
  1076. // The response has been assembled from expiration and validation based resources
  1077. // This can neither be cached nor revalidated, so it should be private/no cache
  1078. $this->assertEmpty($this->response->getContent());
  1079. $this->assertNull($this->response->getTtl());
  1080. $this->assertTrue($this->response->mustRevalidate());
  1081. $this->assertTrue($this->response->headers->hasCacheControlDirective('private'));
  1082. $this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache'));
  1083. }
  1084. public function testEsiRecalculateContentLengthHeader()
  1085. {
  1086. $responses = array(
  1087. array(
  1088. 'status' => 200,
  1089. 'body' => '<esi:include src="/foo" />',
  1090. 'headers' => array(
  1091. 'Content-Length' => 26,
  1092. 'Surrogate-Control' => 'content="ESI/1.0"',
  1093. ),
  1094. ),
  1095. array(
  1096. 'status' => 200,
  1097. 'body' => 'Hello World!',
  1098. 'headers' => array(),
  1099. ),
  1100. );
  1101. $this->setNextResponses($responses);
  1102. $this->request('GET', '/', array(), array(), true);
  1103. $this->assertEquals('Hello World!', $this->response->getContent());
  1104. $this->assertEquals(12, $this->response->headers->get('Content-Length'));
  1105. }
  1106. public function testEsiRecalculateContentLengthHeaderForHeadRequest()
  1107. {
  1108. $responses = array(
  1109. array(
  1110. 'status' => 200,
  1111. 'body' => '<esi:include src="/foo" />',
  1112. 'headers' => array(
  1113. 'Content-Length' => 26,
  1114. 'Surrogate-Control' => 'content="ESI/1.0"',
  1115. ),
  1116. ),
  1117. array(
  1118. 'status' => 200,
  1119. 'body' => 'Hello World!',
  1120. 'headers' => array(),
  1121. ),
  1122. );
  1123. $this->setNextResponses($responses);
  1124. $this->request('HEAD', '/', array(), array(), true);
  1125. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
  1126. // "The Content-Length entity-header field indicates the size of the entity-body,
  1127. // in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD
  1128. // method, the size of the entity-body that would have been sent had the request
  1129. // been a GET."
  1130. $this->assertEmpty($this->response->getContent());
  1131. $this->assertEquals(12, $this->response->headers->get('Content-Length'));
  1132. }
  1133. public function testClientIpIsAlwaysLocalhostForForwardedRequests()
  1134. {
  1135. $this->setNextResponse();
  1136. $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));
  1137. $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR'));
  1138. }
  1139. /**
  1140. * @dataProvider getTrustedProxyData
  1141. */
  1142. public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected)
  1143. {
  1144. Request::setTrustedProxies($existing, Request::HEADER_X_FORWARDED_ALL);
  1145. $this->setNextResponse();
  1146. $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));
  1147. $this->assertEquals($expected, Request::getTrustedProxies());
  1148. }
  1149. public function getTrustedProxyData()
  1150. {
  1151. return array(
  1152. array(array(), array('127.0.0.1')),
  1153. array(array('10.0.0.2'), array('10.0.0.2', '127.0.0.1')),
  1154. array(array('10.0.0.2', '127.0.0.1'), array('10.0.0.2', '127.0.0.1')),
  1155. );
  1156. }
  1157. /**
  1158. * @dataProvider getXForwardedForData
  1159. */
  1160. public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected)
  1161. {
  1162. $this->setNextResponse();
  1163. $server = array('REMOTE_ADDR' => '10.0.0.1');
  1164. if (false !== $xForwardedFor) {
  1165. $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;
  1166. }
  1167. $this->request('GET', '/', $server);
  1168. $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
  1169. }
  1170. public function getXForwardedForData()
  1171. {
  1172. return array(
  1173. array(false, '10.0.0.1'),
  1174. array('10.0.0.2', '10.0.0.2, 10.0.0.1'),
  1175. array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'),
  1176. );
  1177. }
  1178. public function testXForwarderForHeaderForPassRequests()
  1179. {
  1180. $this->setNextResponse();
  1181. $server = array('REMOTE_ADDR' => '10.0.0.1');
  1182. $this->request('POST', '/', $server);
  1183. $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
  1184. }
  1185. public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponses()
  1186. {
  1187. $time = \DateTime::createFromFormat('U', time());
  1188. $responses = array(
  1189. array(
  1190. 'status' => 200,
  1191. 'body' => '<esi:include src="/hey" />',
  1192. 'headers' => array(
  1193. 'Surrogate-Control' => 'content="ESI/1.0"',
  1194. 'ETag' => 'hey',
  1195. 'Last-Modified' => $time->format(DATE_RFC2822),
  1196. ),
  1197. ),
  1198. array(
  1199. 'status' => 200,
  1200. 'body' => 'Hey!',
  1201. 'headers' => array(),
  1202. ),
  1203. );
  1204. $this->setNextResponses($responses);
  1205. $this->request('GET', '/', array(), array(), true);
  1206. $this->assertNull($this->response->getETag());
  1207. $this->assertNull($this->response->getLastModified());
  1208. }
  1209. public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponsesAndHeadRequest()
  1210. {
  1211. $time = \DateTime::createFromFormat('U', time());
  1212. $responses = array(
  1213. array(
  1214. 'status' => 200,
  1215. 'body' => '<esi:include src="/hey" />',
  1216. 'headers' => array(
  1217. 'Surrogate-Control' => 'content="ESI/1.0"',
  1218. 'ETag' => 'hey',
  1219. 'Last-Modified' => $time->format(DATE_RFC2822),
  1220. ),
  1221. ),
  1222. array(
  1223. 'status' => 200,
  1224. 'body' => 'Hey!',
  1225. 'headers' => array(),
  1226. ),
  1227. );
  1228. $this->setNextResponses($responses);
  1229. $this->request('HEAD', '/', array(), array(), true);
  1230. $this->assertEmpty($this->response->getContent());
  1231. $this->assertNull($this->response->getETag());
  1232. $this->assertNull($this->response->getLastModified());
  1233. }
  1234. public function testDoesNotCacheOptionsRequest()
  1235. {
  1236. $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'get');
  1237. $this->request('GET', '/');
  1238. $this->assertHttpKernelIsCalled();
  1239. $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'options');
  1240. $this->request('OPTIONS', '/');
  1241. $this->assertHttpKernelIsCalled();
  1242. $this->request('GET', '/');
  1243. $this->assertHttpKernelIsNotCalled();
  1244. $this->assertSame('get', $this->response->getContent());
  1245. }
  1246. }
  1247. class TestKernel implements HttpKernelInterface
  1248. {
  1249. public $terminateCalled = false;
  1250. public function terminate(Request $request, Response $response)
  1251. {
  1252. $this->terminateCalled = true;
  1253. }
  1254. public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
  1255. {
  1256. }
  1257. }