ResponseTest.php 96 KB

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