ResponseTest.php 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170
  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\Http\Cookie\Cookie;
  18. use Cake\Http\Cookie\CookieCollection;
  19. use Cake\Http\CorsBuilder;
  20. use Cake\Http\Exception\NotFoundException;
  21. use Cake\Http\Response;
  22. use Cake\Http\ServerRequest;
  23. use Cake\TestSuite\TestCase;
  24. use Zend\Diactoros\Stream;
  25. /**
  26. * ResponseTest
  27. */
  28. class ResponseTest extends TestCase
  29. {
  30. /**
  31. * SERVER variable backup.
  32. *
  33. * @var array
  34. */
  35. protected $server = [];
  36. /**
  37. * setup
  38. *
  39. * @return void
  40. */
  41. public function setUp()
  42. {
  43. parent::setUp();
  44. $this->server = $_SERVER;
  45. }
  46. /**
  47. * teardown
  48. *
  49. * @return void
  50. */
  51. public function tearDown()
  52. {
  53. parent::tearDown();
  54. $_SERVER = $this->server;
  55. unset($GLOBALS['mockedHeadersSent']);
  56. }
  57. /**
  58. * Tests the request object constructor
  59. *
  60. * @return void
  61. */
  62. public function testConstruct()
  63. {
  64. $response = new Response();
  65. $this->assertSame('', (string)$response->getBody());
  66. $this->assertEquals('UTF-8', $response->getCharset());
  67. $this->assertEquals('text/html', $response->getType());
  68. $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  69. $this->assertEquals(200, $response->getStatusCode());
  70. $options = [
  71. 'body' => 'This is the body',
  72. 'charset' => 'my-custom-charset',
  73. 'type' => 'mp3',
  74. 'status' => '203'
  75. ];
  76. $response = new Response($options);
  77. $this->assertEquals('This is the body', (string)$response->getBody());
  78. $this->assertEquals('my-custom-charset', $response->getCharset());
  79. $this->assertEquals('audio/mpeg', $response->getType());
  80. $this->assertEquals('audio/mpeg', $response->getHeaderLine('Content-Type'));
  81. $this->assertEquals(203, $response->getStatusCode());
  82. }
  83. /**
  84. * Test statusCodes constructor argument.
  85. *
  86. * @group deprecated
  87. * @return void
  88. */
  89. public function testConstructCustomCodes()
  90. {
  91. $this->deprecated(function () {
  92. $options = [
  93. 'body' => 'This is the body',
  94. 'charset' => 'ISO-8859-1',
  95. 'type' => 'txt',
  96. 'status' => '422',
  97. 'statusCodes' => [
  98. 422 => 'Unprocessable Entity'
  99. ]
  100. ];
  101. $response = new Response($options);
  102. $this->assertEquals($options['body'], (string)$response->getBody());
  103. $this->assertEquals($options['charset'], $response->getCharset());
  104. $this->assertEquals($response->getMimeType($options['type']), $response->getType());
  105. $this->assertEquals($options['status'], $response->getStatusCode());
  106. $this->assertEquals('text/plain; charset=ISO-8859-1', $response->getHeaderLine('Content-Type'));
  107. });
  108. }
  109. /**
  110. * Tests the body method
  111. *
  112. * @group deprecated
  113. * @return void
  114. */
  115. public function testBody()
  116. {
  117. $this->deprecated(function () {
  118. $response = new Response();
  119. $this->assertNull($response->body());
  120. $response->body('Response body');
  121. $this->assertEquals('Response body', $response->body());
  122. $this->assertEquals('Changed Body', $response->body('Changed Body'));
  123. $response = new Response();
  124. $response->body(0);
  125. $this->assertEquals(0, $response->body());
  126. $response = new Response();
  127. $response->body('0');
  128. $this->assertEquals('0', $response->body());
  129. $response = new Response();
  130. $response->body(null);
  131. $this->assertNull($response->body());
  132. });
  133. }
  134. /**
  135. * Tests the charset method
  136. *
  137. * @group deprecated
  138. * @return void
  139. */
  140. public function testCharset()
  141. {
  142. $this->deprecated(function () {
  143. $response = new Response();
  144. $this->assertEquals('UTF-8', $response->charset());
  145. $response->charset('iso-8859-1');
  146. $this->assertEquals('iso-8859-1', $response->charset());
  147. $this->assertEquals('UTF-16', $response->charset('UTF-16'));
  148. });
  149. }
  150. /**
  151. * Tests the getCharset/withCharset methods
  152. *
  153. * @return void
  154. */
  155. public function testWithCharset()
  156. {
  157. $response = new Response();
  158. $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
  159. $new = $response->withCharset('iso-8859-1');
  160. $this->assertNotContains('iso', $response->getHeaderLine('Content-Type'), 'Old instance not changed');
  161. $this->assertSame('iso-8859-1', $new->getCharset());
  162. $this->assertEquals('text/html; charset=iso-8859-1', $new->getHeaderLine('Content-Type'));
  163. }
  164. /**
  165. * Tests the statusCode method
  166. *
  167. * @group deprecated
  168. * @return void
  169. */
  170. public function testStatusCode()
  171. {
  172. $this->deprecated(function () {
  173. $response = new Response();
  174. $this->assertEquals(200, $response->statusCode());
  175. $response->statusCode(404);
  176. $this->assertEquals(404, $response->getStatusCode(), 'Sets shared state.');
  177. $this->assertEquals(404, $response->statusCode());
  178. $this->assertEquals('Not Found', $response->getReasonPhrase());
  179. $this->assertEquals(500, $response->statusCode(500));
  180. });
  181. }
  182. /**
  183. * Test invalid status codes
  184. *
  185. * @group deprecated
  186. * @return void
  187. */
  188. public function testStatusCodeInvalid()
  189. {
  190. $this->expectException(\InvalidArgumentException::class);
  191. $this->deprecated(function () {
  192. $response = new Response();
  193. $response->statusCode(1001);
  194. });
  195. }
  196. /**
  197. * Tests the type method
  198. *
  199. * @group deprecated
  200. * @return void
  201. */
  202. public function testType()
  203. {
  204. $this->deprecated(function () {
  205. $response = new Response();
  206. $this->assertEquals('text/html', $response->type());
  207. $response->type('pdf');
  208. $this->assertEquals('application/pdf', $response->type());
  209. $this->assertEquals('application/crazy-mime', $response->type('application/crazy-mime'));
  210. $this->assertEquals('application/json', $response->type('json'));
  211. $this->assertEquals('text/vnd.wap.wml', $response->type('wap'));
  212. $this->assertEquals('application/vnd.wap.xhtml+xml', $response->type('xhtml-mobile'));
  213. $this->assertEquals('text/csv', $response->type('csv'));
  214. $response->type(['keynote' => 'application/keynote', 'bat' => 'application/bat']);
  215. $this->assertEquals('application/keynote', $response->type('keynote'));
  216. $this->assertEquals('application/bat', $response->type('bat'));
  217. $this->assertFalse($response->type('wackytype'));
  218. });
  219. }
  220. /**
  221. * Tests the getType method
  222. *
  223. * @return void
  224. */
  225. public function testGetType()
  226. {
  227. $response = new Response();
  228. $this->assertEquals('text/html', $response->getType());
  229. $this->assertEquals(
  230. 'application/pdf',
  231. $response->withType('pdf')->getType()
  232. );
  233. $this->assertEquals(
  234. 'custom/stuff',
  235. $response->withType('custom/stuff')->getType()
  236. );
  237. $this->assertEquals(
  238. 'application/json',
  239. $response->withType('json')->getType()
  240. );
  241. }
  242. /**
  243. * @return void
  244. */
  245. public function testSetTypeMap()
  246. {
  247. $response = new Response();
  248. $response->setTypeMap('ical', 'text/calendar');
  249. $response = $response->withType('ical')->getType();
  250. $this->assertEquals('text/calendar', $response);
  251. }
  252. /**
  253. * @return void
  254. */
  255. public function testSetTypeMapAsArray()
  256. {
  257. $response = new Response();
  258. $response->setTypeMap('ical', ['text/calendar']);
  259. $response = $response->withType('ical')->getType();
  260. $this->assertEquals('text/calendar', $response);
  261. }
  262. /**
  263. * Tests the withType method
  264. *
  265. * @return void
  266. */
  267. public function testWithTypeAlias()
  268. {
  269. $response = new Response();
  270. $this->assertEquals(
  271. 'text/html; charset=UTF-8',
  272. $response->getHeaderLine('Content-Type'),
  273. 'Default content-type should match'
  274. );
  275. $new = $response->withType('pdf');
  276. $this->assertNotSame($new, $response, 'Should be a new instance');
  277. $this->assertSame(
  278. 'text/html; charset=UTF-8',
  279. $response->getHeaderLine('Content-Type'),
  280. 'Original object should not be modified'
  281. );
  282. $this->assertSame('application/pdf', $new->getHeaderLine('Content-Type'));
  283. $this->assertSame(
  284. 'application/json; charset=UTF-8',
  285. $new->withType('json')->getHeaderLine('Content-Type')
  286. );
  287. }
  288. /**
  289. * test withType() and full mime-types
  290. *
  291. * @return void
  292. */
  293. public function withTypeFull()
  294. {
  295. $response = new Response();
  296. $this->assertEquals(
  297. 'application/json',
  298. $response->withType('application/json')->getHeaderLine('Content-Type'),
  299. 'Should not add charset to explicit type'
  300. );
  301. $this->assertEquals(
  302. 'custom/stuff',
  303. $response->withType('custom/stuff')->getHeaderLine('Content-Type'),
  304. 'Should allow arbitrary types'
  305. );
  306. }
  307. /**
  308. * Test that an invalid type raises an exception
  309. *
  310. * @return void
  311. */
  312. public function testWithTypeInvalidType()
  313. {
  314. $this->expectException(\InvalidArgumentException::class);
  315. $this->expectExceptionMessage('"beans" is an invalid content type');
  316. $response = new Response();
  317. $response->withType('beans');
  318. }
  319. /**
  320. * Tests the header method
  321. *
  322. * @group deprecated
  323. * @return void
  324. */
  325. public function testHeader()
  326. {
  327. $this->deprecated(function () {
  328. $response = new Response();
  329. $headers = [
  330. 'Content-Type' => 'text/html; charset=UTF-8',
  331. ];
  332. $this->assertEquals($headers, $response->header());
  333. $response->header('Location', 'http://example.com');
  334. $headers += ['Location' => 'http://example.com'];
  335. $this->assertEquals($headers, $response->header());
  336. // Headers with the same name are overwritten
  337. $response->header('Location', 'http://example2.com');
  338. $headers = [
  339. 'Content-Type' => 'text/html; charset=UTF-8',
  340. 'Location' => 'http://example2.com'
  341. ];
  342. $this->assertEquals($headers, $response->header());
  343. $response->header(['WWW-Authenticate' => 'Negotiate']);
  344. $headers += ['WWW-Authenticate' => 'Negotiate'];
  345. $this->assertEquals($headers, $response->header());
  346. $response->header(['WWW-Authenticate' => 'Not-Negotiate']);
  347. $headers['WWW-Authenticate'] = 'Not-Negotiate';
  348. $this->assertEquals($headers, $response->header());
  349. $response->header(['Age' => 12, 'Allow' => 'GET, HEAD']);
  350. $headers += ['Age' => 12, 'Allow' => 'GET, HEAD'];
  351. $this->assertEquals($headers, $response->header());
  352. // String headers are allowed
  353. $response->header('Content-Language: da');
  354. $headers += ['Content-Language' => 'da'];
  355. $this->assertEquals($headers, $response->header());
  356. $response->header('Content-Language: da');
  357. $headers += ['Content-Language' => 'da'];
  358. $this->assertEquals($headers, $response->header());
  359. $response->header(['Content-Encoding: gzip', 'Vary: *', 'Pragma' => 'no-cache']);
  360. $headers += ['Content-Encoding' => 'gzip', 'Vary' => '*', 'Pragma' => 'no-cache'];
  361. $this->assertEquals($headers, $response->header());
  362. $response->header('Access-Control-Allow-Origin', ['domain1', 'domain2']);
  363. $headers += ['Access-Control-Allow-Origin' => ['domain1', 'domain2']];
  364. $this->assertEquals($headers, $response->header());
  365. });
  366. }
  367. /**
  368. * Tests the send method
  369. *
  370. * @group deprecated
  371. * @return void
  372. */
  373. public function testSend()
  374. {
  375. $GLOBALS['mockedHeadersSent'] = false;
  376. $this->deprecated(function () {
  377. $response = $this->getMockBuilder('Cake\Http\Response')
  378. ->setMethods(['_sendHeader', '_sendContent'])
  379. ->getMock();
  380. $response->header([
  381. 'Content-Language' => 'es',
  382. 'WWW-Authenticate' => 'Negotiate',
  383. 'Access-Control-Allow-Origin' => ['domain1', 'domain2'],
  384. ]);
  385. $response->cookie(['name' => 'thing', 'value' => 'value']);
  386. $response->body('the response body');
  387. $response->expects($this->once())->method('_sendContent')->with('the response body');
  388. $response->expects($this->at(0))
  389. ->method('_sendHeader')->with('HTTP/1.1 200 OK');
  390. $response->expects($this->at(1))
  391. ->method('_sendHeader')->with('Content-Type', 'text/html; charset=UTF-8');
  392. $response->expects($this->at(2))
  393. ->method('_sendHeader')->with('Content-Language', 'es');
  394. $response->expects($this->at(3))
  395. ->method('_sendHeader')->with('WWW-Authenticate', 'Negotiate');
  396. $response->expects($this->at(4))
  397. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain1');
  398. $response->expects($this->at(5))
  399. ->method('_sendHeader')->with('Access-Control-Allow-Origin', 'domain2');
  400. $response->send();
  401. $this->assertCount(1, $GLOBALS['mockedCookies']);
  402. $this->assertSame('value', $GLOBALS['mockedCookies'][0]['value']);
  403. $this->assertSame('thing', $GLOBALS['mockedCookies'][0]['name']);
  404. });
  405. }
  406. /**
  407. * Data provider for content type tests.
  408. *
  409. * @return array
  410. */
  411. public static function charsetTypeProvider()
  412. {
  413. return [
  414. ['mp3', 'audio/mpeg'],
  415. ['js', 'application/javascript; charset=UTF-8'],
  416. ['json', 'application/json; charset=UTF-8'],
  417. ['xml', 'application/xml; charset=UTF-8'],
  418. ['txt', 'text/plain; charset=UTF-8'],
  419. ];
  420. }
  421. /**
  422. * Tests the send method and changing the content type
  423. *
  424. * @group deprecated
  425. * @dataProvider charsetTypeProvider
  426. * @return void
  427. */
  428. public function testSendChangingContentType($original, $expected)
  429. {
  430. $this->deprecated(function () use ($original, $expected) {
  431. $response = new Response();
  432. $response->type($original);
  433. $response->body('the response body');
  434. $this->assertEquals($expected, $response->getHeaderLine('Content-Type'));
  435. });
  436. }
  437. /**
  438. * Tests the send method and changing the content type to JS without adding the charset
  439. *
  440. * @group deprecated
  441. * @return void
  442. */
  443. public function testCharsetSetContentTypeWithoutCharset()
  444. {
  445. $this->deprecated(function () {
  446. $response = new Response();
  447. $response->type('js');
  448. $response->charset('');
  449. $this->assertEquals('application/javascript', $response->getHeaderLine('Content-Type'));
  450. });
  451. }
  452. /**
  453. * Tests the send method and changing the content type
  454. *
  455. * @group deprecated
  456. * @return void
  457. */
  458. public function testLocationSetsStatus()
  459. {
  460. $this->deprecated(function () {
  461. $response = new Response();
  462. $response->location('http://www.example.com');
  463. $this->assertEquals(302, $response->getStatusCode());
  464. });
  465. }
  466. /**
  467. * Test that setting certain status codes clears the status code.
  468. *
  469. * @group deprecated
  470. * @return void
  471. */
  472. public function testStatusClearsContentType()
  473. {
  474. $this->deprecated(function () {
  475. $response = new Response();
  476. $response->statusCode(204);
  477. $response->statusCode(304);
  478. $this->assertFalse($response->hasHeader('Content-Type'));
  479. $this->assertSame(304, $response->getStatusCode());
  480. $response = new Response();
  481. $response->type('pdf');
  482. $response->statusCode(204);
  483. $this->assertFalse($response->hasHeader('Content-Type'));
  484. $this->assertSame(204, $response->getStatusCode());
  485. $response = new Response();
  486. $response->statusCode(204);
  487. $response->type('pdf');
  488. $this->assertFalse($response->hasHeader('Content-Type'));
  489. });
  490. }
  491. /**
  492. * Test that setting certain status codes clears the status code.
  493. *
  494. * @return void
  495. */
  496. public function testWithStatusClearsContentType()
  497. {
  498. $response = new Response();
  499. $new = $response->withType('pdf')
  500. ->withStatus(204);
  501. $this->assertFalse($new->hasHeader('Content-Type'));
  502. $this->assertSame(204, $new->getStatusCode());
  503. $response = new Response();
  504. $new = $response->withStatus(304)
  505. ->withType('pdf');
  506. $this->assertFalse($new->hasHeader('Content-Type'));
  507. }
  508. /**
  509. * Tests the send method and changing the content type
  510. *
  511. * @group deprecated
  512. * @return void
  513. */
  514. public function testSendWithCallableBody()
  515. {
  516. $this->deprecated(function () {
  517. $response = $this->getMockBuilder('Cake\Http\Response')
  518. ->setMethods(['_sendHeader'])
  519. ->getMock();
  520. $response->body(function () {
  521. echo 'the response body';
  522. });
  523. ob_start();
  524. $response->send();
  525. $this->assertEquals('the response body', ob_get_clean());
  526. });
  527. }
  528. /**
  529. * Tests that the returned a string from a body callable is also sent
  530. * as the response body
  531. *
  532. * @group deprecated
  533. * @return void
  534. */
  535. public function testSendWithCallableBodyWithReturn()
  536. {
  537. $this->deprecated(function () {
  538. $response = $this->getMockBuilder('Cake\Http\Response')
  539. ->setMethods(['_sendHeader'])
  540. ->getMock();
  541. $response->body(function () {
  542. return 'the response body';
  543. });
  544. ob_start();
  545. $response->send();
  546. $this->assertEquals('the response body', ob_get_clean());
  547. });
  548. }
  549. /**
  550. * Tests that callable strings are not triggered
  551. *
  552. * @group deprecated
  553. * @return void
  554. */
  555. public function testSendWithCallableStringBody()
  556. {
  557. $this->deprecated(function () {
  558. $response = $this->getMockBuilder('Cake\Http\Response')
  559. ->setMethods(['_sendHeader'])
  560. ->getMock();
  561. $response->body('phpversion');
  562. ob_start();
  563. $response->send();
  564. $this->assertEquals('phpversion', ob_get_clean());
  565. });
  566. }
  567. /**
  568. * Tests the disableCache method
  569. *
  570. * @group deprecated
  571. * @return void
  572. */
  573. public function testDisableCache()
  574. {
  575. $this->deprecated(function () {
  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. $response->disableCache();
  584. $this->assertEquals($expected, $response->header());
  585. });
  586. }
  587. /**
  588. * Tests the withDisabledCache method
  589. *
  590. * @return void
  591. */
  592. public function testWithDisabledCache()
  593. {
  594. $response = new Response();
  595. $expected = [
  596. 'Expires' => ['Mon, 26 Jul 1997 05:00:00 GMT'],
  597. 'Last-Modified' => [gmdate('D, d M Y H:i:s') . ' GMT'],
  598. 'Cache-Control' => ['no-store, no-cache, must-revalidate, post-check=0, pre-check=0'],
  599. 'Content-Type' => ['text/html; charset=UTF-8'],
  600. ];
  601. $new = $response->withDisabledCache();
  602. $this->assertFalse($response->hasHeader('Expires'), 'Old instance not mutated.');
  603. $this->assertEquals($expected, $new->getHeaders());
  604. }
  605. /**
  606. * Tests the cache method
  607. *
  608. * @group deprecated
  609. * @return void
  610. */
  611. public function testCache()
  612. {
  613. $this->deprecated(function () {
  614. $response = new Response();
  615. $since = time();
  616. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  617. $response->expires('+1 day');
  618. $expected = [
  619. 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
  620. 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
  621. 'Expires' => $time->format('D, j M Y H:i:s') . ' GMT',
  622. 'Cache-Control' => 'public, max-age=' . ($time->format('U') - time()),
  623. 'Content-Type' => 'text/html; charset=UTF-8',
  624. ];
  625. $response->cache($since);
  626. $this->assertEquals($expected, $response->header());
  627. $response = new Response();
  628. $since = time();
  629. $time = '+5 day';
  630. $expected = [
  631. 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
  632. 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
  633. 'Expires' => gmdate('D, j M Y H:i:s', strtotime($time)) . ' GMT',
  634. 'Cache-Control' => 'public, max-age=' . (strtotime($time) - time()),
  635. 'Content-Type' => 'text/html; charset=UTF-8',
  636. ];
  637. $response->cache($since, $time);
  638. $this->assertEquals($expected, $response->header());
  639. $response = new Response();
  640. $since = time();
  641. $time = time();
  642. $expected = [
  643. 'Date' => gmdate('D, j M Y G:i:s ', $since) . 'GMT',
  644. 'Last-Modified' => gmdate('D, j M Y H:i:s ', $since) . 'GMT',
  645. 'Expires' => gmdate('D, j M Y H:i:s', $time) . ' GMT',
  646. 'Cache-Control' => 'public, max-age=0',
  647. 'Content-Type' => 'text/html; charset=UTF-8',
  648. ];
  649. $response->cache($since, $time);
  650. $this->assertEquals($expected, $response->header());
  651. });
  652. }
  653. /**
  654. * Tests the withCache method
  655. *
  656. * @return void
  657. */
  658. public function testWithCache()
  659. {
  660. $response = new Response();
  661. $since = $time = time();
  662. $new = $response->withCache($since, $time);
  663. $this->assertFalse($response->hasHeader('Date'));
  664. $this->assertFalse($response->hasHeader('Last-Modified'));
  665. $this->assertEquals(gmdate('D, j M Y G:i:s ', $since) . 'GMT', $new->getHeaderLine('Date'));
  666. $this->assertEquals(gmdate('D, j M Y H:i:s ', $since) . 'GMT', $new->getHeaderLine('Last-Modified'));
  667. $this->assertEquals(gmdate('D, j M Y H:i:s', $time) . ' GMT', $new->getHeaderLine('Expires'));
  668. $this->assertEquals('public, max-age=0', $new->getHeaderLine('Cache-Control'));
  669. }
  670. /**
  671. * Tests the compress method
  672. *
  673. * @return void
  674. */
  675. public function testCompress()
  676. {
  677. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  678. $response = new Response();
  679. if (ini_get('zlib.output_compression') === '1' || !extension_loaded('zlib')) {
  680. $this->assertFalse($response->compress());
  681. $this->markTestSkipped('Is not possible to test output compression');
  682. }
  683. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  684. $result = $response->compress();
  685. $this->assertFalse($result);
  686. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  687. $result = $response->compress();
  688. $this->assertTrue($result);
  689. $this->assertContains('ob_gzhandler', ob_list_handlers());
  690. ob_get_clean();
  691. }
  692. /**
  693. * Tests the httpCodes method
  694. *
  695. * @group deprecated
  696. * @return void
  697. */
  698. public function testHttpCodes()
  699. {
  700. $this->expectException(\InvalidArgumentException::class);
  701. $this->deprecated(function () {
  702. $response = new Response();
  703. $result = $response->httpCodes();
  704. $this->assertCount(65, $result);
  705. $result = $response->httpCodes(100);
  706. $expected = [100 => 'Continue'];
  707. $this->assertEquals($expected, $result);
  708. $codes = [
  709. 381 => 'Unicorn Moved',
  710. 555 => 'Unexpected Minotaur'
  711. ];
  712. $result = $response->httpCodes($codes);
  713. $this->assertTrue($result);
  714. $this->assertCount(67, $response->httpCodes());
  715. $result = $response->httpCodes(381);
  716. $expected = [381 => 'Unicorn Moved'];
  717. $this->assertEquals($expected, $result);
  718. $codes = [404 => 'Sorry Bro'];
  719. $result = $response->httpCodes($codes);
  720. $this->assertTrue($result);
  721. $this->assertCount(67, $response->httpCodes());
  722. $result = $response->httpCodes(404);
  723. $expected = [404 => 'Sorry Bro'];
  724. $this->assertEquals($expected, $result);
  725. //Throws exception
  726. $response->httpCodes([
  727. 0 => 'Nothing Here',
  728. -1 => 'Reverse Infinity',
  729. 12345 => 'Universal Password',
  730. 'Hello' => 'World'
  731. ]);
  732. });
  733. }
  734. /**
  735. * Tests the download method
  736. *
  737. * @group deprecated
  738. * @return void
  739. */
  740. public function testDownload()
  741. {
  742. $this->deprecated(function () {
  743. $response = new Response();
  744. $expected = [
  745. 'Content-Type' => 'text/html; charset=UTF-8',
  746. 'Content-Disposition' => 'attachment; filename="myfile.mp3"'
  747. ];
  748. $response->download('myfile.mp3');
  749. $this->assertEquals($expected, $response->header());
  750. });
  751. }
  752. /**
  753. * Tests the withDownload method
  754. *
  755. * @return void
  756. */
  757. public function testWithDownload()
  758. {
  759. $response = new Response();
  760. $new = $response->withDownload('myfile.mp3');
  761. $this->assertFalse($response->hasHeader('Content-Disposition'), 'No mutation');
  762. $expected = 'attachment; filename="myfile.mp3"';
  763. $this->assertEquals($expected, $new->getHeaderLine('Content-Disposition'));
  764. }
  765. /**
  766. * Tests the mapType method
  767. *
  768. * @return void
  769. */
  770. public function testMapType()
  771. {
  772. $response = new Response();
  773. $this->assertEquals('wav', $response->mapType('audio/x-wav'));
  774. $this->assertEquals('pdf', $response->mapType('application/pdf'));
  775. $this->assertEquals('xml', $response->mapType('text/xml'));
  776. $this->assertEquals('html', $response->mapType('*/*'));
  777. $this->assertEquals('csv', $response->mapType('application/vnd.ms-excel'));
  778. $expected = ['json', 'xhtml', 'css'];
  779. $result = $response->mapType(['application/json', 'application/xhtml+xml', 'text/css']);
  780. $this->assertEquals($expected, $result);
  781. }
  782. /**
  783. * Tests the outputCompressed method
  784. *
  785. * @return void
  786. */
  787. public function testOutputCompressed()
  788. {
  789. $response = new Response();
  790. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  791. $result = $response->outputCompressed();
  792. $this->assertFalse($result);
  793. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  794. $result = $response->outputCompressed();
  795. $this->assertFalse($result);
  796. if (!extension_loaded('zlib')) {
  797. $this->markTestSkipped('Skipping further tests for outputCompressed as zlib extension is not loaded');
  798. }
  799. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not implement ob_gzhandler');
  800. if (ini_get('zlib.output_compression') !== '1') {
  801. ob_start('ob_gzhandler');
  802. }
  803. $_SERVER['HTTP_ACCEPT_ENCODING'] = 'gzip';
  804. $result = $response->outputCompressed();
  805. $this->assertTrue($result);
  806. $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
  807. $result = $response->outputCompressed();
  808. $this->assertFalse($result);
  809. if (ini_get('zlib.output_compression') !== '1') {
  810. ob_get_clean();
  811. }
  812. }
  813. /**
  814. * Tests getting/setting the protocol
  815. *
  816. * @group deprecated
  817. * @return void
  818. */
  819. public function testProtocol()
  820. {
  821. $GLOBALS['mockedHeadersSent'] = false;
  822. $this->deprecated(function () {
  823. $response = $this->getMockBuilder('Cake\Http\Response')
  824. ->setMethods(['_sendHeader', '_sendContent'])
  825. ->getMock();
  826. $response->protocol('HTTP/1.0');
  827. $this->assertEquals('HTTP/1.0', $response->protocol());
  828. $response->expects($this->at(0))
  829. ->method('_sendHeader')->with('HTTP/1.0 200 OK');
  830. $response->send();
  831. });
  832. }
  833. /**
  834. * Tests getting/setting the Content-Length
  835. *
  836. * @group deprecated
  837. * @return void
  838. */
  839. public function testLength()
  840. {
  841. $this->deprecated(function () {
  842. $response = new Response();
  843. $response->length(100);
  844. $this->assertEquals(100, $response->length());
  845. $this->assertEquals('100', $response->getHeaderLine('Content-Length'));
  846. });
  847. }
  848. /**
  849. * Tests settings the content length
  850. *
  851. * @return void
  852. */
  853. public function testWithLength()
  854. {
  855. $response = new Response();
  856. $this->assertFalse($response->hasHeader('Content-Length'));
  857. $new = $response->withLength(100);
  858. $this->assertFalse($response->hasHeader('Content-Length'), 'Old instance not modified');
  859. $this->assertSame('100', $new->getHeaderLine('Content-Length'));
  860. }
  861. /**
  862. * Tests settings the link
  863. *
  864. * @return void
  865. */
  866. public function testWithAddedLink()
  867. {
  868. $response = new Response();
  869. $this->assertFalse($response->hasHeader('Link'));
  870. $new = $response->withAddedLink('http://example.com', ['rel' => 'prev']);
  871. $this->assertFalse($response->hasHeader('Link'), 'Old instance not modified');
  872. $this->assertEquals('<http://example.com>; rel="prev"', $new->getHeaderLine('Link'));
  873. $new = $response->withAddedLink('http://example.com');
  874. $this->assertEquals('<http://example.com>', $new->getHeaderLine('Link'));
  875. $new = $response->withAddedLink('http://example.com?p=1', ['rel' => 'prev'])
  876. ->withAddedLink('http://example.com?p=2', ['rel' => 'next', 'foo' => 'bar']);
  877. $this->assertEquals('<http://example.com?p=1>; rel="prev",<http://example.com?p=2>; rel="next"; foo="bar"', $new->getHeaderLine('Link'));
  878. }
  879. /**
  880. * Tests setting the expiration date
  881. *
  882. * @group deprecated
  883. * @return void
  884. */
  885. public function testExpires()
  886. {
  887. $this->deprecated(function () {
  888. $format = 'D, j M Y H:i:s';
  889. $response = new Response();
  890. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  891. $response->expires($now);
  892. $now->setTimeZone(new \DateTimeZone('UTC'));
  893. $this->assertEquals($now->format($format) . ' GMT', $response->expires());
  894. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  895. $now = time();
  896. $response = new Response();
  897. $response->expires($now);
  898. $this->assertEquals(gmdate($format) . ' GMT', $response->expires());
  899. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Expires'));
  900. $response = new Response();
  901. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  902. $response->expires('+1 day');
  903. $this->assertEquals($time->format($format) . ' GMT', $response->expires());
  904. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Expires'));
  905. });
  906. }
  907. /**
  908. * Tests the withExpires method
  909. *
  910. * @return void
  911. */
  912. public function testWithExpires()
  913. {
  914. $format = 'D, j M Y H:i:s';
  915. $response = new Response();
  916. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  917. $new = $response->withExpires($now);
  918. $this->assertFalse($response->hasHeader('Expires'));
  919. $now->setTimeZone(new \DateTimeZone('UTC'));
  920. $this->assertEquals($now->format($format) . ' GMT', $new->getHeaderLine('Expires'));
  921. $now = time();
  922. $new = $response->withExpires($now);
  923. $this->assertEquals(gmdate($format) . ' GMT', $new->getHeaderLine('Expires'));
  924. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  925. $new = $response->withExpires('+1 day');
  926. $this->assertEquals($time->format($format) . ' GMT', $new->getHeaderLine('Expires'));
  927. }
  928. /**
  929. * Tests setting the modification date
  930. *
  931. * @group deprecated
  932. * @return void
  933. */
  934. public function testModified()
  935. {
  936. $this->deprecated(function () {
  937. $format = 'D, j M Y H:i:s';
  938. $response = new Response();
  939. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  940. $response->modified($now);
  941. $now->setTimeZone(new \DateTimeZone('UTC'));
  942. $this->assertEquals($now->format($format) . ' GMT', $response->modified());
  943. $this->assertEquals($now->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  944. $response = new Response();
  945. $now = time();
  946. $response->modified($now);
  947. $this->assertEquals(gmdate($format) . ' GMT', $response->modified());
  948. $this->assertEquals(gmdate($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  949. $response = new Response();
  950. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  951. $response->modified('+1 day');
  952. $this->assertEquals($time->format($format) . ' GMT', $response->modified());
  953. $this->assertEquals($time->format($format) . ' GMT', $response->getHeaderLine('Last-Modified'));
  954. });
  955. }
  956. /**
  957. * Tests the withModified method
  958. *
  959. * @return void
  960. */
  961. public function testWithModified()
  962. {
  963. $format = 'D, j M Y H:i:s';
  964. $response = new Response();
  965. $now = new \DateTime('now', new \DateTimeZone('America/Los_Angeles'));
  966. $new = $response->withModified($now);
  967. $this->assertFalse($response->hasHeader('Last-Modified'));
  968. $now->setTimeZone(new \DateTimeZone('UTC'));
  969. $this->assertEquals($now->format($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  970. $now = time();
  971. $new = $response->withModified($now);
  972. $this->assertEquals(gmdate($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  973. $time = new \DateTime('+1 day', new \DateTimeZone('UTC'));
  974. $new = $response->withModified('+1 day');
  975. $this->assertEquals($time->format($format) . ' GMT', $new->getHeaderLine('Last-Modified'));
  976. }
  977. /**
  978. * Tests setting of public/private Cache-Control directives
  979. *
  980. * @deprecated
  981. * @return void
  982. */
  983. public function testSharable()
  984. {
  985. $this->deprecated(function () {
  986. $response = new Response();
  987. $this->assertNull($response->sharable());
  988. $response->sharable(true);
  989. $this->assertTrue($response->sharable());
  990. $this->assertEquals('public', $response->getHeaderLine('Cache-Control'));
  991. $response = new Response();
  992. $response->sharable(false);
  993. $this->assertFalse($response->sharable());
  994. $this->assertEquals('private', $response->getHeaderLine('Cache-Control'));
  995. $response = new Response();
  996. $response->sharable(true, 3600);
  997. $this->assertEquals('public, max-age=3600', $response->getHeaderLine('Cache-Control'));
  998. $response = new Response();
  999. $response->sharable(false, 3600);
  1000. $this->assertEquals('private, max-age=3600', $response->getHeaderLine('Cache-Control'));
  1001. });
  1002. }
  1003. /**
  1004. * Tests withSharable()
  1005. *
  1006. * @return void
  1007. */
  1008. public function testWithSharable()
  1009. {
  1010. $response = new Response();
  1011. $new = $response->withSharable(true);
  1012. $this->assertFalse($response->hasHeader('Cache-Control'), 'old instance unchanged');
  1013. $this->assertEquals('public', $new->getHeaderLine('Cache-Control'));
  1014. $new = $response->withSharable(false);
  1015. $this->assertEquals('private', $new->getHeaderLine('Cache-Control'));
  1016. $new = $response->withSharable(true, 3600);
  1017. $this->assertEquals('public, max-age=3600', $new->getHeaderLine('Cache-Control'));
  1018. $new = $response->withSharable(false, 3600);
  1019. $this->assertEquals('private, max-age=3600', $new->getHeaderLine('Cache-Control'));
  1020. }
  1021. /**
  1022. * Tests setting of max-age Cache-Control directive
  1023. *
  1024. * @deprecated
  1025. * @return void
  1026. */
  1027. public function testMaxAge()
  1028. {
  1029. $this->deprecated(function () {
  1030. $response = new Response();
  1031. $this->assertNull($response->maxAge());
  1032. $response->maxAge(3600);
  1033. $this->assertEquals(3600, $response->maxAge());
  1034. $this->assertEquals('max-age=3600', $response->getHeaderLine('Cache-Control'));
  1035. $response = new Response();
  1036. $response->maxAge(3600);
  1037. $response->sharable(false);
  1038. $this->assertEquals('max-age=3600, private', $response->getHeaderLine('Cache-Control'));
  1039. });
  1040. }
  1041. /**
  1042. * Tests withMaxAge()
  1043. *
  1044. * @return void
  1045. */
  1046. public function testWithMaxAge()
  1047. {
  1048. $response = new Response();
  1049. $this->assertFalse($response->hasHeader('Cache-Control'));
  1050. $new = $response->withMaxAge(3600);
  1051. $this->assertEquals('max-age=3600', $new->getHeaderLine('Cache-Control'));
  1052. $new = $response->withMaxAge(3600)
  1053. ->withSharable(false);
  1054. $this->assertEquals('max-age=3600, private', $new->getHeaderLine('Cache-Control'));
  1055. }
  1056. /**
  1057. * Tests setting of s-maxage Cache-Control directive
  1058. *
  1059. * @deprecated
  1060. * @return void
  1061. */
  1062. public function testSharedMaxAge()
  1063. {
  1064. $this->deprecated(function () {
  1065. $response = new Response();
  1066. $this->assertNull($response->maxAge());
  1067. $response->sharedMaxAge(3600);
  1068. $this->assertEquals(3600, $response->sharedMaxAge());
  1069. $this->assertEquals('s-maxage=3600', $response->getHeaderLine('Cache-Control'));
  1070. $response = new Response();
  1071. $response->sharedMaxAge(3600);
  1072. $response->sharable(true);
  1073. $this->assertEquals('s-maxage=3600, public', $response->getHeaderLine('Cache-Control'));
  1074. });
  1075. }
  1076. /**
  1077. * Tests setting of s-maxage Cache-Control directive
  1078. *
  1079. * @return void
  1080. */
  1081. public function testWithSharedMaxAge()
  1082. {
  1083. $response = new Response();
  1084. $new = $response->withSharedMaxAge(3600);
  1085. $this->assertFalse($response->hasHeader('Cache-Control'));
  1086. $this->assertEquals('s-maxage=3600', $new->getHeaderLine('Cache-Control'));
  1087. $new = $response->withSharedMaxAge(3600)->withSharable(true);
  1088. $this->assertEquals('s-maxage=3600, public', $new->getHeaderLine('Cache-Control'));
  1089. }
  1090. /**
  1091. * Tests setting of must-revalidate Cache-Control directive
  1092. *
  1093. * @group deprecated
  1094. * @return void
  1095. */
  1096. public function testMustRevalidate()
  1097. {
  1098. $this->deprecated(function () {
  1099. $response = new Response();
  1100. $this->assertFalse($response->mustRevalidate());
  1101. $response->mustRevalidate(true);
  1102. $this->assertTrue($response->mustRevalidate());
  1103. $this->assertEquals('must-revalidate', $response->getHeaderLine('Cache-Control'));
  1104. $response->mustRevalidate(false);
  1105. $this->assertFalse($response->mustRevalidate());
  1106. $response = new Response();
  1107. $response->sharedMaxAge(3600);
  1108. $response->mustRevalidate(true);
  1109. $this->assertEquals('s-maxage=3600, must-revalidate', $response->getHeaderLine('Cache-Control'));
  1110. });
  1111. }
  1112. /**
  1113. * Tests setting of must-revalidate Cache-Control directive
  1114. *
  1115. * @return void
  1116. */
  1117. public function testWithMustRevalidate()
  1118. {
  1119. $response = new Response();
  1120. $this->assertFalse($response->hasHeader('Cache-Control'));
  1121. $new = $response->withMustRevalidate(true);
  1122. $this->assertFalse($response->hasHeader('Cache-Control'));
  1123. $this->assertEquals('must-revalidate', $new->getHeaderLine('Cache-Control'));
  1124. $new = $new->withMustRevalidate(false);
  1125. $this->assertEmpty($new->getHeaderLine('Cache-Control'));
  1126. }
  1127. /**
  1128. * Tests getting/setting the Vary header
  1129. *
  1130. * @group deprecated
  1131. * @return void
  1132. */
  1133. public function testVary()
  1134. {
  1135. $this->deprecated(function () {
  1136. $response = new Response();
  1137. $response->vary('Accept-encoding');
  1138. $this->assertEquals('Accept-encoding', $response->getHeaderLine('vary'));
  1139. $response = new Response();
  1140. $response->vary(['Accept-language', 'Accept-encoding']);
  1141. $this->assertEquals(['Accept-language', 'Accept-encoding'], $response->vary());
  1142. $this->assertEquals('Accept-language, Accept-encoding', $response->getHeaderLine('vary'));
  1143. });
  1144. }
  1145. /**
  1146. * Tests withVary()
  1147. *
  1148. * @return void
  1149. */
  1150. public function testWithVary()
  1151. {
  1152. $response = new Response();
  1153. $new = $response->withVary('Accept-encoding');
  1154. $this->assertFalse($response->hasHeader('Vary'));
  1155. $this->assertEquals('Accept-encoding', $new->getHeaderLine('Vary'));
  1156. $new = $response->withVary(['Accept-encoding', 'Accept-language']);
  1157. $this->assertFalse($response->hasHeader('Vary'));
  1158. $this->assertEquals('Accept-encoding,Accept-language', $new->getHeaderLine('Vary'));
  1159. }
  1160. /**
  1161. * Tests getting/setting the Etag header
  1162. *
  1163. * @group deprecated
  1164. * @return void
  1165. */
  1166. public function testEtag()
  1167. {
  1168. $this->deprecated(function () {
  1169. $response = new Response();
  1170. $response->etag('something');
  1171. $this->assertEquals('"something"', $response->etag());
  1172. $this->assertEquals('"something"', $response->getHeaderLine('Etag'));
  1173. $response = new Response();
  1174. $response->etag('something', true);
  1175. $this->assertEquals('W/"something"', $response->etag());
  1176. $this->assertEquals('W/"something"', $response->getHeaderLine('Etag'));
  1177. });
  1178. }
  1179. /**
  1180. * Tests withEtag()
  1181. *
  1182. * @return void
  1183. */
  1184. public function testWithEtag()
  1185. {
  1186. $response = new Response();
  1187. $new = $response->withEtag('something');
  1188. $this->assertFalse($response->hasHeader('Etag'));
  1189. $this->assertEquals('"something"', $new->getHeaderLine('Etag'));
  1190. $new = $response->withEtag('something', true);
  1191. $this->assertEquals('W/"something"', $new->getHeaderLine('Etag'));
  1192. }
  1193. /**
  1194. * Tests that the response is able to be marked as not modified
  1195. *
  1196. * @return void
  1197. */
  1198. public function testNotModified()
  1199. {
  1200. $response = new Response();
  1201. $response = $response->withStringBody('something')
  1202. ->withStatus(200)
  1203. ->withLength(100)
  1204. ->withModified('now');
  1205. $response->notModified();
  1206. $this->assertFalse($response->hasHeader('Content-Length'));
  1207. $this->assertFalse($response->hasHeader('Modified'));
  1208. $this->assertEmpty((string)$response->getBody());
  1209. $this->assertEquals(304, $response->getStatusCode());
  1210. }
  1211. /**
  1212. * Tests withNotModified()
  1213. *
  1214. * @return void
  1215. */
  1216. public function testWithNotModified()
  1217. {
  1218. $response = new Response(['body' => 'something']);
  1219. $response = $response->withLength(100)
  1220. ->withStatus(200)
  1221. ->withHeader('Last-Modified', 'value')
  1222. ->withHeader('Content-Language', 'en-EN')
  1223. ->withHeader('X-things', 'things')
  1224. ->withType('application/json');
  1225. $new = $response->withNotModified();
  1226. $this->assertTrue($response->hasHeader('Content-Language'), 'old instance not changed');
  1227. $this->assertTrue($response->hasHeader('Content-Length'), 'old instance not changed');
  1228. $this->assertFalse($new->hasHeader('Content-Type'));
  1229. $this->assertFalse($new->hasHeader('Content-Length'));
  1230. $this->assertFalse($new->hasHeader('Content-Language'));
  1231. $this->assertFalse($new->hasHeader('Last-Modified'));
  1232. $this->assertSame('things', $new->getHeaderLine('X-things'), 'Other headers are retained');
  1233. $this->assertSame(304, $new->getStatusCode());
  1234. $this->assertSame('', $new->getBody()->getContents());
  1235. }
  1236. /**
  1237. * Test checkNotModified method
  1238. *
  1239. * @return void
  1240. */
  1241. public function testCheckNotModifiedByEtagStar()
  1242. {
  1243. $request = new ServerRequest();
  1244. $request = $request->withHeader('If-None-Match', '*');
  1245. $response = new Response();
  1246. $response = $response->withEtag('something')
  1247. ->withHeader('Content-Length', 99);
  1248. $this->assertTrue($response->checkNotModified($request));
  1249. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  1250. }
  1251. /**
  1252. * Test checkNotModified method
  1253. *
  1254. * @return void
  1255. */
  1256. public function testCheckNotModifiedByEtagExact()
  1257. {
  1258. $request = new ServerRequest();
  1259. $request = $request->withHeader('If-None-Match', 'W/"something", "other"');
  1260. $response = new Response();
  1261. $response = $response->withEtag('something', true)
  1262. ->withHeader('Content-Length', 99);
  1263. $this->assertTrue($response->checkNotModified($request));
  1264. $this->assertFalse($response->hasHeader('Content-Type'), 'etags match, should be unmodified');
  1265. }
  1266. /**
  1267. * Test checkNotModified method
  1268. *
  1269. * @return void
  1270. */
  1271. public function testCheckNotModifiedByEtagAndTime()
  1272. {
  1273. $request = new ServerRequest();
  1274. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  1275. ->withHeader('If-None-Match', 'W/"something", "other"');
  1276. $response = new Response();
  1277. $response = $response->withModified('2012-01-01 00:00:00')
  1278. ->withEtag('something', true)
  1279. ->withHeader('Content-Length', 99);
  1280. $this->assertTrue($response->checkNotModified($request));
  1281. $this->assertFalse($response->hasHeader('Content-Length'), 'etags match, should be unmodified');
  1282. }
  1283. /**
  1284. * Test checkNotModified method
  1285. *
  1286. * @return void
  1287. */
  1288. public function testCheckNotModifiedByEtagAndTimeMismatch()
  1289. {
  1290. $request = new ServerRequest();
  1291. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  1292. ->withHeader('If-None-Match', 'W/"something", "other"');
  1293. $response = new Response();
  1294. $response = $response->withModified('2012-01-01 00:00:01')
  1295. ->withEtag('something', true)
  1296. ->withHeader('Content-Length', 99);
  1297. $this->assertFalse($response->checkNotModified($request));
  1298. $this->assertTrue($response->hasHeader('Content-Length'), 'timestamp in response is newer');
  1299. }
  1300. /**
  1301. * Test checkNotModified method
  1302. *
  1303. * @return void
  1304. */
  1305. public function testCheckNotModifiedByEtagMismatch()
  1306. {
  1307. $request = new ServerRequest();
  1308. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00')
  1309. ->withHeader('If-None-Match', 'W/"something-else", "other"');
  1310. $response = new Response();
  1311. $response = $response->withModified('2012-01-01 00:00:00')
  1312. ->withEtag('something', true)
  1313. ->withHeader('Content-Length', 99);
  1314. $this->assertFalse($response->checkNotModified($request));
  1315. $this->assertTrue($response->hasHeader('Content-Length'), 'etags do not match');
  1316. }
  1317. /**
  1318. * Test checkNotModified method
  1319. *
  1320. * @return void
  1321. */
  1322. public function testCheckNotModifiedByTime()
  1323. {
  1324. $request = new ServerRequest();
  1325. $request = $request->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1326. $response = new Response();
  1327. $response = $response->withModified('2012-01-01 00:00:00')
  1328. ->withHeader('Content-Length', 99);
  1329. $this->assertTrue($response->checkNotModified($request));
  1330. $this->assertFalse($response->hasHeader('Content-Length'), 'modified time matches');
  1331. }
  1332. /**
  1333. * Test checkNotModified method
  1334. *
  1335. * @return void
  1336. */
  1337. public function testCheckNotModifiedNoHints()
  1338. {
  1339. $request = new ServerRequest();
  1340. $request = $request->withHeader('If-None-Match', 'W/"something", "other"')
  1341. ->withHeader('If-Modified-Since', '2012-01-01 00:00:00');
  1342. $response = $this->getMockBuilder('Cake\Http\Response')
  1343. ->setMethods(['notModified'])
  1344. ->getMock();
  1345. $response->expects($this->never())->method('notModified');
  1346. $this->assertFalse($response->checkNotModified($request));
  1347. }
  1348. /**
  1349. * Test cookie setting
  1350. *
  1351. * @group deprecated
  1352. * @return void
  1353. */
  1354. public function testCookieSettings()
  1355. {
  1356. $this->deprecated(function () {
  1357. $response = new Response();
  1358. $cookie = [
  1359. 'name' => 'CakeTestCookie[Testing]'
  1360. ];
  1361. $response->cookie($cookie);
  1362. $expected = [
  1363. 'name' => 'CakeTestCookie[Testing]',
  1364. 'value' => '',
  1365. 'expire' => 0,
  1366. 'path' => '/',
  1367. 'domain' => '',
  1368. 'secure' => false,
  1369. 'httpOnly' => false
  1370. ];
  1371. $result = $response->cookie('CakeTestCookie[Testing]');
  1372. $this->assertEquals($expected, $result);
  1373. $cookie = [
  1374. 'name' => 'CakeTestCookie[Testing2]',
  1375. 'value' => '[a,b,c]',
  1376. 'expire' => 1000,
  1377. 'path' => '/test',
  1378. 'secure' => true
  1379. ];
  1380. $response->cookie($cookie);
  1381. $expected = [
  1382. 'CakeTestCookie[Testing]' => [
  1383. 'name' => 'CakeTestCookie[Testing]',
  1384. 'value' => '',
  1385. 'expire' => 0,
  1386. 'path' => '/',
  1387. 'domain' => '',
  1388. 'secure' => false,
  1389. 'httpOnly' => false
  1390. ],
  1391. 'CakeTestCookie[Testing2]' => [
  1392. 'name' => 'CakeTestCookie[Testing2]',
  1393. 'value' => '[a,b,c]',
  1394. 'expire' => 1000,
  1395. 'path' => '/test',
  1396. 'domain' => '',
  1397. 'secure' => true,
  1398. 'httpOnly' => false
  1399. ]
  1400. ];
  1401. $result = $response->cookie();
  1402. $this->assertEquals($expected, $result);
  1403. $cookie = $expected['CakeTestCookie[Testing]'];
  1404. $cookie['value'] = 'test';
  1405. $response->cookie($cookie);
  1406. $expected = [
  1407. 'CakeTestCookie[Testing]' => [
  1408. 'name' => 'CakeTestCookie[Testing]',
  1409. 'value' => 'test',
  1410. 'expire' => 0,
  1411. 'path' => '/',
  1412. 'domain' => '',
  1413. 'secure' => false,
  1414. 'httpOnly' => false
  1415. ],
  1416. 'CakeTestCookie[Testing2]' => [
  1417. 'name' => 'CakeTestCookie[Testing2]',
  1418. 'value' => '[a,b,c]',
  1419. 'expire' => 1000,
  1420. 'path' => '/test',
  1421. 'domain' => '',
  1422. 'secure' => true,
  1423. 'httpOnly' => false
  1424. ]
  1425. ];
  1426. $result = $response->cookie();
  1427. $this->assertEquals($expected, $result);
  1428. });
  1429. }
  1430. /**
  1431. * Test setting cookies with no value
  1432. *
  1433. * @return void
  1434. */
  1435. public function testWithCookieEmpty()
  1436. {
  1437. $response = new Response();
  1438. $new = $response->withCookie('testing');
  1439. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  1440. $expected = [
  1441. 'name' => 'testing',
  1442. 'value' => '',
  1443. 'expire' => 0,
  1444. 'path' => '/',
  1445. 'domain' => '',
  1446. 'secure' => false,
  1447. 'httpOnly' => false];
  1448. $result = $new->getCookie('testing');
  1449. $this->assertEquals($expected, $result);
  1450. }
  1451. /**
  1452. * Test setting cookies with scalar values
  1453. *
  1454. * @return void
  1455. */
  1456. public function testWithCookieScalar()
  1457. {
  1458. $response = new Response();
  1459. $new = $response->withCookie('testing', 'abc123');
  1460. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  1461. $this->assertEquals('abc123', $new->getCookie('testing')['value']);
  1462. $new = $response->withCookie('testing', 99);
  1463. $this->assertEquals(99, $new->getCookie('testing')['value']);
  1464. $new = $response->withCookie('testing', false);
  1465. $this->assertFalse($new->getCookie('testing')['value']);
  1466. $new = $response->withCookie('testing', true);
  1467. $this->assertTrue($new->getCookie('testing')['value']);
  1468. }
  1469. /**
  1470. * Test withCookie() and array data.
  1471. *
  1472. * @return void
  1473. */
  1474. public function testWithCookieArray()
  1475. {
  1476. $response = new Response();
  1477. $cookie = [
  1478. 'name' => 'ignored key',
  1479. 'value' => '[a,b,c]',
  1480. 'expire' => 1000,
  1481. 'path' => '/test',
  1482. 'secure' => true
  1483. ];
  1484. $new = $response->withCookie('testing', $cookie);
  1485. $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
  1486. $expected = [
  1487. 'name' => 'testing',
  1488. 'value' => '[a,b,c]',
  1489. 'expire' => 1000,
  1490. 'path' => '/test',
  1491. 'domain' => '',
  1492. 'secure' => true,
  1493. 'httpOnly' => false
  1494. ];
  1495. $this->assertEquals($expected, $new->getCookie('testing'));
  1496. }
  1497. /**
  1498. * Test withCookie() and a cookie instance
  1499. *
  1500. * @return void
  1501. */
  1502. public function testWithCookieObject()
  1503. {
  1504. $response = new Response();
  1505. $cookie = new Cookie('yay', 'a value');
  1506. $new = $response->withCookie($cookie);
  1507. $this->assertNull($response->getCookie('yay'), 'withCookie does not mutate');
  1508. $this->assertNotEmpty($new->getCookie('yay'));
  1509. $this->assertSame($cookie, $new->getCookieCollection()->get('yay'));
  1510. }
  1511. public function testWithExpiredCookieScalar()
  1512. {
  1513. $response = new Response();
  1514. $response = $response->withCookie('testing', 'abc123');
  1515. $this->assertEquals('abc123', $response->getCookie('testing')['value']);
  1516. $new = $response->withExpiredCookie('testing');
  1517. $this->assertNull($response->getCookie('testing')['expire']);
  1518. $this->assertEquals('1', $new->getCookie('testing')['expire']);
  1519. }
  1520. public function testWithExpiredCookieOptions()
  1521. {
  1522. $options = [
  1523. 'name' => 'testing',
  1524. 'value' => 'abc123',
  1525. 'domain' => 'cakephp.org',
  1526. 'path' => '/custompath/',
  1527. 'secure' => true,
  1528. 'httpOnly' => true,
  1529. 'expire' => (string)strtotime('+14 days'),
  1530. ];
  1531. $response = new Response();
  1532. $response = $response->withCookie('testing', $options);
  1533. $this->assertEquals($options, $response->getCookie('testing'));
  1534. $new = $response->withExpiredCookie('testing', $options);
  1535. $this->assertEquals($options['expire'], $response->getCookie('testing')['expire']);
  1536. $this->assertEquals('1', $new->getCookie('testing')['expire']);
  1537. $this->assertEquals('', $new->getCookie('testing')['value']);
  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('testing', 'a')
  1558. ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => 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('testing', 'a')
  1615. ->withCookie('test2', ['value' => 'b', 'path' => '/test', 'secure' => 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. }