ResponseTest.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 2.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Http;
  17. include_once CORE_TEST_CASES . DS . 'Http' . DS . 'server_mocks.php';
  18. use Cake\Core\Configure;
  19. use Cake\Http\Cookie\Cookie;
  20. use Cake\Http\Cookie\CookieCollection;
  21. use Cake\Http\CorsBuilder;
  22. use Cake\Http\Exception\NotFoundException;
  23. use Cake\Http\Response;
  24. use Cake\Http\ServerRequest;
  25. use Cake\I18n\FrozenTime;
  26. use Cake\TestSuite\TestCase;
  27. use Laminas\Diactoros\Stream;
  28. /**
  29. * ResponseTest
  30. */
  31. class ResponseTest extends TestCase
  32. {
  33. /**
  34. * SERVER variable backup.
  35. *
  36. * @var array
  37. */
  38. protected $server = [];
  39. /**
  40. * setup
  41. *
  42. * @return void
  43. */
  44. public function setUp(): void
  45. {
  46. parent::setUp();
  47. $this->server = $_SERVER;
  48. }
  49. /**
  50. * teardown
  51. *
  52. * @return void
  53. */
  54. public function tearDown(): void
  55. {
  56. parent::tearDown();
  57. $_SERVER = $this->server;
  58. unset($GLOBALS['mockedHeadersSent']);
  59. }
  60. /**
  61. * Tests the request object constructor
  62. *
  63. * @return void
  64. */
  65. public function testConstruct()
  66. {
  67. $response = new Response();
  68. $this->assertSame('', (string)$response->getBody());
  69. $this->assertSame('UTF-8', $response->getCharset());
  70. $this->assertSame('text/html', $response->getType());
  71. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  72. $this->assertEquals(200, $response->getStatusCode());
  73. $options = [
  74. 'body' => 'This is the body',
  75. 'charset' => 'my-custom-charset',
  76. 'type' => 'mp3',
  77. 'status' => 203,
  78. ];
  79. $response = new Response($options);
  80. $this->assertSame('This is the body', (string)$response->getBody());
  81. $this->assertSame('my-custom-charset', $response->getCharset());
  82. $this->assertSame('audio/mpeg', $response->getType());
  83. $this->assertSame('audio/mpeg', $response->getHeaderLine('Content-Type'));
  84. $this->assertEquals(203, $response->getStatusCode());
  85. }
  86. /**
  87. * Tests the getCharset/withCharset methods
  88. *
  89. * @return void
  90. */
  91. public function testWithCharset()
  92. {
  93. $response = new Response();
  94. $this->assertSame('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  95. $new = $response->withCharset('iso-8859-1');
  96. $this->assertStringNotContainsString('iso', $response->getHeaderLine('Content-Type'), 'Old instance not changed');
  97. $this->assertSame('iso-8859-1', $new->getCharset());
  98. $this->assertSame('text/html; charset=iso-8859-1', $new->getHeaderLine('Content-Type'));
  99. }
  100. /**
  101. * Tests the getType method
  102. *
  103. * @return void
  104. */
  105. public function testGetType()
  106. {
  107. $response = new Response();
  108. $this->assertSame('text/html', $response->getType());
  109. $this->assertEquals(
  110. 'application/pdf',
  111. $response->withType('pdf')->getType()
  112. );
  113. $this->assertEquals(
  114. 'custom/stuff',
  115. $response->withType('custom/stuff')->getType()
  116. );
  117. $this->assertEquals(
  118. 'application/json',
  119. $response->withType('json')->getType()
  120. );
  121. }
  122. /**
  123. * @return void
  124. */
  125. public function testSetTypeMap()
  126. {
  127. $response = new Response();
  128. $response->setTypeMap('ical', 'text/calendar');
  129. $response = $response->withType('ical')->getType();
  130. $this->assertSame('text/calendar', $response);
  131. }
  132. /**
  133. * @return void
  134. */
  135. public function testSetTypeMapAsArray()
  136. {
  137. $response = new Response();
  138. $response->setTypeMap('ical', ['text/calendar']);
  139. $response = $response->withType('ical')->getType();
  140. $this->assertSame('text/calendar', $response);
  141. }
  142. /**
  143. * Tests the withType method
  144. *
  145. * @return void
  146. */
  147. public function testWithTypeAlias()
  148. {
  149. $response = new Response();
  150. $this->assertEquals(
  151. 'text/html; charset=UTF-8',
  152. $response->getHeaderLine('Content-Type'),
  153. 'Default content-type should match'
  154. );
  155. $new = $response->withType('pdf');
  156. $this->assertNotSame($new, $response, 'Should be a new instance');
  157. $this->assertSame(
  158. 'text/html; charset=UTF-8',
  159. $response->getHeaderLine('Content-Type'),
  160. 'Original object should not be modified'
  161. );
  162. $this->assertSame('application/pdf', $new->getHeaderLine('Content-Type'));
  163. $this->assertSame(
  164. 'application/json',
  165. $new->withType('json')->getHeaderLine('Content-Type')
  166. );
  167. }
  168. /**
  169. * test withType() and full mime-types
  170. *
  171. * @return void
  172. */
  173. public function withTypeFull()
  174. {
  175. $response = new Response();
  176. $this->assertEquals(
  177. 'application/json',
  178. $response->withType('application/json')->getHeaderLine('Content-Type'),
  179. 'Should not add charset to explicit type'
  180. );
  181. $this->assertEquals(
  182. 'custom/stuff',
  183. $response->withType('custom/stuff')->getHeaderLine('Content-Type'),
  184. 'Should allow arbitrary types'
  185. );
  186. }
  187. /**
  188. * Test that an invalid type raises an exception
  189. *
  190. * @return void
  191. */
  192. public function testWithTypeInvalidType()
  193. {
  194. $this->expectException(\InvalidArgumentException::class);
  195. $this->expectExceptionMessage('"beans" is an invalid content type');
  196. $response = new Response();
  197. $response->withType('beans');
  198. }
  199. /**
  200. * Data provider for content type tests.
  201. *
  202. * @return array
  203. */
  204. public static function charsetTypeProvider()
  205. {
  206. return [
  207. ['mp3', 'audio/mpeg'],
  208. ['js', 'application/javascript; charset=UTF-8'],
  209. ['xml', 'application/xml; charset=UTF-8'],
  210. ['txt', 'text/plain; charset=UTF-8'],
  211. ];
  212. }
  213. /**
  214. * Test that setting certain status codes clears the status code.
  215. *
  216. * @return void
  217. */
  218. public function testWithStatusClearsContentType()
  219. {
  220. $response = new Response();
  221. $new = $response->withType('pdf')
  222. ->withStatus(204);
  223. $this->assertFalse($new->hasHeader('Content-Type'));
  224. $this->assertSame(204, $new->getStatusCode());
  225. $response = new Response();
  226. $new = $response->withStatus(304)
  227. ->withType('pdf');
  228. $this->assertFalse($new->hasHeader('Content-Type'));
  229. }
  230. /**
  231. * Tests the withDisabledCache method
  232. *
  233. * @return void
  234. */
  235. public function testWithDisabledCache()
  236. {
  237. $response = new Response();
  238. $expected = [
  239. 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
  240. 'Last-Modified' => [gmdate('D, d M Y H:i:s') . ' GMT'],
  241. 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
  242. 'Content-Type' => ['text/html; charset=UTF-8'],
  243. ];
  244. $new = $response->withDisabledCache();
  245. $this->assertFalse($response->hasHeader('Expires'), 'Old instance not mutated.');
  246. $this->assertEquals($expected, $new->getHeaders());
  247. }
  248. /**
  249. * Tests the withCache method
  250. *
  251. * @return void
  252. */
  253. public function testWithCache()
  254. {
  255. $response = new Response();
  256. $since = $time = time();
  257. $new = $response->withCache($since, $time);
  258. $this->assertFalse($response->hasHeader('Date'));
  259. $this->assertFalse($response->hasHeader('Last-Modified'));
  260. $this->assertEquals(gmdate('D, j M Y G:i:s ', $since) . 'GMT', $new->getHeaderLine('Date'));
  261. $this->assertEquals(gmdate('D, j M Y H:i:s ', $since) . 'GMT', $new->getHeaderLine('Last-Modified'));
  262. $this->assertEquals(gmdate('D, j M Y H:i:s', $time) . ' GMT', $new->getHeaderLine('Expires'));
  263. $this->assertSame('public, max-age=0', $new->getHeaderLine('Cache-Control'));
  264. }
  265. /**
  266. * Tests the compress method
  267. *
  268. * @return void
  269. */
  270. public function testCompress()
  271. {
  272. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  273. $response = new Response();
  274. if (ini_get('zlib.output_compression') === '1' || !extension_loaded('zlib')) {
  275. $this->assertFalse($response->compress());
  276. $this->markTestSkipped('Is not possible to test output compression');
  277. }
  278. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  279. $result = $response->compress();
  280. $this->assertFalse($result);
  281. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  282. $result = $response->compress();
  283. $this->assertTrue($result);
  284. $this->assertContains('ob_gzhandler', ob_list_handlers());
  285. ob_get_clean();
  286. }
  287. /**
  288. * Tests the withDownload method
  289. *
  290. * @return void
  291. */
  292. public function testWithDownload()
  293. {
  294. $response = new Response();
  295. $new = $response->withDownload('myfile.mp3');
  296. $this->assertFalse($response->hasHeader('Content-Disposition'), 'No mutation');
  297. $expected = 'attachment; filename="myfile.mp3"';
  298. $this->assertEquals($expected, $new->getHeaderLine('Content-Disposition'));
  299. }
  300. /**
  301. * Tests the mapType method
  302. *
  303. * @return void
  304. */
  305. public function testMapType()
  306. {
  307. $response = new Response();
  308. $this->assertSame('wav', $response->mapType('audio/x-wav'));
  309. $this->assertSame('pdf', $response->mapType('application/pdf'));
  310. $this->assertSame('xml', $response->mapType('text/xml'));
  311. $this->assertSame('html', $response->mapType('*/*'));
  312. $this->assertSame('csv', $response->mapType('application/vnd.ms-excel'));
  313. $expected = ['json', 'xhtml', 'css'];
  314. $result = $response->mapType(['application/json', 'application/xhtml+xml', 'text/css']);
  315. $this->assertEquals($expected, $result);
  316. }
  317. /**
  318. * Tests the outputCompressed method
  319. *
  320. * @return void
  321. */
  322. public function testOutputCompressed()
  323. {
  324. $response = new Response();
  325. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  326. $result = $response->outputCompressed();
  327. $this->assertFalse($result);
  328. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  329. $result = $response->outputCompressed();
  330. $this->assertFalse($result);
  331. if (!extension_loaded('zlib')) {
  332. $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
  333. }
  334. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  335. if (ini_get('zlib.output_compression') !== '1') {
  336. ob_start('ob_gzhandler');
  337. }
  338. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  339. $result = $response->outputCompressed();
  340. $this->assertTrue($result);
  341. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  342. $result = $response->outputCompressed();
  343. $this->assertFalse($result);
  344. if (ini_get('zlib.output_compression') !== '1') {
  345. ob_get_clean();
  346. }
  347. }
  348. /**
  349. * Tests settings the content length
  350. *
  351. * @return void
  352. */
  353. public function testWithLength()
  354. {
  355. $response = new Response();
  356. $this->assertFalse($response->hasHeader('Content-Length'));
  357. $new = $response->withLength(100);
  358. $this->assertFalse($response->hasHeader('Content-Length'), 'Old instance not modified');
  359. $this->assertSame('100', $new->getHeaderLine('Content-Length'));
  360. }
  361. /**
  362. * Tests settings the link
  363. *
  364. * @return void
  365. */
  366. public function testWithAddedLink()
  367. {
  368. $response = new Response();
  369. $this->assertFalse($response->hasHeader('Link'));
  370. $new = $response->withAddedLink('http://example.com', ['rel' => 'prev']);
  371. $this->assertFalse($response->hasHeader('Link'), 'Old instance not modified');
  372. $this->assertSame('<http://example.com>; rel="prev"', $new->getHeaderLine('Link'));
  373. $new = $response->withAddedLink('http://example.com');
  374. $this->assertSame('<http://example.com>', $new->getHeaderLine('Link'));
  375. $new = $response->withAddedLink('http://example.com?p=1', ['rel' => 'prev'])
  376. ->withAddedLink('http://example.com?p=2', ['rel' => 'next', 'foo' => 'bar']);
  377. $this->assertSame('<http://example.com?p=1>; rel="prev",<http://example.com?p=2>; rel="next"; foo="bar"', $new->getHeaderLine('Link'));
  378. }
  379. /**
  380. * Tests the withExpires method
  381. *
  382. * @return void
  383. */
  384. public function testWithExpires()
  385. {
  386. $format = 'D, j M Y H:i:s';
  387. $response = new Response();
  388. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  389. $new = $response->withExpires($now);
  390. $this->assertFalse($response->hasHeader('Expires'));
  391. $now->setTimeZone(new \DateTimeZone('UTC'));
  392. $this->assertEquals($now->format($format) . ' GMT', $new->getHeaderLine('Expires'));
  393. $now = time();
  394. $new = $response->withExpires($now);
  395. $this->assertEquals(gmdate($format) . ' GMT', $new->getHeaderLine('Expires'));
  396. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  397. $new = $response->withExpires('+1 day');
  398. $this->assertEquals($time->format($format) . ' GMT', $new->getHeaderLine('Expires'));
  399. }
  400. /**
  401. * Tests the withModified method
  402. *
  403. * @return void
  404. */
  405. public function testWithModified()
  406. {
  407. $format = 'D, j M Y H:i:s';
  408. $response = new Response();
  409. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  410. $new = $response->withModified($now);
  411. $this->assertFalse($response->hasHeader('Last-Modified'));
  412. $now->setTimeZone(new \DateTimeZone('UTC'));
  413. $this->assertEquals($now->format($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  414. $now = time();
  415. $new = $response->withModified($now);
  416. $this->assertEquals(gmdate($format, $now) . ' GMT', $new->getHeaderLine('Last-Modified'));
  417. $now = new \DateTimeImmutable();
  418. $new = $response->withModified($now);
  419. $this->assertEquals(gmdate($format, $now->getTimestamp()) . ' GMT', $new->getHeaderLine('Last-Modified'));
  420. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  421. $new = $response->withModified('+1 day');
  422. $this->assertEquals($time->format($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  423. }
  424. /**
  425. * Tests withSharable()
  426. *
  427. * @return void
  428. */
  429. public function testWithSharable()
  430. {
  431. $response = new Response();
  432. $new = $response->withSharable(true);
  433. $this->assertFalse($response->hasHeader('Cache-Control'), 'old instance unchanged');
  434. $this->assertSame('public', $new->getHeaderLine('Cache-Control'));
  435. $new = $response->withSharable(false);
  436. $this->assertSame('private', $new->getHeaderLine('Cache-Control'));
  437. $new = $response->withSharable(true, 3600);
  438. $this->assertSame('public, max-age=3600', $new->getHeaderLine('Cache-Control'));
  439. $new = $response->withSharable(false, 3600);
  440. $this->assertSame('private, max-age=3600', $new->getHeaderLine('Cache-Control'));
  441. }
  442. /**
  443. * Tests withMaxAge()
  444. *
  445. * @return void
  446. */
  447. public function testWithMaxAge()
  448. {
  449. $response = new Response();
  450. $this->assertFalse($response->hasHeader('Cache-Control'));
  451. $new = $response->withMaxAge(3600);
  452. $this->assertSame('max-age=3600', $new->getHeaderLine('Cache-Control'));
  453. $new = $response->withMaxAge(3600)
  454. ->withSharable(false);
  455. $this->assertSame('max-age=3600, private', $new->getHeaderLine('Cache-Control'));
  456. }
  457. /**
  458. * Tests setting of s-maxage Cache-Control directive
  459. *
  460. * @return void
  461. */
  462. public function testWithSharedMaxAge()
  463. {
  464. $response = new Response();
  465. $new = $response->withSharedMaxAge(3600);
  466. $this->assertFalse($response->hasHeader('Cache-Control'));
  467. $this->assertSame('s-maxage=3600', $new->getHeaderLine('Cache-Control'));
  468. $new = $response->withSharedMaxAge(3600)->withSharable(true);
  469. $this->assertSame('s-maxage=3600, public', $new->getHeaderLine('Cache-Control'));
  470. }
  471. /**
  472. * Tests setting of must-revalidate Cache-Control directive
  473. *
  474. * @return void
  475. */
  476. public function testWithMustRevalidate()
  477. {
  478. $response = new Response();
  479. $this->assertFalse($response->hasHeader('Cache-Control'));
  480. $new = $response->withMustRevalidate(true);
  481. $this->assertFalse($response->hasHeader('Cache-Control'));
  482. $this->assertSame('must-revalidate', $new->getHeaderLine('Cache-Control'));
  483. $new = $new->withMustRevalidate(false);
  484. $this->assertEmpty($new->getHeaderLine('Cache-Control'));
  485. }
  486. /**
  487. * Tests withVary()
  488. *
  489. * @return void
  490. */
  491. public function testWithVary()
  492. {
  493. $response = new Response();
  494. $new = $response->withVary('Accept-encoding');
  495. $this->assertFalse($response->hasHeader('Vary'));
  496. $this->assertSame('Accept-encoding', $new->getHeaderLine('Vary'));
  497. $new = $response->withVary(['Accept-encoding', 'Accept-language']);
  498. $this->assertFalse($response->hasHeader('Vary'));
  499. $this->assertSame('Accept-encoding,Accept-language', $new->getHeaderLine('Vary'));
  500. }
  501. /**
  502. * Tests withEtag()
  503. *
  504. * @return void
  505. */
  506. public function testWithEtag()
  507. {
  508. $response = new Response();
  509. $new = $response->withEtag('something');
  510. $this->assertFalse($response->hasHeader('Etag'));
  511. $this->assertSame('"something"', $new->getHeaderLine('Etag'));
  512. $new = $response->withEtag('something', true);
  513. $this->assertSame('W/"something"', $new->getHeaderLine('Etag'));
  514. }
  515. /**
  516. * Tests that the response is able to be marked as not modified
  517. *
  518. * @return void
  519. */
  520. public function testNotModified()
  521. {
  522. $response = new Response();
  523. $response = $response->withStringBody('something')
  524. ->withStatus(200)
  525. ->withLength(100)
  526. ->withModified('now');
  527. $response->notModified();
  528. $this->assertFalse($response->hasHeader('Content-Length'));
  529. $this->assertFalse($response->hasHeader('Modified'));
  530. $this->assertEmpty((string)$response->getBody());
  531. $this->assertEquals(304, $response->getStatusCode());
  532. }
  533. /**
  534. * Tests withNotModified()
  535. *
  536. * @return void
  537. */
  538. public function testWithNotModified()
  539. {
  540. $response = new Response(['body' => 'something']);
  541. $response = $response->withLength(100)
  542. ->withStatus(200)
  543. ->withHeader('Last-Modified', 'value')
  544. ->withHeader('Content-Language', 'en-EN')
  545. ->withHeader('X-things', 'things')
  546. ->withType('application/json');
  547. $new = $response->withNotModified();
  548. $this->assertTrue($response->hasHeader('Content-Language'), 'old instance not changed');
  549. $this->assertTrue($response->hasHeader('Content-Length'), 'old instance not changed');
  550. $this->assertFalse($new->hasHeader('Content-Type'));
  551. $this->assertFalse($new->hasHeader('Content-Length'));
  552. $this->assertFalse($new->hasHeader('Content-Language'));
  553. $this->assertFalse($new->hasHeader('Last-Modified'));
  554. $this->assertSame('things', $new->getHeaderLine('X-things'), 'Other headers are retained');
  555. $this->assertSame(304, $new->getStatusCode());
  556. $this->assertSame('', $new->getBody()->getContents());
  557. }
  558. /**
  559. * Test checkNotModified method
  560. *
  561. * @return void
  562. */
  563. public function testCheckNotModifiedByEtagStar()
  564. {
  565. $request = new ServerRequest();
  566. $request = $request->withHeader('If-None-Match', '*');
  567. $response = new Response();
  568. $response = $response->withEtag('something')
  569. ->withHeader('Content-Length', 99);
  570. $this->assertTrue($response->checkNotModified($request));
  571. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  572. }
  573. /**
  574. * Test checkNotModified method
  575. *
  576. * @return void
  577. */
  578. public function testCheckNotModifiedByEtagExact()
  579. {
  580. $request = new ServerRequest();
  581. $request = $request->withHeader('If-None-Match', 'W/"something", "other"');
  582. $response = new Response();
  583. $response = $response->withEtag('something', true)
  584. ->withHeader('Content-Length', 99);
  585. $this->assertTrue($response->checkNotModified($request));
  586. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  587. }
  588. /**
  589. * Test checkNotModified method
  590. *
  591. * @return void
  592. */
  593. public function testCheckNotModifiedByEtagAndTime()
  594. {
  595. $request = new ServerRequest();
  596. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  597. ->withHeader('If-None-Match', 'W/"something", "other"');
  598. $response = new Response();
  599. $response = $response->withModified('2012-01-01 00:00:00')
  600. ->withEtag('something', true)
  601. ->withHeader('Content-Length', 99);
  602. $this->assertTrue($response->checkNotModified($request));
  603. $this->assertFalse($response->hasHeader('Content-Length'), 'etags match, should be unmodified');
  604. }
  605. /**
  606. * Test checkNotModified method
  607. *
  608. * @return void
  609. */
  610. public function testCheckNotModifiedByEtagAndTimeMismatch()
  611. {
  612. $request = new ServerRequest();
  613. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  614. ->withHeader('If-None-Match', 'W/"something", "other"');
  615. $response = new Response();
  616. $response = $response->withModified('2012-01-01 00:00:01')
  617. ->withEtag('something', true)
  618. ->withHeader('Content-Length', 99);
  619. $this->assertFalse($response->checkNotModified($request));
  620. $this->assertTrue($response->hasHeader('Content-Length'), 'timestamp in response is newer');
  621. }
  622. /**
  623. * Test checkNotModified method
  624. *
  625. * @return void
  626. */
  627. public function testCheckNotModifiedByEtagMismatch()
  628. {
  629. $request = new ServerRequest();
  630. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  631. ->withHeader('If-None-Match', 'W/"something-else", "other"');
  632. $response = new Response();
  633. $response = $response->withModified('2012-01-01 00:00:00')
  634. ->withEtag('something', true)
  635. ->withHeader('Content-Length', 99);
  636. $this->assertFalse($response->checkNotModified($request));
  637. $this->assertTrue($response->hasHeader('Content-Length'), 'etags do not match');
  638. }
  639. /**
  640. * Test checkNotModified method
  641. *
  642. * @return void
  643. */
  644. public function testCheckNotModifiedByTime()
  645. {
  646. $request = new ServerRequest();
  647. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  648. $response = new Response();
  649. $response = $response->withModified('2012-01-01 00:00:00')
  650. ->withHeader('Content-Length', 99);
  651. $this->assertTrue($response->checkNotModified($request));
  652. $this->assertFalse($response->hasHeader('Content-Length'), 'modified time matches');
  653. }
  654. /**
  655. * Test checkNotModified method
  656. *
  657. * @return void
  658. */
  659. public function testCheckNotModifiedNoHints()
  660. {
  661. $request = new ServerRequest();
  662. $request = $request->withHeader('If-None-Match', 'W/"something", "other"')
  663. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  664. $response = new Response();
  665. $this->assertFalse($response->checkNotModified($request));
  666. $this->assertSame(200, $response->getStatusCode());
  667. }
  668. /**
  669. * Test setting cookies with no value
  670. *
  671. * @return void
  672. */
  673. public function testWithCookieEmpty()
  674. {
  675. $response = new Response();
  676. $new = $response->withCookie(new Cookie('testing'));
  677. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  678. $expected = [
  679. 'name' => 'testing',
  680. 'value' => '',
  681. 'expires' => 0,
  682. 'path' => '/',
  683. 'domain' => '',
  684. 'secure' => false,
  685. 'httponly' => false,
  686. ];
  687. $result = $new->getCookie('testing');
  688. $this->assertEquals($expected, $result);
  689. }
  690. /**
  691. * Test setting cookies with scalar values
  692. *
  693. * @return void
  694. */
  695. public function testWithCookieScalar()
  696. {
  697. $response = new Response();
  698. $new = $response->withCookie(new Cookie('testing', 'abc123'));
  699. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  700. $this->assertSame('abc123', $new->getCookie('testing')['value']);
  701. $new = $response->withCookie(new Cookie('testing', 99));
  702. $this->assertEquals(99, $new->getCookie('testing')['value']);
  703. $new = $response->withCookie(new Cookie('testing', false));
  704. $this->assertFalse($new->getCookie('testing')['value']);
  705. $new = $response->withCookie(new Cookie('testing', true));
  706. $this->assertTrue($new->getCookie('testing')['value']);
  707. }
  708. /**
  709. * Test withCookie() and duplicate data
  710. *
  711. * @return void
  712. * @throws \Exception
  713. */
  714. public function testWithDuplicateCookie()
  715. {
  716. $expiry = new \DateTimeImmutable('+24 hours');
  717. $response = new Response();
  718. $cookie = new Cookie(
  719. 'testing',
  720. '[a,b,c]',
  721. $expiry,
  722. '/test',
  723. '',
  724. true
  725. );
  726. $new = $response->withCookie($cookie);
  727. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  728. $expected = [
  729. 'name' => 'testing',
  730. 'value' => '[a,b,c]',
  731. 'expires' => $expiry,
  732. 'path' => '/test',
  733. 'domain' => '',
  734. 'secure' => true,
  735. 'httponly' => false,
  736. ];
  737. // Match the date time formatting to Response::convertCookieToArray
  738. $expected['expires'] = $expiry->format('U');
  739. $this->assertEquals($expected, $new->getCookie('testing'));
  740. }
  741. /**
  742. * Test withCookie() and a cookie instance
  743. *
  744. * @return void
  745. */
  746. public function testWithCookieObject()
  747. {
  748. $response = new Response();
  749. $cookie = new Cookie('yay', 'a value');
  750. $new = $response->withCookie($cookie);
  751. $this->assertNull($response->getCookie('yay'), 'withCookie does not mutate');
  752. $this->assertNotEmpty($new->getCookie('yay'));
  753. $this->assertSame($cookie, $new->getCookieCollection()->get('yay'));
  754. }
  755. public function testWithExpiredCookieScalar()
  756. {
  757. $response = new Response();
  758. $response = $response->withCookie(new Cookie('testing', 'abc123'));
  759. $this->assertSame('abc123', $response->getCookie('testing')['value']);
  760. $new = $response->withExpiredCookie(new Cookie('testing'));
  761. $this->assertSame(0, $response->getCookie('testing')['expires']);
  762. $this->assertLessThan(FrozenTime::createFromTimestamp(1), (string)$new->getCookie('testing')['expires']);
  763. }
  764. /**
  765. * @throws \Exception If DateImmutable emits an error.
  766. */
  767. public function testWithExpiredCookieOptions()
  768. {
  769. $options = [
  770. 'name' => 'testing',
  771. 'value' => 'abc123',
  772. 'options' => [
  773. 'domain' => 'cakephp.org',
  774. 'path' => '/custompath/',
  775. 'secure' => true,
  776. 'httponly' => true,
  777. 'expires' => new \DateTimeImmutable('+14 days'),
  778. ],
  779. ];
  780. $cookie = Cookie::create(
  781. $options['name'],
  782. $options['value'],
  783. $options['options']
  784. );
  785. $response = new Response();
  786. $response = $response->withCookie($cookie);
  787. $options['options']['expires'] = $options['options']['expires']->format('U');
  788. $expected = ['name' => $options['name'], 'value' => $options['value']] + $options['options'];
  789. $this->assertEquals($expected, $response->getCookie('testing'));
  790. $expiredCookie = $response->withExpiredCookie($cookie);
  791. $this->assertEquals($expected['expires'], $response->getCookie('testing')['expires']);
  792. $this->assertLessThan(FrozenTime::createFromTimestamp(1), (string)$expiredCookie->getCookie('testing')['expires']);
  793. }
  794. /**
  795. * @return void
  796. */
  797. public function testWithExpiredCookieObject()
  798. {
  799. $response = new Response();
  800. $cookie = new Cookie('yay', 'a value');
  801. $response = $response->withCookie($cookie);
  802. $this->assertSame('a value', $response->getCookie('yay')['value']);
  803. $new = $response->withExpiredCookie($cookie);
  804. $this->assertSame(0, $response->getCookie('yay')['expires']);
  805. $this->assertSame(1, $new->getCookie('yay')['expires']);
  806. }
  807. /**
  808. * Test getCookies() and array data.
  809. *
  810. * @return void
  811. */
  812. public function testGetCookies()
  813. {
  814. $response = new Response();
  815. $new = $response->withCookie(new Cookie('testing', 'a'))
  816. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  817. $expected = [
  818. 'testing' => [
  819. 'name' => 'testing',
  820. 'value' => 'a',
  821. 'expires' => 0,
  822. 'path' => '/',
  823. 'domain' => '',
  824. 'secure' => false,
  825. 'httponly' => false,
  826. ],
  827. 'test2' => [
  828. 'name' => 'test2',
  829. 'value' => 'b',
  830. 'expires' => 0,
  831. 'path' => '/test',
  832. 'domain' => '',
  833. 'secure' => true,
  834. 'httponly' => false,
  835. ],
  836. ];
  837. $this->assertEquals($expected, $new->getCookies());
  838. }
  839. /**
  840. * Test getCookies() and array data.
  841. *
  842. * @return void
  843. */
  844. public function testGetCookiesArrayValue()
  845. {
  846. $response = new Response();
  847. $cookie = (new Cookie('urmc'))
  848. ->withValue(['user_id' => 1, 'token' => 'abc123'])
  849. ->withHttpOnly(true);
  850. $new = $response->withCookie($cookie);
  851. $expected = [
  852. 'urmc' => [
  853. 'name' => 'urmc',
  854. 'value' => '{"user_id":1,"token":"abc123"}',
  855. 'expires' => 0,
  856. 'path' => '/',
  857. 'domain' => '',
  858. 'secure' => false,
  859. 'httponly' => true,
  860. ],
  861. ];
  862. $this->assertEquals($expected, $new->getCookies());
  863. }
  864. /**
  865. * Test getCookieCollection() as array data
  866. *
  867. * @return void
  868. */
  869. public function testGetCookieCollection()
  870. {
  871. $response = new Response();
  872. $new = $response->withCookie(new Cookie('testing', 'a'))
  873. ->withCookie(new Cookie('test2', 'b', null, '/test', '', true));
  874. $cookies = $response->getCookieCollection();
  875. $this->assertInstanceOf(CookieCollection::class, $cookies);
  876. $this->assertCount(0, $cookies, 'Original response not mutated');
  877. $cookies = $new->getCookieCollection();
  878. $this->assertInstanceOf(CookieCollection::class, $cookies);
  879. $this->assertCount(2, $cookies);
  880. $this->assertTrue($cookies->has('testing'));
  881. $this->assertTrue($cookies->has('test2'));
  882. }
  883. /**
  884. * Test withCookieCollection()
  885. *
  886. * @return void
  887. */
  888. public function testWithCookieCollection()
  889. {
  890. $response = new Response();
  891. $collection = new CookieCollection([new Cookie('foo', 'bar')]);
  892. $newResponse = $response->withCookieCollection($collection);
  893. $this->assertNotSame($response, $newResponse);
  894. $this->assertNotSame($response->getCookieCollection(), $newResponse->getCookieCollection());
  895. $this->assertSame($newResponse->getCookie('foo')['value'], 'bar');
  896. }
  897. /**
  898. * Test that cors() returns a builder.
  899. *
  900. * @return void
  901. */
  902. public function testCors()
  903. {
  904. $request = new ServerRequest([
  905. 'environment' => ['HTTP_ORIGIN' => 'http://example.com'],
  906. ]);
  907. $response = new Response();
  908. $builder = $response->cors($request);
  909. $this->assertInstanceOf(CorsBuilder::class, $builder);
  910. $this->assertSame($response, $builder->build(), 'Empty builder returns same object');
  911. }
  912. /**
  913. * test withFile() not found
  914. *
  915. * @return void
  916. */
  917. public function testWithFileNotFound()
  918. {
  919. $this->expectException(\Cake\Http\Exception\NotFoundException::class);
  920. $this->expectExceptionMessage('The requested file /some/missing/folder/file.jpg was not found');
  921. $response = new Response();
  922. $response->withFile('/some/missing/folder/file.jpg');
  923. }
  924. /**
  925. * test withFile() not found
  926. *
  927. * @return void
  928. */
  929. public function testWithFileNotFoundNoDebug()
  930. {
  931. Configure::write('debug', 0);
  932. $this->expectException(\Cake\Http\Exception\NotFoundException::class);
  933. $this->expectExceptionMessage('The requested file was not found');
  934. $response = new Response();
  935. $response->withFile('/some/missing/folder/file.jpg');
  936. }
  937. /**
  938. * Provider for various kinds of unacceptable files.
  939. *
  940. * @return array
  941. */
  942. public function invalidFileProvider()
  943. {
  944. return [
  945. ['my/../cat.gif', 'The requested file contains `..` and will not be read.'],
  946. ['my\..\cat.gif', 'The requested file contains `..` and will not be read.'],
  947. ['my/ca..t.gif', 'my/ca..t.gif was not found or not readable'],
  948. ['my/ca..t/image.gif', 'my/ca..t/image.gif was not found or not readable'],
  949. ];
  950. }
  951. /**
  952. * test withFile and invalid paths
  953. *
  954. * @dataProvider invalidFileProvider
  955. * @return void
  956. */
  957. public function testWithFileInvalidPath($path, $expectedMessage)
  958. {
  959. $this->expectException(NotFoundException::class);
  960. $this->expectExceptionMessage($expectedMessage);
  961. $response = new Response();
  962. $response->withFile($path);
  963. }
  964. /**
  965. * test withFile() + download & name
  966. *
  967. * @return void
  968. */
  969. public function testWithFileDownloadAndName()
  970. {
  971. $response = new Response();
  972. $new = $response->withFile(
  973. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  974. [
  975. 'name' => 'something_special.css',
  976. 'download' => true,
  977. ]
  978. );
  979. $this->assertEquals(
  980. 'text/html; charset=UTF-8',
  981. $response->getHeaderLine('Content-Type'),
  982. 'No mutation'
  983. );
  984. $this->assertEquals(
  985. 'text/css; charset=UTF-8',
  986. $new->getHeaderLine('Content-Type')
  987. );
  988. $this->assertEquals(
  989. 'attachment; filename="something_special.css"',
  990. $new->getHeaderLine('Content-Disposition')
  991. );
  992. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  993. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  994. $body = $new->getBody();
  995. $this->assertInstanceOf('Laminas\Diactoros\Stream', $body);
  996. $expected = '/* this is the test asset css file */';
  997. $this->assertEquals($expected, trim($body->getContents()));
  998. $file = $new->getFile()->openFile();
  999. $this->assertEquals($expected, trim($file->fread(100)));
  1000. }
  1001. /**
  1002. * test withFile() + a generic agent
  1003. *
  1004. * @return void
  1005. */
  1006. public function testWithFileUnknownFileTypeGeneric()
  1007. {
  1008. $response = new Response();
  1009. $new = $response->withFile(CONFIG . 'no_section.ini');
  1010. $this->assertSame('text/html; charset=UTF-8', $new->getHeaderLine('Content-Type'));
  1011. $this->assertEquals(
  1012. 'attachment; filename="no_section.ini"',
  1013. $new->getHeaderLine('Content-Disposition')
  1014. );
  1015. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1016. $body = $new->getBody();
  1017. $expected = "some_key = some_value\nbool_key = 1\n";
  1018. $this->assertEquals($expected, $body->getContents());
  1019. }
  1020. /**
  1021. * test withFile() + opera
  1022. *
  1023. * @return void
  1024. */
  1025. public function testWithFileUnknownFileTypeOpera()
  1026. {
  1027. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  1028. $response = new Response();
  1029. $new = $response->withFile(CONFIG . 'no_section.ini');
  1030. $this->assertSame('application/octet-stream', $new->getHeaderLine('Content-Type'));
  1031. $this->assertEquals(
  1032. 'attachment; filename="no_section.ini"',
  1033. $new->getHeaderLine('Content-Disposition')
  1034. );
  1035. }
  1036. /**
  1037. * test withFile() + old IE
  1038. *
  1039. * @return void
  1040. */
  1041. public function testWithFileUnknownFileTypeOldIe()
  1042. {
  1043. $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)';
  1044. $response = new Response();
  1045. $new = $response->withFile(CONFIG . 'no_section.ini');
  1046. $this->assertSame('application/force-download', $new->getHeaderLine('Content-Type'));
  1047. }
  1048. /**
  1049. * test withFile() + no download
  1050. *
  1051. * @return void
  1052. */
  1053. public function testWithFileNoDownload()
  1054. {
  1055. $response = new Response();
  1056. $new = $response->withFile(CONFIG . 'no_section.ini', [
  1057. 'download' => false,
  1058. ]);
  1059. $this->assertEquals(
  1060. 'text/html; charset=UTF-8',
  1061. $new->getHeaderLine('Content-Type')
  1062. );
  1063. $this->assertFalse($new->hasHeader('Content-Disposition'));
  1064. $this->assertFalse($new->hasHeader('Content-Transfer-Encoding'));
  1065. }
  1066. /**
  1067. * Test that uppercase extensions result in correct content-types
  1068. *
  1069. * @return void
  1070. */
  1071. public function testWithFileUpperExtension()
  1072. {
  1073. $response = new Response();
  1074. $new = $response->withFile(TEST_APP . 'vendor/img/test_2.JPG');
  1075. $this->assertSame('image/jpeg', $new->getHeaderLine('Content-Type'));
  1076. }
  1077. /**
  1078. * A data provider for testing various ranges
  1079. *
  1080. * @return array
  1081. */
  1082. public static function rangeProvider()
  1083. {
  1084. return [
  1085. // suffix-byte-range
  1086. [
  1087. 'bytes=-25', 25, 'bytes 13-37/38',
  1088. ],
  1089. [
  1090. 'bytes=0-', 38, 'bytes 0-37/38',
  1091. ],
  1092. [
  1093. 'bytes=10-', 28, 'bytes 10-37/38',
  1094. ],
  1095. [
  1096. 'bytes=10-20', 11, 'bytes 10-20/38',
  1097. ],
  1098. // Spaced out
  1099. [
  1100. 'bytes = 10 - 20', 11, 'bytes 10-20/38',
  1101. ],
  1102. ];
  1103. }
  1104. /**
  1105. * Test withFile() & the various range offset types.
  1106. *
  1107. * @dataProvider rangeProvider
  1108. * @return void
  1109. */
  1110. public function testWithFileRangeOffsets($range, $length, $offsetResponse)
  1111. {
  1112. $_SERVER['HTTP_RANGE'] = $range;
  1113. $response = new Response();
  1114. $new = $response->withFile(
  1115. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1116. ['download' => true]
  1117. );
  1118. $this->assertEquals(
  1119. 'attachment; filename="test_asset.css"',
  1120. $new->getHeaderLine('Content-Disposition')
  1121. );
  1122. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1123. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1124. $this->assertEquals($length, $new->getHeaderLine('Content-Length'));
  1125. $this->assertEquals($offsetResponse, $new->getHeaderLine('Content-Range'));
  1126. }
  1127. /**
  1128. * Test withFile() fetching ranges from a file.
  1129. *
  1130. * @return void
  1131. */
  1132. public function testWithFileRange()
  1133. {
  1134. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1135. $response = new Response();
  1136. $new = $response->withFile(
  1137. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1138. ['download' => true]
  1139. );
  1140. $this->assertEquals(
  1141. 'attachment; filename="test_asset.css"',
  1142. $new->getHeaderLine('Content-Disposition')
  1143. );
  1144. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1145. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1146. $this->assertSame('18', $new->getHeaderLine('Content-Length'));
  1147. $this->assertSame('bytes 8-25/38', $new->getHeaderLine('Content-Range'));
  1148. $this->assertEquals(206, $new->getStatusCode());
  1149. }
  1150. /**
  1151. * Provider for invalid range header values.
  1152. *
  1153. * @return array
  1154. */
  1155. public function invalidFileRangeProvider()
  1156. {
  1157. return [
  1158. // malformed range
  1159. [
  1160. 'bytes=0,38',
  1161. ],
  1162. // malformed punctuation
  1163. [
  1164. 'bytes: 0 - 38',
  1165. ],
  1166. ];
  1167. }
  1168. /**
  1169. * Test withFile() and invalid ranges
  1170. *
  1171. * @dataProvider invalidFileRangeProvider
  1172. * @return void
  1173. */
  1174. public function testWithFileInvalidRange($range)
  1175. {
  1176. $_SERVER['HTTP_RANGE'] = $range;
  1177. $response = new Response();
  1178. $new = $response->withFile(
  1179. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1180. ['download' => true]
  1181. );
  1182. $this->assertEquals(
  1183. 'attachment; filename="test_asset.css"',
  1184. $new->getHeaderLine('Content-Disposition')
  1185. );
  1186. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1187. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1188. $this->assertSame('38', $new->getHeaderLine('Content-Length'));
  1189. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1190. $this->assertEquals(206, $new->getStatusCode());
  1191. }
  1192. /**
  1193. * Test withFile() and a reversed range
  1194. *
  1195. * @return void
  1196. */
  1197. public function testWithFileReversedRange()
  1198. {
  1199. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1200. $response = new Response();
  1201. $new = $response->withFile(
  1202. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1203. ['download' => true]
  1204. );
  1205. $this->assertEquals(
  1206. 'attachment; filename="test_asset.css"',
  1207. $new->getHeaderLine('Content-Disposition')
  1208. );
  1209. $this->assertSame('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1210. $this->assertSame('bytes', $new->getHeaderLine('Accept-Ranges'));
  1211. $this->assertSame('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  1212. $this->assertEquals(416, $new->getStatusCode());
  1213. }
  1214. /**
  1215. * Test the withLocation method.
  1216. *
  1217. * @return void
  1218. */
  1219. public function testWithLocation()
  1220. {
  1221. $response = new Response();
  1222. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  1223. $new = $response->withLocation('http://example.org');
  1224. $this->assertNotSame($new, $response);
  1225. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  1226. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  1227. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  1228. }
  1229. /**
  1230. * Test get protocol version.
  1231. *
  1232. * @return void
  1233. */
  1234. public function getProtocolVersion()
  1235. {
  1236. $response = new Response();
  1237. $version = $response->getProtocolVersion();
  1238. $this->assertSame('1.1', $version);
  1239. }
  1240. /**
  1241. * Test with protocol.
  1242. *
  1243. * @return void
  1244. */
  1245. public function testWithProtocol()
  1246. {
  1247. $response = new Response();
  1248. $version = $response->getProtocolVersion();
  1249. $this->assertSame('1.1', $version);
  1250. $response2 = $response->withProtocolVersion('1.0');
  1251. $version = $response2->getProtocolVersion();
  1252. $this->assertSame('1.0', $version);
  1253. $version = $response->getProtocolVersion();
  1254. $this->assertSame('1.1', $version);
  1255. $this->assertNotEquals($response, $response2);
  1256. }
  1257. /**
  1258. * Test with protocol.
  1259. *
  1260. * @return void
  1261. */
  1262. public function testWithStatusCode()
  1263. {
  1264. $response = new Response();
  1265. $statusCode = $response->getStatusCode();
  1266. $this->assertEquals(200, $statusCode);
  1267. $response2 = $response->withStatus(404);
  1268. $statusCode = $response2->getStatusCode();
  1269. $this->assertEquals(404, $statusCode);
  1270. $statusCode = $response->getStatusCode();
  1271. $this->assertEquals(200, $statusCode);
  1272. $this->assertNotEquals($response, $response2);
  1273. }
  1274. /**
  1275. * Test invalid status codes
  1276. *
  1277. * @return void
  1278. */
  1279. public function testWithStatusInvalid()
  1280. {
  1281. $this->expectException(\InvalidArgumentException::class);
  1282. $this->expectExceptionMessage('Invalid status code: 1001. Use a valid HTTP status code in range 1xx - 5xx.');
  1283. $response = new Response();
  1284. $response->withStatus(1001);
  1285. }
  1286. /**
  1287. * Test get reason phrase.
  1288. *
  1289. * @return void
  1290. */
  1291. public function testGetReasonPhrase()
  1292. {
  1293. $response = new Response();
  1294. $this->assertSame('OK', $response->getReasonPhrase());
  1295. $response = $response->withStatus(404);
  1296. $reasonPhrase = $response->getReasonPhrase();
  1297. $this->assertSame('Not Found', $reasonPhrase);
  1298. }
  1299. /**
  1300. * Test with body.
  1301. *
  1302. * @return void
  1303. */
  1304. public function testWithBody()
  1305. {
  1306. $response = new Response();
  1307. $body = $response->getBody();
  1308. $body->rewind();
  1309. $result = $body->getContents();
  1310. $this->assertSame('', $result);
  1311. $stream = new Stream('php://memory', 'wb+');
  1312. $stream->write('test1');
  1313. $response2 = $response->withBody($stream);
  1314. $body = $response2->getBody();
  1315. $body->rewind();
  1316. $result = $body->getContents();
  1317. $this->assertSame('test1', $result);
  1318. $body = $response->getBody();
  1319. $body->rewind();
  1320. $result = $body->getContents();
  1321. $this->assertSame('', $result);
  1322. }
  1323. /**
  1324. * Test with string body.
  1325. *
  1326. * @return void
  1327. */
  1328. public function testWithStringBody()
  1329. {
  1330. $response = new Response();
  1331. $newResponse = $response->withStringBody('Foo');
  1332. $body = $newResponse->getBody();
  1333. $this->assertSame('Foo', (string)$body);
  1334. $this->assertNotSame($response, $newResponse);
  1335. $response = new Response();
  1336. $newResponse = $response->withStringBody('');
  1337. $body = $newResponse->getBody();
  1338. $this->assertSame('', (string)$body);
  1339. $this->assertNotSame($response, $newResponse);
  1340. $response = new Response();
  1341. $newResponse = $response->withStringBody(null);
  1342. $body = $newResponse->getBody();
  1343. $this->assertSame('', (string)$body);
  1344. $this->assertNotSame($response, $newResponse);
  1345. $response = new Response();
  1346. $newResponse = $response->withStringBody('1337');
  1347. $body = $newResponse->getBody();
  1348. $this->assertSame('1337', (string)$body);
  1349. $this->assertNotSame($response, $newResponse);
  1350. }
  1351. /**
  1352. * Test get Body.
  1353. *
  1354. * @return void
  1355. */
  1356. public function testGetBody()
  1357. {
  1358. $response = new Response();
  1359. $stream = $response->getBody();
  1360. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  1361. }
  1362. /**
  1363. * Test with header.
  1364. *
  1365. * @return void
  1366. */
  1367. public function testWithHeader()
  1368. {
  1369. $response = new Response();
  1370. $response2 = $response->withHeader('Accept', 'application/json');
  1371. $result = $response2->getHeaders();
  1372. $expected = [
  1373. 'Content-Type' => ['text/html; charset=UTF-8'],
  1374. 'Accept' => ['application/json'],
  1375. ];
  1376. $this->assertEquals($expected, $result);
  1377. $this->assertFalse($response->hasHeader('Accept'));
  1378. }
  1379. /**
  1380. * Test get headers.
  1381. *
  1382. * @return void
  1383. */
  1384. public function testGetHeaders()
  1385. {
  1386. $response = new Response();
  1387. $headers = $response->getHeaders();
  1388. $response = $response->withAddedHeader('Location', 'localhost');
  1389. $response = $response->withAddedHeader('Accept', 'application/json');
  1390. $headers = $response->getHeaders();
  1391. $expected = [
  1392. 'Content-Type' => ['text/html; charset=UTF-8'],
  1393. 'Location' => ['localhost'],
  1394. 'Accept' => ['application/json'],
  1395. ];
  1396. $this->assertEquals($expected, $headers);
  1397. }
  1398. /**
  1399. * Test without header.
  1400. *
  1401. * @return void
  1402. */
  1403. public function testWithoutHeader()
  1404. {
  1405. $response = new Response();
  1406. $response = $response->withAddedHeader('Location', 'localhost');
  1407. $response = $response->withAddedHeader('Accept', 'application/json');
  1408. $response2 = $response->withoutHeader('Location');
  1409. $headers = $response2->getHeaders();
  1410. $expected = [
  1411. 'Content-Type' => ['text/html; charset=UTF-8'],
  1412. 'Accept' => ['application/json'],
  1413. ];
  1414. $this->assertEquals($expected, $headers);
  1415. }
  1416. /**
  1417. * Test get header.
  1418. *
  1419. * @return void
  1420. */
  1421. public function testGetHeader()
  1422. {
  1423. $response = new Response();
  1424. $response = $response->withAddedHeader('Location', 'localhost');
  1425. $result = $response->getHeader('Location');
  1426. $this->assertEquals(['localhost'], $result);
  1427. $result = $response->getHeader('location');
  1428. $this->assertEquals(['localhost'], $result);
  1429. $result = $response->getHeader('does-not-exist');
  1430. $this->assertEquals([], $result);
  1431. }
  1432. /**
  1433. * Test get header line.
  1434. *
  1435. * @return void
  1436. */
  1437. public function testGetHeaderLine()
  1438. {
  1439. $response = new Response();
  1440. $headers = $response->getHeaderLine('Accept');
  1441. $this->assertSame('', $headers);
  1442. $response = $response->withAddedHeader('Accept', 'application/json');
  1443. $response = $response->withAddedHeader('Accept', 'application/xml');
  1444. $result = $response->getHeaderLine('Accept');
  1445. $expected = 'application/json,application/xml';
  1446. $this->assertEquals($expected, $result);
  1447. $result = $response->getHeaderLine('accept');
  1448. $this->assertEquals($expected, $result);
  1449. }
  1450. /**
  1451. * Test has header.
  1452. *
  1453. * @return void
  1454. */
  1455. public function testHasHeader()
  1456. {
  1457. $response = new Response();
  1458. $response = $response->withAddedHeader('Location', 'localhost');
  1459. $this->assertTrue($response->hasHeader('Location'));
  1460. $this->assertTrue($response->hasHeader('location'));
  1461. $this->assertTrue($response->hasHeader('locATIon'));
  1462. $this->assertFalse($response->hasHeader('Accept'));
  1463. $this->assertFalse($response->hasHeader('accept'));
  1464. }
  1465. /**
  1466. * Tests __debugInfo
  1467. *
  1468. * @return void
  1469. */
  1470. public function testDebugInfo()
  1471. {
  1472. $response = new Response();
  1473. $response = $response->withStringBody('Foo');
  1474. $result = $response->__debugInfo();
  1475. $expected = [
  1476. 'status' => 200,
  1477. 'contentType' => 'text/html',
  1478. 'headers' => [
  1479. 'Content-Type' => ['text/html; charset=UTF-8'],
  1480. ],
  1481. 'file' => null,
  1482. 'fileRange' => [],
  1483. 'cookies' => new CookieCollection(),
  1484. 'cacheDirectives' => [],
  1485. 'body' => 'Foo',
  1486. ];
  1487. $this->assertEquals($expected, $result);
  1488. }
  1489. }