You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResponseTest.php 35 KiB

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