ResponseTest.php 98 KB

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