ResponseTest.php 104 KB

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