ResponseTest.php 98 KB

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