ResponseTest.php 96 KB

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