ResponseTest.php 94 KB

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