ResponseTest.php 36KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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\HttpFoundation\Tests;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. /**
  14. * @group time-sensitive
  15. */
  16. class ResponseTest extends ResponseTestCase
  17. {
  18. public function testCreate()
  19. {
  20. $response = Response::create('foo', 301, array('Foo' => 'bar'));
  21. $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
  22. $this->assertEquals(301, $response->getStatusCode());
  23. $this->assertEquals('bar', $response->headers->get('foo'));
  24. }
  25. public function testToString()
  26. {
  27. $response = new Response();
  28. $response = explode("\r\n", $response);
  29. $this->assertEquals('HTTP/1.0 200 OK', $response[0]);
  30. $this->assertEquals('Cache-Control: no-cache, private', $response[1]);
  31. }
  32. public function testClone()
  33. {
  34. $response = new Response();
  35. $responseClone = clone $response;
  36. $this->assertEquals($response, $responseClone);
  37. }
  38. public function testSendHeaders()
  39. {
  40. $response = new Response();
  41. $headers = $response->sendHeaders();
  42. $this->assertObjectHasAttribute('headers', $headers);
  43. $this->assertObjectHasAttribute('content', $headers);
  44. $this->assertObjectHasAttribute('version', $headers);
  45. $this->assertObjectHasAttribute('statusCode', $headers);
  46. $this->assertObjectHasAttribute('statusText', $headers);
  47. $this->assertObjectHasAttribute('charset', $headers);
  48. }
  49. public function testSend()
  50. {
  51. $response = new Response();
  52. $responseSend = $response->send();
  53. $this->assertObjectHasAttribute('headers', $responseSend);
  54. $this->assertObjectHasAttribute('content', $responseSend);
  55. $this->assertObjectHasAttribute('version', $responseSend);
  56. $this->assertObjectHasAttribute('statusCode', $responseSend);
  57. $this->assertObjectHasAttribute('statusText', $responseSend);
  58. $this->assertObjectHasAttribute('charset', $responseSend);
  59. }
  60. public function testGetCharset()
  61. {
  62. $response = new Response();
  63. $charsetOrigin = 'UTF-8';
  64. $response->setCharset($charsetOrigin);
  65. $charset = $response->getCharset();
  66. $this->assertEquals($charsetOrigin, $charset);
  67. }
  68. public function testIsCacheable()
  69. {
  70. $response = new Response();
  71. $this->assertFalse($response->isCacheable());
  72. }
  73. public function testIsCacheableWithErrorCode()
  74. {
  75. $response = new Response('', 500);
  76. $this->assertFalse($response->isCacheable());
  77. }
  78. public function testIsCacheableWithNoStoreDirective()
  79. {
  80. $response = new Response();
  81. $response->headers->set('cache-control', 'private');
  82. $this->assertFalse($response->isCacheable());
  83. }
  84. public function testIsCacheableWithSetTtl()
  85. {
  86. $response = new Response();
  87. $response->setTtl(10);
  88. $this->assertTrue($response->isCacheable());
  89. }
  90. public function testMustRevalidate()
  91. {
  92. $response = new Response();
  93. $this->assertFalse($response->mustRevalidate());
  94. }
  95. public function testMustRevalidateWithMustRevalidateCacheControlHeader()
  96. {
  97. $response = new Response();
  98. $response->headers->set('cache-control', 'must-revalidate');
  99. $this->assertTrue($response->mustRevalidate());
  100. }
  101. public function testMustRevalidateWithProxyRevalidateCacheControlHeader()
  102. {
  103. $response = new Response();
  104. $response->headers->set('cache-control', 'proxy-revalidate');
  105. $this->assertTrue($response->mustRevalidate());
  106. }
  107. public function testSetNotModified()
  108. {
  109. $response = new Response();
  110. $modified = $response->setNotModified();
  111. $this->assertObjectHasAttribute('headers', $modified);
  112. $this->assertObjectHasAttribute('content', $modified);
  113. $this->assertObjectHasAttribute('version', $modified);
  114. $this->assertObjectHasAttribute('statusCode', $modified);
  115. $this->assertObjectHasAttribute('statusText', $modified);
  116. $this->assertObjectHasAttribute('charset', $modified);
  117. $this->assertEquals(304, $modified->getStatusCode());
  118. }
  119. public function testIsSuccessful()
  120. {
  121. $response = new Response();
  122. $this->assertTrue($response->isSuccessful());
  123. }
  124. public function testIsNotModified()
  125. {
  126. $response = new Response();
  127. $modified = $response->isNotModified(new Request());
  128. $this->assertFalse($modified);
  129. }
  130. public function testIsNotModifiedNotSafe()
  131. {
  132. $request = Request::create('/homepage', 'POST');
  133. $response = new Response();
  134. $this->assertFalse($response->isNotModified($request));
  135. }
  136. public function testIsNotModifiedLastModified()
  137. {
  138. $before = 'Sun, 25 Aug 2013 18:32:31 GMT';
  139. $modified = 'Sun, 25 Aug 2013 18:33:31 GMT';
  140. $after = 'Sun, 25 Aug 2013 19:33:31 GMT';
  141. $request = new Request();
  142. $request->headers->set('If-Modified-Since', $modified);
  143. $response = new Response();
  144. $response->headers->set('Last-Modified', $modified);
  145. $this->assertTrue($response->isNotModified($request));
  146. $response->headers->set('Last-Modified', $before);
  147. $this->assertTrue($response->isNotModified($request));
  148. $response->headers->set('Last-Modified', $after);
  149. $this->assertFalse($response->isNotModified($request));
  150. $response->headers->set('Last-Modified', '');
  151. $this->assertFalse($response->isNotModified($request));
  152. }
  153. public function testIsNotModifiedEtag()
  154. {
  155. $etagOne = 'randomly_generated_etag';
  156. $etagTwo = 'randomly_generated_etag_2';
  157. $request = new Request();
  158. $request->headers->set('if_none_match', sprintf('%s, %s, %s', $etagOne, $etagTwo, 'etagThree'));
  159. $response = new Response();
  160. $response->headers->set('ETag', $etagOne);
  161. $this->assertTrue($response->isNotModified($request));
  162. $response->headers->set('ETag', $etagTwo);
  163. $this->assertTrue($response->isNotModified($request));
  164. $response->headers->set('ETag', '');
  165. $this->assertFalse($response->isNotModified($request));
  166. }
  167. public function testIsNotModifiedLastModifiedAndEtag()
  168. {
  169. $before = 'Sun, 25 Aug 2013 18:32:31 GMT';
  170. $modified = 'Sun, 25 Aug 2013 18:33:31 GMT';
  171. $after = 'Sun, 25 Aug 2013 19:33:31 GMT';
  172. $etag = 'randomly_generated_etag';
  173. $request = new Request();
  174. $request->headers->set('if_none_match', sprintf('%s, %s', $etag, 'etagThree'));
  175. $request->headers->set('If-Modified-Since', $modified);
  176. $response = new Response();
  177. $response->headers->set('ETag', $etag);
  178. $response->headers->set('Last-Modified', $after);
  179. $this->assertFalse($response->isNotModified($request));
  180. $response->headers->set('ETag', 'non-existent-etag');
  181. $response->headers->set('Last-Modified', $before);
  182. $this->assertFalse($response->isNotModified($request));
  183. $response->headers->set('ETag', $etag);
  184. $response->headers->set('Last-Modified', $modified);
  185. $this->assertTrue($response->isNotModified($request));
  186. }
  187. public function testIsNotModifiedIfModifiedSinceAndEtagWithoutLastModified()
  188. {
  189. $modified = 'Sun, 25 Aug 2013 18:33:31 GMT';
  190. $etag = 'randomly_generated_etag';
  191. $request = new Request();
  192. $request->headers->set('if_none_match', sprintf('%s, %s', $etag, 'etagThree'));
  193. $request->headers->set('If-Modified-Since', $modified);
  194. $response = new Response();
  195. $response->headers->set('ETag', $etag);
  196. $this->assertTrue($response->isNotModified($request));
  197. $response->headers->set('ETag', 'non-existent-etag');
  198. $this->assertFalse($response->isNotModified($request));
  199. }
  200. public function testIsValidateable()
  201. {
  202. $response = new Response('', 200, array('Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
  203. $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present');
  204. $response = new Response('', 200, array('ETag' => '"12345"'));
  205. $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if ETag is present');
  206. $response = new Response();
  207. $this->assertFalse($response->isValidateable(), '->isValidateable() returns false when no validator is present');
  208. }
  209. public function testGetDate()
  210. {
  211. $oneHourAgo = $this->createDateTimeOneHourAgo();
  212. $response = new Response('', 200, array('Date' => $oneHourAgo->format(DATE_RFC2822)));
  213. $date = $response->getDate();
  214. $this->assertEquals($oneHourAgo->getTimestamp(), $date->getTimestamp(), '->getDate() returns the Date header if present');
  215. $response = new Response();
  216. $date = $response->getDate();
  217. $this->assertEquals(time(), $date->getTimestamp(), '->getDate() returns the current Date if no Date header present');
  218. $response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
  219. $now = $this->createDateTimeNow();
  220. $response->headers->set('Date', $now->format(DATE_RFC2822));
  221. $date = $response->getDate();
  222. $this->assertEquals($now->getTimestamp(), $date->getTimestamp(), '->getDate() returns the date when the header has been modified');
  223. $response = new Response('', 200);
  224. $now = $this->createDateTimeNow();
  225. $response->headers->remove('Date');
  226. $date = $response->getDate();
  227. $this->assertEquals($now->getTimestamp(), $date->getTimestamp(), '->getDate() returns the current Date when the header has previously been removed');
  228. }
  229. public function testGetMaxAge()
  230. {
  231. $response = new Response();
  232. $response->headers->set('Cache-Control', 's-maxage=600, max-age=0');
  233. $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() uses s-maxage cache control directive when present');
  234. $response = new Response();
  235. $response->headers->set('Cache-Control', 'max-age=600');
  236. $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() falls back to max-age when no s-maxage directive present');
  237. $response = new Response();
  238. $response->headers->set('Cache-Control', 'must-revalidate');
  239. $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
  240. $this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present');
  241. $response = new Response();
  242. $response->headers->set('Cache-Control', 'must-revalidate');
  243. $response->headers->set('Expires', -1);
  244. $this->assertLessThanOrEqual(time() - 2 * 86400, $response->getExpires()->format('U'));
  245. $response = new Response();
  246. $this->assertNull($response->getMaxAge(), '->getMaxAge() returns null if no freshness information available');
  247. }
  248. public function testSetSharedMaxAge()
  249. {
  250. $response = new Response();
  251. $response->setSharedMaxAge(20);
  252. $cacheControl = $response->headers->get('Cache-Control');
  253. $this->assertEquals('public, s-maxage=20', $cacheControl);
  254. }
  255. public function testIsPrivate()
  256. {
  257. $response = new Response();
  258. $response->headers->set('Cache-Control', 'max-age=100');
  259. $response->setPrivate();
  260. $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
  261. $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
  262. $response = new Response();
  263. $response->headers->set('Cache-Control', 'public, max-age=100');
  264. $response->setPrivate();
  265. $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
  266. $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
  267. $this->assertFalse($response->headers->hasCacheControlDirective('public'), '->isPrivate() removes the public Cache-Control directive');
  268. }
  269. public function testExpire()
  270. {
  271. $response = new Response();
  272. $response->headers->set('Cache-Control', 'max-age=100');
  273. $response->expire();
  274. $this->assertEquals(100, $response->headers->get('Age'), '->expire() sets the Age to max-age when present');
  275. $response = new Response();
  276. $response->headers->set('Cache-Control', 'max-age=100, s-maxage=500');
  277. $response->expire();
  278. $this->assertEquals(500, $response->headers->get('Age'), '->expire() sets the Age to s-maxage when both max-age and s-maxage are present');
  279. $response = new Response();
  280. $response->headers->set('Cache-Control', 'max-age=5, s-maxage=500');
  281. $response->headers->set('Age', '1000');
  282. $response->expire();
  283. $this->assertEquals(1000, $response->headers->get('Age'), '->expire() does nothing when the response is already stale/expired');
  284. $response = new Response();
  285. $response->expire();
  286. $this->assertFalse($response->headers->has('Age'), '->expire() does nothing when the response does not include freshness information');
  287. $response = new Response();
  288. $response->headers->set('Expires', -1);
  289. $response->expire();
  290. $this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired');
  291. }
  292. public function testGetTtl()
  293. {
  294. $response = new Response();
  295. $this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present');
  296. $response = new Response();
  297. $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
  298. $this->assertEquals(3600, $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present');
  299. $response = new Response();
  300. $response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(DATE_RFC2822));
  301. $this->assertLessThan(0, $response->getTtl(), '->getTtl() returns negative values when Expires is in past');
  302. $response = new Response();
  303. $response->headers->set('Expires', $response->getDate()->format(DATE_RFC2822));
  304. $response->headers->set('Age', 0);
  305. $this->assertSame(0, $response->getTtl(), '->getTtl() correctly handles zero');
  306. $response = new Response();
  307. $response->headers->set('Cache-Control', 'max-age=60');
  308. $this->assertEquals(60, $response->getTtl(), '->getTtl() uses Cache-Control max-age when present');
  309. }
  310. public function testSetClientTtl()
  311. {
  312. $response = new Response();
  313. $response->setClientTtl(10);
  314. $this->assertEquals($response->getMaxAge(), $response->getAge() + 10);
  315. }
  316. public function testGetSetProtocolVersion()
  317. {
  318. $response = new Response();
  319. $this->assertEquals('1.0', $response->getProtocolVersion());
  320. $response->setProtocolVersion('1.1');
  321. $this->assertEquals('1.1', $response->getProtocolVersion());
  322. }
  323. public function testGetVary()
  324. {
  325. $response = new Response();
  326. $this->assertEquals(array(), $response->getVary(), '->getVary() returns an empty array if no Vary header is present');
  327. $response = new Response();
  328. $response->headers->set('Vary', 'Accept-Language');
  329. $this->assertEquals(array('Accept-Language'), $response->getVary(), '->getVary() parses a single header name value');
  330. $response = new Response();
  331. $response->headers->set('Vary', 'Accept-Language User-Agent X-Foo');
  332. $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by spaces');
  333. $response = new Response();
  334. $response->headers->set('Vary', 'Accept-Language,User-Agent, X-Foo');
  335. $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by commas');
  336. $vary = array('Accept-Language', 'User-Agent', 'X-foo');
  337. $response = new Response();
  338. $response->headers->set('Vary', $vary);
  339. $this->assertEquals($vary, $response->getVary(), '->getVary() parses multiple header name values in arrays');
  340. $response = new Response();
  341. $response->headers->set('Vary', 'Accept-Language, User-Agent, X-foo');
  342. $this->assertEquals($vary, $response->getVary(), '->getVary() parses multiple header name values in arrays');
  343. }
  344. public function testSetVary()
  345. {
  346. $response = new Response();
  347. $response->setVary('Accept-Language');
  348. $this->assertEquals(array('Accept-Language'), $response->getVary());
  349. $response->setVary('Accept-Language, User-Agent');
  350. $this->assertEquals(array('Accept-Language', 'User-Agent'), $response->getVary(), '->setVary() replace the vary header by default');
  351. $response->setVary('X-Foo', false);
  352. $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->setVary() doesn\'t wipe out earlier Vary headers if replace is set to false');
  353. }
  354. public function testDefaultContentType()
  355. {
  356. $headerMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\ResponseHeaderBag')->setMethods(array('set'))->getMock();
  357. $headerMock->expects($this->at(0))
  358. ->method('set')
  359. ->with('Content-Type', 'text/html');
  360. $headerMock->expects($this->at(1))
  361. ->method('set')
  362. ->with('Content-Type', 'text/html; charset=UTF-8');
  363. $response = new Response('foo');
  364. $response->headers = $headerMock;
  365. $response->prepare(new Request());
  366. }
  367. public function testContentTypeCharset()
  368. {
  369. $response = new Response();
  370. $response->headers->set('Content-Type', 'text/css');
  371. // force fixContentType() to be called
  372. $response->prepare(new Request());
  373. $this->assertEquals('text/css; charset=UTF-8', $response->headers->get('Content-Type'));
  374. }
  375. public function testPrepareDoesNothingIfContentTypeIsSet()
  376. {
  377. $response = new Response('foo');
  378. $response->headers->set('Content-Type', 'text/plain');
  379. $response->prepare(new Request());
  380. $this->assertEquals('text/plain; charset=UTF-8', $response->headers->get('content-type'));
  381. }
  382. public function testPrepareDoesNothingIfRequestFormatIsNotDefined()
  383. {
  384. $response = new Response('foo');
  385. $response->prepare(new Request());
  386. $this->assertEquals('text/html; charset=UTF-8', $response->headers->get('content-type'));
  387. }
  388. public function testPrepareSetContentType()
  389. {
  390. $response = new Response('foo');
  391. $request = Request::create('/');
  392. $request->setRequestFormat('json');
  393. $response->prepare($request);
  394. $this->assertEquals('application/json', $response->headers->get('content-type'));
  395. }
  396. public function testPrepareRemovesContentForHeadRequests()
  397. {
  398. $response = new Response('foo');
  399. $request = Request::create('/', 'HEAD');
  400. $length = 12345;
  401. $response->headers->set('Content-Length', $length);
  402. $response->prepare($request);
  403. $this->assertEquals('', $response->getContent());
  404. $this->assertEquals($length, $response->headers->get('Content-Length'), 'Content-Length should be as if it was GET; see RFC2616 14.13');
  405. }
  406. public function testPrepareRemovesContentForInformationalResponse()
  407. {
  408. $response = new Response('foo');
  409. $request = Request::create('/');
  410. $response->setContent('content');
  411. $response->setStatusCode(101);
  412. $response->prepare($request);
  413. $this->assertEquals('', $response->getContent());
  414. $this->assertFalse($response->headers->has('Content-Type'));
  415. $this->assertFalse($response->headers->has('Content-Type'));
  416. $response->setContent('content');
  417. $response->setStatusCode(304);
  418. $response->prepare($request);
  419. $this->assertEquals('', $response->getContent());
  420. $this->assertFalse($response->headers->has('Content-Type'));
  421. $this->assertFalse($response->headers->has('Content-Length'));
  422. }
  423. public function testPrepareRemovesContentLength()
  424. {
  425. $response = new Response('foo');
  426. $request = Request::create('/');
  427. $response->headers->set('Content-Length', 12345);
  428. $response->prepare($request);
  429. $this->assertEquals(12345, $response->headers->get('Content-Length'));
  430. $response->headers->set('Transfer-Encoding', 'chunked');
  431. $response->prepare($request);
  432. $this->assertFalse($response->headers->has('Content-Length'));
  433. }
  434. public function testPrepareSetsPragmaOnHttp10Only()
  435. {
  436. $request = Request::create('/', 'GET');
  437. $request->server->set('SERVER_PROTOCOL', 'HTTP/1.0');
  438. $response = new Response('foo');
  439. $response->prepare($request);
  440. $this->assertEquals('no-cache', $response->headers->get('pragma'));
  441. $this->assertEquals('-1', $response->headers->get('expires'));
  442. $request->server->set('SERVER_PROTOCOL', 'HTTP/1.1');
  443. $response = new Response('foo');
  444. $response->prepare($request);
  445. $this->assertFalse($response->headers->has('pragma'));
  446. $this->assertFalse($response->headers->has('expires'));
  447. }
  448. public function testSetCache()
  449. {
  450. $response = new Response();
  451. //array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public')
  452. try {
  453. $response->setCache(array('wrong option' => 'value'));
  454. $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported');
  455. } catch (\Exception $e) {
  456. $this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported');
  457. $this->assertContains('"wrong option"', $e->getMessage());
  458. }
  459. $options = array('etag' => '"whatever"');
  460. $response->setCache($options);
  461. $this->assertEquals($response->getEtag(), '"whatever"');
  462. $now = $this->createDateTimeNow();
  463. $options = array('last_modified' => $now);
  464. $response->setCache($options);
  465. $this->assertEquals($response->getLastModified()->getTimestamp(), $now->getTimestamp());
  466. $options = array('max_age' => 100);
  467. $response->setCache($options);
  468. $this->assertEquals($response->getMaxAge(), 100);
  469. $options = array('s_maxage' => 200);
  470. $response->setCache($options);
  471. $this->assertEquals($response->getMaxAge(), 200);
  472. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  473. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  474. $response->setCache(array('public' => true));
  475. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  476. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  477. $response->setCache(array('public' => false));
  478. $this->assertFalse($response->headers->hasCacheControlDirective('public'));
  479. $this->assertTrue($response->headers->hasCacheControlDirective('private'));
  480. $response->setCache(array('private' => true));
  481. $this->assertFalse($response->headers->hasCacheControlDirective('public'));
  482. $this->assertTrue($response->headers->hasCacheControlDirective('private'));
  483. $response->setCache(array('private' => false));
  484. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  485. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  486. $response->setCache(array('immutable' => true));
  487. $this->assertTrue($response->headers->hasCacheControlDirective('immutable'));
  488. $response->setCache(array('immutable' => false));
  489. $this->assertFalse($response->headers->hasCacheControlDirective('immutable'));
  490. }
  491. public function testSendContent()
  492. {
  493. $response = new Response('test response rendering', 200);
  494. ob_start();
  495. $response->sendContent();
  496. $string = ob_get_clean();
  497. $this->assertContains('test response rendering', $string);
  498. }
  499. public function testSetPublic()
  500. {
  501. $response = new Response();
  502. $response->setPublic();
  503. $this->assertTrue($response->headers->hasCacheControlDirective('public'));
  504. $this->assertFalse($response->headers->hasCacheControlDirective('private'));
  505. }
  506. public function testSetImmutable()
  507. {
  508. $response = new Response();
  509. $response->setImmutable();
  510. $this->assertTrue($response->headers->hasCacheControlDirective('immutable'));
  511. }
  512. public function testIsImmutable()
  513. {
  514. $response = new Response();
  515. $response->setImmutable();
  516. $this->assertTrue($response->isImmutable());
  517. }
  518. public function testSetDate()
  519. {
  520. $response = new Response();
  521. $response->setDate(\DateTime::createFromFormat(\DateTime::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));
  522. $this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTime::ATOM));
  523. }
  524. public function testSetDateWithImmutable()
  525. {
  526. $response = new Response();
  527. $response->setDate(\DateTimeImmutable::createFromFormat(\DateTime::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));
  528. $this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTime::ATOM));
  529. }
  530. public function testSetExpires()
  531. {
  532. $response = new Response();
  533. $response->setExpires(null);
  534. $this->assertNull($response->getExpires(), '->setExpires() remove the header when passed null');
  535. $now = $this->createDateTimeNow();
  536. $response->setExpires($now);
  537. $this->assertEquals($response->getExpires()->getTimestamp(), $now->getTimestamp());
  538. }
  539. public function testSetExpiresWithImmutable()
  540. {
  541. $response = new Response();
  542. $now = $this->createDateTimeImmutableNow();
  543. $response->setExpires($now);
  544. $this->assertEquals($response->getExpires()->getTimestamp(), $now->getTimestamp());
  545. }
  546. public function testSetLastModified()
  547. {
  548. $response = new Response();
  549. $response->setLastModified($this->createDateTimeNow());
  550. $this->assertNotNull($response->getLastModified());
  551. $response->setLastModified(null);
  552. $this->assertNull($response->getLastModified());
  553. }
  554. public function testSetLastModifiedWithImmutable()
  555. {
  556. $response = new Response();
  557. $response->setLastModified($this->createDateTimeImmutableNow());
  558. $this->assertNotNull($response->getLastModified());
  559. $response->setLastModified(null);
  560. $this->assertNull($response->getLastModified());
  561. }
  562. public function testIsInvalid()
  563. {
  564. $response = new Response();
  565. try {
  566. $response->setStatusCode(99);
  567. $this->fail();
  568. } catch (\InvalidArgumentException $e) {
  569. $this->assertTrue($response->isInvalid());
  570. }
  571. try {
  572. $response->setStatusCode(650);
  573. $this->fail();
  574. } catch (\InvalidArgumentException $e) {
  575. $this->assertTrue($response->isInvalid());
  576. }
  577. $response = new Response('', 200);
  578. $this->assertFalse($response->isInvalid());
  579. }
  580. /**
  581. * @dataProvider getStatusCodeFixtures
  582. */
  583. public function testSetStatusCode($code, $text, $expectedText)
  584. {
  585. $response = new Response();
  586. $response->setStatusCode($code, $text);
  587. $statusText = new \ReflectionProperty($response, 'statusText');
  588. $statusText->setAccessible(true);
  589. $this->assertEquals($expectedText, $statusText->getValue($response));
  590. }
  591. public function getStatusCodeFixtures()
  592. {
  593. return array(
  594. array('200', null, 'OK'),
  595. array('200', false, ''),
  596. array('200', 'foo', 'foo'),
  597. array('199', null, 'unknown status'),
  598. array('199', false, ''),
  599. array('199', 'foo', 'foo'),
  600. );
  601. }
  602. public function testIsInformational()
  603. {
  604. $response = new Response('', 100);
  605. $this->assertTrue($response->isInformational());
  606. $response = new Response('', 200);
  607. $this->assertFalse($response->isInformational());
  608. }
  609. public function testIsRedirectRedirection()
  610. {
  611. foreach (array(301, 302, 303, 307) as $code) {
  612. $response = new Response('', $code);
  613. $this->assertTrue($response->isRedirection());
  614. $this->assertTrue($response->isRedirect());
  615. }
  616. $response = new Response('', 304);
  617. $this->assertTrue($response->isRedirection());
  618. $this->assertFalse($response->isRedirect());
  619. $response = new Response('', 200);
  620. $this->assertFalse($response->isRedirection());
  621. $this->assertFalse($response->isRedirect());
  622. $response = new Response('', 404);
  623. $this->assertFalse($response->isRedirection());
  624. $this->assertFalse($response->isRedirect());
  625. $response = new Response('', 301, array('Location' => '/good-uri'));
  626. $this->assertFalse($response->isRedirect('/bad-uri'));
  627. $this->assertTrue($response->isRedirect('/good-uri'));
  628. }
  629. public function testIsNotFound()
  630. {
  631. $response = new Response('', 404);
  632. $this->assertTrue($response->isNotFound());
  633. $response = new Response('', 200);
  634. $this->assertFalse($response->isNotFound());
  635. }
  636. public function testIsEmpty()
  637. {
  638. foreach (array(204, 304) as $code) {
  639. $response = new Response('', $code);
  640. $this->assertTrue($response->isEmpty());
  641. }
  642. $response = new Response('', 200);
  643. $this->assertFalse($response->isEmpty());
  644. }
  645. public function testIsForbidden()
  646. {
  647. $response = new Response('', 403);
  648. $this->assertTrue($response->isForbidden());
  649. $response = new Response('', 200);
  650. $this->assertFalse($response->isForbidden());
  651. }
  652. public function testIsOk()
  653. {
  654. $response = new Response('', 200);
  655. $this->assertTrue($response->isOk());
  656. $response = new Response('', 404);
  657. $this->assertFalse($response->isOk());
  658. }
  659. public function testIsServerOrClientError()
  660. {
  661. $response = new Response('', 404);
  662. $this->assertTrue($response->isClientError());
  663. $this->assertFalse($response->isServerError());
  664. $response = new Response('', 500);
  665. $this->assertFalse($response->isClientError());
  666. $this->assertTrue($response->isServerError());
  667. }
  668. public function testHasVary()
  669. {
  670. $response = new Response();
  671. $this->assertFalse($response->hasVary());
  672. $response->setVary('User-Agent');
  673. $this->assertTrue($response->hasVary());
  674. }
  675. public function testSetEtag()
  676. {
  677. $response = new Response('', 200, array('ETag' => '"12345"'));
  678. $response->setEtag();
  679. $this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null');
  680. }
  681. /**
  682. * @dataProvider validContentProvider
  683. */
  684. public function testSetContent($content)
  685. {
  686. $response = new Response();
  687. $response->setContent($content);
  688. $this->assertEquals((string) $content, $response->getContent());
  689. }
  690. /**
  691. * @expectedException \UnexpectedValueException
  692. * @dataProvider invalidContentProvider
  693. */
  694. public function testSetContentInvalid($content)
  695. {
  696. $response = new Response();
  697. $response->setContent($content);
  698. }
  699. public function testSettersAreChainable()
  700. {
  701. $response = new Response();
  702. $setters = array(
  703. 'setProtocolVersion' => '1.0',
  704. 'setCharset' => 'UTF-8',
  705. 'setPublic' => null,
  706. 'setPrivate' => null,
  707. 'setDate' => $this->createDateTimeNow(),
  708. 'expire' => null,
  709. 'setMaxAge' => 1,
  710. 'setSharedMaxAge' => 1,
  711. 'setTtl' => 1,
  712. 'setClientTtl' => 1,
  713. );
  714. foreach ($setters as $setter => $arg) {
  715. $this->assertEquals($response, $response->{$setter}($arg));
  716. }
  717. }
  718. public function testNoDeprecationsAreTriggered()
  719. {
  720. new DefaultResponse();
  721. $this->getMockBuilder(Response::class)->getMock();
  722. // we just need to ensure that subclasses of Response can be created without any deprecations
  723. // being triggered if the subclass does not override any final methods
  724. $this->addToAssertionCount(1);
  725. }
  726. public function validContentProvider()
  727. {
  728. return array(
  729. 'obj' => array(new StringableObject()),
  730. 'string' => array('Foo'),
  731. 'int' => array(2),
  732. );
  733. }
  734. public function invalidContentProvider()
  735. {
  736. return array(
  737. 'obj' => array(new \stdClass()),
  738. 'array' => array(array()),
  739. 'bool' => array(true, '1'),
  740. );
  741. }
  742. protected function createDateTimeOneHourAgo()
  743. {
  744. return $this->createDateTimeNow()->sub(new \DateInterval('PT1H'));
  745. }
  746. protected function createDateTimeOneHourLater()
  747. {
  748. return $this->createDateTimeNow()->add(new \DateInterval('PT1H'));
  749. }
  750. protected function createDateTimeNow()
  751. {
  752. $date = new \DateTime();
  753. return $date->setTimestamp(time());
  754. }
  755. protected function createDateTimeImmutableNow()
  756. {
  757. $date = new \DateTimeImmutable();
  758. return $date->setTimestamp(time());
  759. }
  760. protected function provideResponse()
  761. {
  762. return new Response();
  763. }
  764. /**
  765. * @see http://github.com/zendframework/zend-diactoros for the canonical source repository
  766. *
  767. * @author Fábio Pacheco
  768. * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
  769. * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
  770. */
  771. public function ianaCodesReasonPhrasesProvider()
  772. {
  773. if (!in_array('https', stream_get_wrappers(), true)) {
  774. $this->markTestSkipped('The "https" wrapper is not available');
  775. }
  776. $ianaHttpStatusCodes = new \DOMDocument();
  777. libxml_set_streams_context(stream_context_create(array(
  778. 'http' => array(
  779. 'method' => 'GET',
  780. 'timeout' => 30,
  781. ),
  782. )));
  783. $ianaHttpStatusCodes->load('https://www.iana.org/assignments/http-status-codes/http-status-codes.xml');
  784. if (!$ianaHttpStatusCodes->relaxNGValidate(__DIR__.'/schema/http-status-codes.rng')) {
  785. self::fail('Invalid IANA\'s HTTP status code list.');
  786. }
  787. $ianaCodesReasonPhrases = array();
  788. $xpath = new \DOMXPath($ianaHttpStatusCodes);
  789. $xpath->registerNamespace('ns', 'http://www.iana.org/assignments');
  790. $records = $xpath->query('//ns:record');
  791. foreach ($records as $record) {
  792. $value = $xpath->query('.//ns:value', $record)->item(0)->nodeValue;
  793. $description = $xpath->query('.//ns:description', $record)->item(0)->nodeValue;
  794. if (in_array($description, array('Unassigned', '(Unused)'), true)) {
  795. continue;
  796. }
  797. if (preg_match('/^([0-9]+)\s*\-\s*([0-9]+)$/', $value, $matches)) {
  798. for ($value = $matches[1]; $value <= $matches[2]; ++$value) {
  799. $ianaCodesReasonPhrases[] = array($value, $description);
  800. }
  801. } else {
  802. $ianaCodesReasonPhrases[] = array($value, $description);
  803. }
  804. }
  805. return $ianaCodesReasonPhrases;
  806. }
  807. /**
  808. * @dataProvider ianaCodesReasonPhrasesProvider
  809. */
  810. public function testReasonPhraseDefaultsAgainstIana($code, $reasonPhrase)
  811. {
  812. $this->assertEquals($reasonPhrase, Response::$statusTexts[$code]);
  813. }
  814. }
  815. class StringableObject
  816. {
  817. public function __toString()
  818. {
  819. return 'Foo';
  820. }
  821. }
  822. class DefaultResponse extends Response
  823. {
  824. }