ResponseTest.php 97 KB

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