ResponseTest.php 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Network;
  16. use Cake\Network\Request;
  17. use Cake\Network\Response;
  18. use Cake\TestSuite\TestCase;
  19. use Zend\Diactoros\Stream;
  20. /**
  21. * ResponseTest
  22. */
  23. class ResponseTest extends TestCase
  24. {
  25. /**
  26. * Setup for tests
  27. *
  28. * @return void
  29. */
  30. public function setUp()
  31. {
  32. parent::setUp();
  33. include_once __DIR__ . DS . 'mocks.php';
  34. }
  35. /**
  36. * Cleanup after tests
  37. *
  38. * @return void
  39. */
  40. public function tearDown()
  41. {
  42. parent::tearDown();
  43. }
  44. /**
  45. * Tests the request object constructor
  46. *
  47. * @return void
  48. */
  49. public function testConstruct()
  50. {
  51. $response = new Response();
  52. $this->assertNull($response->body());
  53. $this->assertEquals('UTF-8', $response->charset());
  54. $this->assertEquals('text/html', $response->type());
  55. $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  56. $this->assertEquals(200, $response->statusCode());
  57. $options = [
  58. 'body' => 'This is the body',
  59. 'charset' => 'my-custom-charset',
  60. 'type' => 'mp3',
  61. 'status' => '203'
  62. ];
  63. $response = new Response($options);
  64. $this->assertEquals('This is the body', $response->body());
  65. $this->assertEquals('my-custom-charset', $response->charset());
  66. $this->assertEquals('audio/mpeg', $response->type());
  67. $this->assertEquals('audio/mpeg', $response->getHeaderLine('Content-Type'));
  68. $this->assertEquals(203, $response->statusCode());
  69. $options = [
  70. 'body' => 'This is the body',
  71. 'charset' => 'ISO-8859-1',
  72. 'type' => 'txt',
  73. 'status' => '422',
  74. 'statusCodes' => [
  75. 422 => 'Unprocessable Entity'
  76. ]
  77. ];
  78. $response = new Response($options);
  79. $this->assertEquals($options['body'], $response->body());
  80. $this->assertEquals($options['charset'], $response->charset());
  81. $this->assertEquals($response->getMimeType($options['type']), $response->type());
  82. $this->assertEquals($options['status'], $response->statusCode());
  83. $this->assertEquals('text/plain; charset=ISO-8859-1', $response->getHeaderLine('Content-Type'));
  84. }
  85. /**
  86. * Tests the body method
  87. *
  88. * @return void
  89. */
  90. public function testBody()
  91. {
  92. $response = new Response();
  93. $this->assertNull($response->body());
  94. $response->body('Response body');
  95. $this->assertEquals('Response body', $response->body());
  96. $this->assertEquals('Changed Body', $response->body('Changed Body'));
  97. $response = new Response();
  98. $response->body(0);
  99. $this->assertEquals(0, $response->body());
  100. $response = new Response();
  101. $response->body('0');
  102. $this->assertEquals('0', $response->body());
  103. $response = new Response();
  104. $response->body(null);
  105. $this->assertEquals(null, $response->body());
  106. }
  107. /**
  108. * Tests the charset method
  109. *
  110. * @return void
  111. */
  112. public function testCharset()
  113. {
  114. $response = new Response();
  115. $this->assertEquals('UTF-8', $response->charset());
  116. $response->charset('iso-8859-1');
  117. $this->assertEquals('iso-8859-1', $response->charset());
  118. $this->assertEquals('UTF-16', $response->charset('UTF-16'));
  119. }
  120. /**
  121. * Tests the statusCode method
  122. *
  123. * @expectedException \InvalidArgumentException
  124. * @return void
  125. */
  126. public function testStatusCode()
  127. {
  128. $response = new Response();
  129. $this->assertEquals(200, $response->statusCode());
  130. $response->statusCode(404);
  131. $this->assertEquals(404, $response->statusCode());
  132. $this->assertEquals(500, $response->statusCode(500));
  133. //Throws exception
  134. $response->statusCode(1001);
  135. }
  136. /**
  137. * Tests the type method
  138. *
  139. * @return void
  140. */
  141. public function testType()
  142. {
  143. $response = new Response();
  144. $this->assertEquals('text/html', $response->type());
  145. $response->type('pdf');
  146. $this->assertEquals('application/pdf', $response->type());
  147. $this->assertEquals('application/crazy-mime', $response->type('application/crazy-mime'));
  148. $this->assertEquals('application/json', $response->type('json'));
  149. $this->assertEquals('text/vnd.wap.wml', $response->type('wap'));
  150. $this->assertEquals('application/vnd.wap.xhtml+xml', $response->type('xhtml-mobile'));
  151. $this->assertEquals('text/csv', $response->type('csv'));
  152. $response->type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);
  153. $this->assertEquals('application/keynote', $response->type('keynote'));
  154. $this->assertEquals('application/bat', $response->type('bat'));
  155. $this->assertFalse($response->type('wackytype'));
  156. }
  157. /**
  158. * Tests the withType method
  159. *
  160. * @return void
  161. */
  162. public function testWithTypeAlias()
  163. {
  164. $response = new Response();
  165. $this->assertEquals(
  166. 'text/html; charset=UTF-8',
  167. $response->getHeaderLine('Content-Type'),
  168. 'Default content-type should match'
  169. );
  170. $new = $response->withType('pdf');
  171. $this->assertNotSame($new, $response, 'Should be a new instance');
  172. $this->assertSame(
  173. 'text/html; charset=UTF-8',
  174. $response->getHeaderLine('Content-Type'),
  175. 'Original object should not be modified'
  176. );
  177. $this->assertSame('application/pdf', $new->getHeaderLine('Content-Type'));
  178. $this->assertSame(
  179. 'application/json; charset=UTF-8',
  180. $new->withType('json')->getHeaderLine('Content-Type')
  181. );
  182. }
  183. /**
  184. * test withType() and full mime-types
  185. *
  186. * @return void
  187. */
  188. public function withTypeFull()
  189. {
  190. $response = new Response();
  191. $this->assertEquals(
  192. 'application/json',
  193. $response->withType('application/json')->getHeaderLine('Content-Type'),
  194. 'Should not add charset to explicit type'
  195. );
  196. $this->assertEquals(
  197. 'custom/stuff',
  198. $response->withType('custom/stuff')->getHeaderLine('Content-Type'),
  199. 'Should allow arbitrary types'
  200. );
  201. }
  202. /**
  203. * Test that an invalid type raises an exception
  204. *
  205. * @expectedException InvalidArgumentException
  206. * @expectedExceptionMessage "beans" is an invalid content type
  207. * @return void
  208. */
  209. public function testWithTypeInvalidType()
  210. {
  211. $response = new Response();
  212. $response->withType('beans');
  213. }
  214. /**
  215. * Tests the header method
  216. *
  217. * @return void
  218. */
  219. public function testHeader()
  220. {
  221. $response = new Response();
  222. $headers = [
  223. 'Content-Type' => 'text/html; charset=UTF-8',
  224. ];
  225. $this->assertEquals($headers, $response->header());
  226. $response->header('Location', 'http://example.com');
  227. $headers += ['Location' => 'http://example.com'];
  228. $this->assertEquals($headers, $response->header());
  229. // Headers with the same name are overwritten
  230. $response->header('Location', 'http://example2.com');
  231. $headers = [
  232. 'Content-Type' => 'text/html; charset=UTF-8',
  233. 'Location' => 'http://example2.com'
  234. ];
  235. $this->assertEquals($headers, $response->header());
  236. $response->header(['WWW-Authenticate' => 'Negotiate']);
  237. $headers += ['WWW-Authenticate' => 'Negotiate'];
  238. $this->assertEquals($headers, $response->header());
  239. $response->header(['WWW-Authenticate' => 'Not-Negotiate']);
  240. $headers['WWW-Authenticate'] = 'Not-Negotiate';
  241. $this->assertEquals($headers, $response->header());
  242. $response->header(['Age' => 12, 'Allow' => 'GET, HEAD']);
  243. $headers += ['Age' => 12, 'Allow' => 'GET, HEAD'];
  244. $this->assertEquals($headers, $response->header());
  245. // String headers are allowed
  246. $response->header('Content-Language: da');
  247. $headers += ['Content-Language' => 'da'];
  248. $this->assertEquals($headers, $response->header());
  249. $response->header('Content-Language: da');
  250. $headers += ['Content-Language' => 'da'];
  251. $this->assertEquals($headers, $response->header());
  252. $response->header(['Content-Encoding: gzip', 'Vary: *', 'Pragma' => 'no-cache']);
  253. $headers += ['Content-Encoding' => 'gzip', 'Vary' => '*', 'Pragma' => 'no-cache'];
  254. $this->assertEquals($headers, $response->header());
  255. $response->header('Access-Control-Allow-Origin', ['domain1', 'domain2']);
  256. $headers += ['Access-Control-Allow-Origin' => ['domain1', 'domain2']];
  257. $this->assertEquals($headers, $response->header());
  258. }
  259. /**
  260. * Tests the send method
  261. *
  262. * @return void
  263. */
  264. public function testSend()
  265. {
  266. $response = $this->getMockBuilder('Cake\Network\Response')
  267. ->setMethods(['_sendHeader', '_sendContent', '_setCookies'])
  268. ->getMock();
  269. $response->header([
  270. 'Content-Language' => 'es',
  271. 'WWW-Authenticate' => 'Negotiate',
  272. 'Access-Control-Allow-Origin' => ['domain1', 'domain2'],
  273. ]);
  274. $response->body('the response body');
  275. $response->expects($this->once())->method('_sendContent')->with('the response body');
  276. $response->expects($this->at(0))->method('_setCookies');
  277. $response->expects($this->at(1))
  278. ->method('_sendHeader')->with('HTTP/1.1 200 OK');
  279. $response->expects($this->at(2))
  280. ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8');
  281. $response->expects($this->at(3))
  282. ->method('_sendHeader')->with('Content-Language', 'es');
  283. $response->expects($this->at(4))
  284. ->method('_sendHeader')->with('WWW-Authenticate', 'Negotiate');
  285. $response->expects($this->at(5))
  286. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain1');
  287. $response->expects($this->at(6))
  288. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain2');
  289. $response->send();
  290. }
  291. /**
  292. * Data provider for content type tests.
  293. *
  294. * @return array
  295. */
  296. public static function charsetTypeProvider()
  297. {
  298. return [
  299. ['mp3', 'audio/mpeg'],
  300. ['js', 'application/javascript; charset=UTF-8'],
  301. ['json', 'application/json; charset=UTF-8'],
  302. ['xml', 'application/xml; charset=UTF-8'],
  303. ['txt', 'text/plain; charset=UTF-8'],
  304. ];
  305. }
  306. /**
  307. * Tests the send method and changing the content type
  308. *
  309. * @dataProvider charsetTypeProvider
  310. * @return void
  311. */
  312. public function testSendChangingContentType($original, $expected)
  313. {
  314. $response = new Response();
  315. $response->type($original);
  316. $response->body('the response body');
  317. $this->assertEquals($expected, $response->getHeaderLine('Content-Type'));
  318. }
  319. /**
  320. * Tests the send method and changing the content type to JS without adding the charset
  321. *
  322. * @return void
  323. */
  324. public function testCharsetSetContentTypeWithoutCharset()
  325. {
  326. $response = new Response();
  327. $response->type('js');
  328. $response->charset('');
  329. $this->assertEquals('application/javascript', $response->getHeaderLine('Content-Type'));
  330. }
  331. /**
  332. * Tests the send method and changing the content type
  333. *
  334. * @return void
  335. */
  336. public function testLocationSetsStatus()
  337. {
  338. $response = new Response();
  339. $response->location('http://www.example.com');
  340. $this->assertEquals(302, $response->getStatusCode());
  341. }
  342. /**
  343. * Test that setting certain status codes clears the status code.
  344. *
  345. * @return void
  346. */
  347. public function testStatusClearsContentType()
  348. {
  349. $response = new Response();
  350. $response->statusCode(204);
  351. $response->statusCode(304);
  352. $this->assertFalse($response->hasHeader('Content-Type'));
  353. $this->assertSame(304, $response->getStatusCode());
  354. $response = new Response();
  355. $response->type('pdf');
  356. $response->statusCode(204);
  357. $this->assertFalse($response->hasHeader('Content-Type'));
  358. $this->assertSame(204, $response->getStatusCode());
  359. $response = new Response();
  360. $new = $response->withType('pdf')
  361. ->withStatus(204);
  362. $this->assertFalse($new->hasHeader('Content-Type'));
  363. $this->assertSame(204, $new->getStatusCode());
  364. $response = new Response();
  365. $new = $response->withStatus(304)
  366. ->withType('pdf');
  367. $this->assertFalse($new->hasHeader('Content-Type'));
  368. $response = new Response();
  369. $response->statusCode(204);
  370. $response->type('pdf');
  371. $this->assertFalse($response->hasHeader('Content-Type'));
  372. }
  373. /**
  374. * Tests the send method and changing the content type
  375. *
  376. * @return void
  377. */
  378. public function testSendWithCallableBody()
  379. {
  380. $response = $this->getMockBuilder('Cake\Network\Response')
  381. ->setMethods(['_sendHeader'])
  382. ->getMock();
  383. $response->body(function () {
  384. echo 'the response body';
  385. });
  386. ob_start();
  387. $response->send();
  388. $this->assertEquals('the response body', ob_get_clean());
  389. }
  390. /**
  391. * Tests that the returned a string from a body callable is also sent
  392. * as the response body
  393. *
  394. * @return void
  395. */
  396. public function testSendWithCallableBodyWithReturn()
  397. {
  398. $response = $this->getMockBuilder('Cake\Network\Response')
  399. ->setMethods(['_sendHeader'])
  400. ->getMock();
  401. $response->body(function () {
  402. return 'the response body';
  403. });
  404. ob_start();
  405. $response->send();
  406. $this->assertEquals('the response body', ob_get_clean());
  407. }
  408. /**
  409. * Tests the disableCache method
  410. *
  411. * @return void
  412. */
  413. public function testDisableCache()
  414. {
  415. $response = new Response();
  416. $expected = [
  417. 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
  418. 'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT",
  419. 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  420. 'Content-Type' => 'text/html; charset=UTF-8',
  421. ];
  422. $response->disableCache();
  423. $this->assertEquals($expected, $response->header());
  424. }
  425. /**
  426. * Tests the cache method
  427. *
  428. * @return void
  429. */
  430. public function testCache()
  431. {
  432. $response = new Response();
  433. $since = time();
  434. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  435. $response->expires('+1 day');
  436. $expected = [
  437. 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
  438. 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
  439. 'Expires' => $time->format('D, j M Y H:i:s') . ' GMT',
  440. 'Cache-Control' => 'public, max-age=' . ($time->format('U') - time()),
  441. 'Content-Type' => 'text/html; charset=UTF-8',
  442. ];
  443. $response->cache($since);
  444. $this->assertEquals($expected, $response->header());
  445. $response = new Response();
  446. $since = time();
  447. $time = '+5 day';
  448. $expected = [
  449. 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
  450. 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
  451. 'Expires' => gmdate("D, j M Y H:i:s", strtotime($time)) . " GMT",
  452. 'Cache-Control' => 'public, max-age=' . (strtotime($time) - time()),
  453. 'Content-Type' => 'text/html; charset=UTF-8',
  454. ];
  455. $response->cache($since, $time);
  456. $this->assertEquals($expected, $response->header());
  457. $response = new Response();
  458. $since = time();
  459. $time = time();
  460. $expected = [
  461. 'Date' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
  462. 'Last-Modified' => gmdate("D, j M Y H:i:s ", $since) . 'GMT',
  463. 'Expires' => gmdate("D, j M Y H:i:s", $time) . " GMT",
  464. 'Cache-Control' => 'public, max-age=0',
  465. 'Content-Type' => 'text/html; charset=UTF-8',
  466. ];
  467. $response->cache($since, $time);
  468. $this->assertEquals($expected, $response->header());
  469. }
  470. /**
  471. * Tests the compress method
  472. *
  473. * @return void
  474. */
  475. public function testCompress()
  476. {
  477. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  478. $response = new Response();
  479. if (ini_get("zlib.output_compression") === '1' || !extension_loaded("zlib")) {
  480. $this->assertFalse($response->compress());
  481. $this->markTestSkipped('Is not possible to test output compression');
  482. }
  483. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  484. $result = $response->compress();
  485. $this->assertFalse($result);
  486. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  487. $result = $response->compress();
  488. $this->assertTrue($result);
  489. $this->assertTrue(in_array('ob_gzhandler', ob_list_handlers()));
  490. ob_get_clean();
  491. }
  492. /**
  493. * Tests the httpCodes method
  494. *
  495. * @expectedException \InvalidArgumentException
  496. * @return void
  497. */
  498. public function testHttpCodes()
  499. {
  500. $response = new Response();
  501. $result = $response->httpCodes();
  502. $this->assertEquals(65, count($result));
  503. $result = $response->httpCodes(100);
  504. $expected = [100 => 'Continue'];
  505. $this->assertEquals($expected, $result);
  506. $codes = [
  507. 381 => 'Unicorn Moved',
  508. 555 => 'Unexpected Minotaur'
  509. ];
  510. $result = $response->httpCodes($codes);
  511. $this->assertTrue($result);
  512. $this->assertEquals(67, count($response->httpCodes()));
  513. $result = $response->httpCodes(381);
  514. $expected = [381 => 'Unicorn Moved'];
  515. $this->assertEquals($expected, $result);
  516. $codes = [404 => 'Sorry Bro'];
  517. $result = $response->httpCodes($codes);
  518. $this->assertTrue($result);
  519. $this->assertEquals(67, count($response->httpCodes()));
  520. $result = $response->httpCodes(404);
  521. $expected = [404 => 'Sorry Bro'];
  522. $this->assertEquals($expected, $result);
  523. //Throws exception
  524. $response->httpCodes([
  525. 0 => 'Nothing Here',
  526. -1 => 'Reverse Infinity',
  527. 12345 => 'Universal Password',
  528. 'Hello' => 'World'
  529. ]);
  530. }
  531. /**
  532. * Tests the download method
  533. *
  534. * @return void
  535. */
  536. public function testDownload()
  537. {
  538. $response = new Response();
  539. $expected = [
  540. 'Content-Type' => 'text/html; charset=UTF-8',
  541. 'Content-Disposition' => 'attachment; filename="myfile.mp3"'
  542. ];
  543. $response->download('myfile.mp3');
  544. $this->assertEquals($expected, $response->header());
  545. }
  546. /**
  547. * Tests the mapType method
  548. *
  549. * @return void
  550. */
  551. public function testMapType()
  552. {
  553. $response = new Response();
  554. $this->assertEquals('wav', $response->mapType('audio/x-wav'));
  555. $this->assertEquals('pdf', $response->mapType('application/pdf'));
  556. $this->assertEquals('xml', $response->mapType('text/xml'));
  557. $this->assertEquals('html', $response->mapType('*/*'));
  558. $this->assertEquals('csv', $response->mapType('application/vnd.ms-excel'));
  559. $expected = ['json', 'xhtml', 'css'];
  560. $result = $response->mapType(['application/json', 'application/xhtml+xml', 'text/css']);
  561. $this->assertEquals($expected, $result);
  562. }
  563. /**
  564. * Tests the outputCompressed method
  565. *
  566. * @return void
  567. */
  568. public function testOutputCompressed()
  569. {
  570. $response = new Response();
  571. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  572. $result = $response->outputCompressed();
  573. $this->assertFalse($result);
  574. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  575. $result = $response->outputCompressed();
  576. $this->assertFalse($result);
  577. if (!extension_loaded("zlib")) {
  578. $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
  579. }
  580. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  581. if (ini_get("zlib.output_compression") !== '1') {
  582. ob_start('ob_gzhandler');
  583. }
  584. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  585. $result = $response->outputCompressed();
  586. $this->assertTrue($result);
  587. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  588. $result = $response->outputCompressed();
  589. $this->assertFalse($result);
  590. if (ini_get("zlib.output_compression") !== '1') {
  591. ob_get_clean();
  592. }
  593. }
  594. /**
  595. * Tests getting/setting the protocol
  596. *
  597. * @return void
  598. */
  599. public function testProtocol()
  600. {
  601. $response = $this->getMockBuilder('Cake\Network\Response')
  602. ->setMethods(['_sendHeader', '_sendContent'])
  603. ->getMock();
  604. $response->protocol('HTTP/1.0');
  605. $this->assertEquals('HTTP/1.0', $response->protocol());
  606. $response->expects($this->at(0))
  607. ->method('_sendHeader')->with('HTTP/1.0 200 OK');
  608. $response->send();
  609. }
  610. /**
  611. * Tests getting/setting the Content-Length
  612. *
  613. * @return void
  614. */
  615. public function testLength()
  616. {
  617. $response = new Response();
  618. $response->length(100);
  619. $this->assertEquals(100, $response->length());
  620. $this->assertEquals('100', $response->getHeaderLine('Content-Length'));
  621. }
  622. /**
  623. * Tests setting the expiration date
  624. *
  625. * @return void
  626. */
  627. public function testExpires()
  628. {
  629. $format = 'D, j M Y H:i:s';
  630. $response = new Response();
  631. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  632. $response->expires($now);
  633. $now->setTimeZone(new \DateTimeZone('UTC'));
  634. $this->assertEquals($now->format($format) . ' GMT', $response->expires());
  635. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  636. $now = time();
  637. $response = new Response();
  638. $response->expires($now);
  639. $this->assertEquals(gmdate($format) . ' GMT', $response->expires());
  640. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Expires'));
  641. $response = new Response();
  642. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  643. $response->expires('+1 day');
  644. $this->assertEquals($time->format($format) . ' GMT', $response->expires());
  645. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  646. }
  647. /**
  648. * Tests setting the modification date
  649. *
  650. * @return void
  651. */
  652. public function testModified()
  653. {
  654. $format = 'D, j M Y H:i:s';
  655. $response = new Response();
  656. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  657. $response->modified($now);
  658. $now->setTimeZone(new \DateTimeZone('UTC'));
  659. $this->assertEquals($now->format($format) . ' GMT', $response->modified());
  660. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  661. $response = new Response();
  662. $now = time();
  663. $response->modified($now);
  664. $this->assertEquals(gmdate($format) . ' GMT', $response->modified());
  665. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  666. $response = new Response();
  667. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  668. $response->modified('+1 day');
  669. $this->assertEquals($time->format($format) . ' GMT', $response->modified());
  670. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  671. }
  672. /**
  673. * Tests setting of public/private Cache-Control directives
  674. *
  675. * @return void
  676. */
  677. public function testSharable()
  678. {
  679. $response = new Response();
  680. $this->assertNull($response->sharable());
  681. $response->sharable(true);
  682. $this->assertTrue($response->sharable());
  683. $this->assertEquals('public', $response->getHeaderLine('Cache-Control'));
  684. $response = new Response();
  685. $response->sharable(false);
  686. $this->assertFalse($response->sharable());
  687. $this->assertEquals('private', $response->getHeaderLine('Cache-Control'));
  688. $response = new Response();
  689. $response->sharable(true, 3600);
  690. $this->assertEquals('public, max-age=3600', $response->getHeaderLine('Cache-Control'));
  691. $response = new Response();
  692. $response->sharable(false, 3600);
  693. $this->assertEquals('private, max-age=3600', $response->getHeaderLine('Cache-Control'));
  694. }
  695. /**
  696. * Tests setting of max-age Cache-Control directive
  697. *
  698. * @return void
  699. */
  700. public function testMaxAge()
  701. {
  702. $response = new Response();
  703. $this->assertNull($response->maxAge());
  704. $response->maxAge(3600);
  705. $this->assertEquals(3600, $response->maxAge());
  706. $this->assertEquals('max-age=3600', $response->getHeaderLine('Cache-Control'));
  707. $response = new Response();
  708. $response->maxAge(3600);
  709. $response->sharable(false);
  710. $this->assertEquals('max-age=3600, private', $response->getHeaderLine('Cache-Control'));
  711. }
  712. /**
  713. * Tests setting of s-maxage Cache-Control directive
  714. *
  715. * @return void
  716. */
  717. public function testSharedMaxAge()
  718. {
  719. $response = new Response();
  720. $this->assertNull($response->maxAge());
  721. $response->sharedMaxAge(3600);
  722. $this->assertEquals(3600, $response->sharedMaxAge());
  723. $this->assertEquals('s-maxage=3600', $response->getHeaderLine('Cache-Control'));
  724. $response = new Response();
  725. $response->sharedMaxAge(3600);
  726. $response->sharable(true);
  727. $this->assertEquals('s-maxage=3600, public', $response->getHeaderLine('Cache-Control'));
  728. }
  729. /**
  730. * Tests setting of must-revalidate Cache-Control directive
  731. *
  732. * @return void
  733. */
  734. public function testMustRevalidate()
  735. {
  736. $response = $this->getMockBuilder('Cake\Network\Response')
  737. ->setMethods(['_sendHeader', '_sendContent'])
  738. ->getMock();
  739. $response = new Response();
  740. $this->assertFalse($response->mustRevalidate());
  741. $response->mustRevalidate(true);
  742. $this->assertTrue($response->mustRevalidate());
  743. $this->assertEquals('must-revalidate', $response->getHeaderLine('Cache-Control'));
  744. $response->mustRevalidate(false);
  745. $this->assertFalse($response->mustRevalidate());
  746. $response = new Response();
  747. $response->sharedMaxAge(3600);
  748. $response->mustRevalidate(true);
  749. $this->assertEquals('s-maxage=3600, must-revalidate', $response->getHeaderLine('Cache-Control'));
  750. }
  751. /**
  752. * Tests getting/setting the Vary header
  753. *
  754. * @return void
  755. */
  756. public function testVary()
  757. {
  758. $response = new Response();
  759. $response->vary('Accept-encoding');
  760. $this->assertEquals('Accept-encoding', $response->getHeaderLine('vary'));
  761. $response = new Response();
  762. $response->vary(['Accept-language', 'Accept-encoding']);
  763. $this->assertEquals(['Accept-language', 'Accept-encoding'], $response->vary());
  764. $this->assertEquals('Accept-language, Accept-encoding', $response->getHeaderLine('vary'));
  765. }
  766. /**
  767. * Tests getting/setting the Etag header
  768. *
  769. * @return void
  770. */
  771. public function testEtag()
  772. {
  773. $response = new Response();
  774. $response->etag('something');
  775. $this->assertEquals('"something"', $response->etag());
  776. $this->assertEquals('"something"', $response->getHeaderLine('Etag'));
  777. $response = new Response();
  778. $response->etag('something', true);
  779. $this->assertEquals('W/"something"', $response->etag());
  780. $this->assertEquals('W/"something"', $response->getHeaderLine('Etag'));
  781. }
  782. /**
  783. * Tests that the response is able to be marked as not modified
  784. *
  785. * @return void
  786. */
  787. public function testNotModified()
  788. {
  789. $response = $this->getMockBuilder('Cake\Network\Response')
  790. ->setMethods(['_sendHeader', '_sendContent'])
  791. ->getMock();
  792. $response->body('something');
  793. $response->statusCode(200);
  794. $response->length(100);
  795. $response->modified('now');
  796. $response->notModified();
  797. $this->assertEmpty($response->header());
  798. $this->assertEmpty($response->body());
  799. $this->assertEquals(304, $response->statusCode());
  800. }
  801. /**
  802. * Test checkNotModified method
  803. *
  804. * @return void
  805. */
  806. public function testCheckNotModifiedByEtagStar()
  807. {
  808. $_SERVER['HTTP_IF_NONE_MATCH'] = '*';
  809. $response = $this->getMockBuilder('Cake\Network\Response')
  810. ->setMethods(['notModified'])
  811. ->getMock();
  812. $response->etag('something');
  813. $response->expects($this->once())->method('notModified');
  814. $response->checkNotModified(new Request);
  815. }
  816. /**
  817. * Test checkNotModified method
  818. *
  819. * @return void
  820. */
  821. public function testCheckNotModifiedByEtagExact()
  822. {
  823. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  824. $response = $this->getMockBuilder('Cake\Network\Response')
  825. ->setMethods(['notModified'])
  826. ->getMock();
  827. $response->etag('something', true);
  828. $response->expects($this->once())->method('notModified');
  829. $this->assertTrue($response->checkNotModified(new Request));
  830. }
  831. /**
  832. * Test checkNotModified method
  833. *
  834. * @return void
  835. */
  836. public function testCheckNotModifiedByEtagAndTime()
  837. {
  838. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  839. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  840. $response = $this->getMockBuilder('Cake\Network\Response')
  841. ->setMethods(['notModified'])
  842. ->getMock();
  843. $response->etag('something', true);
  844. $response->modified('2012-01-01 00:00:00');
  845. $response->expects($this->once())->method('notModified');
  846. $this->assertTrue($response->checkNotModified(new Request));
  847. }
  848. /**
  849. * Test checkNotModified method
  850. *
  851. * @return void
  852. */
  853. public function testCheckNotModifiedByEtagAndTimeMismatch()
  854. {
  855. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  856. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  857. $response = $this->getMockBuilder('Cake\Network\Response')
  858. ->setMethods(['notModified'])
  859. ->getMock();
  860. $response->etag('something', true);
  861. $response->modified('2012-01-01 00:00:01');
  862. $response->expects($this->never())->method('notModified');
  863. $this->assertFalse($response->checkNotModified(new Request));
  864. }
  865. /**
  866. * Test checkNotModified method
  867. *
  868. * @return void
  869. */
  870. public function testCheckNotModifiedByEtagMismatch()
  871. {
  872. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something-else", "other"';
  873. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  874. $response = $this->getMockBuilder('Cake\Network\Response')
  875. ->setMethods(['notModified'])
  876. ->getMock();
  877. $response->etag('something', true);
  878. $response->modified('2012-01-01 00:00:00');
  879. $response->expects($this->never())->method('notModified');
  880. $this->assertFalse($response->checkNotModified(new Request));
  881. }
  882. /**
  883. * Test checkNotModified method
  884. *
  885. * @return void
  886. */
  887. public function testCheckNotModifiedByTime()
  888. {
  889. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  890. $response = $this->getMockBuilder('Cake\Network\Response')
  891. ->setMethods(['notModified'])
  892. ->getMock();
  893. $response->modified('2012-01-01 00:00:00');
  894. $response->expects($this->once())->method('notModified');
  895. $this->assertTrue($response->checkNotModified(new Request));
  896. }
  897. /**
  898. * Test checkNotModified method
  899. *
  900. * @return void
  901. */
  902. public function testCheckNotModifiedNoHints()
  903. {
  904. $_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
  905. $_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
  906. $response = $this->getMockBuilder('Cake\Network\Response')
  907. ->setMethods(['notModified'])
  908. ->getMock();
  909. $response->expects($this->never())->method('notModified');
  910. $this->assertFalse($response->checkNotModified(new Request));
  911. }
  912. /**
  913. * Test cookie setting
  914. *
  915. * @return void
  916. */
  917. public function testCookieSettings()
  918. {
  919. $response = new Response();
  920. $cookie = [
  921. 'name' => 'CakeTestCookie[Testing]'
  922. ];
  923. $response->cookie($cookie);
  924. $expected = [
  925. 'name' => 'CakeTestCookie[Testing]',
  926. 'value' => '',
  927. 'expire' => 0,
  928. 'path' => '/',
  929. 'domain' => '',
  930. 'secure' => false,
  931. 'httpOnly' => false];
  932. $result = $response->cookie('CakeTestCookie[Testing]');
  933. $this->assertEquals($expected, $result);
  934. $cookie = [
  935. 'name' => 'CakeTestCookie[Testing2]',
  936. 'value' => '[a,b,c]',
  937. 'expire' => 1000,
  938. 'path' => '/test',
  939. 'secure' => true
  940. ];
  941. $response->cookie($cookie);
  942. $expected = [
  943. 'CakeTestCookie[Testing]' => [
  944. 'name' => 'CakeTestCookie[Testing]',
  945. 'value' => '',
  946. 'expire' => 0,
  947. 'path' => '/',
  948. 'domain' => '',
  949. 'secure' => false,
  950. 'httpOnly' => false
  951. ],
  952. 'CakeTestCookie[Testing2]' => [
  953. 'name' => 'CakeTestCookie[Testing2]',
  954. 'value' => '[a,b,c]',
  955. 'expire' => 1000,
  956. 'path' => '/test',
  957. 'domain' => '',
  958. 'secure' => true,
  959. 'httpOnly' => false
  960. ]
  961. ];
  962. $result = $response->cookie();
  963. $this->assertEquals($expected, $result);
  964. $cookie = $expected['CakeTestCookie[Testing]'];
  965. $cookie['value'] = 'test';
  966. $response->cookie($cookie);
  967. $expected = [
  968. 'CakeTestCookie[Testing]' => [
  969. 'name' => 'CakeTestCookie[Testing]',
  970. 'value' => 'test',
  971. 'expire' => 0,
  972. 'path' => '/',
  973. 'domain' => '',
  974. 'secure' => false,
  975. 'httpOnly' => false
  976. ],
  977. 'CakeTestCookie[Testing2]' => [
  978. 'name' => 'CakeTestCookie[Testing2]',
  979. 'value' => '[a,b,c]',
  980. 'expire' => 1000,
  981. 'path' => '/test',
  982. 'domain' => '',
  983. 'secure' => true,
  984. 'httpOnly' => false
  985. ]
  986. ];
  987. $result = $response->cookie();
  988. $this->assertEquals($expected, $result);
  989. }
  990. /**
  991. * Test CORS
  992. *
  993. * @dataProvider corsData
  994. * @param Request $request
  995. * @param string $origin
  996. * @param string|array $domains
  997. * @param string|array $methods
  998. * @param string|array $headers
  999. * @param string|bool $expectedOrigin
  1000. * @param string|bool $expectedMethods
  1001. * @param string|bool $expectedHeaders
  1002. * @return void
  1003. */
  1004. public function testCors($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods = false, $expectedHeaders = false)
  1005. {
  1006. $request->env('HTTP_ORIGIN', $origin);
  1007. $response = new Response();
  1008. $result = $response->cors($request, $domains, $methods, $headers);
  1009. $this->assertInstanceOf('Cake\Network\CorsBuilder', $result);
  1010. $headers = $response->header();
  1011. if ($expectedOrigin) {
  1012. $this->assertArrayHasKey('Access-Control-Allow-Origin', $headers);
  1013. $this->assertEquals($expectedOrigin, $headers['Access-Control-Allow-Origin']);
  1014. }
  1015. if ($expectedMethods) {
  1016. $this->assertArrayHasKey('Access-Control-Allow-Methods', $headers);
  1017. $this->assertEquals($expectedMethods, $headers['Access-Control-Allow-Methods']);
  1018. }
  1019. if ($expectedHeaders) {
  1020. $this->assertArrayHasKey('Access-Control-Allow-Headers', $headers);
  1021. $this->assertEquals($expectedHeaders, $headers['Access-Control-Allow-Headers']);
  1022. }
  1023. unset($_SERVER['HTTP_ORIGIN']);
  1024. }
  1025. /**
  1026. * Feed for testCors
  1027. *
  1028. * @return array
  1029. */
  1030. public function corsData()
  1031. {
  1032. $fooRequest = new Request();
  1033. $secureRequest = function () {
  1034. $secureRequest = $this->getMockBuilder('Cake\Network\Request')
  1035. ->setMethods(['is'])
  1036. ->getMock();
  1037. $secureRequest->expects($this->any())
  1038. ->method('is')
  1039. ->with('ssl')
  1040. ->will($this->returnValue(true));
  1041. return $secureRequest;
  1042. };
  1043. return [
  1044. // [$fooRequest, null, '*', '', '', false, false],
  1045. // [$fooRequest, 'http://www.foo.com', '*', '', '', '*', false],
  1046. // [$fooRequest, 'http://www.foo.com', 'www.foo.com', '', '', 'http://www.foo.com', false],
  1047. // [$fooRequest, 'http://www.foo.com', '*.foo.com', '', '', 'http://www.foo.com', false],
  1048. // [$fooRequest, 'http://www.foo.com', 'http://*.foo.com', '', '', 'http://www.foo.com', false],
  1049. // [$fooRequest, 'http://www.foo.com', 'https://www.foo.com', '', '', false, false],
  1050. // [$fooRequest, 'http://www.foo.com', 'https://*.foo.com', '', '', false, false],
  1051. // [$fooRequest, 'http://www.foo.com', ['*.bar.com', '*.foo.com'], '', '', 'http://www.foo.com', false],
  1052. // [$fooRequest, 'http://not-foo.com', '*.foo.com', '', '', false, false],
  1053. // [$fooRequest, 'http://bad.academy', '*.acad.my', '', '', false, false],
  1054. // [$fooRequest, 'http://www.foo.com.at.bad.com', '*.foo.com', '', '', false, false],
  1055. // [$fooRequest, 'https://www.foo.com', '*.foo.com', '', '', false, false],
  1056. [$secureRequest(), 'https://www.bar.com', 'www.bar.com', '', '', 'https://www.bar.com', false],
  1057. [$secureRequest(), 'https://www.bar.com', 'http://www.bar.com', '', '', false, false],
  1058. [$secureRequest(), 'https://www.bar.com', '*.bar.com', '', '', 'https://www.bar.com', false],
  1059. [$secureRequest(), 'http://www.bar.com', '*.bar.com', '', '', false, false],
  1060. [$fooRequest, 'http://www.foo.com', '*', 'GET', '', '*', 'GET'],
  1061. [$fooRequest, 'http://www.foo.com', '*.foo.com', 'GET', '', 'http://www.foo.com', 'GET'],
  1062. [$fooRequest, 'http://www.foo.com', '*.foo.com', ['GET', 'POST'], '', 'http://www.foo.com', 'GET, POST'],
  1063. [$fooRequest, 'http://www.foo.com', '*', '', 'X-CakePHP', '*', false, 'X-CakePHP'],
  1064. [$fooRequest, 'http://www.foo.com', '*', '', ['X-CakePHP', 'X-MyApp'], '*', false, 'X-CakePHP, X-MyApp'],
  1065. [$fooRequest, 'http://www.foo.com', '*', ['GET', 'OPTIONS'], ['X-CakePHP', 'X-MyApp'], '*', 'GET, OPTIONS', 'X-CakePHP, X-MyApp'],
  1066. ];
  1067. }
  1068. /**
  1069. * testFileNotFound
  1070. *
  1071. * @expectedException \Cake\Network\Exception\NotFoundException
  1072. * @return void
  1073. */
  1074. public function testFileNotFound()
  1075. {
  1076. $response = new Response();
  1077. $response->file('/some/missing/folder/file.jpg');
  1078. }
  1079. /**
  1080. * test file with ../
  1081. *
  1082. * @expectedException \Cake\Network\Exception\NotFoundException
  1083. * @expectedExceptionMessage The requested file contains `..` and will not be read.
  1084. * @return void
  1085. */
  1086. public function testFileWithForwardSlashPathTraversal()
  1087. {
  1088. $response = new Response();
  1089. $response->file('my/../cat.gif');
  1090. }
  1091. /**
  1092. * test file with ..\
  1093. *
  1094. * @expectedException \Cake\Network\Exception\NotFoundException
  1095. * @expectedExceptionMessage The requested file contains `..` and will not be read.
  1096. * @return void
  1097. */
  1098. public function testFileWithBackwardSlashPathTraversal()
  1099. {
  1100. $response = new Response();
  1101. $response->file('my\..\cat.gif');
  1102. }
  1103. /**
  1104. * test file with ..
  1105. *
  1106. * @expectedException \Cake\Network\Exception\NotFoundException
  1107. * @expectedExceptionMessage my/ca..t.gif was not found or not readable
  1108. * @return void
  1109. */
  1110. public function testFileWithDotsInTheFilename()
  1111. {
  1112. $response = new Response();
  1113. $response->file('my/ca..t.gif');
  1114. }
  1115. /**
  1116. * test file with .. in a path fragment
  1117. *
  1118. * @expectedException \Cake\Network\Exception\NotFoundException
  1119. * @expectedExceptionMessage my/ca..t/image.gif was not found or not readable
  1120. * @return void
  1121. */
  1122. public function testFileWithDotsInAPathFragment()
  1123. {
  1124. $response = new Response();
  1125. $response->file('my/ca..t/image.gif');
  1126. }
  1127. /**
  1128. * testFile method
  1129. *
  1130. * @return void
  1131. */
  1132. public function testFile()
  1133. {
  1134. $response = $this->getMockBuilder('Cake\Network\Response')
  1135. ->setMethods([
  1136. 'header',
  1137. 'type',
  1138. '_sendHeader',
  1139. '_setContentType',
  1140. '_isActive',
  1141. ])
  1142. ->getMock();
  1143. $response->expects($this->exactly(1))
  1144. ->method('type')
  1145. ->with('css')
  1146. ->will($this->returnArgument(0));
  1147. $response->expects($this->at(1))
  1148. ->method('header')
  1149. ->with('Accept-Ranges', 'bytes');
  1150. $response->expects($this->exactly(1))
  1151. ->method('_isActive')
  1152. ->will($this->returnValue(true));
  1153. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1154. ob_start();
  1155. $result = $response->send();
  1156. $output = ob_get_clean();
  1157. $this->assertEquals("/* this is the test asset css file */", trim($output));
  1158. $this->assertTrue($result !== false);
  1159. }
  1160. /**
  1161. * testFileWithDownloadAndName
  1162. *
  1163. * @return void
  1164. */
  1165. public function testFileWithDownloadAndName()
  1166. {
  1167. $response = $this->getMockBuilder('Cake\Network\Response')
  1168. ->setMethods([
  1169. 'header',
  1170. 'type',
  1171. 'download',
  1172. '_sendHeader',
  1173. '_setContentType',
  1174. '_isActive',
  1175. ])
  1176. ->getMock();
  1177. $response->expects($this->exactly(1))
  1178. ->method('type')
  1179. ->with('css')
  1180. ->will($this->returnArgument(0));
  1181. $response->expects($this->once())
  1182. ->method('download')
  1183. ->with('something_special.css');
  1184. $response->expects($this->at(2))
  1185. ->method('header')
  1186. ->with('Content-Transfer-Encoding', 'binary');
  1187. $response->expects($this->at(3))
  1188. ->method('header')
  1189. ->with('Accept-Ranges', 'bytes');
  1190. $response->expects($this->exactly(1))
  1191. ->method('_isActive')
  1192. ->will($this->returnValue(true));
  1193. $response->file(
  1194. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1195. [
  1196. 'name' => 'something_special.css',
  1197. 'download' => true,
  1198. ]
  1199. );
  1200. ob_start();
  1201. $result = $response->send();
  1202. $output = ob_get_clean();
  1203. $this->assertEquals("/* this is the test asset css file */\n", $output);
  1204. $this->assertNotSame(false, $result);
  1205. }
  1206. /**
  1207. * testFileWithUnknownFileTypeGeneric method
  1208. *
  1209. * @return void
  1210. */
  1211. public function testFileWithUnknownFileTypeGeneric()
  1212. {
  1213. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1214. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1215. $response = $this->getMockBuilder('Cake\Network\Response')
  1216. ->setMethods([
  1217. 'header',
  1218. 'type',
  1219. 'download',
  1220. '_sendHeader',
  1221. '_setContentType',
  1222. '_isActive',
  1223. ])
  1224. ->getMock();
  1225. $response->expects($this->exactly(1))
  1226. ->method('type')
  1227. ->with('ini')
  1228. ->will($this->returnValue(false));
  1229. $response->expects($this->once())
  1230. ->method('download')
  1231. ->with('no_section.ini');
  1232. $response->expects($this->at(2))
  1233. ->method('header')
  1234. ->with('Content-Transfer-Encoding', 'binary');
  1235. $response->expects($this->at(3))
  1236. ->method('header')
  1237. ->with('Accept-Ranges', 'bytes');
  1238. $response->expects($this->exactly(1))
  1239. ->method('_isActive')
  1240. ->will($this->returnValue(true));
  1241. $response->file(CONFIG . 'no_section.ini');
  1242. ob_start();
  1243. $result = $response->send();
  1244. $output = ob_get_clean();
  1245. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1246. $this->assertNotSame(false, $result);
  1247. if ($currentUserAgent !== null) {
  1248. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1249. }
  1250. }
  1251. /**
  1252. * testFileWithUnknownFileTypeOpera method
  1253. *
  1254. * @return void
  1255. */
  1256. public function testFileWithUnknownFileTypeOpera()
  1257. {
  1258. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1259. $_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
  1260. $response = $this->getMockBuilder('Cake\Network\Response')
  1261. ->setMethods([
  1262. 'header',
  1263. 'type',
  1264. 'download',
  1265. '_sendHeader',
  1266. '_setContentType',
  1267. '_isActive',
  1268. ])
  1269. ->getMock();
  1270. $response->expects($this->at(0))
  1271. ->method('type')
  1272. ->with('ini')
  1273. ->will($this->returnValue(false));
  1274. $response->expects($this->at(1))
  1275. ->method('type')
  1276. ->with('application/octet-stream')
  1277. ->will($this->returnValue(false));
  1278. $response->expects($this->once())
  1279. ->method('download')
  1280. ->with('no_section.ini');
  1281. $response->expects($this->at(3))
  1282. ->method('header')
  1283. ->with('Content-Transfer-Encoding', 'binary');
  1284. $response->expects($this->at(4))
  1285. ->method('header')
  1286. ->with('Accept-Ranges', 'bytes');
  1287. $response->expects($this->exactly(1))
  1288. ->method('_isActive')
  1289. ->will($this->returnValue(true));
  1290. $response->file(CONFIG . 'no_section.ini');
  1291. ob_start();
  1292. $result = $response->send();
  1293. $output = ob_get_clean();
  1294. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1295. $this->assertNotSame(false, $result);
  1296. if ($currentUserAgent !== null) {
  1297. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1298. }
  1299. }
  1300. /**
  1301. * testFileWithUnknownFileTypeIE method
  1302. *
  1303. * @return void
  1304. */
  1305. public function testFileWithUnknownFileTypeIE()
  1306. {
  1307. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1308. $_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)';
  1309. $response = $this->getMockBuilder('Cake\Network\Response')
  1310. ->setMethods([
  1311. 'header',
  1312. 'type',
  1313. 'download',
  1314. '_sendHeader',
  1315. '_setContentType',
  1316. '_isActive',
  1317. ])
  1318. ->getMock();
  1319. $response->expects($this->at(0))
  1320. ->method('type')
  1321. ->with('ini')
  1322. ->will($this->returnValue(false));
  1323. $response->expects($this->at(1))
  1324. ->method('type')
  1325. ->with('application/force-download')
  1326. ->will($this->returnValue(false));
  1327. $response->expects($this->once())
  1328. ->method('download')
  1329. ->with('config.ini');
  1330. $response->expects($this->at(3))
  1331. ->method('header')
  1332. ->with('Content-Transfer-Encoding', 'binary');
  1333. $response->expects($this->at(4))
  1334. ->method('header')
  1335. ->with('Accept-Ranges', 'bytes');
  1336. $response->expects($this->exactly(1))
  1337. ->method('_isActive')
  1338. ->will($this->returnValue(true));
  1339. $response->file(CONFIG . 'no_section.ini', [
  1340. 'name' => 'config.ini'
  1341. ]);
  1342. ob_start();
  1343. $result = $response->send();
  1344. $output = ob_get_clean();
  1345. $this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
  1346. $this->assertNotSame(false, $result);
  1347. if ($currentUserAgent !== null) {
  1348. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1349. }
  1350. }
  1351. /**
  1352. * testFileWithUnknownFileNoDownload method
  1353. *
  1354. * @return void
  1355. */
  1356. public function testFileWithUnknownFileNoDownload()
  1357. {
  1358. $currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  1359. $_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
  1360. $response = $this->getMockBuilder('Cake\Network\Response')
  1361. ->setMethods([
  1362. 'header',
  1363. 'type',
  1364. 'download',
  1365. '_sendHeader',
  1366. '_setContentType',
  1367. '_isActive',
  1368. ])
  1369. ->getMock();
  1370. $response->expects($this->exactly(1))
  1371. ->method('type')
  1372. ->with('ini')
  1373. ->will($this->returnValue(false));
  1374. $response->expects($this->at(1))
  1375. ->method('header')
  1376. ->with('Accept-Ranges', 'bytes');
  1377. $response->expects($this->never())
  1378. ->method('download');
  1379. $response->file(CONFIG . 'no_section.ini', [
  1380. 'download' => false
  1381. ]);
  1382. if ($currentUserAgent !== null) {
  1383. $_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
  1384. }
  1385. }
  1386. /**
  1387. * test getFile method
  1388. *
  1389. * @return void
  1390. */
  1391. public function testGetFile()
  1392. {
  1393. $response = new Response();
  1394. $this->assertNull($response->getFile(), 'No file to get');
  1395. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1396. $file = $response->getFile();
  1397. $this->assertInstanceOf('Cake\Filesystem\File', $file, 'Should get a file');
  1398. $this->assertPathEquals(TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css', $file->path);
  1399. }
  1400. /**
  1401. * testConnectionAbortedOnBuffering method
  1402. *
  1403. * @return void
  1404. */
  1405. public function testConnectionAbortedOnBuffering()
  1406. {
  1407. $response = $this->getMockBuilder('Cake\Network\Response')
  1408. ->setMethods([
  1409. 'header',
  1410. 'type',
  1411. 'download',
  1412. '_sendHeader',
  1413. '_setContentType',
  1414. '_isActive',
  1415. ])
  1416. ->getMock();
  1417. $response->expects($this->any())
  1418. ->method('type')
  1419. ->with('css')
  1420. ->will($this->returnArgument(0));
  1421. $response->expects($this->at(0))
  1422. ->method('_isActive')
  1423. ->will($this->returnValue(false));
  1424. $response->file(TEST_APP . 'vendor/css/test_asset.css');
  1425. $result = $response->send();
  1426. $this->assertNull($result);
  1427. }
  1428. /**
  1429. * Test downloading files with UPPERCASE extensions.
  1430. *
  1431. * @return void
  1432. */
  1433. public function testFileUpperExtension()
  1434. {
  1435. $response = $this->getMockBuilder('Cake\Network\Response')
  1436. ->setMethods([
  1437. 'header',
  1438. 'type',
  1439. 'download',
  1440. '_sendHeader',
  1441. '_setContentType',
  1442. '_isActive',
  1443. ])
  1444. ->getMock();
  1445. $response->expects($this->any())
  1446. ->method('type')
  1447. ->with('jpg')
  1448. ->will($this->returnArgument(0));
  1449. $response->expects($this->at(0))
  1450. ->method('_isActive')
  1451. ->will($this->returnValue(true));
  1452. $response->file(TEST_APP . 'vendor/img/test_2.JPG');
  1453. }
  1454. /**
  1455. * Test downloading files with extension not explicitly set.
  1456. *
  1457. * @return void
  1458. */
  1459. public function testFileExtensionNotSet()
  1460. {
  1461. $response = $this->getMockBuilder('Cake\Network\Response')
  1462. ->setMethods([
  1463. 'header',
  1464. 'type',
  1465. 'download',
  1466. '_sendHeader',
  1467. '_setContentType',
  1468. '_isActive',
  1469. ])
  1470. ->getMock();
  1471. $response->expects($this->any())
  1472. ->method('type')
  1473. ->with('jpg')
  1474. ->will($this->returnArgument(0));
  1475. $response->expects($this->at(0))
  1476. ->method('_isActive')
  1477. ->will($this->returnValue(true));
  1478. $response->file(TEST_APP . 'vendor/img/test_2.JPG');
  1479. }
  1480. /**
  1481. * A data provider for testing various ranges
  1482. *
  1483. * @return array
  1484. */
  1485. public static function rangeProvider()
  1486. {
  1487. return [
  1488. // suffix-byte-range
  1489. [
  1490. 'bytes=-25', 25, 'bytes 13-37/38'
  1491. ],
  1492. [
  1493. 'bytes=0-', 38, 'bytes 0-37/38'
  1494. ],
  1495. [
  1496. 'bytes=10-', 28, 'bytes 10-37/38'
  1497. ],
  1498. [
  1499. 'bytes=10-20', 11, 'bytes 10-20/38'
  1500. ],
  1501. // Spaced out
  1502. [
  1503. 'bytes = 10 - 20', 11, 'bytes 10-20/38'
  1504. ],
  1505. ];
  1506. }
  1507. /**
  1508. * Test the various range offset types.
  1509. *
  1510. * @dataProvider rangeProvider
  1511. * @return void
  1512. */
  1513. public function testFileRangeOffsets($range, $length, $offsetResponse)
  1514. {
  1515. $_SERVER['HTTP_RANGE'] = $range;
  1516. $response = $this->getMockBuilder('Cake\Network\Response')
  1517. ->setMethods([
  1518. 'header',
  1519. 'type',
  1520. '_sendHeader',
  1521. '_setContentType',
  1522. '_isActive',
  1523. ])
  1524. ->getMock();
  1525. $response->expects($this->at(1))
  1526. ->method('header')
  1527. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  1528. $response->expects($this->at(2))
  1529. ->method('header')
  1530. ->with('Content-Transfer-Encoding', 'binary');
  1531. $response->expects($this->at(3))
  1532. ->method('header')
  1533. ->with('Accept-Ranges', 'bytes');
  1534. $response->expects($this->at(4))
  1535. ->method('header')
  1536. ->with([
  1537. 'Content-Length' => $length,
  1538. 'Content-Range' => $offsetResponse,
  1539. ]);
  1540. $response->expects($this->any())
  1541. ->method('_isActive')
  1542. ->will($this->returnValue(true));
  1543. $response->file(
  1544. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1545. ['download' => true]
  1546. );
  1547. ob_start();
  1548. $result = $response->send();
  1549. ob_get_clean();
  1550. }
  1551. /**
  1552. * Test fetching ranges from a file.
  1553. *
  1554. * @return void
  1555. */
  1556. public function testFileRange()
  1557. {
  1558. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1559. $response = $this->getMockBuilder('Cake\Network\Response')
  1560. ->setMethods([
  1561. 'header',
  1562. 'type',
  1563. '_sendHeader',
  1564. '_setContentType',
  1565. '_isActive',
  1566. ])
  1567. ->getMock();
  1568. $response->expects($this->exactly(1))
  1569. ->method('type')
  1570. ->with('css')
  1571. ->will($this->returnArgument(0));
  1572. $response->expects($this->at(1))
  1573. ->method('header')
  1574. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  1575. $response->expects($this->at(2))
  1576. ->method('header')
  1577. ->with('Content-Transfer-Encoding', 'binary');
  1578. $response->expects($this->at(3))
  1579. ->method('header')
  1580. ->with('Accept-Ranges', 'bytes');
  1581. $response->expects($this->at(4))
  1582. ->method('header')
  1583. ->with([
  1584. 'Content-Length' => 18,
  1585. 'Content-Range' => 'bytes 8-25/38',
  1586. ]);
  1587. $response->expects($this->any())
  1588. ->method('_isActive')
  1589. ->will($this->returnValue(true));
  1590. $response->file(
  1591. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1592. ['download' => true]
  1593. );
  1594. ob_start();
  1595. $result = $response->send();
  1596. $output = ob_get_clean();
  1597. $this->assertEquals(206, $response->statusCode());
  1598. $this->assertEquals("is the test asset ", $output);
  1599. $this->assertNotSame(false, $result);
  1600. }
  1601. /**
  1602. * Provider for invalid range header values.
  1603. *
  1604. * @return array
  1605. */
  1606. public function invalidFileRangeProvider()
  1607. {
  1608. return [
  1609. // malformed range
  1610. [
  1611. 'bytes=0,38'
  1612. ],
  1613. // malformed punctuation
  1614. [
  1615. 'bytes: 0 - 38'
  1616. ],
  1617. ];
  1618. }
  1619. /**
  1620. * Test invalid file ranges.
  1621. *
  1622. * @dataProvider invalidFileRangeProvider
  1623. * @return void
  1624. */
  1625. public function testFileRangeInvalid($range)
  1626. {
  1627. $_SERVER['HTTP_RANGE'] = $range;
  1628. $response = $this->getMockBuilder('Cake\Network\Response')
  1629. ->setMethods([
  1630. '_sendHeader',
  1631. '_isActive',
  1632. ])
  1633. ->getMock();
  1634. $response->file(
  1635. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1636. ['download' => true]
  1637. );
  1638. $expected = [
  1639. 'Content-Type' => 'text/css; charset=UTF-8',
  1640. 'Content-Disposition' => 'attachment; filename="test_asset.css"',
  1641. 'Content-Transfer-Encoding' => 'binary',
  1642. 'Accept-Ranges' => 'bytes',
  1643. 'Content-Range' => 'bytes 0-37/38',
  1644. 'Content-Length' => 38,
  1645. ];
  1646. $this->assertEquals($expected, $response->header());
  1647. }
  1648. /**
  1649. * Test reversed file ranges.
  1650. *
  1651. * @return void
  1652. */
  1653. public function testFileRangeReversed()
  1654. {
  1655. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1656. $response = $this->getMockBuilder('Cake\Network\Response')
  1657. ->setMethods([
  1658. 'header',
  1659. 'type',
  1660. '_sendHeader',
  1661. '_isActive',
  1662. ])
  1663. ->getMock();
  1664. $response->expects($this->at(1))
  1665. ->method('header')
  1666. ->with('Content-Disposition', 'attachment; filename="test_asset.css"');
  1667. $response->expects($this->at(2))
  1668. ->method('header')
  1669. ->with('Content-Transfer-Encoding', 'binary');
  1670. $response->expects($this->at(3))
  1671. ->method('header')
  1672. ->with('Accept-Ranges', 'bytes');
  1673. $response->expects($this->at(4))
  1674. ->method('header')
  1675. ->with([
  1676. 'Content-Range' => 'bytes 0-37/38',
  1677. ]);
  1678. $response->file(
  1679. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1680. ['download' => true]
  1681. );
  1682. $this->assertEquals(416, $response->statusCode());
  1683. $result = $response->send();
  1684. }
  1685. /**
  1686. * testFileRangeOffsetsNoDownload method
  1687. *
  1688. * @dataProvider rangeProvider
  1689. * @return void
  1690. */
  1691. public function testFileRangeOffsetsNoDownload($range, $length, $offsetResponse)
  1692. {
  1693. $_SERVER['HTTP_RANGE'] = $range;
  1694. $response = $this->getMockBuilder('Cake\Network\Response')
  1695. ->setMethods([
  1696. 'header',
  1697. 'type',
  1698. '_sendHeader',
  1699. '_isActive',
  1700. ])
  1701. ->getMock();
  1702. $response->expects($this->at(1))
  1703. ->method('header')
  1704. ->with('Accept-Ranges', 'bytes');
  1705. $response->expects($this->at(2))
  1706. ->method('header')
  1707. ->with([
  1708. 'Content-Length' => $length,
  1709. 'Content-Range' => $offsetResponse,
  1710. ]);
  1711. $response->expects($this->any())
  1712. ->method('_isActive')
  1713. ->will($this->returnValue(true));
  1714. $response->file(
  1715. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1716. ['download' => false]
  1717. );
  1718. ob_start();
  1719. $result = $response->send();
  1720. ob_get_clean();
  1721. }
  1722. /**
  1723. * testFileRangeNoDownload method
  1724. *
  1725. * @return void
  1726. */
  1727. public function testFileRangeNoDownload()
  1728. {
  1729. $_SERVER['HTTP_RANGE'] = 'bytes=8-25';
  1730. $response = $this->getMockBuilder('Cake\Network\Response')
  1731. ->setMethods([
  1732. 'header',
  1733. 'type',
  1734. '_sendHeader',
  1735. '_isActive',
  1736. ])
  1737. ->getMock();
  1738. $response->expects($this->exactly(1))
  1739. ->method('type')
  1740. ->with('css')
  1741. ->will($this->returnArgument(0));
  1742. $response->expects($this->at(1))
  1743. ->method('header')
  1744. ->with('Accept-Ranges', 'bytes');
  1745. $response->expects($this->at(2))
  1746. ->method('header')
  1747. ->with([
  1748. 'Content-Length' => 18,
  1749. 'Content-Range' => 'bytes 8-25/38',
  1750. ]);
  1751. $response->expects($this->any())
  1752. ->method('_isActive')
  1753. ->will($this->returnValue(true));
  1754. $response->file(
  1755. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1756. ['download' => false]
  1757. );
  1758. ob_start();
  1759. $result = $response->send();
  1760. $output = ob_get_clean();
  1761. $this->assertEquals(206, $response->statusCode());
  1762. $this->assertEquals("is the test asset ", $output);
  1763. $this->assertNotSame(false, $result);
  1764. }
  1765. /**
  1766. * testFileRangeInvalidNoDownload method
  1767. *
  1768. * @return void
  1769. */
  1770. public function testFileRangeInvalidNoDownload()
  1771. {
  1772. $_SERVER['HTTP_RANGE'] = 'bytes=30-2';
  1773. $response = $this->getMockBuilder('Cake\Network\Response')
  1774. ->setMethods([
  1775. 'header',
  1776. 'type',
  1777. '_sendHeader',
  1778. '_isActive',
  1779. ])
  1780. ->getMock();
  1781. $response->expects($this->at(1))
  1782. ->method('header')
  1783. ->with('Accept-Ranges', 'bytes');
  1784. $response->expects($this->at(2))
  1785. ->method('header')
  1786. ->with([
  1787. 'Content-Range' => 'bytes 0-37/38',
  1788. ]);
  1789. $response->file(
  1790. TEST_APP . 'vendor' . DS . 'css' . DS . 'test_asset.css',
  1791. ['download' => false]
  1792. );
  1793. $this->assertEquals(416, $response->statusCode());
  1794. $result = $response->send();
  1795. }
  1796. /**
  1797. * Test the location method.
  1798. *
  1799. * @return void
  1800. */
  1801. public function testLocation()
  1802. {
  1803. $response = new Response();
  1804. $this->assertNull($response->location(), 'No header should be set.');
  1805. $this->assertNull($response->location('http://example.org'), 'Setting a location should return null');
  1806. $this->assertEquals('http://example.org', $response->location(), 'Reading a location should return the value.');
  1807. }
  1808. /**
  1809. * Test the withLocation method.
  1810. *
  1811. * @return void
  1812. */
  1813. public function testWithLocation()
  1814. {
  1815. $response = new Response();
  1816. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set.');
  1817. $new = $response->withLocation('http://example.org');
  1818. $this->assertNotSame($new, $response);
  1819. $this->assertSame('', $response->getHeaderLine('Location'), 'No header should be set');
  1820. $this->assertSame('http://example.org', $new->getHeaderLine('Location'), 'Header should be set');
  1821. $this->assertSame(302, $new->getStatusCode(), 'Status should be updated');
  1822. }
  1823. /**
  1824. * Test get protocol version.
  1825. *
  1826. * @return void
  1827. */
  1828. public function getProtocolVersion()
  1829. {
  1830. $response = new Response();
  1831. $version = $response->getProtocolVersion();
  1832. $this->assertEquals('1.1', $version);
  1833. }
  1834. /**
  1835. * Test with protocol.
  1836. *
  1837. * @return void
  1838. */
  1839. public function testWithProtocol()
  1840. {
  1841. $response = new Response();
  1842. $version = $response->getProtocolVersion();
  1843. $this->assertEquals('1.1', $version);
  1844. $response2 = $response->withProtocolVersion('1.0');
  1845. $version = $response2->getProtocolVersion();
  1846. $this->assertEquals('1.0', $version);
  1847. $version = $response->getProtocolVersion();
  1848. $this->assertEquals('1.1', $version);
  1849. $this->assertNotEquals($response, $response2);
  1850. }
  1851. /**
  1852. * Test with protocol.
  1853. *
  1854. * @return void
  1855. */
  1856. public function testWithStatusCode()
  1857. {
  1858. $response = new Response();
  1859. $statusCode = $response->getStatusCode();
  1860. $this->assertEquals(200, $statusCode);
  1861. $response2 = $response->withStatus(404);
  1862. $statusCode = $response2->getStatusCode();
  1863. $this->assertEquals(404, $statusCode);
  1864. $statusCode = $response->getStatusCode();
  1865. $this->assertEquals(200, $statusCode);
  1866. $this->assertNotEquals($response, $response2);
  1867. }
  1868. /**
  1869. * Test get reason phrase.
  1870. *
  1871. * @return void
  1872. */
  1873. public function testGetReasonPhrase()
  1874. {
  1875. $response = new Response();
  1876. $reasonPhrase = $response->getReasonPhrase();
  1877. $this->assertNull($reasonPhrase);
  1878. $response = $response->withStatus(404);
  1879. $reasonPhrase = $response->getReasonPhrase();
  1880. $this->assertEquals('Not Found', $reasonPhrase);
  1881. }
  1882. /**
  1883. * Test with body.
  1884. *
  1885. * @return void
  1886. */
  1887. public function testWithBody()
  1888. {
  1889. $response = new Response();
  1890. $body = $response->getBody();
  1891. $body->rewind();
  1892. $result = $body->getContents();
  1893. $this->assertEquals('', $result);
  1894. $stream = new Stream('php://memory', 'wb+');
  1895. $stream->write('test1');
  1896. $response2 = $response->withBody($stream);
  1897. $body = $response2->getBody();
  1898. $body->rewind();
  1899. $result = $body->getContents();
  1900. $this->assertEquals('test1', $result);
  1901. $body = $response->getBody();
  1902. $body->rewind();
  1903. $result = $body->getContents();
  1904. $this->assertEquals('', $result);
  1905. }
  1906. /**
  1907. * Test get Body.
  1908. *
  1909. * @return void
  1910. */
  1911. public function testGetBody()
  1912. {
  1913. $response = new Response();
  1914. $stream = $response->getBody();
  1915. $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $stream);
  1916. }
  1917. /**
  1918. * Test with header.
  1919. *
  1920. * @return void
  1921. */
  1922. public function testWithHeader()
  1923. {
  1924. $response = new Response();
  1925. $response2 = $response->withHeader('Accept', 'application/json');
  1926. $result = $response2->getHeaders();
  1927. $expected = [
  1928. 'Content-Type' => ['text/html; charset=UTF-8'],
  1929. 'Accept' => ['application/json']
  1930. ];
  1931. $this->assertEquals($expected, $result);
  1932. $this->assertFalse($response->hasHeader('Accept'));
  1933. }
  1934. /**
  1935. * Test get headers.
  1936. *
  1937. * @return void
  1938. */
  1939. public function testGetHeaders()
  1940. {
  1941. $response = new Response();
  1942. $headers = $response->getHeaders();
  1943. $response = $response->withAddedHeader('Location', 'localhost');
  1944. $response = $response->withAddedHeader('Accept', 'application/json');
  1945. $headers = $response->getHeaders();
  1946. $expected = [
  1947. 'Content-Type' => ['text/html; charset=UTF-8'],
  1948. 'Location' => ['localhost'],
  1949. 'Accept' => ['application/json']
  1950. ];
  1951. $this->assertEquals($expected, $headers);
  1952. }
  1953. /**
  1954. * Test without header.
  1955. *
  1956. * @return void
  1957. */
  1958. public function testWithoutHeader()
  1959. {
  1960. $response = new Response();
  1961. $response = $response->withAddedHeader('Location', 'localhost');
  1962. $response = $response->withAddedHeader('Accept', 'application/json');
  1963. $response2 = $response->withoutHeader('Location');
  1964. $headers = $response2->getHeaders();
  1965. $expected = [
  1966. 'Content-Type' => ['text/html; charset=UTF-8'],
  1967. 'Accept' => ['application/json']
  1968. ];
  1969. $this->assertEquals($expected, $headers);
  1970. }
  1971. /**
  1972. * Test get header.
  1973. *
  1974. * @return void
  1975. */
  1976. public function testGetHeader()
  1977. {
  1978. $response = new Response();
  1979. $response = $response->withAddedHeader('Location', 'localhost');
  1980. $result = $response->getHeader('Location');
  1981. $this->assertEquals(['localhost'], $result);
  1982. $result = $response->getHeader('location');
  1983. $this->assertEquals(['localhost'], $result);
  1984. $result = $response->getHeader('does-not-exist');
  1985. $this->assertEquals([], $result);
  1986. }
  1987. /**
  1988. * Test get header line.
  1989. *
  1990. * @return void
  1991. */
  1992. public function testGetHeaderLine()
  1993. {
  1994. $response = new Response();
  1995. $headers = $response->getHeaderLine('Accept');
  1996. $this->assertEquals('', $headers);
  1997. $response = $response->withAddedHeader('Accept', 'application/json');
  1998. $response = $response->withAddedHeader('Accept', 'application/xml');
  1999. $result = $response->getHeaderLine('Accept');
  2000. $expected = 'application/json,application/xml';
  2001. $this->assertEquals($expected, $result);
  2002. $result = $response->getHeaderLine('accept');
  2003. $this->assertEquals($expected, $result);
  2004. }
  2005. /**
  2006. * Test has header.
  2007. *
  2008. * @return void
  2009. */
  2010. public function testHasHeader()
  2011. {
  2012. $response = new Response();
  2013. $response = $response->withAddedHeader('Location', 'localhost');
  2014. $this->assertTrue($response->hasHeader('Location'));
  2015. $this->assertTrue($response->hasHeader('location'));
  2016. $this->assertTrue($response->hasHeader('locATIon'));
  2017. $this->assertFalse($response->hasHeader('Accept'));
  2018. $this->assertFalse($response->hasHeader('accept'));
  2019. }
  2020. /**
  2021. * Tests __debugInfo
  2022. *
  2023. * @return void
  2024. */
  2025. public function testDebugInfo()
  2026. {
  2027. $response = new Response();
  2028. $result = $response->__debugInfo();
  2029. $expected = [
  2030. 'status' => 200,
  2031. 'contentType' => 'text/html',
  2032. 'headers' => [
  2033. 'Content-Type' => ['text/html; charset=UTF-8']
  2034. ],
  2035. 'file' => null,
  2036. 'fileRange' => [],
  2037. 'cookies' => [],
  2038. 'cacheDirectives' => [],
  2039. 'body' => ''
  2040. ];
  2041. $this->assertEquals($expected, $result);
  2042. }
  2043. }