ResponseTest.php 97 KB

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