ResponseTest.php 94 KB

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