ResponseTest.php 100 KB

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