ResponseTest.php 99 KB

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