ResponseTest.php 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Network;
  16. use Cake\Network\Request;
  17. use Cake\Network\Response;
  18. use Cake\TestSuite\TestCase;
  19. use Zend\Diactoros\Stream;
  20. /**
  21. * ResponseTest
  22. */
  23. class ResponseTest extends TestCase
  24. {
  25. /**
  26. * Setup for tests
  27. *
  28. * @return void
  29. */
  30. public function setUp()
  31. {
  32. parent::setUp();
  33. include_once __DIR__ . DS . 'mocks.php';
  34. }
  35. /**
  36. * Cleanup after tests
  37. *
  38. * @return void
  39. */
  40. public function tearDown()
  41. {
  42. parent::tearDown();
  43. }
  44. /**
  45. * Tests the request object constructor
  46. *
  47. * @return void
  48. */
  49. public function testConstruct()
  50. {
  51. $response = new Response();
  52. $this->assertNull($response->body());
  53. $this->assertEquals('UTF-8', $response->charset());
  54. $this->assertEquals('text/html', $response->type());
  55. $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  56. $this->assertEquals(200, $response->statusCode());
  57. $options = [
  58. 'body' => 'This is the body',
  59. 'charset' => 'my-custom-charset',
  60. 'type' => 'mp3',
  61. 'status' => '203'
  62. ];
  63. $response = new Response($options);
  64. $this->assertEquals('This is the body', $response->body());
  65. $this->assertEquals('my-custom-charset', $response->charset());
  66. $this->assertEquals('audio/mpeg', $response->type());
  67. $this->assertEquals('audio/mpeg', $response->getHeaderLine('Content-Type'));
  68. $this->assertEquals(203, $response->statusCode());
  69. $options = [
  70. 'body' => 'This is the body',
  71. 'charset' => 'ISO-8859-1',
  72. 'type' => 'txt',
  73. 'status' => '422',
  74. 'statusCodes' => [
  75. 422 => 'Unprocessable Entity'
  76. ]
  77. ];
  78. $response = new Response($options);
  79. $this->assertEquals($options['body'], $response->body());
  80. $this->assertEquals($options['charset'], $response->charset());
  81. $this->assertEquals($response->getMimeType($options['type']), $response->type());
  82. $this->assertEquals($options['status'], $response->statusCode());
  83. $this->assertEquals('text/plain; charset=ISO-8859-1', $response->getHeaderLine('Content-Type'));
  84. }
  85. /**
  86. * Tests the body method
  87. *
  88. * @return void
  89. */
  90. public function testBody()
  91. {
  92. $response = new Response();
  93. $this->assertNull($response->body());
  94. $response->body('Response body');
  95. $this->assertEquals('Response body', $response->body());
  96. $this->assertEquals('Changed Body', $response->body('Changed Body'));
  97. $response = new Response();
  98. $response->body(0);
  99. $this->assertEquals(0, $response->body());
  100. $response = new Response();
  101. $response->body('0');
  102. $this->assertEquals('0', $response->body());
  103. $response = new Response();
  104. $response->body(null);
  105. $this->assertEquals(null, $response->body());
  106. }
  107. /**
  108. * Tests the charset method
  109. *
  110. * @return void
  111. */
  112. public function testCharset()
  113. {
  114. $response = new Response();
  115. $this->assertEquals('UTF-8', $response->charset());
  116. $response->charset('iso-8859-1');
  117. $this->assertEquals('iso-8859-1', $response->charset());
  118. $this->assertEquals('UTF-16', $response->charset('UTF-16'));
  119. }
  120. /**
  121. * Tests withCharset method
  122. *
  123. * @return void
  124. */
  125. public function testWithCharset()
  126. {
  127. $response = new Response();
  128. $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  129. $new = $response->withCharset('iso-8859-1');
  130. $this->assertNotContains('iso', $response->getHeaderLine('Content-Type'), 'Old instance not changed');
  131. $this->assertEquals('text/html; charset=iso-8859-1', $new->getHeaderLine('Content-Type'));
  132. }
  133. /**
  134. * Tests the statusCode method
  135. *
  136. * @expectedException \InvalidArgumentException
  137. * @return void
  138. */
  139. public function testStatusCode()
  140. {
  141. $response = new Response();
  142. $this->assertEquals(200, $response->statusCode());
  143. $response->statusCode(404);
  144. $this->assertEquals(404, $response->statusCode());
  145. $this->assertEquals(500, $response->statusCode(500));
  146. //Throws exception
  147. $response->statusCode(1001);
  148. }
  149. /**
  150. * Tests the type method
  151. *
  152. * @return void
  153. */
  154. public function testType()
  155. {
  156. $response = new Response();
  157. $this->assertEquals('text/html', $response->type());
  158. $response->type('pdf');
  159. $this->assertEquals('application/pdf', $response->type());
  160. $this->assertEquals('application/crazy-mime', $response->type('application/crazy-mime'));
  161. $this->assertEquals('application/json', $response->type('json'));
  162. $this->assertEquals('text/vnd.wap.wml', $response->type('wap'));
  163. $this->assertEquals('application/vnd.wap.xhtml+xml', $response->type('xhtml-mobile'));
  164. $this->assertEquals('text/csv', $response->type('csv'));
  165. $response->type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);
  166. $this->assertEquals('application/keynote', $response->type('keynote'));
  167. $this->assertEquals('application/bat', $response->type('bat'));
  168. $this->assertFalse($response->type('wackytype'));
  169. }
  170. /**
  171. * Tests the withType method
  172. *
  173. * @return void
  174. */
  175. public function testWithTypeAlias()
  176. {
  177. $response = new Response();
  178. $this->assertEquals(
  179. 'text/html; charset=UTF-8',
  180. $response->getHeaderLine('Content-Type'),
  181. 'Default content-type should match'
  182. );
  183. $new = $response->withType('pdf');
  184. $this->assertNotSame($new, $response, 'Should be a new instance');
  185. $this->assertSame(
  186. 'text/html; charset=UTF-8',
  187. $response->getHeaderLine('Content-Type'),
  188. 'Original object should not be modified'
  189. );
  190. $this->assertSame('application/pdf', $new->getHeaderLine('Content-Type'));
  191. $this->assertSame(
  192. 'application/json; charset=UTF-8',
  193. $new->withType('json')->getHeaderLine('Content-Type')
  194. );
  195. }
  196. /**
  197. * test withType() and full mime-types
  198. *
  199. * @return void
  200. */
  201. public function withTypeFull()
  202. {
  203. $response = new Response();
  204. $this->assertEquals(
  205. 'application/json',
  206. $response->withType('application/json')->getHeaderLine('Content-Type'),
  207. 'Should not add charset to explicit type'
  208. );
  209. $this->assertEquals(
  210. 'custom/stuff',
  211. $response->withType('custom/stuff')->getHeaderLine('Content-Type'),
  212. 'Should allow arbitrary types'
  213. );
  214. }
  215. /**
  216. * Test that an invalid type raises an exception
  217. *
  218. * @expectedException InvalidArgumentException
  219. * @expectedExceptionMessage "beans" is an invalid content type
  220. * @return void
  221. */
  222. public function testWithTypeInvalidType()
  223. {
  224. $response = new Response();
  225. $response->withType('beans');
  226. }
  227. /**
  228. * Tests the header method
  229. *
  230. * @return void
  231. */
  232. public function testHeader()
  233. {
  234. $response = new Response();
  235. $headers = [
  236. 'Content-Type' => 'text/html; charset=UTF-8',
  237. ];
  238. $this->assertEquals($headers, $response->header());
  239. $response->header('Location', 'http://example.com');
  240. $headers += ['Location' => 'http://example.com'];
  241. $this->assertEquals($headers, $response->header());
  242. // Headers with the same name are overwritten
  243. $response->header('Location', 'http://example2.com');
  244. $headers = [
  245. 'Content-Type' => 'text/html; charset=UTF-8',
  246. 'Location' => 'http://example2.com'
  247. ];
  248. $this->assertEquals($headers, $response->header());
  249. $response->header(['WWW-Authenticate' => 'Negotiate']);
  250. $headers += ['WWW-Authenticate' => 'Negotiate'];
  251. $this->assertEquals($headers, $response->header());
  252. $response->header(['WWW-Authenticate' => 'Not-Negotiate']);
  253. $headers['WWW-Authenticate'] = 'Not-Negotiate';
  254. $this->assertEquals($headers, $response->header());
  255. $response->header(['Age' => 12, 'Allow' => 'GET, HEAD']);
  256. $headers += ['Age' => 12, 'Allow' => 'GET, HEAD'];
  257. $this->assertEquals($headers, $response->header());
  258. // String headers are allowed
  259. $response->header('Content-Language: da');
  260. $headers += ['Content-Language' => 'da'];
  261. $this->assertEquals($headers, $response->header());
  262. $response->header('Content-Language: da');
  263. $headers += ['Content-Language' => 'da'];
  264. $this->assertEquals($headers, $response->header());
  265. $response->header(['Content-Encoding: gzip', 'Vary: *', 'Pragma' => 'no-cache']);
  266. $headers += ['Content-Encoding' => 'gzip', 'Vary' => '*', 'Pragma' => 'no-cache'];
  267. $this->assertEquals($headers, $response->header());
  268. $response->header('Access-Control-Allow-Origin', ['domain1', 'domain2']);
  269. $headers += ['Access-Control-Allow-Origin' => ['domain1', 'domain2']];
  270. $this->assertEquals($headers, $response->header());
  271. }
  272. /**
  273. * Tests the send method
  274. *
  275. * @return void
  276. */
  277. public function testSend()
  278. {
  279. $response = $this->getMockBuilder('Cake\Network\Response')
  280. ->setMethods(['_sendHeader', '_sendContent', '_setCookies'])
  281. ->getMock();
  282. $response->header([
  283. 'Content-Language' => 'es',
  284. 'WWW-Authenticate' => 'Negotiate',
  285. 'Access-Control-Allow-Origin' => ['domain1', 'domain2'],
  286. ]);
  287. $response->body('the response body');
  288. $response->expects($this->once())->method('_sendContent')->with('the response body');
  289. $response->expects($this->at(0))->method('_setCookies');
  290. $response->expects($this->at(1))
  291. ->method('_sendHeader')->with('HTTP/1.1 200 OK');
  292. $response->expects($this->at(2))
  293. ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8');
  294. $response->expects($this->at(3))
  295. ->method('_sendHeader')->with('Content-Language', 'es');
  296. $response->expects($this->at(4))
  297. ->method('_sendHeader')->with('WWW-Authenticate', 'Negotiate');
  298. $response->expects($this->at(5))
  299. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain1');
  300. $response->expects($this->at(6))
  301. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain2');
  302. $response->send();
  303. }
  304. /**
  305. * Data provider for content type tests.
  306. *
  307. * @return array
  308. */
  309. public static function charsetTypeProvider()
  310. {
  311. return [
  312. ['mp3', 'audio/mpeg'],
  313. ['js', 'application/javascript; charset=UTF-8'],
  314. ['json', 'application/json; charset=UTF-8'],
  315. ['xml', 'application/xml; charset=UTF-8'],
  316. ['txt', 'text/plain; charset=UTF-8'],
  317. ];
  318. }
  319. /**
  320. * Tests the send method and changing the content type
  321. *
  322. * @dataProvider charsetTypeProvider
  323. * @return void
  324. */
  325. public function testSendChangingContentType($original, $expected)
  326. {
  327. $response = new Response();
  328. $response->type($original);
  329. $response->body('the response body');
  330. $this->assertEquals($expected, $response->getHeaderLine('Content-Type'));
  331. }
  332. /**
  333. * Tests the send method and changing the content type to JS without adding the charset
  334. *
  335. * @return void
  336. */
  337. public function testCharsetSetContentTypeWithoutCharset()
  338. {
  339. $response = new Response();
  340. $response->type('js');
  341. $response->charset('');
  342. $this->assertEquals('application/javascript', $response->getHeaderLine('Content-Type'));
  343. }
  344. /**
  345. * Tests the send method and changing the content type
  346. *
  347. * @return void
  348. */
  349. public function testLocationSetsStatus()
  350. {
  351. $response = new Response();
  352. $response->location('http://www.example.com');
  353. $this->assertEquals(302, $response->getStatusCode());
  354. }
  355. /**
  356. * Test that setting certain status codes clears the status code.
  357. *
  358. * @return void
  359. */
  360. public function testStatusClearsContentType()
  361. {
  362. $response = new Response();
  363. $response->statusCode(204);
  364. $response->statusCode(304);
  365. $this->assertFalse($response->hasHeader('Content-Type'));
  366. $this->assertSame(304, $response->getStatusCode());
  367. $response = new Response();
  368. $response->type('pdf');
  369. $response->statusCode(204);
  370. $this->assertFalse($response->hasHeader('Content-Type'));
  371. $this->assertSame(204, $response->getStatusCode());
  372. $response = new Response();
  373. $new = $response->withType('pdf')
  374. ->withStatus(204);
  375. $this->assertFalse($new->hasHeader('Content-Type'));
  376. $this->assertSame(204, $new->getStatusCode());
  377. $response = new Response();
  378. $new = $response->withStatus(304)
  379. ->withType('pdf');
  380. $this->assertFalse($new->hasHeader('Content-Type'));
  381. $response = new Response();
  382. $response->statusCode(204);
  383. $response->type('pdf');
  384. $this->assertFalse($response->hasHeader('Content-Type'));
  385. }
  386. /**
  387. * Tests the send method and changing the content type
  388. *
  389. * @return void
  390. */
  391. public function testSendWithCallableBody()
  392. {
  393. $response = $this->getMockBuilder('Cake\Network\Response')
  394. ->setMethods(['_sendHeader'])
  395. ->getMock();
  396. $response->body(function () {
  397. echo 'the response body';
  398. });
  399. ob_start();
  400. $response->send();
  401. $this->assertEquals('the response body', ob_get_clean());
  402. }
  403. /**
  404. * Tests that the returned a string from a body callable is also sent
  405. * as the response body
  406. *
  407. * @return void
  408. */
  409. public function testSendWithCallableBodyWithReturn()
  410. {
  411. $response = $this->getMockBuilder('Cake\Network\Response')
  412. ->setMethods(['_sendHeader'])
  413. ->getMock();
  414. $response->body(function () {
  415. return 'the response body';
  416. });
  417. ob_start();
  418. $response->send();
  419. $this->assertEquals('the response body', ob_get_clean());
  420. }
  421. /**
  422. * Tests the disableCache method
  423. *
  424. * @return void
  425. */
  426. public function testDisableCache()
  427. {
  428. $response = new Response();
  429. $expected = [
  430. 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
  431. 'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT",
  432. 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  433. 'Content-Type' => 'text/html; charset=UTF-8',
  434. ];
  435. $response->disableCache();
  436. $this->assertEquals($expected, $response->header());
  437. }
  438. /**
  439. * Tests the withDisabledCache method
  440. *
  441. * @return void
  442. */
  443. public function testWithDisabledCache()
  444. {
  445. $response = new Response();
  446. $expected = [
  447. 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
  448. 'Last-Modified' => [gmdate("D, d M Y H:i:s") . " GMT"],
  449. 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
  450. 'Content-Type' => ['text/html; charset=UTF-8'],
  451. ];
  452. $new = $response->withDisabledCache();
  453. $this->assertFalse($response->hasHeader('Expires'), 'Old instance not mutated.');
  454. $this->assertEquals($expected, $new->getHeaders());
  455. }
  456. /**
  457. * Tests the cache method
  458. *
  459. * @return void
  460. */
  461. public function testCache()
  462. {
  463. $response = new Response();
  464. $since = time();
  465. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  466. $response->expires('+1 day');
  467. $expected = [
  468. 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
  469. 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
  470. 'Expires' => $time->format('D, j M Y H:i:s') . ' GMT',
  471. 'Cache-Control' => 'public, max-age=' . ($time->format('U') - time()),
  472. 'Content-Type' => 'text/html; charset=UTF-8',
  473. ];
  474. $response->cache($since);
  475. $this->assertEquals($expected, $response->header());
  476. $response = new Response();
  477. $since = time();
  478. $time = '+5 day';
  479. $expected = [
  480. 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
  481. 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
  482. 'Expires' => gmdate("D, j M Y H:i:s", strtotime($time)) . " GMT",
  483. 'Cache-Control' => 'public, max-age=' . (strtotime($time) - time()),
  484. 'Content-Type' => 'text/html; charset=UTF-8',
  485. ];
  486. $response->cache($since, $time);
  487. $this->assertEquals($expected, $response->header());
  488. $response = new Response();
  489. $since = time();
  490. $time = time();
  491. $expected = [
  492. 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
  493. 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
  494. 'Expires' => gmdate("D, j M Y H:i:s", $time) . " GMT",
  495. 'Cache-Control' => 'public, max-age=0',
  496. 'Content-Type' => 'text/html; charset=UTF-8',
  497. ];
  498. $response->cache($since, $time);
  499. $this->assertEquals($expected, $response->header());
  500. }
  501. /**
  502. * Tests the compress method
  503. *
  504. * @return void
  505. */
  506. public function testCompress()
  507. {
  508. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  509. $response = new Response();
  510. if (ini_get("zlib.output_compression") === '1' || !extension_loaded("zlib")) {
  511. $this->assertFalse($response->compress());
  512. $this->markTestSkipped('Is not possible to test output compression');
  513. }
  514. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  515. $result = $response->compress();
  516. $this->assertFalse($result);
  517. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  518. $result = $response->compress();
  519. $this->assertTrue($result);
  520. $this->assertTrue(in_array('ob_gzhandler', ob_list_handlers()));
  521. ob_get_clean();
  522. }
  523. /**
  524. * Tests the httpCodes method
  525. *
  526. * @expectedException \InvalidArgumentException
  527. * @return void
  528. */
  529. public function testHttpCodes()
  530. {
  531. $response = new Response();
  532. $result = $response->httpCodes();
  533. $this->assertEquals(65, count($result));
  534. $result = $response->httpCodes(100);
  535. $expected = [100 => 'Continue'];
  536. $this->assertEquals($expected, $result);
  537. $codes = [
  538. 381 => 'Unicorn Moved',
  539. 555 => 'Unexpected Minotaur'
  540. ];
  541. $result = $response->httpCodes($codes);
  542. $this->assertTrue($result);
  543. $this->assertEquals(67, count($response->httpCodes()));
  544. $result = $response->httpCodes(381);
  545. $expected = [381 => 'Unicorn Moved'];
  546. $this->assertEquals($expected, $result);
  547. $codes = [404 => 'Sorry Bro'];
  548. $result = $response->httpCodes($codes);
  549. $this->assertTrue($result);
  550. $this->assertEquals(67, count($response->httpCodes()));
  551. $result = $response->httpCodes(404);
  552. $expected = [404 => 'Sorry Bro'];
  553. $this->assertEquals($expected, $result);
  554. //Throws exception
  555. $response->httpCodes([
  556. 0 => 'Nothing Here',
  557. -1 => 'Reverse Infinity',
  558. 12345 => 'Universal Password',
  559. 'Hello' => 'World'
  560. ]);
  561. }
  562. /**
  563. * Tests the download method
  564. *
  565. * @return void
  566. */
  567. public function testDownload()
  568. {
  569. $response = new Response();
  570. $expected = [
  571. 'Content-Type' => 'text/html; charset=UTF-8',
  572. 'Content-Disposition' => 'attachment; filename="myfile.mp3"'
  573. ];
  574. $response->download('myfile.mp3');
  575. $this->assertEquals($expected, $response->header());
  576. }
  577. /**
  578. * Tests the mapType method
  579. *
  580. * @return void
  581. */
  582. public function testMapType()
  583. {
  584. $response = new Response();
  585. $this->assertEquals('wav', $response->mapType('audio/x-wav'));
  586. $this->assertEquals('pdf', $response->mapType('application/pdf'));
  587. $this->assertEquals('xml', $response->mapType('text/xml'));
  588. $this->assertEquals('html', $response->mapType('*/*'));
  589. $this->assertEquals('csv', $response->mapType('application/vnd.ms-excel'));
  590. $expected = ['json', 'xhtml', 'css'];
  591. $result = $response->mapType(['application/json', 'application/xhtml+xml', 'text/css']);
  592. $this->assertEquals($expected, $result);
  593. }
  594. /**
  595. * Tests the outputCompressed method
  596. *
  597. * @return void
  598. */
  599. public function testOutputCompressed()
  600. {
  601. $response = new Response();
  602. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  603. $result = $response->outputCompressed();
  604. $this->assertFalse($result);
  605. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  606. $result = $response->outputCompressed();
  607. $this->assertFalse($result);
  608. if (!extension_loaded("zlib")) {
  609. $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
  610. }
  611. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  612. if (ini_get("zlib.output_compression") !== '1') {
  613. ob_start('ob_gzhandler');
  614. }
  615. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  616. $result = $response->outputCompressed();
  617. $this->assertTrue($result);
  618. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  619. $result = $response->outputCompressed();
  620. $this->assertFalse($result);
  621. if (ini_get("zlib.output_compression") !== '1') {
  622. ob_get_clean();
  623. }
  624. }
  625. /**
  626. * Tests getting/setting the protocol
  627. *
  628. * @return void
  629. */
  630. public function testProtocol()
  631. {
  632. $response = $this->getMockBuilder('Cake\Network\Response')
  633. ->setMethods(['_sendHeader', '_sendContent'])
  634. ->getMock();
  635. $response->protocol('HTTP/1.0');
  636. $this->assertEquals('HTTP/1.0', $response->protocol());
  637. $response->expects($this->at(0))
  638. ->method('_sendHeader')->with('HTTP/1.0 200 OK');
  639. $response->send();
  640. }
  641. /**
  642. * Tests getting/setting the Content-Length
  643. *
  644. * @return void
  645. */
  646. public function testLength()
  647. {
  648. $response = new Response();
  649. $response->length(100);
  650. $this->assertEquals(100, $response->length());
  651. $this->assertEquals('100', $response->getHeaderLine('Content-Length'));
  652. }
  653. /**
  654. * Tests settings the content length
  655. *
  656. * @return void
  657. */
  658. public function testWithLength()
  659. {
  660. $response = new Response();
  661. $this->assertFalse($response->hasHeader('Content-Length'));
  662. $new = $response->withLength(100);
  663. $this->assertFalse($response->hasHeader('Content-Length'), 'Old instance not modified');
  664. $this->assertSame('100', $new->getHeaderLine('Content-Length'));
  665. $this->assertSame('100', $new->length(), 'new method is compat with old.');
  666. }
  667. /**
  668. * Tests setting the expiration date
  669. *
  670. * @return void
  671. */
  672. public function testExpires()
  673. {
  674. $format = 'D, j M Y H:i:s';
  675. $response = new Response();
  676. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  677. $response->expires($now);
  678. $now->setTimeZone(new \DateTimeZone('UTC'));
  679. $this->assertEquals($now->format($format) . ' GMT', $response->expires());
  680. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  681. $now = time();
  682. $response = new Response();
  683. $response->expires($now);
  684. $this->assertEquals(gmdate($format) . ' GMT', $response->expires());
  685. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Expires'));
  686. $response = new Response();
  687. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  688. $response->expires('+1 day');
  689. $this->assertEquals($time->format($format) . ' GMT', $response->expires());
  690. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  691. }
  692. /**
  693. * Tests setting the modification date
  694. *
  695. * @return void
  696. */
  697. public function testModified()
  698. {
  699. $format = 'D, j M Y H:i:s';
  700. $response = new Response();
  701. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  702. $response->modified($now);
  703. $now->setTimeZone(new \DateTimeZone('UTC'));
  704. $this->assertEquals($now->format($format) . ' GMT', $response->modified());
  705. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  706. $response = new Response();
  707. $now = time();
  708. $response->modified($now);
  709. $this->assertEquals(gmdate($format) . ' GMT', $response->modified());
  710. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  711. $response = new Response();
  712. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  713. $response->modified('+1 day');
  714. $this->assertEquals($time->format($format) . ' GMT', $response->modified());
  715. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  716. }
  717. /**
  718. * Tests setting of public/private Cache-Control directives
  719. *
  720. * @return void
  721. */
  722. public function testSharable()
  723. {
  724. $response = new Response();
  725. $this->assertNull($response->sharable());
  726. $response->sharable(true);
  727. $this->assertTrue($response->sharable());
  728. $this->assertEquals('public', $response->getHeaderLine('Cache-Control'));
  729. $response = new Response();
  730. $response->sharable(false);
  731. $this->assertFalse($response->sharable());
  732. $this->assertEquals('private', $response->getHeaderLine('Cache-Control'));
  733. $response = new Response();
  734. $response->sharable(true, 3600);
  735. $this->assertEquals('public, max-age=3600', $response->getHeaderLine('Cache-Control'));
  736. $response = new Response();
  737. $response->sharable(false, 3600);
  738. $this->assertEquals('private, max-age=3600', $response->getHeaderLine('Cache-Control'));
  739. }
  740. /**
  741. * Tests withSharable()
  742. *
  743. * @return void
  744. */
  745. public function testWithSharable()
  746. {
  747. $response = new Response();
  748. $new = $response->withSharable(true);
  749. $this->assertFalse($response->hasHeader('Cache-Control'), 'old instance unchanged');
  750. $this->assertEquals('public', $new->getHeaderLine('Cache-Control'));
  751. $new = $response->withSharable(false);
  752. $this->assertEquals('private', $new->getHeaderLine('Cache-Control'));
  753. $new = $response->withSharable(true, 3600);
  754. $this->assertEquals('public, max-age=3600', $new->getHeaderLine('Cache-Control'));
  755. $new = $response->withSharable(false, 3600);
  756. $this->assertEquals('private, max-age=3600', $new->getHeaderLine('Cache-Control'));
  757. }
  758. /**
  759. * Tests setting of max-age Cache-Control directive
  760. *
  761. * @return void
  762. */
  763. public function testMaxAge()
  764. {
  765. $response = new Response();
  766. $this->assertNull($response->maxAge());
  767. $response->maxAge(3600);
  768. $this->assertEquals(3600, $response->maxAge());
  769. $this->assertEquals('max-age=3600', $response->getHeaderLine('Cache-Control'));
  770. $response = new Response();
  771. $response->maxAge(3600);
  772. $response->sharable(false);
  773. $this->assertEquals('max-age=3600, private', $response->getHeaderLine('Cache-Control'));
  774. }
  775. /**
  776. * Tests withMaxAge()
  777. *
  778. * @return void
  779. */
  780. public function testWithMaxAge()
  781. {
  782. $response = new Response();
  783. $this->assertFalse($response->hasHeader('Cache-Control'));
  784. $new = $response->withMaxAge(3600);
  785. $this->assertEquals('max-age=3600', $new->getHeaderLine('Cache-Control'));
  786. $new = $response->withMaxAge(3600)
  787. ->withSharable(false);
  788. $this->assertEquals('max-age=3600, private', $new->getHeaderLine('Cache-Control'));
  789. }
  790. /**
  791. * Tests setting of s-maxage Cache-Control directive
  792. *
  793. * @return void
  794. */
  795. public function testSharedMaxAge()
  796. {
  797. $response = new Response();
  798. $this->assertNull($response->maxAge());
  799. $response->sharedMaxAge(3600);
  800. $this->assertEquals(3600, $response->sharedMaxAge());
  801. $this->assertEquals('s-maxage=3600', $response->getHeaderLine('Cache-Control'));
  802. $response = new Response();
  803. $response->sharedMaxAge(3600);
  804. $response->sharable(true);
  805. $this->assertEquals('s-maxage=3600, public', $response->getHeaderLine('Cache-Control'));
  806. }
  807. /**
  808. * Tests setting of must-revalidate Cache-Control directive
  809. *
  810. * @return void
  811. */
  812. public function testMustRevalidate()
  813. {
  814. $response = $this->getMockBuilder('Cake\Network\Response')
  815. ->setMethods(['_sendHeader', '_sendContent'])
  816. ->getMock();
  817. $response = new Response();
  818. $this->assertFalse($response->mustRevalidate());
  819. $response->mustRevalidate(true);
  820. $this->assertTrue($response->mustRevalidate());
  821. $this->assertEquals('must-revalidate', $response->getHeaderLine('Cache-Control'));
  822. $response->mustRevalidate(false);
  823. $this->assertFalse($response->mustRevalidate());
  824. $response = new Response();
  825. $response->sharedMaxAge(3600);
  826. $response->mustRevalidate(true);
  827. $this->assertEquals('s-maxage=3600, must-revalidate', $response->getHeaderLine('Cache-Control'));
  828. }
  829. /**
  830. * Tests getting/setting the Vary header
  831. *
  832. * @return void
  833. */
  834. public function testVary()
  835. {
  836. $response = new Response();
  837. $response->vary('Accept-encoding');
  838. $this->assertEquals('Accept-encoding', $response->getHeaderLine('vary'));
  839. $response = new Response();
  840. $response->vary(['Accept-language', 'Accept-encoding']);
  841. $this->assertEquals(['Accept-language', 'Accept-encoding'], $response->vary());
  842. $this->assertEquals('Accept-language, Accept-encoding', $response->getHeaderLine('vary'));
  843. }
  844. /**
  845. * Tests withVary()
  846. *
  847. * @return void
  848. */
  849. public function testWithVary()
  850. {
  851. $response = new Response();
  852. $new = $response->withVary('Accept-encoding');
  853. $this->assertFalse($response->hasHeader('Vary'));
  854. $this->assertEquals('Accept-encoding', $new->getHeaderLine('Vary'));
  855. $new = $response->withVary(['Accept-encoding', 'Accept-language']);
  856. $this->assertFalse($response->hasHeader('Vary'));
  857. $this->assertEquals('Accept-encoding,Accept-language', $new->getHeaderLine('Vary'));
  858. }
  859. /**
  860. * Tests getting/setting the Etag header
  861. *
  862. * @return void
  863. */
  864. public function testEtag()
  865. {
  866. $response = new Response();
  867. $response->etag('something');
  868. $this->assertEquals('"something"', $response->etag());
  869. $this->assertEquals('"something"', $response->getHeaderLine('Etag'));
  870. $response = new Response();
  871. $response->etag('something', true);
  872. $this->assertEquals('W/"something"', $response->etag());
  873. $this->assertEquals('W/"something"', $response->getHeaderLine('Etag'));
  874. }
  875. /**
  876. * Tests withEtag()
  877. *
  878. * @return void
  879. */
  880. public function testWithEtag()
  881. {
  882. $response = new Response();
  883. $new = $response->withEtag('something');
  884. $this->assertFalse($response->hasHeader('Etag'));
  885. $this->assertEquals('"something"', $new->getHeaderLine('Etag'));
  886. $new = $response->withEtag('something', true);
  887. $this->assertEquals('W/"something"', $new->getHeaderLine('Etag'));
  888. }
  889. /**
  890. * Tests that the response is able to be marked as not modified
  891. *
  892. * @return void
  893. */
  894. public function testNotModified()
  895. {
  896. $response = $this->getMockBuilder('Cake\Network\Response')
  897. ->setMethods(['_sendHeader', '_sendContent'])
  898. ->getMock();
  899. $response->body('something');
  900. $response->statusCode(200);
  901. $response->length(100);
  902. $response->modified('now');
  903. $response->notModified();
  904. $this->assertEmpty($response->header());
  905. $this->assertEmpty($response->body());
  906. $this->assertEquals(304, $response->statusCode());
  907. }
  908. /**
  909. * Tests withNotModified()
  910. *
  911. * @return void
  912. */
  913. public function testWithNotModified()
  914. {
  915. $response = new Response(['body' => 'something']);
  916. $response = $response->withLength(100)
  917. ->withStatus(200)
  918. ->withHeader('Last-Modified', 'value')
  919. ->withHeader('Content-Language', 'en-EN')
  920. ->withHeader('X-things', 'things')
  921. ->withType('application/json');
  922. $new = $response->withNotModified();
  923. $this->assertTrue($response->hasHeader('Content-Language'), 'old instance not changed');
  924. $this->assertTrue($response->hasHeader('Content-Length'), 'old instance not changed');
  925. $this->assertFalse($new->hasHeader('Content-Type'));
  926. $this->assertFalse($new->hasHeader('Content-Length'));
  927. $this->assertFalse($new->hasHeader('Content-Language'));
  928. $this->assertFalse($new->hasHeader('Last-Modified'));
  929. $this->assertSame('things', $new->getHeaderLine('X-things'), 'Other headers are retained');
  930. $this->assertSame(304, $new->getStatusCode());
  931. $this->assertSame('', $new->getBody()->getContents());
  932. }
  933. /**
  934. * Test checkNotModified method
  935. *
  936. * @return void
  937. */
  938. public function testCheckNotModifiedByEtagStar()
  939. {
  940. $_SERVER['HTTP_IF_NONE_MATCH'] = '*';
  941. $response = $this->getMockBuilder('Cake\Network\Response')
  942. ->setMethods(['notModified'])
  943. ->getMock();
  944. $response->etag('something');
  945. $response->expects($this->once())->method('notModified');
  946. $response->checkNotModified(new Request);
  947. }
  948. /**
  949. * Test checkNotModified method
  950. *
  951. * @return void
  952. */
  953. public function testCheckNotModifiedByEtagExact()
  954. {
  955. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  956. $response = $this->getMockBuilder('Cake\Network\Response')
  957. ->setMethods(['notModified'])
  958. ->getMock();
  959. $response->etag('something', true);
  960. $response->expects($this->once())->method('notModified');
  961. $this->assertTrue($response->checkNotModified(new Request));
  962. }
  963. /**
  964. * Test checkNotModified method
  965. *
  966. * @return void
  967. */
  968. public function testCheckNotModifiedByEtagAndTime()
  969. {
  970. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  971. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  972. $response = $this->getMockBuilder('Cake\Network\Response')
  973. ->setMethods(['notModified'])
  974. ->getMock();
  975. $response->etag('something', true);
  976. $response->modified('2012-01-01 00:00:00');
  977. $response->expects($this->once())->method('notModified');
  978. $this->assertTrue($response->checkNotModified(new Request));
  979. }
  980. /**
  981. * Test checkNotModified method
  982. *
  983. * @return void
  984. */
  985. public function testCheckNotModifiedByEtagAndTimeMismatch()
  986. {
  987. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  988. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  989. $response = $this->getMockBuilder('Cake\Network\Response')
  990. ->setMethods(['notModified'])
  991. ->getMock();
  992. $response->etag('something', true);
  993. $response->modified('2012-01-01 00:00:01');
  994. $response->expects($this->never())->method('notModified');
  995. $this->assertFalse($response->checkNotModified(new Request));
  996. }
  997. /**
  998. * Test checkNotModified method
  999. *
  1000. * @return void
  1001. */
  1002. public function testCheckNotModifiedByEtagMismatch()
  1003. {
  1004. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something-else", "other"';
  1005. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  1006. $response = $this->getMockBuilder('Cake\Network\Response')
  1007. ->setMethods(['notModified'])
  1008. ->getMock();
  1009. $response->etag('something', true);
  1010. $response->modified('2012-01-01 00:00:00');
  1011. $response->expects($this->never())->method('notModified');
  1012. $this->assertFalse($response->checkNotModified(new Request));
  1013. }
  1014. /**
  1015. * Test checkNotModified method
  1016. *
  1017. * @return void
  1018. */
  1019. public function testCheckNotModifiedByTime()
  1020. {
  1021. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  1022. $response = $this->getMockBuilder('Cake\Network\Response')
  1023. ->setMethods(['notModified'])
  1024. ->getMock();
  1025. $response->modified('2012-01-01 00:00:00');
  1026. $response->expects($this->once())->method('notModified');
  1027. $this->assertTrue($response->checkNotModified(new Request));
  1028. }
  1029. /**
  1030. * Test checkNotModified method
  1031. *
  1032. * @return void
  1033. */
  1034. public function testCheckNotModifiedNoHints()
  1035. {
  1036. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  1037. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  1038. $response = $this->getMockBuilder('Cake\Network\Response')
  1039. ->setMethods(['notModified'])
  1040. ->getMock();
  1041. $response->expects($this->never())->method('notModified');
  1042. $this->assertFalse($response->checkNotModified(new Request));
  1043. }
  1044. /**
  1045. * Test cookie setting
  1046. *
  1047. * @return void
  1048. */
  1049. public function testCookieSettings()
  1050. {
  1051. $response = new Response();
  1052. $cookie = [
  1053. 'name' => 'CakeTestCookie[Testing]'
  1054. ];
  1055. $response->cookie($cookie);
  1056. $expected = [
  1057. 'name' => 'CakeTestCookie[Testing]',
  1058. 'value' => '',
  1059. 'expire' => 0,
  1060. 'path' => '/',
  1061. 'domain' => '',
  1062. 'secure' => false,
  1063. 'httpOnly' => false];
  1064. $result = $response->cookie('CakeTestCookie[Testing]');
  1065. $this->assertEquals($expected, $result);
  1066. $cookie = [
  1067. 'name' => 'CakeTestCookie[Testing2]',
  1068. 'value' => '[a,b,c]',
  1069. 'expire' => 1000,
  1070. 'path' => '/test',
  1071. 'secure' => true
  1072. ];
  1073. $response->cookie($cookie);
  1074. $expected = [
  1075. 'CakeTestCookie[Testing]' => [
  1076. 'name' => 'CakeTestCookie[Testing]',
  1077. 'value' => '',
  1078. 'expire' => 0,
  1079. 'path' => '/',
  1080. 'domain' => '',
  1081. 'secure' => false,
  1082. 'httpOnly' => false
  1083. ],
  1084. 'CakeTestCookie[Testing2]' => [
  1085. 'name' => 'CakeTestCookie[Testing2]',
  1086. 'value' => '[a,b,c]',
  1087. 'expire' => 1000,
  1088. 'path' => '/test',
  1089. 'domain' => '',
  1090. 'secure' => true,
  1091. 'httpOnly' => false
  1092. ]
  1093. ];
  1094. $result = $response->cookie();
  1095. $this->assertEquals($expected, $result);
  1096. $cookie = $expected['CakeTestCookie[Testing]'];
  1097. $cookie['value'] = 'test';
  1098. $response->cookie($cookie);
  1099. $expected = [
  1100. 'CakeTestCookie[Testing]' => [
  1101. 'name' => 'CakeTestCookie[Testing]',
  1102. 'value' => 'test',
  1103. 'expire' => 0,
  1104. 'path' => '/',
  1105. 'domain' => '',
  1106. 'secure' => false,
  1107. 'httpOnly' => false
  1108. ],
  1109. 'CakeTestCookie[Testing2]' => [
  1110. 'name' => 'CakeTestCookie[Testing2]',
  1111. 'value' => '[a,b,c]',
  1112. 'expire' => 1000,
  1113. 'path' => '/test',
  1114. 'domain' => '',
  1115. 'secure' => true,
  1116. 'httpOnly' => false
  1117. ]
  1118. ];
  1119. $result = $response->cookie();
  1120. $this->assertEquals($expected, $result);
  1121. }
  1122. /**
  1123. * Test CORS
  1124. *
  1125. * @dataProvider corsData
  1126. * @param Request $request
  1127. * @param string $origin
  1128. * @param string|array $domains
  1129. * @param string|array $methods
  1130. * @param string|array $headers
  1131. * @param string|bool $expectedOrigin
  1132. * @param string|bool $expectedMethods
  1133. * @param string|bool $expectedHeaders
  1134. * @return void
  1135. */
  1136. public function testCors($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods = false, $expectedHeaders = false)
  1137. {
  1138. $request->env('HTTP_ORIGIN', $origin);
  1139. $response = new Response();
  1140. $result = $response->cors($request, $domains, $methods, $headers);
  1141. $this->assertInstanceOf('Cake\Network\CorsBuilder', $result);
  1142. $headers = $response->header();
  1143. if ($expectedOrigin) {
  1144. $this->assertArrayHasKey('Access-Control-Allow-Origin', $headers);
  1145. $this->assertEquals($expectedOrigin, $headers['Access-Control-Allow-Origin']);
  1146. }
  1147. if ($expectedMethods) {
  1148. $this->assertArrayHasKey('Access-Control-Allow-Methods', $headers);
  1149. $this->assertEquals($expectedMethods, $headers['Access-Control-Allow-Methods']);
  1150. }
  1151. if ($expectedHeaders) {
  1152. $this->assertArrayHasKey('Access-Control-Allow-Headers', $headers);
  1153. $this->assertEquals($expectedHeaders, $headers['Access-Control-Allow-Headers']);
  1154. }
  1155. unset($_SERVER['HTTP_ORIGIN']);
  1156. }
  1157. /**
  1158. * Feed for testCors
  1159. *
  1160. * @return array
  1161. */
  1162. public function corsData()
  1163. {
  1164. $fooRequest = new Request();
  1165. $secureRequest = function () {
  1166. $secureRequest = $this->getMockBuilder('Cake\Network\Request')
  1167. ->setMethods(['is'])
  1168. ->getMock();
  1169. $secureRequest->expects($this->any())
  1170. ->method('is')
  1171. ->with('ssl')
  1172. ->will($this->returnValue(true));
  1173. return $secureRequest;
  1174. };
  1175. return [
  1176. // [$fooRequest, null, '*', '', '', false, false],
  1177. // [$fooRequest, 'http://www.foo.com', '*', '', '', '*', false],
  1178. // [$fooRequest, 'http://www.foo.com', 'www.foo.com', '', '', 'http://www.foo.com', false],
  1179. // [$fooRequest, 'http://www.foo.com', '*.foo.com', '', '', 'http://www.foo.com', false],
  1180. // [$fooRequest, 'http://www.foo.com', 'http://*.foo.com', '', '', 'http://www.foo.com', false],
  1181. // [$fooRequest, 'http://www.foo.com', 'https://www.foo.com', '', '', false, false],
  1182. // [$fooRequest, 'http://www.foo.com', 'https://*.foo.com', '', '', false, false],
  1183. // [$fooRequest, 'http://www.foo.com', ['*.bar.com', '*.foo.com'], '', '', 'http://www.foo.com', false],
  1184. // [$fooRequest, 'http://not-foo.com', '*.foo.com', '', '', false, false],
  1185. // [$fooRequest, 'http://bad.academy', '*.acad.my', '', '', false, false],
  1186. // [$fooRequest, 'http://www.foo.com.at.bad.com', '*.foo.com', '', '', false, false],
  1187. // [$fooRequest, 'https://www.foo.com', '*.foo.com', '', '', false, false],
  1188. [$secureRequest(), 'https://www.bar.com', 'www.bar.com', '', '', 'https://www.bar.com', false],
  1189. [$secureRequest(), 'https://www.bar.com', 'http://www.bar.com', '', '', false, false],
  1190. [$secureRequest(), 'https://www.bar.com', '*.bar.com', '', '', 'https://www.bar.com', false],
  1191. [$secureRequest(), 'http://www.bar.com', '*.bar.com', '', '', false, false],
  1192. [$fooRequest, 'http://www.foo.com', '*', 'GET', '', '*', 'GET'],
  1193. [$fooRequest, 'http://www.foo.com', '*.foo.com', 'GET', '', 'http://www.foo.com', 'GET'],
  1194. [$fooRequest, 'http://www.foo.com', '*.foo.com', ['GET', 'POST'], '', 'http://www.foo.com', 'GET, POST'],
  1195. [$fooRequest, 'http://www.foo.com', '*', '', 'X-CakePHP', '*', false, 'X-CakePHP'],
  1196. [$fooRequest, 'http://www.foo.com', '*', '', ['X-CakePHP', 'X-MyApp'], '*', false, 'X-CakePHP, X-MyApp'],
  1197. [$fooRequest, 'http://www.foo.com', '*', ['GET', 'OPTIONS'], ['X-CakePHP', 'X-MyApp'], '*', 'GET, OPTIONS', 'X-CakePHP, X-MyApp'],
  1198. ];
  1199. }
  1200. /**
  1201. * testFileNotFound
  1202. *
  1203. * @expectedException \Cake\Network\Exception\NotFoundException
  1204. * @return void
  1205. */
  1206. public function testFileNotFound()
  1207. {
  1208. $response = new Response();
  1209. $response->file('/some/missing/folder/file.jpg');
  1210. }
  1211. /**
  1212. * test file with ../
  1213. *
  1214. * @expectedException \Cake\Network\Exception\NotFoundException
  1215. * @expectedExceptionMessage The requested file contains `..` and will not be read.
  1216. * @return void
  1217. */
  1218. public function testFileWithForwardSlashPathTraversal()
  1219. {
  1220. $response = new Response();
  1221. $response->file('my/../cat.gif');
  1222. }
  1223. /**
  1224. * test file with ..\
  1225. *
  1226. * @expectedException \Cake\Network\Exception\NotFoundException
  1227. * @expectedExceptionMessage The requested file contains `..` and will not be read.
  1228. * @return void
  1229. */
  1230. public function testFileWithBackwardSlashPathTraversal()
  1231. {
  1232. $response = new Response();
  1233. $response->file('my\..\cat.gif');
  1234. }
  1235. /**
  1236. * test file with ..
  1237. *
  1238. * @expectedException \Cake\Network\Exception\NotFoundException
  1239. * @expectedExceptionMessage my/ca..t.gif was not found or not readable
  1240. * @return void
  1241. */
  1242. public function testFileWithDotsInTheFilename()
  1243. {
  1244. $response = new Response();
  1245. $response->file('my/ca..t.gif');
  1246. }
  1247. /**
  1248. * test file with .. in a path fragment
  1249. *
  1250. * @expectedException \Cake\Network\Exception\NotFoundException
  1251. * @expectedExceptionMessage my/ca..t/image.gif was not found or not readable
  1252. * @return void
  1253. */
  1254. public function testFileWithDotsInAPathFragment()
  1255. {
  1256. $response = new Response();
  1257. $response->file('my/ca..t/image.gif');
  1258. }
  1259. /**
  1260. * testFile method
  1261. *
  1262. * @return void
  1263. */
  1264. public function testFile()
  1265. {
  1266. $response = $this->getMockBuilder('Cake\Network\Response')
  1267. ->setMethods([
  1268. 'header',
  1269. 'type',
  1270. '_sendHeader',
  1271. '_setContentType',
  1272. '_isActive',
  1273. ])
  1274. ->getMock();
  1275. $response->expects($this->exactly(1))
  1276. ->method('type')
  1277. ->with('css')
  1278. ->will($this->returnArgument(0));
  1279. $response->expects($this->at(1))
  1280. ->method('header')
  1281. ->with('Accept-Ranges', 'bytes');
  1282. $response->expects($this->exactly(1))
  1283. ->method('_isActive')
  1284. ->will($this->returnValue(true));
  1285. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1286. ob_start();
  1287. $result = $response->send();
  1288. $output = ob_get_clean();
  1289. $this->assertEquals("/* this is the test asset css file */", trim($output));
  1290. $this->assertTrue($result !== false);
  1291. }
  1292. /**
  1293. * testFileWithDownloadAndName
  1294. *
  1295. * @return void
  1296. */
  1297. public function testFileWithDownloadAndName()
  1298. {
  1299. $response = $this->getMockBuilder('Cake\Network\Response')
  1300. ->setMethods([
  1301. 'header',
  1302. 'type',
  1303. 'download',
  1304. '_sendHeader',
  1305. '_setContentType',
  1306. '_isActive',
  1307. ])
  1308. ->getMock();
  1309. $response->expects($this->exactly(1))
  1310. ->method('type')
  1311. ->with('css')
  1312. ->will($this->returnArgument(0));
  1313. $response->expects($this->once())
  1314. ->method('download')
  1315. ->with('something_special.css');
  1316. $response->expects($this->at(2))
  1317. ->method('header')
  1318. ->with('Content-Transfer-Encoding', 'binary');
  1319. $response->expects($this->at(3))
  1320. ->method('header')
  1321. ->with('Accept-Ranges', 'bytes');
  1322. $response->expects($this->exactly(1))
  1323. ->method('_isActive')
  1324. ->will($this->returnValue(true));
  1325. $response->file(
  1326. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1327. [
  1328. 'name' => 'something_special.css',
  1329. 'download' => true,
  1330. ]
  1331. );
  1332. ob_start();
  1333. $result = $response->send();
  1334. $output = ob_get_clean();
  1335. $this->assertEquals("/* this is the test asset css file */\n", $output);
  1336. $this->assertNotSame(false, $result);
  1337. }
  1338. /**
  1339. * testFileWithUnknownFileTypeGeneric method
  1340. *
  1341. * @return void
  1342. */
  1343. public function testFileWithUnknownFileTypeGeneric()
  1344. {
  1345. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1346. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1347. $response = $this->getMockBuilder('Cake\Network\Response')
  1348. ->setMethods([
  1349. 'header',
  1350. 'type',
  1351. 'download',
  1352. '_sendHeader',
  1353. '_setContentType',
  1354. '_isActive',
  1355. ])
  1356. ->getMock();
  1357. $response->expects($this->exactly(1))
  1358. ->method('type')
  1359. ->with('ini')
  1360. ->will($this->returnValue(false));
  1361. $response->expects($this->once())
  1362. ->method('download')
  1363. ->with('no_section.ini');
  1364. $response->expects($this->at(2))
  1365. ->method('header')
  1366. ->with('Content-Transfer-Encoding', 'binary');
  1367. $response->expects($this->at(3))
  1368. ->method('header')
  1369. ->with('Accept-Ranges', 'bytes');
  1370. $response->expects($this->exactly(1))
  1371. ->method('_isActive')
  1372. ->will($this->returnValue(true));
  1373. $response->file(CONFIG . 'no_section.ini');
  1374. ob_start();
  1375. $result = $response->send();
  1376. $output = ob_get_clean();
  1377. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1378. $this->assertNotSame(false, $result);
  1379. if ($currentUserAgent !== null) {
  1380. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1381. }
  1382. }
  1383. /**
  1384. * testFileWithUnknownFileTypeOpera method
  1385. *
  1386. * @return void
  1387. */
  1388. public function testFileWithUnknownFileTypeOpera()
  1389. {
  1390. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1391. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  1392. $response = $this->getMockBuilder('Cake\Network\Response')
  1393. ->setMethods([
  1394. 'header',
  1395. 'type',
  1396. 'download',
  1397. '_sendHeader',
  1398. '_setContentType',
  1399. '_isActive',
  1400. ])
  1401. ->getMock();
  1402. $response->expects($this->at(0))
  1403. ->method('type')
  1404. ->with('ini')
  1405. ->will($this->returnValue(false));
  1406. $response->expects($this->at(1))
  1407. ->method('type')
  1408. ->with('application/octet-stream')
  1409. ->will($this->returnValue(false));
  1410. $response->expects($this->once())
  1411. ->method('download')
  1412. ->with('no_section.ini');
  1413. $response->expects($this->at(3))
  1414. ->method('header')
  1415. ->with('Content-Transfer-Encoding', 'binary');
  1416. $response->expects($this->at(4))
  1417. ->method('header')
  1418. ->with('Accept-Ranges', 'bytes');
  1419. $response->expects($this->exactly(1))
  1420. ->method('_isActive')
  1421. ->will($this->returnValue(true));
  1422. $response->file(CONFIG . 'no_section.ini');
  1423. ob_start();
  1424. $result = $response->send();
  1425. $output = ob_get_clean();
  1426. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1427. $this->assertNotSame(false, $result);
  1428. if ($currentUserAgent !== null) {
  1429. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1430. }
  1431. }
  1432. /**
  1433. * testFileWithUnknownFileTypeIE method
  1434. *
  1435. * @return void
  1436. */
  1437. public function testFileWithUnknownFileTypeIE()
  1438. {
  1439. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1440. $_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)';
  1441. $response = $this->getMockBuilder('Cake\Network\Response')
  1442. ->setMethods([
  1443. 'header',
  1444. 'type',
  1445. 'download',
  1446. '_sendHeader',
  1447. '_setContentType',
  1448. '_isActive',
  1449. ])
  1450. ->getMock();
  1451. $response->expects($this->at(0))
  1452. ->method('type')
  1453. ->with('ini')
  1454. ->will($this->returnValue(false));
  1455. $response->expects($this->at(1))
  1456. ->method('type')
  1457. ->with('application/force-download')
  1458. ->will($this->returnValue(false));
  1459. $response->expects($this->once())
  1460. ->method('download')
  1461. ->with('config.ini');
  1462. $response->expects($this->at(3))
  1463. ->method('header')
  1464. ->with('Content-Transfer-Encoding', 'binary');
  1465. $response->expects($this->at(4))
  1466. ->method('header')
  1467. ->with('Accept-Ranges', 'bytes');
  1468. $response->expects($this->exactly(1))
  1469. ->method('_isActive')
  1470. ->will($this->returnValue(true));
  1471. $response->file(CONFIG . 'no_section.ini', [
  1472. 'name' => 'config.ini'
  1473. ]);
  1474. ob_start();
  1475. $result = $response->send();
  1476. $output = ob_get_clean();
  1477. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1478. $this->assertNotSame(false, $result);
  1479. if ($currentUserAgent !== null) {
  1480. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1481. }
  1482. }
  1483. /**
  1484. * testFileWithUnknownFileNoDownload method
  1485. *
  1486. * @return void
  1487. */
  1488. public function testFileWithUnknownFileNoDownload()
  1489. {
  1490. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1491. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1492. $response = $this->getMockBuilder('Cake\Network\Response')
  1493. ->setMethods([
  1494. 'header',
  1495. 'type',
  1496. 'download',
  1497. '_sendHeader',
  1498. '_setContentType',
  1499. '_isActive',
  1500. ])
  1501. ->getMock();
  1502. $response->expects($this->exactly(1))
  1503. ->method('type')
  1504. ->with('ini')
  1505. ->will($this->returnValue(false));
  1506. $response->expects($this->at(1))
  1507. ->method('header')
  1508. ->with('Accept-Ranges', 'bytes');
  1509. $response->expects($this->never())
  1510. ->method('download');
  1511. $response->file(CONFIG . 'no_section.ini', [
  1512. 'download' => false
  1513. ]);
  1514. if ($currentUserAgent !== null) {
  1515. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1516. }
  1517. }
  1518. /**
  1519. * test getFile method
  1520. *
  1521. * @return void
  1522. */
  1523. public function testGetFile()
  1524. {
  1525. $response = new Response();
  1526. $this->assertNull($response->getFile(), 'No file to get');
  1527. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1528. $file = $response->getFile();
  1529. $this->assertInstanceOf('Cake\Filesystem\File', $file, 'Should get a file');
  1530. $this->assertPathEquals(TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css', $file->path);
  1531. }
  1532. /**
  1533. * testConnectionAbortedOnBuffering method
  1534. *
  1535. * @return void
  1536. */
  1537. public function testConnectionAbortedOnBuffering()
  1538. {
  1539. $response = $this->getMockBuilder('Cake\Network\Response')
  1540. ->setMethods([
  1541. 'header',
  1542. 'type',
  1543. 'download',
  1544. '_sendHeader',
  1545. '_setContentType',
  1546. '_isActive',
  1547. ])
  1548. ->getMock();
  1549. $response->expects($this->any())
  1550. ->method('type')
  1551. ->with('css')
  1552. ->will($this->returnArgument(0));
  1553. $response->expects($this->at(0))
  1554. ->method('_isActive')
  1555. ->will($this->returnValue(false));
  1556. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1557. $result = $response->send();
  1558. $this->assertNull($result);
  1559. }
  1560. /**
  1561. * Test downloading files with UPPERCASE extensions.
  1562. *
  1563. * @return void
  1564. */
  1565. public function testFileUpperExtension()
  1566. {
  1567. $response = $this->getMockBuilder('Cake\Network\Response')
  1568. ->setMethods([
  1569. 'header',
  1570. 'type',
  1571. 'download',
  1572. '_sendHeader',
  1573. '_setContentType',
  1574. '_isActive',
  1575. ])
  1576. ->getMock();
  1577. $response->expects($this->any())
  1578. ->method('type')
  1579. ->with('jpg')
  1580. ->will($this->returnArgument(0));
  1581. $response->expects($this->at(0))
  1582. ->method('_isActive')
  1583. ->will($this->returnValue(true));
  1584. $response->file(TEST_APP . 'vendor/img/test_2.JPG');
  1585. }
  1586. /**
  1587. * Test downloading files with extension not explicitly set.
  1588. *
  1589. * @return void
  1590. */
  1591. public function testFileExtensionNotSet()
  1592. {
  1593. $response = $this->getMockBuilder('Cake\Network\Response')
  1594. ->setMethods([
  1595. 'header',
  1596. 'type',
  1597. 'download',
  1598. '_sendHeader',
  1599. '_setContentType',
  1600. '_isActive',
  1601. ])
  1602. ->getMock();
  1603. $response->expects($this->any())
  1604. ->method('type')
  1605. ->with('jpg')
  1606. ->will($this->returnArgument(0));
  1607. $response->expects($this->at(0))
  1608. ->method('_isActive')
  1609. ->will($this->returnValue(true));
  1610. $response->file(TEST_APP . 'vendor/img/test_2.JPG');
  1611. }
  1612. /**
  1613. * A data provider for testing various ranges
  1614. *
  1615. * @return array
  1616. */
  1617. public static function rangeProvider()
  1618. {
  1619. return [
  1620. // suffix-byte-range
  1621. [
  1622. 'bytes=-25', 25, 'bytes 13-37/38'
  1623. ],
  1624. [
  1625. 'bytes=0-', 38, 'bytes 0-37/38'
  1626. ],
  1627. [
  1628. 'bytes=10-', 28, 'bytes 10-37/38'
  1629. ],
  1630. [
  1631. 'bytes=10-20', 11, 'bytes 10-20/38'
  1632. ],
  1633. // Spaced out
  1634. [
  1635. 'bytes = 10 - 20', 11, 'bytes 10-20/38'
  1636. ],
  1637. ];
  1638. }
  1639. /**
  1640. * Test the various range offset types.
  1641. *
  1642. * @dataProvider rangeProvider
  1643. * @return void
  1644. */
  1645. public function testFileRangeOffsets($range, $length, $offsetResponse)
  1646. {
  1647. $_SERVER['HTTP_RANGE'] = $range;
  1648. $response = $this->getMockBuilder('Cake\Network\Response')
  1649. ->setMethods([
  1650. 'header',
  1651. 'type',
  1652. '_sendHeader',
  1653. '_setContentType',
  1654. '_isActive',
  1655. ])
  1656. ->getMock();
  1657. $response->expects($this->at(1))
  1658. ->method('header')
  1659. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  1660. $response->expects($this->at(2))
  1661. ->method('header')
  1662. ->with('Content-Transfer-Encoding', 'binary');
  1663. $response->expects($this->at(3))
  1664. ->method('header')
  1665. ->with('Accept-Ranges', 'bytes');
  1666. $response->expects($this->at(4))
  1667. ->method('header')
  1668. ->with([
  1669. 'Content-Length' => $length,
  1670. 'Content-Range' => $offsetResponse,
  1671. ]);
  1672. $response->expects($this->any())
  1673. ->method('_isActive')
  1674. ->will($this->returnValue(true));
  1675. $response->file(
  1676. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1677. ['download' => true]
  1678. );
  1679. ob_start();
  1680. $result = $response->send();
  1681. ob_get_clean();
  1682. }
  1683. /**
  1684. * Test fetching ranges from a file.
  1685. *
  1686. * @return void
  1687. */
  1688. public function testFileRange()
  1689. {
  1690. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1691. $response = $this->getMockBuilder('Cake\Network\Response')
  1692. ->setMethods([
  1693. 'header',
  1694. 'type',
  1695. '_sendHeader',
  1696. '_setContentType',
  1697. '_isActive',
  1698. ])
  1699. ->getMock();
  1700. $response->expects($this->exactly(1))
  1701. ->method('type')
  1702. ->with('css')
  1703. ->will($this->returnArgument(0));
  1704. $response->expects($this->at(1))
  1705. ->method('header')
  1706. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  1707. $response->expects($this->at(2))
  1708. ->method('header')
  1709. ->with('Content-Transfer-Encoding', 'binary');
  1710. $response->expects($this->at(3))
  1711. ->method('header')
  1712. ->with('Accept-Ranges', 'bytes');
  1713. $response->expects($this->at(4))
  1714. ->method('header')
  1715. ->with([
  1716. 'Content-Length' => 18,
  1717. 'Content-Range' => 'bytes 8-25/38',
  1718. ]);
  1719. $response->expects($this->any())
  1720. ->method('_isActive')
  1721. ->will($this->returnValue(true));
  1722. $response->file(
  1723. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1724. ['download' => true]
  1725. );
  1726. ob_start();
  1727. $result = $response->send();
  1728. $output = ob_get_clean();
  1729. $this->assertEquals(206, $response->statusCode());
  1730. $this->assertEquals("is the test asset ", $output);
  1731. $this->assertNotSame(false, $result);
  1732. }
  1733. /**
  1734. * Provider for invalid range header values.
  1735. *
  1736. * @return array
  1737. */
  1738. public function invalidFileRangeProvider()
  1739. {
  1740. return [
  1741. // malformed range
  1742. [
  1743. 'bytes=0,38'
  1744. ],
  1745. // malformed punctuation
  1746. [
  1747. 'bytes: 0 - 38'
  1748. ],
  1749. ];
  1750. }
  1751. /**
  1752. * Test invalid file ranges.
  1753. *
  1754. * @dataProvider invalidFileRangeProvider
  1755. * @return void
  1756. */
  1757. public function testFileRangeInvalid($range)
  1758. {
  1759. $_SERVER['HTTP_RANGE'] = $range;
  1760. $response = $this->getMockBuilder('Cake\Network\Response')
  1761. ->setMethods([
  1762. '_sendHeader',
  1763. '_isActive',
  1764. ])
  1765. ->getMock();
  1766. $response->file(
  1767. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1768. ['download' => true]
  1769. );
  1770. $expected = [
  1771. 'Content-Type' => 'text/css; charset=UTF-8',
  1772. 'Content-Disposition' => 'attachment; filename="test_asset.css"',
  1773. 'Content-Transfer-Encoding' => 'binary',
  1774. 'Accept-Ranges' => 'bytes',
  1775. 'Content-Range' => 'bytes 0-37/38',
  1776. 'Content-Length' => 38,
  1777. ];
  1778. $this->assertEquals($expected, $response->header());
  1779. }
  1780. /**
  1781. * Test reversed file ranges.
  1782. *
  1783. * @return void
  1784. */
  1785. public function testFileRangeReversed()
  1786. {
  1787. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1788. $response = $this->getMockBuilder('Cake\Network\Response')
  1789. ->setMethods([
  1790. 'header',
  1791. 'type',
  1792. '_sendHeader',
  1793. '_isActive',
  1794. ])
  1795. ->getMock();
  1796. $response->expects($this->at(1))
  1797. ->method('header')
  1798. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  1799. $response->expects($this->at(2))
  1800. ->method('header')
  1801. ->with('Content-Transfer-Encoding', 'binary');
  1802. $response->expects($this->at(3))
  1803. ->method('header')
  1804. ->with('Accept-Ranges', 'bytes');
  1805. $response->expects($this->at(4))
  1806. ->method('header')
  1807. ->with([
  1808. 'Content-Range' => 'bytes 0-37/38',
  1809. ]);
  1810. $response->file(
  1811. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1812. ['download' => true]
  1813. );
  1814. $this->assertEquals(416, $response->statusCode());
  1815. $result = $response->send();
  1816. }
  1817. /**
  1818. * testFileRangeOffsetsNoDownload method
  1819. *
  1820. * @dataProvider rangeProvider
  1821. * @return void
  1822. */
  1823. public function testFileRangeOffsetsNoDownload($range, $length, $offsetResponse)
  1824. {
  1825. $_SERVER['HTTP_RANGE'] = $range;
  1826. $response = $this->getMockBuilder('Cake\Network\Response')
  1827. ->setMethods([
  1828. 'header',
  1829. 'type',
  1830. '_sendHeader',
  1831. '_isActive',
  1832. ])
  1833. ->getMock();
  1834. $response->expects($this->at(1))
  1835. ->method('header')
  1836. ->with('Accept-Ranges', 'bytes');
  1837. $response->expects($this->at(2))
  1838. ->method('header')
  1839. ->with([
  1840. 'Content-Length' => $length,
  1841. 'Content-Range' => $offsetResponse,
  1842. ]);
  1843. $response->expects($this->any())
  1844. ->method('_isActive')
  1845. ->will($this->returnValue(true));
  1846. $response->file(
  1847. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1848. ['download' => false]
  1849. );
  1850. ob_start();
  1851. $result = $response->send();
  1852. ob_get_clean();
  1853. }
  1854. /**
  1855. * testFileRangeNoDownload method
  1856. *
  1857. * @return void
  1858. */
  1859. public function testFileRangeNoDownload()
  1860. {
  1861. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1862. $response = $this->getMockBuilder('Cake\Network\Response')
  1863. ->setMethods([
  1864. 'header',
  1865. 'type',
  1866. '_sendHeader',
  1867. '_isActive',
  1868. ])
  1869. ->getMock();
  1870. $response->expects($this->exactly(1))
  1871. ->method('type')
  1872. ->with('css')
  1873. ->will($this->returnArgument(0));
  1874. $response->expects($this->at(1))
  1875. ->method('header')
  1876. ->with('Accept-Ranges', 'bytes');
  1877. $response->expects($this->at(2))
  1878. ->method('header')
  1879. ->with([
  1880. 'Content-Length' => 18,
  1881. 'Content-Range' => 'bytes 8-25/38',
  1882. ]);
  1883. $response->expects($this->any())
  1884. ->method('_isActive')
  1885. ->will($this->returnValue(true));
  1886. $response->file(
  1887. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1888. ['download' => false]
  1889. );
  1890. ob_start();
  1891. $result = $response->send();
  1892. $output = ob_get_clean();
  1893. $this->assertEquals(206, $response->statusCode());
  1894. $this->assertEquals("is the test asset ", $output);
  1895. $this->assertNotSame(false, $result);
  1896. }
  1897. /**
  1898. * testFileRangeInvalidNoDownload method
  1899. *
  1900. * @return void
  1901. */
  1902. public function testFileRangeInvalidNoDownload()
  1903. {
  1904. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1905. $response = $this->getMockBuilder('Cake\Network\Response')
  1906. ->setMethods([
  1907. 'header',
  1908. 'type',
  1909. '_sendHeader',
  1910. '_isActive',
  1911. ])
  1912. ->getMock();
  1913. $response->expects($this->at(1))
  1914. ->method('header')
  1915. ->with('Accept-Ranges', 'bytes');
  1916. $response->expects($this->at(2))
  1917. ->method('header')
  1918. ->with([
  1919. 'Content-Range' => 'bytes 0-37/38',
  1920. ]);
  1921. $response->file(
  1922. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1923. ['download' => false]
  1924. );
  1925. $this->assertEquals(416, $response->statusCode());
  1926. $result = $response->send();
  1927. }
  1928. /**
  1929. * Test the location method.
  1930. *
  1931. * @return void
  1932. */
  1933. public function testLocation()
  1934. {
  1935. $response = new Response();
  1936. $this->assertNull($response->location(), 'No header should be set.');
  1937. $this->assertNull($response->location('http://example.org'), 'Setting a location should return null');
  1938. $this->assertEquals('http://example.org', $response->location(), 'Reading a location should return the value.');
  1939. }
  1940. /**
  1941. * Test the withLocation method.
  1942. *
  1943. * @return void
  1944. */
  1945. public function testWithLocation()
  1946. {
  1947. $response = new Response();
  1948. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  1949. $new = $response->withLocation('http://example.org');
  1950. $this->assertNotSame($new, $response);
  1951. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  1952. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  1953. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  1954. }
  1955. /**
  1956. * Test get protocol version.
  1957. *
  1958. * @return void
  1959. */
  1960. public function getProtocolVersion()
  1961. {
  1962. $response = new Response();
  1963. $version = $response->getProtocolVersion();
  1964. $this->assertEquals('1.1', $version);
  1965. }
  1966. /**
  1967. * Test with protocol.
  1968. *
  1969. * @return void
  1970. */
  1971. public function testWithProtocol()
  1972. {
  1973. $response = new Response();
  1974. $version = $response->getProtocolVersion();
  1975. $this->assertEquals('1.1', $version);
  1976. $response2 = $response->withProtocolVersion('1.0');
  1977. $version = $response2->getProtocolVersion();
  1978. $this->assertEquals('1.0', $version);
  1979. $version = $response->getProtocolVersion();
  1980. $this->assertEquals('1.1', $version);
  1981. $this->assertNotEquals($response, $response2);
  1982. }
  1983. /**
  1984. * Test with protocol.
  1985. *
  1986. * @return void
  1987. */
  1988. public function testWithStatusCode()
  1989. {
  1990. $response = new Response();
  1991. $statusCode = $response->getStatusCode();
  1992. $this->assertEquals(200, $statusCode);
  1993. $response2 = $response->withStatus(404);
  1994. $statusCode = $response2->getStatusCode();
  1995. $this->assertEquals(404, $statusCode);
  1996. $statusCode = $response->getStatusCode();
  1997. $this->assertEquals(200, $statusCode);
  1998. $this->assertNotEquals($response, $response2);
  1999. }
  2000. /**
  2001. * Test get reason phrase.
  2002. *
  2003. * @return void
  2004. */
  2005. public function testGetReasonPhrase()
  2006. {
  2007. $response = new Response();
  2008. $reasonPhrase = $response->getReasonPhrase();
  2009. $this->assertNull($reasonPhrase);
  2010. $response = $response->withStatus(404);
  2011. $reasonPhrase = $response->getReasonPhrase();
  2012. $this->assertEquals('Not Found', $reasonPhrase);
  2013. }
  2014. /**
  2015. * Test with body.
  2016. *
  2017. * @return void
  2018. */
  2019. public function testWithBody()
  2020. {
  2021. $response = new Response();
  2022. $body = $response->getBody();
  2023. $body->rewind();
  2024. $result = $body->getContents();
  2025. $this->assertEquals('', $result);
  2026. $stream = new Stream('php://memory', 'wb+');
  2027. $stream->write('test1');
  2028. $response2 = $response->withBody($stream);
  2029. $body = $response2->getBody();
  2030. $body->rewind();
  2031. $result = $body->getContents();
  2032. $this->assertEquals('test1', $result);
  2033. $body = $response->getBody();
  2034. $body->rewind();
  2035. $result = $body->getContents();
  2036. $this->assertEquals('', $result);
  2037. }
  2038. /**
  2039. * Test get Body.
  2040. *
  2041. * @return void
  2042. */
  2043. public function testGetBody()
  2044. {
  2045. $response = new Response();
  2046. $stream = $response->getBody();
  2047. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  2048. }
  2049. /**
  2050. * Test with header.
  2051. *
  2052. * @return void
  2053. */
  2054. public function testWithHeader()
  2055. {
  2056. $response = new Response();
  2057. $response2 = $response->withHeader('Accept', 'application/json');
  2058. $result = $response2->getHeaders();
  2059. $expected = [
  2060. 'Content-Type' => ['text/html; charset=UTF-8'],
  2061. 'Accept' => ['application/json']
  2062. ];
  2063. $this->assertEquals($expected, $result);
  2064. $this->assertFalse($response->hasHeader('Accept'));
  2065. }
  2066. /**
  2067. * Test get headers.
  2068. *
  2069. * @return void
  2070. */
  2071. public function testGetHeaders()
  2072. {
  2073. $response = new Response();
  2074. $headers = $response->getHeaders();
  2075. $response = $response->withAddedHeader('Location', 'localhost');
  2076. $response = $response->withAddedHeader('Accept', 'application/json');
  2077. $headers = $response->getHeaders();
  2078. $expected = [
  2079. 'Content-Type' => ['text/html; charset=UTF-8'],
  2080. 'Location' => ['localhost'],
  2081. 'Accept' => ['application/json']
  2082. ];
  2083. $this->assertEquals($expected, $headers);
  2084. }
  2085. /**
  2086. * Test without header.
  2087. *
  2088. * @return void
  2089. */
  2090. public function testWithoutHeader()
  2091. {
  2092. $response = new Response();
  2093. $response = $response->withAddedHeader('Location', 'localhost');
  2094. $response = $response->withAddedHeader('Accept', 'application/json');
  2095. $response2 = $response->withoutHeader('Location');
  2096. $headers = $response2->getHeaders();
  2097. $expected = [
  2098. 'Content-Type' => ['text/html; charset=UTF-8'],
  2099. 'Accept' => ['application/json']
  2100. ];
  2101. $this->assertEquals($expected, $headers);
  2102. }
  2103. /**
  2104. * Test get header.
  2105. *
  2106. * @return void
  2107. */
  2108. public function testGetHeader()
  2109. {
  2110. $response = new Response();
  2111. $response = $response->withAddedHeader('Location', 'localhost');
  2112. $result = $response->getHeader('Location');
  2113. $this->assertEquals(['localhost'], $result);
  2114. $result = $response->getHeader('location');
  2115. $this->assertEquals(['localhost'], $result);
  2116. $result = $response->getHeader('does-not-exist');
  2117. $this->assertEquals([], $result);
  2118. }
  2119. /**
  2120. * Test get header line.
  2121. *
  2122. * @return void
  2123. */
  2124. public function testGetHeaderLine()
  2125. {
  2126. $response = new Response();
  2127. $headers = $response->getHeaderLine('Accept');
  2128. $this->assertEquals('', $headers);
  2129. $response = $response->withAddedHeader('Accept', 'application/json');
  2130. $response = $response->withAddedHeader('Accept', 'application/xml');
  2131. $result = $response->getHeaderLine('Accept');
  2132. $expected = 'application/json,application/xml';
  2133. $this->assertEquals($expected, $result);
  2134. $result = $response->getHeaderLine('accept');
  2135. $this->assertEquals($expected, $result);
  2136. }
  2137. /**
  2138. * Test has header.
  2139. *
  2140. * @return void
  2141. */
  2142. public function testHasHeader()
  2143. {
  2144. $response = new Response();
  2145. $response = $response->withAddedHeader('Location', 'localhost');
  2146. $this->assertTrue($response->hasHeader('Location'));
  2147. $this->assertTrue($response->hasHeader('location'));
  2148. $this->assertTrue($response->hasHeader('locATIon'));
  2149. $this->assertFalse($response->hasHeader('Accept'));
  2150. $this->assertFalse($response->hasHeader('accept'));
  2151. }
  2152. /**
  2153. * Tests __debugInfo
  2154. *
  2155. * @return void
  2156. */
  2157. public function testDebugInfo()
  2158. {
  2159. $response = new Response();
  2160. $result = $response->__debugInfo();
  2161. $expected = [
  2162. 'status' => 200,
  2163. 'contentType' => 'text/html',
  2164. 'headers' => [
  2165. 'Content-Type' => ['text/html; charset=UTF-8']
  2166. ],
  2167. 'file' => null,
  2168. 'fileRange' => [],
  2169. 'cookies' => [],
  2170. 'cacheDirectives' => [],
  2171. 'body' => ''
  2172. ];
  2173. $this->assertEquals($expected, $result);
  2174. }
  2175. }