HttpCacheTest.php 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
  445. $this->assertTrue($this->response->headers->get('Age') > 0);
  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->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
  466. $this->assertTrue($this->response->headers->get('Age') > 0);
  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->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
  519. $this->assertTrue($this->response->headers->get('Age') > 0);
  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->assertTrue($this->response->headers->get('Age') <= 1);
  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->assertTrue($this->response->headers->get('Age') <= 1);
  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->assertTrue($this->response->headers->get('Age') <= 1);
  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=300'),
  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. // check for 100 or 99 as the test can be executed after a second change
  1004. $this->assertTrue(in_array($this->response->getTtl(), array(99, 100)));
  1005. }
  1006. public function testEsiCacheForceValidation()
  1007. {
  1008. $responses = array(
  1009. array(
  1010. 'status' => 200,
  1011. 'body' => '<esi:include src="/foo" /> <esi:include src="/bar" />',
  1012. 'headers' => array(
  1013. 'Cache-Control' => 's-maxage=300',
  1014. 'Surrogate-Control' => 'content="ESI/1.0"',
  1015. ),
  1016. ),
  1017. array(
  1018. 'status' => 200,
  1019. 'body' => 'Hello World!',
  1020. 'headers' => array('ETag' => 'foobar'),
  1021. ),
  1022. array(
  1023. 'status' => 200,
  1024. 'body' => 'My name is Bobby.',
  1025. 'headers' => array('Cache-Control' => 's-maxage=100'),
  1026. ),
  1027. );
  1028. $this->setNextResponses($responses);
  1029. $this->request('GET', '/', array(), array(), true);
  1030. $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent());
  1031. $this->assertNull($this->response->getTtl());
  1032. $this->assertTrue($this->response->mustRevalidate());
  1033. $this->assertTrue($this->response->headers->hasCacheControlDirective('private'));
  1034. $this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache'));
  1035. }
  1036. public function testEsiRecalculateContentLengthHeader()
  1037. {
  1038. $responses = array(
  1039. array(
  1040. 'status' => 200,
  1041. 'body' => '<esi:include src="/foo" />',
  1042. 'headers' => array(
  1043. 'Content-Length' => 26,
  1044. 'Cache-Control' => 's-maxage=300',
  1045. 'Surrogate-Control' => 'content="ESI/1.0"',
  1046. ),
  1047. ),
  1048. array(
  1049. 'status' => 200,
  1050. 'body' => 'Hello World!',
  1051. 'headers' => array(),
  1052. ),
  1053. );
  1054. $this->setNextResponses($responses);
  1055. $this->request('GET', '/', array(), array(), true);
  1056. $this->assertEquals('Hello World!', $this->response->getContent());
  1057. $this->assertEquals(12, $this->response->headers->get('Content-Length'));
  1058. }
  1059. public function testClientIpIsAlwaysLocalhostForForwardedRequests()
  1060. {
  1061. $this->setNextResponse();
  1062. $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));
  1063. $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR'));
  1064. }
  1065. /**
  1066. * @dataProvider getTrustedProxyData
  1067. */
  1068. public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected)
  1069. {
  1070. Request::setTrustedProxies($existing, Request::HEADER_X_FORWARDED_ALL);
  1071. $this->setNextResponse();
  1072. $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));
  1073. $this->assertEquals($expected, Request::getTrustedProxies());
  1074. }
  1075. public function getTrustedProxyData()
  1076. {
  1077. return array(
  1078. array(array(), array('127.0.0.1')),
  1079. array(array('10.0.0.2'), array('10.0.0.2', '127.0.0.1')),
  1080. array(array('10.0.0.2', '127.0.0.1'), array('10.0.0.2', '127.0.0.1')),
  1081. );
  1082. }
  1083. /**
  1084. * @dataProvider getXForwardedForData
  1085. */
  1086. public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected)
  1087. {
  1088. $this->setNextResponse();
  1089. $server = array('REMOTE_ADDR' => '10.0.0.1');
  1090. if (false !== $xForwardedFor) {
  1091. $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;
  1092. }
  1093. $this->request('GET', '/', $server);
  1094. $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
  1095. }
  1096. public function getXForwardedForData()
  1097. {
  1098. return array(
  1099. array(false, '10.0.0.1'),
  1100. array('10.0.0.2', '10.0.0.2, 10.0.0.1'),
  1101. array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'),
  1102. );
  1103. }
  1104. public function testXForwarderForHeaderForPassRequests()
  1105. {
  1106. $this->setNextResponse();
  1107. $server = array('REMOTE_ADDR' => '10.0.0.1');
  1108. $this->request('POST', '/', $server);
  1109. $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
  1110. }
  1111. public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponses()
  1112. {
  1113. $time = \DateTime::createFromFormat('U', time());
  1114. $responses = array(
  1115. array(
  1116. 'status' => 200,
  1117. 'body' => '<esi:include src="/hey" />',
  1118. 'headers' => array(
  1119. 'Surrogate-Control' => 'content="ESI/1.0"',
  1120. 'ETag' => 'hey',
  1121. 'Last-Modified' => $time->format(DATE_RFC2822),
  1122. ),
  1123. ),
  1124. array(
  1125. 'status' => 200,
  1126. 'body' => 'Hey!',
  1127. 'headers' => array(),
  1128. ),
  1129. );
  1130. $this->setNextResponses($responses);
  1131. $this->request('GET', '/', array(), array(), true);
  1132. $this->assertNull($this->response->getETag());
  1133. $this->assertNull($this->response->getLastModified());
  1134. }
  1135. public function testDoesNotCacheOptionsRequest()
  1136. {
  1137. $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'get');
  1138. $this->request('GET', '/');
  1139. $this->assertHttpKernelIsCalled();
  1140. $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'options');
  1141. $this->request('OPTIONS', '/');
  1142. $this->assertHttpKernelIsCalled();
  1143. $this->request('GET', '/');
  1144. $this->assertHttpKernelIsNotCalled();
  1145. $this->assertSame('get', $this->response->getContent());
  1146. }
  1147. }
  1148. class TestKernel implements HttpKernelInterface
  1149. {
  1150. public $terminateCalled = false;
  1151. public function terminate(Request $request, Response $response)
  1152. {
  1153. $this->terminateCalled = true;
  1154. }
  1155. public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
  1156. {
  1157. }
  1158. }