ResponseTest.php 97 KB

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