ClientTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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\Network\Http;
  15. use Cake\Core\Configure;
  16. use Cake\Network\Http\Client;
  17. use Cake\Network\Http\Request;
  18. use Cake\Network\Http\Response;
  19. use Cake\TestSuite\TestCase;
  20. use Zend\Diactoros\Uri;
  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\Network\Http\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\Network\Http\Request', $request);
  168. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  169. $this->assertEquals('http://cakephp.org/test.html', $request->getUri() . '');
  170. $this->assertEquals($cookies, $request->cookies());
  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 querystring data
  185. *
  186. * @return void
  187. */
  188. public function testGetQuerystring()
  189. {
  190. $response = new Response();
  191. $mock = $this->getMockBuilder('Cake\Network\Http\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->assertEquals(
  199. 'http://cakephp.org/search?q=hi+there&Category%5Bid%5D%5B0%5D=2&Category%5Bid%5D%5B1%5D=3',
  200. $request->getUri() . ''
  201. );
  202. return true;
  203. }))
  204. ->will($this->returnValue([$response]));
  205. $http = new Client([
  206. 'host' => 'cakephp.org',
  207. 'adapter' => $mock
  208. ]);
  209. $result = $http->get('/search', [
  210. 'q' => 'hi there',
  211. 'Category' => ['id' => [2, 3]]
  212. ]);
  213. $this->assertSame($result, $response);
  214. }
  215. /**
  216. * test get request with string of query data.
  217. *
  218. * @return void
  219. */
  220. public function testGetQuerystringString()
  221. {
  222. $response = new Response();
  223. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  224. ->setMethods(['send'])
  225. ->getMock();
  226. $mock->expects($this->once())
  227. ->method('send')
  228. ->with($this->callback(function ($request) {
  229. $this->assertEquals(
  230. 'http://cakephp.org/search?q=hi+there&Category%5Bid%5D%5B0%5D=2&Category%5Bid%5D%5B1%5D=3',
  231. $request->getUri() . ''
  232. );
  233. return true;
  234. }))
  235. ->will($this->returnValue([$response]));
  236. $http = new Client([
  237. 'host' => 'cakephp.org',
  238. 'adapter' => $mock
  239. ]);
  240. $data = [
  241. 'q' => 'hi there',
  242. 'Category' => ['id' => [2, 3]]
  243. ];
  244. $result = $http->get('/search', http_build_query($data));
  245. $this->assertSame($response, $result);
  246. }
  247. /**
  248. * Test a GET with a request body. Services like
  249. * elasticsearch use this feature.
  250. *
  251. * @return void
  252. */
  253. public function testGetWithContent()
  254. {
  255. $response = new Response();
  256. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  257. ->setMethods(['send'])
  258. ->getMock();
  259. $mock->expects($this->once())
  260. ->method('send')
  261. ->with($this->callback(function ($request) {
  262. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  263. $this->assertEquals('http://cakephp.org/search', '' . $request->getUri());
  264. $this->assertEquals('some data', '' . $request->getBody());
  265. return true;
  266. }))
  267. ->will($this->returnValue([$response]));
  268. $http = new Client([
  269. 'host' => 'cakephp.org',
  270. 'adapter' => $mock
  271. ]);
  272. $result = $http->get('/search', [
  273. '_content' => 'some data'
  274. ]);
  275. $this->assertSame($result, $response);
  276. }
  277. /**
  278. * Test invalid authentication types throw exceptions.
  279. *
  280. * @expectedException \Cake\Core\Exception\Exception
  281. * @return void
  282. */
  283. public function testInvalidAuthenticationType()
  284. {
  285. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  286. ->setMethods(['send'])
  287. ->getMock();
  288. $mock->expects($this->never())
  289. ->method('send');
  290. $http = new Client([
  291. 'host' => 'cakephp.org',
  292. 'adapter' => $mock
  293. ]);
  294. $result = $http->get('/', [], [
  295. 'auth' => ['type' => 'horribly broken']
  296. ]);
  297. }
  298. /**
  299. * Test setting basic authentication with get
  300. *
  301. * @return void
  302. */
  303. public function testGetWithAuthenticationAndProxy()
  304. {
  305. $response = new Response();
  306. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  307. ->setMethods(['send'])
  308. ->getMock();
  309. $headers = [
  310. 'Authorization' => 'Basic ' . base64_encode('mark:secret'),
  311. 'Proxy-Authorization' => 'Basic ' . base64_encode('mark:pass'),
  312. ];
  313. $mock->expects($this->once())
  314. ->method('send')
  315. ->with($this->callback(function ($request) use ($headers) {
  316. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  317. $this->assertEquals('http://cakephp.org/', '' . $request->getUri());
  318. $this->assertEquals($headers['Authorization'], $request->getHeaderLine('Authorization'));
  319. $this->assertEquals($headers['Proxy-Authorization'], $request->getHeaderLine('Proxy-Authorization'));
  320. return true;
  321. }))
  322. ->will($this->returnValue([$response]));
  323. $http = new Client([
  324. 'host' => 'cakephp.org',
  325. 'adapter' => $mock
  326. ]);
  327. $result = $http->get('/', [], [
  328. 'auth' => ['username' => 'mark', 'password' => 'secret'],
  329. 'proxy' => ['username' => 'mark', 'password' => 'pass'],
  330. ]);
  331. $this->assertSame($result, $response);
  332. }
  333. /**
  334. * Test authentication adapter that mutates request.
  335. *
  336. * @return void
  337. */
  338. public function testAuthenticationWithMutation()
  339. {
  340. Configure::write('App.namespace', 'TestApp');
  341. $response = new Response();
  342. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  343. ->setMethods(['send'])
  344. ->getMock();
  345. $headers = [
  346. 'Authorization' => 'Bearer abc123',
  347. 'Proxy-Authorization' => 'Bearer abc123',
  348. ];
  349. $mock->expects($this->once())
  350. ->method('send')
  351. ->with($this->callback(function ($request) use ($headers) {
  352. $this->assertEquals(Request::METHOD_GET, $request->getMethod());
  353. $this->assertEquals('http://cakephp.org/', '' . $request->getUri());
  354. $this->assertEquals($headers['Authorization'], $request->getHeaderLine('Authorization'));
  355. $this->assertEquals($headers['Proxy-Authorization'], $request->getHeaderLine('Proxy-Authorization'));
  356. return true;
  357. }))
  358. ->will($this->returnValue([$response]));
  359. $http = new Client([
  360. 'host' => 'cakephp.org',
  361. 'adapter' => $mock
  362. ]);
  363. $result = $http->get('/', [], [
  364. 'auth' => ['type' => 'TestApp\Http\CompatAuth'],
  365. 'proxy' => ['type' => 'TestApp\Http\CompatAuth'],
  366. ]);
  367. $this->assertSame($result, $response);
  368. }
  369. /**
  370. * Return a list of HTTP methods.
  371. *
  372. * @return array
  373. */
  374. public static function methodProvider()
  375. {
  376. return [
  377. [Request::METHOD_GET],
  378. [Request::METHOD_POST],
  379. [Request::METHOD_PUT],
  380. [Request::METHOD_DELETE],
  381. [Request::METHOD_PATCH],
  382. [Request::METHOD_OPTIONS],
  383. [Request::METHOD_TRACE],
  384. ];
  385. }
  386. /**
  387. * test simple POST request.
  388. *
  389. * @dataProvider methodProvider
  390. * @return void
  391. */
  392. public function testMethodsSimple($method)
  393. {
  394. $response = new Response();
  395. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  396. ->setMethods(['send'])
  397. ->getMock();
  398. $mock->expects($this->once())
  399. ->method('send')
  400. ->with($this->callback(function ($request) use ($method) {
  401. $this->assertInstanceOf('Cake\Network\Http\Request', $request);
  402. $this->assertEquals($method, $request->getMethod());
  403. $this->assertEquals('http://cakephp.org/projects/add', '' . $request->getUri());
  404. return true;
  405. }))
  406. ->will($this->returnValue([$response]));
  407. $http = new Client([
  408. 'host' => 'cakephp.org',
  409. 'adapter' => $mock
  410. ]);
  411. $result = $http->{$method}('/projects/add');
  412. $this->assertSame($result, $response);
  413. }
  414. /**
  415. * Provider for testing the type option.
  416. *
  417. * @return array
  418. */
  419. public static function typeProvider()
  420. {
  421. return [
  422. ['application/json', 'application/json'],
  423. ['json', 'application/json'],
  424. ['xml', 'application/xml'],
  425. ['application/xml', 'application/xml'],
  426. ];
  427. }
  428. /**
  429. * Test that using the 'type' option sets the correct headers
  430. *
  431. * @dataProvider typeProvider
  432. * @return void
  433. */
  434. public function testPostWithTypeKey($type, $mime)
  435. {
  436. $response = new Response();
  437. $data = 'some data';
  438. $headers = [
  439. 'Content-Type' => $mime,
  440. 'Accept' => $mime,
  441. ];
  442. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  443. ->setMethods(['send'])
  444. ->getMock();
  445. $mock->expects($this->once())
  446. ->method('send')
  447. ->with($this->callback(function ($request) use ($headers) {
  448. $this->assertEquals(Request::METHOD_POST, $request->getMethod());
  449. $this->assertEquals($headers['Content-Type'], $request->getHeaderLine('Content-Type'));
  450. $this->assertEquals($headers['Accept'], $request->getHeaderLine('Accept'));
  451. return true;
  452. }))
  453. ->will($this->returnValue([$response]));
  454. $http = new Client([
  455. 'host' => 'cakephp.org',
  456. 'adapter' => $mock
  457. ]);
  458. $http->post('/projects/add', $data, ['type' => $type]);
  459. }
  460. /**
  461. * Test that string payloads with no content type have a default content-type set.
  462. *
  463. * @return void
  464. */
  465. public function testPostWithStringDataDefaultsToFormEncoding()
  466. {
  467. $response = new Response();
  468. $data = 'some=value&more=data';
  469. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  470. ->setMethods(['send'])
  471. ->getMock();
  472. $mock->expects($this->any())
  473. ->method('send')
  474. ->with($this->callback(function ($request) use ($data) {
  475. $this->assertEquals($data, '' . $request->getBody());
  476. $this->assertEquals('application/x-www-form-urlencoded', $request->getHeaderLine('content-type'));
  477. return true;
  478. }))
  479. ->will($this->returnValue([$response]));
  480. $http = new Client([
  481. 'host' => 'cakephp.org',
  482. 'adapter' => $mock
  483. ]);
  484. $http->post('/projects/add', $data);
  485. $http->put('/projects/add', $data);
  486. $http->delete('/projects/add', $data);
  487. }
  488. /**
  489. * Test that exceptions are raised on invalid types.
  490. *
  491. * @expectedException \Cake\Core\Exception\Exception
  492. * @return void
  493. */
  494. public function testExceptionOnUnknownType()
  495. {
  496. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  497. ->setMethods(['send'])
  498. ->getMock();
  499. $mock->expects($this->never())
  500. ->method('send');
  501. $http = new Client([
  502. 'host' => 'cakephp.org',
  503. 'adapter' => $mock
  504. ]);
  505. $http->post('/projects/add', 'it works', ['type' => 'invalid']);
  506. }
  507. /**
  508. * Test that Client stores cookies
  509. *
  510. * @return void
  511. */
  512. public function testCookieStorage()
  513. {
  514. $adapter = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  515. ->setMethods(['send'])
  516. ->getMock();
  517. $cookieJar = $this->getMockBuilder('Cake\Network\Http\CookieCollection')->getMock();
  518. $headers = [
  519. 'HTTP/1.0 200 Ok',
  520. 'Set-Cookie: first=1',
  521. 'Set-Cookie: expiring=now; Expires=Wed, 09-Jun-1999 10:18:14 GMT'
  522. ];
  523. $response = new Response($headers, '');
  524. $cookieJar->expects($this->at(0))
  525. ->method('get')
  526. ->with('http://cakephp.org/projects')
  527. ->will($this->returnValue([]));
  528. $cookieJar->expects($this->at(1))
  529. ->method('store')
  530. ->with($response);
  531. $adapter->expects($this->at(0))
  532. ->method('send')
  533. ->will($this->returnValue([$response]));
  534. $http = new Client([
  535. 'host' => 'cakephp.org',
  536. 'adapter' => $adapter,
  537. 'cookieJar' => $cookieJar
  538. ]);
  539. $http->get('/projects');
  540. }
  541. /**
  542. * test head request with querystring data
  543. *
  544. * @return void
  545. */
  546. public function testHeadQuerystring()
  547. {
  548. $response = new Response();
  549. $mock = $this->getMockBuilder('Cake\Network\Http\Adapter\Stream')
  550. ->setMethods(['send'])
  551. ->getMock();
  552. $mock->expects($this->once())
  553. ->method('send')
  554. ->with($this->callback(function ($request) {
  555. $this->assertInstanceOf('Cake\Network\Http\Request', $request);
  556. $this->assertEquals(Request::METHOD_HEAD, $request->getMethod());
  557. $this->assertEquals('http://cakephp.org/search?q=hi+there', '' . $request->getUri());
  558. return true;
  559. }))
  560. ->will($this->returnValue([$response]));
  561. $http = new Client([
  562. 'host' => 'cakephp.org',
  563. 'adapter' => $mock
  564. ]);
  565. $result = $http->head('/search', [
  566. 'q' => 'hi there',
  567. ]);
  568. $this->assertSame($result, $response);
  569. }
  570. }