ResponseTest.php 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055
  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. /**
  1326. * Test getCookies() and array data.
  1327. *
  1328. * @return void
  1329. */
  1330. public function testGetCookies()
  1331. {
  1332. $response = new Response();
  1333. $new = $response->withCookie('testing', 'a')
  1334. ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => true]);
  1335. $expected = [
  1336. 'testing' => [
  1337. 'name' => 'testing',
  1338. 'value' => 'a',
  1339. 'expire' => null,
  1340. 'path' => '/',
  1341. 'domain' => '',
  1342. 'secure' => false,
  1343. 'httpOnly' => false
  1344. ],
  1345. 'test2' => [
  1346. 'name' => 'test2',
  1347. 'value' => 'b',
  1348. 'expire' => null,
  1349. 'path' => '/test',
  1350. 'domain' => '',
  1351. 'secure' => true,
  1352. 'httpOnly' => false
  1353. ]
  1354. ];
  1355. $this->assertEquals($expected, $new->getCookies());
  1356. }
  1357. /**
  1358. * Test getCookieCollection() as array data
  1359. *
  1360. * @return void
  1361. */
  1362. public function testGetCookieCollection()
  1363. {
  1364. $response = new Response();
  1365. $new = $response->withCookie('testing', 'a')
  1366. ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => true]);
  1367. $cookies = $response->getCookieCollection();
  1368. $this->assertInstanceOf(CookieCollection::class, $cookies);
  1369. $this->assertCount(0, $cookies, 'Original response not mutated');
  1370. $cookies = $new->getCookieCollection();
  1371. $this->assertInstanceOf(CookieCollection::class, $cookies);
  1372. $this->assertCount(2, $cookies);
  1373. $this->assertTrue($cookies->has('testing'));
  1374. $this->assertTrue($cookies->has('test2'));
  1375. }
  1376. /**
  1377. * Test CORS
  1378. *
  1379. * @dataProvider corsData
  1380. * @param Request $request
  1381. * @param string $origin
  1382. * @param string|array $domains
  1383. * @param string|array $methods
  1384. * @param string|array $headers
  1385. * @param string|bool $expectedOrigin
  1386. * @param string|bool $expectedMethods
  1387. * @param string|bool $expectedHeaders
  1388. * @return void
  1389. */
  1390. public function testCors($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods = false, $expectedHeaders = false)
  1391. {
  1392. $request->env('HTTP_ORIGIN', $origin);
  1393. $response = new Response();
  1394. $result = $response->cors($request, $domains, $methods, $headers);
  1395. $this->assertInstanceOf('Cake\Network\CorsBuilder', $result);
  1396. $headers = $response->header();
  1397. if ($expectedOrigin) {
  1398. $this->assertArrayHasKey('Access-Control-Allow-Origin', $headers);
  1399. $this->assertEquals($expectedOrigin, $headers['Access-Control-Allow-Origin']);
  1400. }
  1401. if ($expectedMethods) {
  1402. $this->assertArrayHasKey('Access-Control-Allow-Methods', $headers);
  1403. $this->assertEquals($expectedMethods, $headers['Access-Control-Allow-Methods']);
  1404. }
  1405. if ($expectedHeaders) {
  1406. $this->assertArrayHasKey('Access-Control-Allow-Headers', $headers);
  1407. $this->assertEquals($expectedHeaders, $headers['Access-Control-Allow-Headers']);
  1408. }
  1409. unset($_SERVER['HTTP_ORIGIN']);
  1410. }
  1411. /**
  1412. * Feed for testCors
  1413. *
  1414. * @return array
  1415. */
  1416. public function corsData()
  1417. {
  1418. $fooRequest = new ServerRequest();
  1419. $secureRequest = function () {
  1420. $secureRequest = $this->getMockBuilder('Cake\Http\ServerRequest')
  1421. ->setMethods(['is'])
  1422. ->getMock();
  1423. $secureRequest->expects($this->any())
  1424. ->method('is')
  1425. ->with('ssl')
  1426. ->will($this->returnValue(true));
  1427. return $secureRequest;
  1428. };
  1429. return [
  1430. [$fooRequest, null, '*', '', '', false, false],
  1431. [$fooRequest, 'http://www.foo.com', '*', '', '', '*', false],
  1432. [$fooRequest, 'http://www.foo.com', 'www.foo.com', '', '', 'http://www.foo.com', false],
  1433. [$fooRequest, 'http://www.foo.com', '*.foo.com', '', '', 'http://www.foo.com', false],
  1434. [$fooRequest, 'http://www.foo.com', 'http://*.foo.com', '', '', 'http://www.foo.com', false],
  1435. [$fooRequest, 'http://www.foo.com', 'https://www.foo.com', '', '', false, false],
  1436. [$fooRequest, 'http://www.foo.com', 'https://*.foo.com', '', '', false, false],
  1437. [$fooRequest, 'http://www.foo.com', ['*.bar.com', '*.foo.com'], '', '', 'http://www.foo.com', false],
  1438. [$fooRequest, 'http://not-foo.com', '*.foo.com', '', '', false, false],
  1439. [$fooRequest, 'http://bad.academy', '*.acad.my', '', '', false, false],
  1440. [$fooRequest, 'http://www.foo.com.at.bad.com', '*.foo.com', '', '', false, false],
  1441. [$fooRequest, 'https://www.foo.com', '*.foo.com', '', '', false, false],
  1442. [$secureRequest(), 'https://www.bar.com', 'www.bar.com', '', '', 'https://www.bar.com', false],
  1443. [$secureRequest(), 'https://www.bar.com', 'http://www.bar.com', '', '', false, false],
  1444. [$secureRequest(), 'https://www.bar.com', '*.bar.com', '', '', 'https://www.bar.com', false],
  1445. [$secureRequest(), 'http://www.bar.com', '*.bar.com', '', '', false, false],
  1446. [$fooRequest, 'http://www.foo.com', '*', 'GET', '', '*', 'GET'],
  1447. [$fooRequest, 'http://www.foo.com', '*.foo.com', 'GET', '', 'http://www.foo.com', 'GET'],
  1448. [$fooRequest, 'http://www.foo.com', '*.foo.com', ['GET', 'POST'], '', 'http://www.foo.com', 'GET, POST'],
  1449. [$fooRequest, 'http://www.foo.com', '*', '', 'X-CakePHP', '*', false, 'X-CakePHP'],
  1450. [$fooRequest, 'http://www.foo.com', '*', '', ['X-CakePHP', 'X-MyApp'], '*', false, 'X-CakePHP, X-MyApp'],
  1451. [$fooRequest, 'http://www.foo.com', '*', ['GET', 'OPTIONS'], ['X-CakePHP', 'X-MyApp'], '*', 'GET, OPTIONS', 'X-CakePHP, X-MyApp'],
  1452. ];
  1453. }
  1454. /**
  1455. * testFileNotFound
  1456. *
  1457. * @expectedException \Cake\Network\Exception\NotFoundException
  1458. * @return void
  1459. */
  1460. public function testFileNotFound()
  1461. {
  1462. $response = new Response();
  1463. $response->file('/some/missing/folder/file.jpg');
  1464. }
  1465. /**
  1466. * test withFile() not found
  1467. *
  1468. * @expectedException \Cake\Network\Exception\NotFoundException
  1469. * @return void
  1470. */
  1471. public function testWithFileNotFound()
  1472. {
  1473. $response = new Response();
  1474. $response->withFile('/some/missing/folder/file.jpg');
  1475. }
  1476. /**
  1477. * Provider for various kinds of unacceptable files.
  1478. *
  1479. * @return array
  1480. */
  1481. public function invalidFileProvider()
  1482. {
  1483. return [
  1484. ['my/../cat.gif', 'The requested file contains `..` and will not be read.'],
  1485. ['my\..\cat.gif', 'The requested file contains `..` and will not be read.'],
  1486. ['my/ca..t.gif', 'my/ca..t.gif was not found or not readable'],
  1487. ['my/ca..t/image.gif', 'my/ca..t/image.gif was not found or not readable'],
  1488. ];
  1489. }
  1490. /**
  1491. * test invalid file paths.
  1492. *
  1493. * @dataProvider invalidFileProvider
  1494. * @return void
  1495. */
  1496. public function testFileInvalidPath($path, $expectedMessage)
  1497. {
  1498. $response = new Response();
  1499. try {
  1500. $response->file($path);
  1501. } catch (NotFoundException $e) {
  1502. $this->assertContains($expectedMessage, $e->getMessage());
  1503. }
  1504. }
  1505. /**
  1506. * test withFile and invalid paths
  1507. *
  1508. * @dataProvider invalidFileProvider
  1509. * @return void
  1510. */
  1511. public function testWithFileInvalidPath($path, $expectedMessage)
  1512. {
  1513. $response = new Response();
  1514. try {
  1515. $response->withFile($path);
  1516. } catch (NotFoundException $e) {
  1517. $this->assertContains($expectedMessage, $e->getMessage());
  1518. }
  1519. }
  1520. /**
  1521. * testFile method
  1522. *
  1523. * @return void
  1524. */
  1525. public function testFile()
  1526. {
  1527. $response = $this->getMockBuilder('Cake\Http\Response')
  1528. ->setMethods([
  1529. 'header',
  1530. 'type',
  1531. '_sendHeader',
  1532. '_setContentType',
  1533. '_isActive',
  1534. ])
  1535. ->getMock();
  1536. $response->expects($this->exactly(1))
  1537. ->method('type')
  1538. ->with('css')
  1539. ->will($this->returnArgument(0));
  1540. $response->expects($this->at(1))
  1541. ->method('header')
  1542. ->with('Accept-Ranges', 'bytes');
  1543. $response->expects($this->exactly(1))
  1544. ->method('_isActive')
  1545. ->will($this->returnValue(true));
  1546. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1547. ob_start();
  1548. $result = $response->send();
  1549. $this->assertTrue($result !== false);
  1550. $output = ob_get_clean();
  1551. $expected = '/* this is the test asset css file */';
  1552. $this->assertEquals($expected, trim($output));
  1553. $this->assertEquals($expected, trim($response->getBody()->getContents()));
  1554. }
  1555. /**
  1556. * test withFile() + download & name
  1557. *
  1558. * @return void
  1559. */
  1560. public function testWithFileDownloadAndName()
  1561. {
  1562. $response = new Response();
  1563. $new = $response->withFile(
  1564. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1565. [
  1566. 'name' => 'something_special.css',
  1567. 'download' => true,
  1568. ]
  1569. );
  1570. $this->assertEquals(
  1571. 'text/html; charset=UTF-8',
  1572. $response->getHeaderLine('Content-Type'),
  1573. 'No mutation'
  1574. );
  1575. $this->assertEquals(
  1576. 'text/css; charset=UTF-8',
  1577. $new->getHeaderLine('Content-Type')
  1578. );
  1579. $this->assertEquals(
  1580. 'attachment; filename="something_special.css"',
  1581. $new->getHeaderLine('Content-Disposition')
  1582. );
  1583. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  1584. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  1585. $body = $new->getBody();
  1586. $this->assertInstanceOf('Zend\Diactoros\Stream', $body);
  1587. $expected = '/* this is the test asset css file */';
  1588. $this->assertEquals($expected, trim($body->getContents()));
  1589. $this->assertEquals($expected, trim($new->getFile()->read()));
  1590. }
  1591. /**
  1592. * testFileWithDownloadAndName
  1593. *
  1594. * @return void
  1595. */
  1596. public function testFileWithDownloadAndName()
  1597. {
  1598. $response = $this->getMockBuilder('Cake\Http\Response')
  1599. ->setMethods([
  1600. 'header',
  1601. 'type',
  1602. 'download',
  1603. '_sendHeader',
  1604. '_setContentType',
  1605. '_isActive',
  1606. ])
  1607. ->getMock();
  1608. $response->expects($this->exactly(1))
  1609. ->method('type')
  1610. ->with('css')
  1611. ->will($this->returnArgument(0));
  1612. $response->expects($this->once())
  1613. ->method('download')
  1614. ->with('something_special.css');
  1615. $response->expects($this->at(2))
  1616. ->method('header')
  1617. ->with('Content-Transfer-Encoding', 'binary');
  1618. $response->expects($this->at(3))
  1619. ->method('header')
  1620. ->with('Accept-Ranges', 'bytes');
  1621. $response->expects($this->exactly(1))
  1622. ->method('_isActive')
  1623. ->will($this->returnValue(true));
  1624. $response->file(
  1625. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1626. [
  1627. 'name' => 'something_special.css',
  1628. 'download' => true,
  1629. ]
  1630. );
  1631. ob_start();
  1632. $result = $response->send();
  1633. $output = ob_get_clean();
  1634. $this->assertEquals("/* this is the test asset css file */\n", $output);
  1635. $this->assertNotSame(false, $result);
  1636. }
  1637. /**
  1638. * testFileWithUnknownFileTypeGeneric method
  1639. *
  1640. * @return void
  1641. */
  1642. public function testFileWithUnknownFileTypeGeneric()
  1643. {
  1644. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1645. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1646. $response = $this->getMockBuilder('Cake\Http\Response')
  1647. ->setMethods([
  1648. 'header',
  1649. 'type',
  1650. 'download',
  1651. '_sendHeader',
  1652. '_setContentType',
  1653. '_isActive',
  1654. ])
  1655. ->getMock();
  1656. $response->expects($this->exactly(1))
  1657. ->method('type')
  1658. ->with('ini')
  1659. ->will($this->returnValue(false));
  1660. $response->expects($this->once())
  1661. ->method('download')
  1662. ->with('no_section.ini');
  1663. $response->expects($this->at(2))
  1664. ->method('header')
  1665. ->with('Content-Transfer-Encoding', 'binary');
  1666. $response->expects($this->at(3))
  1667. ->method('header')
  1668. ->with('Accept-Ranges', 'bytes');
  1669. $response->expects($this->exactly(1))
  1670. ->method('_isActive')
  1671. ->will($this->returnValue(true));
  1672. $response->file(CONFIG . 'no_section.ini');
  1673. ob_start();
  1674. $result = $response->send();
  1675. $output = ob_get_clean();
  1676. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1677. $this->assertNotSame(false, $result);
  1678. if ($currentUserAgent !== null) {
  1679. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1680. }
  1681. }
  1682. /**
  1683. * test withFile() + a generic agent
  1684. *
  1685. * @return void
  1686. */
  1687. public function testWithFileUnknownFileTypeGeneric()
  1688. {
  1689. $response = new Response();
  1690. $new = $response->withFile(CONFIG . 'no_section.ini');
  1691. $this->assertEquals('text/html; charset=UTF-8', $new->getHeaderLine('Content-Type'));
  1692. $this->assertEquals(
  1693. 'attachment; filename="no_section.ini"',
  1694. $new->getHeaderLine('Content-Disposition')
  1695. );
  1696. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  1697. $body = $new->getBody();
  1698. $expected = "some_key = some_value\nbool_key = 1\n";
  1699. $this->assertEquals($expected, $body->getContents());
  1700. }
  1701. /**
  1702. * testFileWithUnknownFileTypeOpera method
  1703. *
  1704. * @return void
  1705. */
  1706. public function testFileWithUnknownFileTypeOpera()
  1707. {
  1708. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1709. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  1710. $response = $this->getMockBuilder('Cake\Http\Response')
  1711. ->setMethods([
  1712. 'header',
  1713. 'type',
  1714. 'download',
  1715. '_sendHeader',
  1716. '_setContentType',
  1717. '_isActive',
  1718. ])
  1719. ->getMock();
  1720. $response->expects($this->at(0))
  1721. ->method('type')
  1722. ->with('ini')
  1723. ->will($this->returnValue(false));
  1724. $response->expects($this->at(1))
  1725. ->method('type')
  1726. ->with('application/octet-stream')
  1727. ->will($this->returnValue(false));
  1728. $response->expects($this->once())
  1729. ->method('download')
  1730. ->with('no_section.ini');
  1731. $response->expects($this->at(3))
  1732. ->method('header')
  1733. ->with('Content-Transfer-Encoding', 'binary');
  1734. $response->expects($this->at(4))
  1735. ->method('header')
  1736. ->with('Accept-Ranges', 'bytes');
  1737. $response->expects($this->exactly(1))
  1738. ->method('_isActive')
  1739. ->will($this->returnValue(true));
  1740. $response->file(CONFIG . 'no_section.ini');
  1741. ob_start();
  1742. $result = $response->send();
  1743. $output = ob_get_clean();
  1744. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1745. $this->assertNotSame(false, $result);
  1746. if ($currentUserAgent !== null) {
  1747. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1748. }
  1749. }
  1750. /**
  1751. * test withFile() + opera
  1752. *
  1753. * @return void
  1754. */
  1755. public function testWithFileUnknownFileTypeOpera()
  1756. {
  1757. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1758. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  1759. $response = new Response();
  1760. $new = $response->withFile(CONFIG . 'no_section.ini');
  1761. $this->assertEquals('application/octet-stream', $new->getHeaderLine('Content-Type'));
  1762. $this->assertEquals(
  1763. 'attachment; filename="no_section.ini"',
  1764. $new->getHeaderLine('Content-Disposition')
  1765. );
  1766. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1767. }
  1768. /**
  1769. * testFileWithUnknownFileTypeIE method
  1770. *
  1771. * @return void
  1772. */
  1773. public function testFileWithUnknownFileTypeIE()
  1774. {
  1775. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1776. $_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)';
  1777. $response = $this->getMockBuilder('Cake\Http\Response')
  1778. ->setMethods([
  1779. 'header',
  1780. 'type',
  1781. 'download',
  1782. '_sendHeader',
  1783. '_setContentType',
  1784. '_isActive',
  1785. ])
  1786. ->getMock();
  1787. $response->expects($this->at(0))
  1788. ->method('type')
  1789. ->with('ini')
  1790. ->will($this->returnValue(false));
  1791. $response->expects($this->at(1))
  1792. ->method('type')
  1793. ->with('application/force-download')
  1794. ->will($this->returnValue(false));
  1795. $response->expects($this->once())
  1796. ->method('download')
  1797. ->with('config.ini');
  1798. $response->expects($this->at(3))
  1799. ->method('header')
  1800. ->with('Content-Transfer-Encoding', 'binary');
  1801. $response->expects($this->at(4))
  1802. ->method('header')
  1803. ->with('Accept-Ranges', 'bytes');
  1804. $response->expects($this->exactly(1))
  1805. ->method('_isActive')
  1806. ->will($this->returnValue(true));
  1807. $response->file(CONFIG . 'no_section.ini', [
  1808. 'name' => 'config.ini'
  1809. ]);
  1810. ob_start();
  1811. $result = $response->send();
  1812. $output = ob_get_clean();
  1813. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1814. $this->assertNotSame(false, $result);
  1815. if ($currentUserAgent !== null) {
  1816. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1817. }
  1818. }
  1819. /**
  1820. * test withFile() + old IE
  1821. *
  1822. * @return void
  1823. */
  1824. public function testWithFileUnknownFileTypeOldIe()
  1825. {
  1826. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1827. $_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)';
  1828. $response = new Response();
  1829. $new = $response->withFile(CONFIG . 'no_section.ini');
  1830. $this->assertEquals('application/force-download', $new->getHeaderLine('Content-Type'));
  1831. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1832. }
  1833. /**
  1834. * testFileWithUnknownFileNoDownload method
  1835. *
  1836. * @return void
  1837. */
  1838. public function testFileWithUnknownFileNoDownload()
  1839. {
  1840. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1841. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1842. $response = $this->getMockBuilder('Cake\Http\Response')
  1843. ->setMethods([
  1844. 'header',
  1845. 'type',
  1846. 'download',
  1847. '_sendHeader',
  1848. '_setContentType',
  1849. '_isActive',
  1850. ])
  1851. ->getMock();
  1852. $response->expects($this->exactly(1))
  1853. ->method('type')
  1854. ->with('ini')
  1855. ->will($this->returnValue(false));
  1856. $response->expects($this->at(1))
  1857. ->method('header')
  1858. ->with('Accept-Ranges', 'bytes');
  1859. $response->expects($this->never())
  1860. ->method('download');
  1861. $response->file(CONFIG . 'no_section.ini', [
  1862. 'download' => false
  1863. ]);
  1864. if ($currentUserAgent !== null) {
  1865. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1866. }
  1867. }
  1868. /**
  1869. * test withFile() + no download
  1870. *
  1871. * @return void
  1872. */
  1873. public function testWithFileNoDownload()
  1874. {
  1875. $response = new Response();
  1876. $new = $response->withFile(CONFIG . 'no_section.ini', [
  1877. 'download' => false
  1878. ]);
  1879. $this->assertEquals(
  1880. 'text/html; charset=UTF-8',
  1881. $new->getHeaderLine('Content-Type')
  1882. );
  1883. $this->assertFalse($new->hasHeader('Content-Disposition'));
  1884. $this->assertFalse($new->hasHeader('Content-Transfer-Encoding'));
  1885. }
  1886. /**
  1887. * test getFile method
  1888. *
  1889. * @return void
  1890. */
  1891. public function testGetFile()
  1892. {
  1893. $response = new Response();
  1894. $this->assertNull($response->getFile(), 'No file to get');
  1895. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1896. $file = $response->getFile();
  1897. $this->assertInstanceOf('Cake\Filesystem\File', $file, 'Should get a file');
  1898. $this->assertPathEquals(TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css', $file->path);
  1899. }
  1900. /**
  1901. * testConnectionAbortedOnBuffering method
  1902. *
  1903. * @return void
  1904. */
  1905. public function testConnectionAbortedOnBuffering()
  1906. {
  1907. $response = $this->getMockBuilder('Cake\Http\Response')
  1908. ->setMethods([
  1909. 'header',
  1910. 'type',
  1911. 'download',
  1912. '_sendHeader',
  1913. '_setContentType',
  1914. '_isActive',
  1915. ])
  1916. ->getMock();
  1917. $response->expects($this->any())
  1918. ->method('type')
  1919. ->with('css')
  1920. ->will($this->returnArgument(0));
  1921. $response->expects($this->at(0))
  1922. ->method('_isActive')
  1923. ->will($this->returnValue(false));
  1924. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1925. $result = $response->send();
  1926. $this->assertNull($result);
  1927. }
  1928. /**
  1929. * Test downloading files with UPPERCASE extensions.
  1930. *
  1931. * @return void
  1932. */
  1933. public function testFileUpperExtension()
  1934. {
  1935. $response = $this->getMockBuilder('Cake\Http\Response')
  1936. ->setMethods([
  1937. 'header',
  1938. 'type',
  1939. 'download',
  1940. '_sendHeader',
  1941. '_setContentType',
  1942. '_isActive',
  1943. ])
  1944. ->getMock();
  1945. $response->expects($this->any())
  1946. ->method('type')
  1947. ->with('jpg')
  1948. ->will($this->returnArgument(0));
  1949. $response->expects($this->at(0))
  1950. ->method('_isActive')
  1951. ->will($this->returnValue(true));
  1952. $response->file(TEST_APP . 'vendor/img/test_2.JPG');
  1953. }
  1954. /**
  1955. * Test that uppercase extensions result in correct content-types
  1956. *
  1957. * @return void
  1958. */
  1959. public function testWithFileUpperExtension()
  1960. {
  1961. $response = new Response();
  1962. $new = $response->withFile(TEST_APP . 'vendor/img/test_2.JPG');
  1963. $this->assertEquals('image/jpeg', $new->getHeaderLine('Content-Type'));
  1964. }
  1965. /**
  1966. * Test downloading files with extension not explicitly set.
  1967. *
  1968. * @return void
  1969. */
  1970. public function testFileExtensionNotSet()
  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. * A data provider for testing various ranges
  1993. *
  1994. * @return array
  1995. */
  1996. public static function rangeProvider()
  1997. {
  1998. return [
  1999. // suffix-byte-range
  2000. [
  2001. 'bytes=-25', 25, 'bytes 13-37/38'
  2002. ],
  2003. [
  2004. 'bytes=0-', 38, 'bytes 0-37/38'
  2005. ],
  2006. [
  2007. 'bytes=10-', 28, 'bytes 10-37/38'
  2008. ],
  2009. [
  2010. 'bytes=10-20', 11, 'bytes 10-20/38'
  2011. ],
  2012. // Spaced out
  2013. [
  2014. 'bytes = 10 - 20', 11, 'bytes 10-20/38'
  2015. ],
  2016. ];
  2017. }
  2018. /**
  2019. * Test the various range offset types.
  2020. *
  2021. * @dataProvider rangeProvider
  2022. * @return void
  2023. */
  2024. public function testFileRangeOffsets($range, $length, $offsetResponse)
  2025. {
  2026. $_SERVER['HTTP_RANGE'] = $range;
  2027. $response = $this->getMockBuilder('Cake\Http\Response')
  2028. ->setMethods([
  2029. 'header',
  2030. 'type',
  2031. '_sendHeader',
  2032. '_setContentType',
  2033. '_isActive',
  2034. ])
  2035. ->getMock();
  2036. $response->expects($this->at(1))
  2037. ->method('header')
  2038. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  2039. $response->expects($this->at(2))
  2040. ->method('header')
  2041. ->with('Content-Transfer-Encoding', 'binary');
  2042. $response->expects($this->at(3))
  2043. ->method('header')
  2044. ->with('Accept-Ranges', 'bytes');
  2045. $response->expects($this->at(4))
  2046. ->method('header')
  2047. ->with([
  2048. 'Content-Length' => $length,
  2049. 'Content-Range' => $offsetResponse,
  2050. ]);
  2051. $response->expects($this->any())
  2052. ->method('_isActive')
  2053. ->will($this->returnValue(true));
  2054. $response->file(
  2055. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2056. ['download' => true]
  2057. );
  2058. ob_start();
  2059. $result = $response->send();
  2060. ob_get_clean();
  2061. }
  2062. /**
  2063. * Test withFile() & the various range offset types.
  2064. *
  2065. * @dataProvider rangeProvider
  2066. * @return void
  2067. */
  2068. public function testWithFileRangeOffsets($range, $length, $offsetResponse)
  2069. {
  2070. $_SERVER['HTTP_RANGE'] = $range;
  2071. $response = new Response();
  2072. $new = $response->withFile(
  2073. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2074. ['download' => true]
  2075. );
  2076. $this->assertEquals(
  2077. 'attachment; filename="test_asset.css"',
  2078. $new->getHeaderLine('Content-Disposition')
  2079. );
  2080. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2081. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2082. $this->assertEquals($length, $new->getHeaderLine('Content-Length'));
  2083. $this->assertEquals($offsetResponse, $new->getHeaderLine('Content-Range'));
  2084. }
  2085. /**
  2086. * Test fetching ranges from a file.
  2087. *
  2088. * @return void
  2089. */
  2090. public function testFileRange()
  2091. {
  2092. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  2093. $response = $this->getMockBuilder('Cake\Http\Response')
  2094. ->setMethods([
  2095. 'header',
  2096. 'type',
  2097. '_sendHeader',
  2098. '_setContentType',
  2099. '_isActive',
  2100. ])
  2101. ->getMock();
  2102. $response->expects($this->exactly(1))
  2103. ->method('type')
  2104. ->with('css')
  2105. ->will($this->returnArgument(0));
  2106. $response->expects($this->at(1))
  2107. ->method('header')
  2108. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  2109. $response->expects($this->at(2))
  2110. ->method('header')
  2111. ->with('Content-Transfer-Encoding', 'binary');
  2112. $response->expects($this->at(3))
  2113. ->method('header')
  2114. ->with('Accept-Ranges', 'bytes');
  2115. $response->expects($this->at(4))
  2116. ->method('header')
  2117. ->with([
  2118. 'Content-Length' => 18,
  2119. 'Content-Range' => 'bytes 8-25/38',
  2120. ]);
  2121. $response->expects($this->any())
  2122. ->method('_isActive')
  2123. ->will($this->returnValue(true));
  2124. $response->file(
  2125. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2126. ['download' => true]
  2127. );
  2128. ob_start();
  2129. $result = $response->send();
  2130. $output = ob_get_clean();
  2131. $this->assertEquals(206, $response->statusCode());
  2132. $this->assertEquals('is the test asset ', $output);
  2133. $this->assertNotSame(false, $result);
  2134. }
  2135. /**
  2136. * Test withFile() fetching ranges from a file.
  2137. *
  2138. * @return void
  2139. */
  2140. public function testWithFileRange()
  2141. {
  2142. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  2143. $response = new Response();
  2144. $new = $response->withFile(
  2145. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2146. ['download' => true]
  2147. );
  2148. $this->assertEquals(
  2149. 'attachment; filename="test_asset.css"',
  2150. $new->getHeaderLine('Content-Disposition')
  2151. );
  2152. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2153. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2154. $this->assertEquals('18', $new->getHeaderLine('Content-Length'));
  2155. $this->assertEquals('bytes 8-25/38', $new->getHeaderLine('Content-Range'));
  2156. $this->assertEquals(206, $new->getStatusCode());
  2157. }
  2158. /**
  2159. * Provider for invalid range header values.
  2160. *
  2161. * @return array
  2162. */
  2163. public function invalidFileRangeProvider()
  2164. {
  2165. return [
  2166. // malformed range
  2167. [
  2168. 'bytes=0,38'
  2169. ],
  2170. // malformed punctuation
  2171. [
  2172. 'bytes: 0 - 38'
  2173. ],
  2174. ];
  2175. }
  2176. /**
  2177. * Test invalid file ranges.
  2178. *
  2179. * @dataProvider invalidFileRangeProvider
  2180. * @return void
  2181. */
  2182. public function testFileRangeInvalid($range)
  2183. {
  2184. $_SERVER['HTTP_RANGE'] = $range;
  2185. $response = $this->getMockBuilder('Cake\Http\Response')
  2186. ->setMethods([
  2187. '_sendHeader',
  2188. '_isActive',
  2189. ])
  2190. ->getMock();
  2191. $response->file(
  2192. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2193. ['download' => true]
  2194. );
  2195. $expected = [
  2196. 'Content-Type' => 'text/css; charset=UTF-8',
  2197. 'Content-Disposition' => 'attachment; filename="test_asset.css"',
  2198. 'Content-Transfer-Encoding' => 'binary',
  2199. 'Accept-Ranges' => 'bytes',
  2200. 'Content-Range' => 'bytes 0-37/38',
  2201. 'Content-Length' => 38,
  2202. ];
  2203. $this->assertEquals($expected, $response->header());
  2204. }
  2205. /**
  2206. * Test withFile() and invalid ranges
  2207. *
  2208. * @dataProvider invalidFileRangeProvider
  2209. * @return void
  2210. */
  2211. public function testWithFileInvalidRange($range)
  2212. {
  2213. $_SERVER['HTTP_RANGE'] = $range;
  2214. $response = new Response();
  2215. $new = $response->withFile(
  2216. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2217. ['download' => true]
  2218. );
  2219. $this->assertEquals(
  2220. 'attachment; filename="test_asset.css"',
  2221. $new->getHeaderLine('Content-Disposition')
  2222. );
  2223. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2224. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2225. $this->assertEquals('38', $new->getHeaderLine('Content-Length'));
  2226. $this->assertEquals('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  2227. $this->assertEquals(206, $new->getStatusCode());
  2228. }
  2229. /**
  2230. * Test reversed file ranges.
  2231. *
  2232. * @return void
  2233. */
  2234. public function testFileRangeReversed()
  2235. {
  2236. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  2237. $response = $this->getMockBuilder('Cake\Http\Response')
  2238. ->setMethods([
  2239. 'header',
  2240. 'type',
  2241. '_sendHeader',
  2242. '_isActive',
  2243. ])
  2244. ->getMock();
  2245. $response->expects($this->at(1))
  2246. ->method('header')
  2247. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  2248. $response->expects($this->at(2))
  2249. ->method('header')
  2250. ->with('Content-Transfer-Encoding', 'binary');
  2251. $response->expects($this->at(3))
  2252. ->method('header')
  2253. ->with('Accept-Ranges', 'bytes');
  2254. $response->expects($this->at(4))
  2255. ->method('header')
  2256. ->with([
  2257. 'Content-Range' => 'bytes 0-37/38',
  2258. ]);
  2259. $response->file(
  2260. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2261. ['download' => true]
  2262. );
  2263. $this->assertEquals(416, $response->statusCode());
  2264. $result = $response->send();
  2265. }
  2266. /**
  2267. * Test withFile() and a reversed range
  2268. *
  2269. * @return void
  2270. */
  2271. public function testWithFileReversedRange()
  2272. {
  2273. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  2274. $response = new Response();
  2275. $new = $response->withFile(
  2276. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2277. ['download' => true]
  2278. );
  2279. $this->assertEquals(
  2280. 'attachment; filename="test_asset.css"',
  2281. $new->getHeaderLine('Content-Disposition')
  2282. );
  2283. $this->assertEquals('binary', $new->getHeaderLine('Content-Transfer-Encoding'));
  2284. $this->assertEquals('bytes', $new->getHeaderLine('Accept-Ranges'));
  2285. $this->assertEquals('bytes 0-37/38', $new->getHeaderLine('Content-Range'));
  2286. $this->assertEquals(416, $new->getStatusCode());
  2287. }
  2288. /**
  2289. * testFileRangeOffsetsNoDownload method
  2290. *
  2291. * @dataProvider rangeProvider
  2292. * @return void
  2293. */
  2294. public function testFileRangeOffsetsNoDownload($range, $length, $offsetResponse)
  2295. {
  2296. $_SERVER['HTTP_RANGE'] = $range;
  2297. $response = $this->getMockBuilder('Cake\Http\Response')
  2298. ->setMethods([
  2299. 'header',
  2300. 'type',
  2301. '_sendHeader',
  2302. '_isActive',
  2303. ])
  2304. ->getMock();
  2305. $response->expects($this->at(1))
  2306. ->method('header')
  2307. ->with('Accept-Ranges', 'bytes');
  2308. $response->expects($this->at(2))
  2309. ->method('header')
  2310. ->with([
  2311. 'Content-Length' => $length,
  2312. 'Content-Range' => $offsetResponse,
  2313. ]);
  2314. $response->expects($this->any())
  2315. ->method('_isActive')
  2316. ->will($this->returnValue(true));
  2317. $response->file(
  2318. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2319. ['download' => false]
  2320. );
  2321. ob_start();
  2322. $result = $response->send();
  2323. ob_get_clean();
  2324. }
  2325. /**
  2326. * testFileRangeNoDownload method
  2327. *
  2328. * @return void
  2329. */
  2330. public function testFileRangeNoDownload()
  2331. {
  2332. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  2333. $response = $this->getMockBuilder('Cake\Http\Response')
  2334. ->setMethods([
  2335. 'header',
  2336. 'type',
  2337. '_sendHeader',
  2338. '_isActive',
  2339. ])
  2340. ->getMock();
  2341. $response->expects($this->exactly(1))
  2342. ->method('type')
  2343. ->with('css')
  2344. ->will($this->returnArgument(0));
  2345. $response->expects($this->at(1))
  2346. ->method('header')
  2347. ->with('Accept-Ranges', 'bytes');
  2348. $response->expects($this->at(2))
  2349. ->method('header')
  2350. ->with([
  2351. 'Content-Length' => 18,
  2352. 'Content-Range' => 'bytes 8-25/38',
  2353. ]);
  2354. $response->expects($this->any())
  2355. ->method('_isActive')
  2356. ->will($this->returnValue(true));
  2357. $response->file(
  2358. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2359. ['download' => false]
  2360. );
  2361. ob_start();
  2362. $result = $response->send();
  2363. $output = ob_get_clean();
  2364. $this->assertEquals(206, $response->statusCode());
  2365. $this->assertEquals('is the test asset ', $output);
  2366. $this->assertNotSame(false, $result);
  2367. }
  2368. /**
  2369. * testFileRangeInvalidNoDownload method
  2370. *
  2371. * @return void
  2372. */
  2373. public function testFileRangeInvalidNoDownload()
  2374. {
  2375. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  2376. $response = $this->getMockBuilder('Cake\Http\Response')
  2377. ->setMethods([
  2378. 'header',
  2379. 'type',
  2380. '_sendHeader',
  2381. '_isActive',
  2382. ])
  2383. ->getMock();
  2384. $response->expects($this->at(1))
  2385. ->method('header')
  2386. ->with('Accept-Ranges', 'bytes');
  2387. $response->expects($this->at(2))
  2388. ->method('header')
  2389. ->with([
  2390. 'Content-Range' => 'bytes 0-37/38',
  2391. ]);
  2392. $response->file(
  2393. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  2394. ['download' => false]
  2395. );
  2396. $this->assertEquals(416, $response->statusCode());
  2397. $result = $response->send();
  2398. }
  2399. /**
  2400. * Test the location method.
  2401. *
  2402. * @return void
  2403. */
  2404. public function testLocation()
  2405. {
  2406. $response = new Response();
  2407. $this->assertNull($response->location(), 'No header should be set.');
  2408. $this->assertNull($response->location('http://example.org'), 'Setting a location should return null');
  2409. $this->assertEquals('http://example.org', $response->location(), 'Reading a location should return the value.');
  2410. }
  2411. /**
  2412. * Test the withLocation method.
  2413. *
  2414. * @return void
  2415. */
  2416. public function testWithLocation()
  2417. {
  2418. $response = new Response();
  2419. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  2420. $new = $response->withLocation('http://example.org');
  2421. $this->assertNotSame($new, $response);
  2422. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  2423. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  2424. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  2425. }
  2426. /**
  2427. * Test get protocol version.
  2428. *
  2429. * @return void
  2430. */
  2431. public function getProtocolVersion()
  2432. {
  2433. $response = new Response();
  2434. $version = $response->getProtocolVersion();
  2435. $this->assertEquals('1.1', $version);
  2436. }
  2437. /**
  2438. * Test with protocol.
  2439. *
  2440. * @return void
  2441. */
  2442. public function testWithProtocol()
  2443. {
  2444. $response = new Response();
  2445. $version = $response->getProtocolVersion();
  2446. $this->assertEquals('1.1', $version);
  2447. $response2 = $response->withProtocolVersion('1.0');
  2448. $version = $response2->getProtocolVersion();
  2449. $this->assertEquals('1.0', $version);
  2450. $version = $response->getProtocolVersion();
  2451. $this->assertEquals('1.1', $version);
  2452. $this->assertNotEquals($response, $response2);
  2453. }
  2454. /**
  2455. * Test with protocol.
  2456. *
  2457. * @return void
  2458. */
  2459. public function testWithStatusCode()
  2460. {
  2461. $response = new Response();
  2462. $statusCode = $response->getStatusCode();
  2463. $this->assertEquals(200, $statusCode);
  2464. $response2 = $response->withStatus(404);
  2465. $statusCode = $response2->getStatusCode();
  2466. $this->assertEquals(404, $statusCode);
  2467. $statusCode = $response->getStatusCode();
  2468. $this->assertEquals(200, $statusCode);
  2469. $this->assertNotEquals($response, $response2);
  2470. }
  2471. /**
  2472. * Test get reason phrase.
  2473. *
  2474. * @return void
  2475. */
  2476. public function testGetReasonPhrase()
  2477. {
  2478. $response = new Response();
  2479. $this->assertSame('OK', $response->getReasonPhrase());
  2480. $response = $response->withStatus(404);
  2481. $reasonPhrase = $response->getReasonPhrase();
  2482. $this->assertEquals('Not Found', $reasonPhrase);
  2483. }
  2484. /**
  2485. * Test with body.
  2486. *
  2487. * @return void
  2488. */
  2489. public function testWithBody()
  2490. {
  2491. $response = new Response();
  2492. $body = $response->getBody();
  2493. $body->rewind();
  2494. $result = $body->getContents();
  2495. $this->assertEquals('', $result);
  2496. $stream = new Stream('php://memory', 'wb+');
  2497. $stream->write('test1');
  2498. $response2 = $response->withBody($stream);
  2499. $body = $response2->getBody();
  2500. $body->rewind();
  2501. $result = $body->getContents();
  2502. $this->assertEquals('test1', $result);
  2503. $body = $response->getBody();
  2504. $body->rewind();
  2505. $result = $body->getContents();
  2506. $this->assertEquals('', $result);
  2507. }
  2508. /**
  2509. * Test with string body.
  2510. *
  2511. * @return void
  2512. */
  2513. public function testWithStringBody()
  2514. {
  2515. $response = new Response();
  2516. $newResponse = $response->withStringBody('Foo');
  2517. $body = $newResponse->getBody();
  2518. $this->assertSame('Foo', (string)$body);
  2519. $this->assertNotSame($response, $newResponse);
  2520. $response = new Response();
  2521. $newResponse = $response->withStringBody('');
  2522. $body = $newResponse->getBody();
  2523. $this->assertSame('', (string)$body);
  2524. $this->assertNotSame($response, $newResponse);
  2525. $response = new Response();
  2526. $newResponse = $response->withStringBody(null);
  2527. $body = $newResponse->getBody();
  2528. $this->assertSame('', (string)$body);
  2529. $this->assertNotSame($response, $newResponse);
  2530. $response = new Response();
  2531. $newResponse = $response->withStringBody(1337);
  2532. $body = $newResponse->getBody();
  2533. $this->assertSame('1337', (string)$body);
  2534. $this->assertNotSame($response, $newResponse);
  2535. }
  2536. /**
  2537. * Test with string body with passed array.
  2538. *
  2539. * This should produce an "Array to string conversion" error
  2540. * which gets thrown as a \PHPUnit\Framework\Error\Error Exception by PHPUnit.
  2541. *
  2542. * @expectedException \PHPUnit\Framework\Error\Error
  2543. * @expectedExceptionMessage Array to string conversion
  2544. * @return void
  2545. */
  2546. public function testWithStringBodyArray()
  2547. {
  2548. $response = new Response();
  2549. $newResponse = $response->withStringBody(['foo' => 'bar']);
  2550. $body = $newResponse->getBody();
  2551. $this->assertSame('', (string)$body);
  2552. $this->assertNotSame($response, $newResponse);
  2553. }
  2554. /**
  2555. * Test get Body.
  2556. *
  2557. * @return void
  2558. */
  2559. public function testGetBody()
  2560. {
  2561. $response = new Response();
  2562. $stream = $response->getBody();
  2563. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  2564. }
  2565. /**
  2566. * Test with header.
  2567. *
  2568. * @return void
  2569. */
  2570. public function testWithHeader()
  2571. {
  2572. $response = new Response();
  2573. $response2 = $response->withHeader('Accept', 'application/json');
  2574. $result = $response2->getHeaders();
  2575. $expected = [
  2576. 'Content-Type' => ['text/html; charset=UTF-8'],
  2577. 'Accept' => ['application/json']
  2578. ];
  2579. $this->assertEquals($expected, $result);
  2580. $this->assertFalse($response->hasHeader('Accept'));
  2581. }
  2582. /**
  2583. * Test get headers.
  2584. *
  2585. * @return void
  2586. */
  2587. public function testGetHeaders()
  2588. {
  2589. $response = new Response();
  2590. $headers = $response->getHeaders();
  2591. $response = $response->withAddedHeader('Location', 'localhost');
  2592. $response = $response->withAddedHeader('Accept', 'application/json');
  2593. $headers = $response->getHeaders();
  2594. $expected = [
  2595. 'Content-Type' => ['text/html; charset=UTF-8'],
  2596. 'Location' => ['localhost'],
  2597. 'Accept' => ['application/json']
  2598. ];
  2599. $this->assertEquals($expected, $headers);
  2600. }
  2601. /**
  2602. * Test without header.
  2603. *
  2604. * @return void
  2605. */
  2606. public function testWithoutHeader()
  2607. {
  2608. $response = new Response();
  2609. $response = $response->withAddedHeader('Location', 'localhost');
  2610. $response = $response->withAddedHeader('Accept', 'application/json');
  2611. $response2 = $response->withoutHeader('Location');
  2612. $headers = $response2->getHeaders();
  2613. $expected = [
  2614. 'Content-Type' => ['text/html; charset=UTF-8'],
  2615. 'Accept' => ['application/json']
  2616. ];
  2617. $this->assertEquals($expected, $headers);
  2618. }
  2619. /**
  2620. * Test get header.
  2621. *
  2622. * @return void
  2623. */
  2624. public function testGetHeader()
  2625. {
  2626. $response = new Response();
  2627. $response = $response->withAddedHeader('Location', 'localhost');
  2628. $result = $response->getHeader('Location');
  2629. $this->assertEquals(['localhost'], $result);
  2630. $result = $response->getHeader('location');
  2631. $this->assertEquals(['localhost'], $result);
  2632. $result = $response->getHeader('does-not-exist');
  2633. $this->assertEquals([], $result);
  2634. }
  2635. /**
  2636. * Test get header line.
  2637. *
  2638. * @return void
  2639. */
  2640. public function testGetHeaderLine()
  2641. {
  2642. $response = new Response();
  2643. $headers = $response->getHeaderLine('Accept');
  2644. $this->assertEquals('', $headers);
  2645. $response = $response->withAddedHeader('Accept', 'application/json');
  2646. $response = $response->withAddedHeader('Accept', 'application/xml');
  2647. $result = $response->getHeaderLine('Accept');
  2648. $expected = 'application/json,application/xml';
  2649. $this->assertEquals($expected, $result);
  2650. $result = $response->getHeaderLine('accept');
  2651. $this->assertEquals($expected, $result);
  2652. }
  2653. /**
  2654. * Test has header.
  2655. *
  2656. * @return void
  2657. */
  2658. public function testHasHeader()
  2659. {
  2660. $response = new Response();
  2661. $response = $response->withAddedHeader('Location', 'localhost');
  2662. $this->assertTrue($response->hasHeader('Location'));
  2663. $this->assertTrue($response->hasHeader('location'));
  2664. $this->assertTrue($response->hasHeader('locATIon'));
  2665. $this->assertFalse($response->hasHeader('Accept'));
  2666. $this->assertFalse($response->hasHeader('accept'));
  2667. }
  2668. /**
  2669. * Tests __debugInfo
  2670. *
  2671. * @return void
  2672. */
  2673. public function testDebugInfo()
  2674. {
  2675. $response = new Response();
  2676. $result = $response->__debugInfo();
  2677. $expected = [
  2678. 'status' => 200,
  2679. 'contentType' => 'text/html',
  2680. 'headers' => [
  2681. 'Content-Type' => ['text/html; charset=UTF-8']
  2682. ],
  2683. 'file' => null,
  2684. 'fileRange' => [],
  2685. 'cookies' => new CookieCollection(),
  2686. 'cacheDirectives' => [],
  2687. 'body' => ''
  2688. ];
  2689. $this->assertEquals($expected, $result);
  2690. }
  2691. }