ClientTest.php 20 KB

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