HttpCacheTest.php 62 KB

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