ResponseTest.php 37 KB

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