ResponseTest.php 70 KB

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