ClientTest.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @since 3.0.0
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Test\TestCase\Http;
  15. use Cake\Core\Configure;
  16. use Cake\Http\Client;
  17. use Cake\Http\Client\Request;
  18. use Cake\Http\Client\Response;
  19. use Cake\Http\Cookie\CookieCollection;
  20. use Cake\TestSuite\TestCase;
  21. /**
  22. * HTTP client test.
  23. */
  24. class ClientTest extends TestCase
  25. {
  26. /**
  27. * Test storing config options and modifying them.
  28. *
  29. * @return void
  30. */
  31. public function testConstructConfig()
  32. {
  33. $config = [
  34. 'scheme' => 'http',
  35. 'host' => 'example.org',
  36. ];
  37. $http = new Client($config);
  38. $result = $http->config();
  39. foreach ($config as $key => $val) {
  40. $this->assertEquals($val, $result[$key]);
  41. }
  42. $result = $http->config([
  43. 'auth' => ['username' => 'mark', 'password' => 'secret']
  44. ]);
  45. $this->assertSame($result, $http);
  46. $result = $http->config();
  47. $expected = [
  48. 'scheme' => 'http',
  49. 'host' => 'example.org',
  50. 'auth' => ['username' => 'mark', 'password' => 'secret']
  51. ];
  52. foreach ($expected as $key => $val) {
  53. $this->assertEquals($val, $result[$key]);
  54. }
  55. }
  56. /**
  57. * Data provider for buildUrl() tests
  58. *
  59. * @return array
  60. */
  61. public static function urlProvider()
  62. {
  63. return [
  64. [
  65. 'http://example.com/test.html',
  66. 'http://example.com/test.html',
  67. [],
  68. null,
  69. 'Null options'
  70. ],
  71. [
  72. 'http://example.com/test.html',
  73. 'http://example.com/test.html',
  74. [],
  75. [],
  76. 'Simple string'
  77. ],
  78. [
  79. 'http://example.com/test.html',
  80. '/test.html',
  81. [],
  82. ['host' => 'example.com'],
  83. 'host name option',
  84. ],
  85. [
  86. 'https://example.com/test.html',
  87. '/test.html',
  88. [],
  89. ['host' => 'example.com', 'scheme' => 'https'],
  90. 'HTTPS',
  91. ],
  92. [
  93. 'http://example.com:8080/test.html',
  94. '/test.html',
  95. [],
  96. ['host' => 'example.com', 'port' => '8080'],
  97. 'Non standard port',
  98. ],
  99. [
  100. 'http://example.com/test.html',
  101. '/test.html',
  102. [],
  103. ['host' => 'example.com', 'port' => '80'],
  104. 'standard port, does not display'
  105. ],
  106. [
  107. 'https://example.com/test.html',
  108. '/test.html',
  109. [],
  110. ['host' => 'example.com', 'scheme' => 'https', 'port' => '443'],
  111. 'standard port, does not display'
  112. ],
  113. [
  114. 'http://example.com/test.html',
  115. 'http://example.com/test.html',
  116. [],
  117. ['host' => 'example.com', 'scheme' => 'https'],
  118. 'options do not duplicate'
  119. ],
  120. [
  121. 'http://example.com/search?q=hi+there&cat%5Bid%5D%5B0%5D=2&cat%5Bid%5D%5B1%5D=3',
  122. 'http://example.com/search',
  123. ['q' => 'hi there', 'cat' => ['id' => [2, 3]]],
  124. [],
  125. 'query string data.'
  126. ],
  127. [
  128. 'http://example.com/search?q=hi+there&id=12',
  129. 'http://example.com/search?q=hi+there',
  130. ['id' => '12'],
  131. [],
  132. 'query string data with some already on the url.'
  133. ],
  134. ];
  135. }
  136. /**
  137. * @dataProvider urlProvider
  138. */
  139. public function testBuildUrl($expected, $url, $query, $opts)
  140. {
  141. $http = new Client();
  142. $result = $http->buildUrl($url, $query, $opts);
  143. $this->assertEquals($expected, $result);
  144. }
  145. /**
  146. * test simple get request with headers & cookies.
  147. *
  148. * @return void
  149. */
  150. public function testGetSimpleWithHeadersAndCookies()
  151. {
  152. $response = new Response();
  153. $headers = [
  154. 'User-Agent' => 'Cake',
  155. 'Connection' => 'close',
  156. 'Content-Type' => 'application/x-www-form-urlencoded',
  157. ];
  158. $cookies = [
  159. 'split' => 'value'
  160. ];
  161. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  162. ->setMethods(['send'])
  163. ->getMock();
  164. $mock->expects($this->once())
  165. ->method('send')
  166. ->with($this->callback(function ($request) use ($cookies, $headers) {
  167. $this->assertInstanceOf('Cake\Http\Client\Request', $request);
  168. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  169. $this->assertEquals('http://cakephp.org/test.html', $request->getUri() . '');
  170. $this->assertEquals('split=value', $request->getHeaderLine('Cookie'));
  171. $this->assertEquals($headers['Content-Type'], $request->getHeaderLine('content-type'));
  172. $this->assertEquals($headers['Connection'], $request->getHeaderLine('connection'));
  173. return true;
  174. }))
  175. ->will($this->returnValue([$response]));
  176. $http = new Client(['adapter' => $mock]);
  177. $result = $http->get('http://cakephp.org/test.html', [], [
  178. 'headers' => $headers,
  179. 'cookies' => $cookies,
  180. ]);
  181. $this->assertSame($result, $response);
  182. }
  183. /**
  184. * test get request with no data
  185. *
  186. * @return void
  187. */
  188. public function testGetNoData()
  189. {
  190. $response = new Response();
  191. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  192. ->setMethods(['send'])
  193. ->getMock();
  194. $mock->expects($this->once())
  195. ->method('send')
  196. ->with($this->callback(function ($request) {
  197. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  198. $this->assertEmpty($request->getHeaderLine('Content-Type'), 'Should have no content-type set');
  199. $this->assertEquals(
  200. 'http://cakephp.org/search',
  201. $request->getUri() . ''
  202. );
  203. return true;
  204. }))
  205. ->will($this->returnValue([$response]));
  206. $http = new Client([
  207. 'host' => 'cakephp.org',
  208. 'adapter' => $mock
  209. ]);
  210. $result = $http->get('/search');
  211. $this->assertSame($result, $response);
  212. }
  213. /**
  214. * test get request with querystring data
  215. *
  216. * @return void
  217. */
  218. public function testGetQuerystring()
  219. {
  220. $response = new Response();
  221. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  222. ->setMethods(['send'])
  223. ->getMock();
  224. $mock->expects($this->once())
  225. ->method('send')
  226. ->with($this->callback(function ($request) {
  227. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  228. $this->assertEquals(
  229. 'http://cakephp.org/search?q=hi+there&Category%5Bid%5D%5B0%5D=2&Category%5Bid%5D%5B1%5D=3',
  230. $request->getUri() . ''
  231. );
  232. return true;
  233. }))
  234. ->will($this->returnValue([$response]));
  235. $http = new Client([
  236. 'host' => 'cakephp.org',
  237. 'adapter' => $mock
  238. ]);
  239. $result = $http->get('/search', [
  240. 'q' => 'hi there',
  241. 'Category' => ['id' => [2, 3]]
  242. ]);
  243. $this->assertSame($result, $response);
  244. }
  245. /**
  246. * test get request with string of query data.
  247. *
  248. * @return void
  249. */
  250. public function testGetQuerystringString()
  251. {
  252. $response = new Response();
  253. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  254. ->setMethods(['send'])
  255. ->getMock();
  256. $mock->expects($this->once())
  257. ->method('send')
  258. ->with($this->callback(function ($request) {
  259. $this->assertEquals(
  260. 'http://cakephp.org/search?q=hi+there&Category%5Bid%5D%5B0%5D=2&Category%5Bid%5D%5B1%5D=3',
  261. $request->getUri() . ''
  262. );
  263. return true;
  264. }))
  265. ->will($this->returnValue([$response]));
  266. $http = new Client([
  267. 'host' => 'cakephp.org',
  268. 'adapter' => $mock
  269. ]);
  270. $data = [
  271. 'q' => 'hi there',
  272. 'Category' => ['id' => [2, 3]]
  273. ];
  274. $result = $http->get('/search', http_build_query($data));
  275. $this->assertSame($response, $result);
  276. }
  277. /**
  278. * Test a GET with a request body. Services like
  279. * elasticsearch use this feature.
  280. *
  281. * @return void
  282. */
  283. public function testGetWithContent()
  284. {
  285. $response = new Response();
  286. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  287. ->setMethods(['send'])
  288. ->getMock();
  289. $mock->expects($this->once())
  290. ->method('send')
  291. ->with($this->callback(function ($request) {
  292. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  293. $this->assertEquals('http://cakephp.org/search', '' . $request->getUri());
  294. $this->assertEquals('some data', '' . $request->getBody());
  295. return true;
  296. }))
  297. ->will($this->returnValue([$response]));
  298. $http = new Client([
  299. 'host' => 'cakephp.org',
  300. 'adapter' => $mock
  301. ]);
  302. $result = $http->get('/search', [
  303. '_content' => 'some data'
  304. ]);
  305. $this->assertSame($result, $response);
  306. }
  307. /**
  308. * Test invalid authentication types throw exceptions.
  309. *
  310. * @expectedException \Cake\Core\Exception\Exception
  311. * @return void
  312. */
  313. public function testInvalidAuthenticationType()
  314. {
  315. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  316. ->setMethods(['send'])
  317. ->getMock();
  318. $mock->expects($this->never())
  319. ->method('send');
  320. $http = new Client([
  321. 'host' => 'cakephp.org',
  322. 'adapter' => $mock
  323. ]);
  324. $result = $http->get('/', [], [
  325. 'auth' => ['type' => 'horribly broken']
  326. ]);
  327. }
  328. /**
  329. * Test setting basic authentication with get
  330. *
  331. * @return void
  332. */
  333. public function testGetWithAuthenticationAndProxy()
  334. {
  335. $response = new Response();
  336. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  337. ->setMethods(['send'])
  338. ->getMock();
  339. $headers = [
  340. 'Authorization' => 'Basic ' . base64_encode('mark:secret'),
  341. 'Proxy-Authorization' => 'Basic ' . base64_encode('mark:pass'),
  342. ];
  343. $mock->expects($this->once())
  344. ->method('send')
  345. ->with($this->callback(function ($request) use ($headers) {
  346. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  347. $this->assertEquals('http://cakephp.org/', '' . $request->getUri());
  348. $this->assertEquals($headers['Authorization'], $request->getHeaderLine('Authorization'));
  349. $this->assertEquals($headers['Proxy-Authorization'], $request->getHeaderLine('Proxy-Authorization'));
  350. return true;
  351. }))
  352. ->will($this->returnValue([$response]));
  353. $http = new Client([
  354. 'host' => 'cakephp.org',
  355. 'adapter' => $mock
  356. ]);
  357. $result = $http->get('/', [], [
  358. 'auth' => ['username' => 'mark', 'password' => 'secret'],
  359. 'proxy' => ['username' => 'mark', 'password' => 'pass'],
  360. ]);
  361. $this->assertSame($result, $response);
  362. }
  363. /**
  364. * Test authentication adapter that mutates request.
  365. *
  366. * @return void
  367. */
  368. public function testAuthenticationWithMutation()
  369. {
  370. Configure::write('App.namespace', 'TestApp');
  371. $response = new Response();
  372. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  373. ->setMethods(['send'])
  374. ->getMock();
  375. $headers = [
  376. 'Authorization' => 'Bearer abc123',
  377. 'Proxy-Authorization' => 'Bearer abc123',
  378. ];
  379. $mock->expects($this->once())
  380. ->method('send')
  381. ->with($this->callback(function ($request) use ($headers) {
  382. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  383. $this->assertEquals('http://cakephp.org/', '' . $request->getUri());
  384. $this->assertEquals($headers['Authorization'], $request->getHeaderLine('Authorization'));
  385. $this->assertEquals($headers['Proxy-Authorization'], $request->getHeaderLine('Proxy-Authorization'));
  386. return true;
  387. }))
  388. ->will($this->returnValue([$response]));
  389. $http = new Client([
  390. 'host' => 'cakephp.org',
  391. 'adapter' => $mock
  392. ]);
  393. $result = $http->get('/', [], [
  394. 'auth' => ['type' => 'TestApp\Http\CompatAuth'],
  395. 'proxy' => ['type' => 'TestApp\Http\CompatAuth'],
  396. ]);
  397. $this->assertSame($result, $response);
  398. }
  399. /**
  400. * Return a list of HTTP methods.
  401. *
  402. * @return array
  403. */
  404. public static function methodProvider()
  405. {
  406. return [
  407. [Request::METHOD_GET],
  408. [Request::METHOD_POST],
  409. [Request::METHOD_PUT],
  410. [Request::METHOD_DELETE],
  411. [Request::METHOD_PATCH],
  412. [Request::METHOD_OPTIONS],
  413. [Request::METHOD_TRACE],
  414. ];
  415. }
  416. /**
  417. * test simple POST request.
  418. *
  419. * @dataProvider methodProvider
  420. * @return void
  421. */
  422. public function testMethodsSimple($method)
  423. {
  424. $response = new Response();
  425. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  426. ->setMethods(['send'])
  427. ->getMock();
  428. $mock->expects($this->once())
  429. ->method('send')
  430. ->with($this->callback(function ($request) use ($method) {
  431. $this->assertInstanceOf('Cake\Http\Client\Request', $request);
  432. $this->assertEquals($method, $request->getMethod());
  433. $this->assertEquals('http://cakephp.org/projects/add', '' . $request->getUri());
  434. return true;
  435. }))
  436. ->will($this->returnValue([$response]));
  437. $http = new Client([
  438. 'host' => 'cakephp.org',
  439. 'adapter' => $mock
  440. ]);
  441. $result = $http->{$method}('/projects/add');
  442. $this->assertSame($result, $response);
  443. }
  444. /**
  445. * Provider for testing the type option.
  446. *
  447. * @return array
  448. */
  449. public static function typeProvider()
  450. {
  451. return [
  452. ['application/json', 'application/json'],
  453. ['json', 'application/json'],
  454. ['xml', 'application/xml'],
  455. ['application/xml', 'application/xml'],
  456. ];
  457. }
  458. /**
  459. * Test that using the 'type' option sets the correct headers
  460. *
  461. * @dataProvider typeProvider
  462. * @return void
  463. */
  464. public function testPostWithTypeKey($type, $mime)
  465. {
  466. $response = new Response();
  467. $data = 'some data';
  468. $headers = [
  469. 'Content-Type' => $mime,
  470. 'Accept' => $mime,
  471. ];
  472. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  473. ->setMethods(['send'])
  474. ->getMock();
  475. $mock->expects($this->once())
  476. ->method('send')
  477. ->with($this->callback(function ($request) use ($headers) {
  478. $this->assertEquals(Request::METHOD_POST, $request->getMethod());
  479. $this->assertEquals($headers['Content-Type'], $request->getHeaderLine('Content-Type'));
  480. $this->assertEquals($headers['Accept'], $request->getHeaderLine('Accept'));
  481. return true;
  482. }))
  483. ->will($this->returnValue([$response]));
  484. $http = new Client([
  485. 'host' => 'cakephp.org',
  486. 'adapter' => $mock
  487. ]);
  488. $http->post('/projects/add', $data, ['type' => $type]);
  489. }
  490. /**
  491. * Test that string payloads with no content type have a default content-type set.
  492. *
  493. * @return void
  494. */
  495. public function testPostWithStringDataDefaultsToFormEncoding()
  496. {
  497. $response = new Response();
  498. $data = 'some=value&more=data';
  499. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  500. ->setMethods(['send'])
  501. ->getMock();
  502. $mock->expects($this->any())
  503. ->method('send')
  504. ->with($this->callback(function ($request) use ($data) {
  505. $this->assertEquals($data, '' . $request->getBody());
  506. $this->assertEquals('application/x-www-form-urlencoded', $request->getHeaderLine('content-type'));
  507. return true;
  508. }))
  509. ->will($this->returnValue([$response]));
  510. $http = new Client([
  511. 'host' => 'cakephp.org',
  512. 'adapter' => $mock
  513. ]);
  514. $http->post('/projects/add', $data);
  515. $http->put('/projects/add', $data);
  516. $http->delete('/projects/add', $data);
  517. }
  518. /**
  519. * Test that exceptions are raised on invalid types.
  520. *
  521. * @expectedException \Cake\Core\Exception\Exception
  522. * @return void
  523. */
  524. public function testExceptionOnUnknownType()
  525. {
  526. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  527. ->setMethods(['send'])
  528. ->getMock();
  529. $mock->expects($this->never())
  530. ->method('send');
  531. $http = new Client([
  532. 'host' => 'cakephp.org',
  533. 'adapter' => $mock
  534. ]);
  535. $http->post('/projects/add', 'it works', ['type' => 'invalid']);
  536. }
  537. /**
  538. * Test that Client stores cookies
  539. *
  540. * @return void
  541. */
  542. public function testCookieStorage()
  543. {
  544. $adapter = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  545. ->setMethods(['send'])
  546. ->getMock();
  547. $headers = [
  548. 'HTTP/1.0 200 Ok',
  549. 'Set-Cookie: first=1',
  550. 'Set-Cookie: expiring=now; Expires=Wed, 09-Jun-1999 10:18:14 GMT'
  551. ];
  552. $response = new Response($headers, '');
  553. $adapter->expects($this->at(0))
  554. ->method('send')
  555. ->will($this->returnValue([$response]));
  556. $http = new Client([
  557. 'host' => 'cakephp.org',
  558. 'adapter' => $adapter,
  559. ]);
  560. $http->get('/projects');
  561. $cookies = $http->cookies();
  562. $this->assertCount(1, $cookies);
  563. $this->assertTrue($cookies->has('first'));
  564. $this->assertFalse($cookies->has('expiring'));
  565. }
  566. /**
  567. * Test cookie collection getter and setter,
  568. *
  569. * @return void
  570. */
  571. public function testCookies()
  572. {
  573. $jar = new CookieCollection();
  574. $http = new Client([
  575. 'cookieJar' => $jar
  576. ]);
  577. $this->assertSame($jar, $http->getCookies());
  578. $cookies = new CookieCollection();
  579. $http->setCookies($cookies);
  580. $this->assertSame($cookies, $http->getCookies());
  581. }
  582. /**
  583. * test head request with querystring data
  584. *
  585. * @return void
  586. */
  587. public function testHeadQuerystring()
  588. {
  589. $response = new Response();
  590. $mock = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  591. ->setMethods(['send'])
  592. ->getMock();
  593. $mock->expects($this->once())
  594. ->method('send')
  595. ->with($this->callback(function ($request) {
  596. $this->assertInstanceOf('Cake\Http\Client\Request', $request);
  597. $this->assertEquals(Request::METHOD_HEAD, $request->getMethod());
  598. $this->assertEquals('http://cakephp.org/search?q=hi+there', '' . $request->getUri());
  599. return true;
  600. }))
  601. ->will($this->returnValue([$response]));
  602. $http = new Client([
  603. 'host' => 'cakephp.org',
  604. 'adapter' => $mock
  605. ]);
  606. $result = $http->head('/search', [
  607. 'q' => 'hi there',
  608. ]);
  609. $this->assertSame($result, $response);
  610. }
  611. }