ResponseTest.php 96 KB

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