ResponseTest.php 95 KB

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