ClientTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. <?php
  2. namespace GuzzleHttp\Tests;
  3. use GuzzleHttp\Client;
  4. use GuzzleHttp\Cookie\CookieJar;
  5. use GuzzleHttp\Handler\MockHandler;
  6. use GuzzleHttp\HandlerStack;
  7. use GuzzleHttp\Middleware;
  8. use GuzzleHttp\Promise\PromiseInterface;
  9. use GuzzleHttp\Psr7;
  10. use GuzzleHttp\Psr7\Request;
  11. use GuzzleHttp\Psr7\Response;
  12. use GuzzleHttp\Psr7\Uri;
  13. use GuzzleHttp\RequestOptions;
  14. use PHPUnit\Framework\TestCase;
  15. use Psr\Http\Message\ResponseInterface;
  16. class ClientTest extends TestCase
  17. {
  18. public function testUsesDefaultHandler()
  19. {
  20. $client = new Client();
  21. Server::enqueue([new Response(200, ['Content-Length' => 0])]);
  22. $response = $client->get(Server::$url);
  23. self::assertSame(200, $response->getStatusCode());
  24. }
  25. public function testValidatesArgsForMagicMethods()
  26. {
  27. $client = new Client();
  28. $this->expectException(\InvalidArgumentException::class);
  29. $this->expectExceptionMessage('Magic request methods require a URI and optional options array');
  30. $client->options();
  31. }
  32. public function testCanSendAsyncGetRequests()
  33. {
  34. $client = new Client();
  35. Server::flush();
  36. Server::enqueue([new Response(200, ['Content-Length' => 2], 'hi')]);
  37. $p = $client->getAsync(Server::$url, ['query' => ['test' => 'foo']]);
  38. self::assertInstanceOf(PromiseInterface::class, $p);
  39. self::assertSame(200, $p->wait()->getStatusCode());
  40. $received = Server::received(true);
  41. self::assertCount(1, $received);
  42. self::assertSame('test=foo', $received[0]->getUri()->getQuery());
  43. }
  44. public function testCanSendSynchronously()
  45. {
  46. $client = new Client(['handler' => new MockHandler([new Response()])]);
  47. $request = new Request('GET', 'http://example.com');
  48. $r = $client->send($request);
  49. self::assertInstanceOf(ResponseInterface::class, $r);
  50. self::assertSame(200, $r->getStatusCode());
  51. }
  52. public function testClientHasOptions()
  53. {
  54. $client = new Client([
  55. 'base_uri' => 'http://foo.com',
  56. 'timeout' => 2,
  57. 'headers' => ['bar' => 'baz'],
  58. 'handler' => new MockHandler(),
  59. ]);
  60. $config = Helpers::readObjectAttribute($client, 'config');
  61. self::assertArrayHasKey('base_uri', $config);
  62. self::assertInstanceOf(Uri::class, $config['base_uri']);
  63. self::assertSame('http://foo.com', (string) $config['base_uri']);
  64. self::assertArrayHasKey('handler', $config);
  65. self::assertNotNull($config['handler']);
  66. self::assertArrayHasKey('timeout', $config);
  67. self::assertSame(2, $config['timeout']);
  68. }
  69. public function testCanMergeOnBaseUri()
  70. {
  71. $mock = new MockHandler([new Response()]);
  72. $client = new Client([
  73. 'base_uri' => 'http://foo.com/bar/',
  74. 'handler' => $mock,
  75. ]);
  76. $client->get('baz');
  77. self::assertSame(
  78. 'http://foo.com/bar/baz',
  79. (string) $mock->getLastRequest()->getUri()
  80. );
  81. }
  82. public function testCanMergeOnBaseUriWithRequest()
  83. {
  84. $mock = new MockHandler([new Response(), new Response()]);
  85. $client = new Client([
  86. 'handler' => $mock,
  87. 'base_uri' => 'http://foo.com/bar/',
  88. ]);
  89. $client->request('GET', new Uri('baz'));
  90. self::assertSame(
  91. 'http://foo.com/bar/baz',
  92. (string) $mock->getLastRequest()->getUri()
  93. );
  94. $client->request('GET', new Uri('baz'), ['base_uri' => 'http://example.com/foo/']);
  95. self::assertSame(
  96. 'http://example.com/foo/baz',
  97. (string) $mock->getLastRequest()->getUri(),
  98. 'Can overwrite the base_uri through the request options'
  99. );
  100. }
  101. public function testCanUseRelativeUriWithSend()
  102. {
  103. $mock = new MockHandler([new Response()]);
  104. $client = new Client([
  105. 'handler' => $mock,
  106. 'base_uri' => 'http://bar.com',
  107. ]);
  108. $config = Helpers::readObjectAttribute($client, 'config');
  109. self::assertSame('http://bar.com', (string) $config['base_uri']);
  110. $request = new Request('GET', '/baz');
  111. $client->send($request);
  112. self::assertSame(
  113. 'http://bar.com/baz',
  114. (string) $mock->getLastRequest()->getUri()
  115. );
  116. }
  117. public function testMergesDefaultOptionsAndDoesNotOverwriteUa()
  118. {
  119. $client = new Client(['headers' => ['User-agent' => 'foo']]);
  120. $config = Helpers::readObjectAttribute($client, 'config');
  121. self::assertSame(['User-agent' => 'foo'], $config['headers']);
  122. self::assertIsArray($config['allow_redirects']);
  123. self::assertTrue($config['http_errors']);
  124. self::assertTrue($config['decode_content']);
  125. self::assertTrue($config['verify']);
  126. }
  127. public function testDoesNotOverwriteHeaderWithDefault()
  128. {
  129. $mock = new MockHandler([new Response()]);
  130. $c = new Client([
  131. 'headers' => ['User-agent' => 'foo'],
  132. 'handler' => $mock,
  133. ]);
  134. $c->get('http://example.com', ['headers' => ['User-Agent' => 'bar']]);
  135. self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
  136. }
  137. public function testDoesNotOverwriteHeaderWithDefaultInRequest()
  138. {
  139. $mock = new MockHandler([new Response()]);
  140. $c = new Client([
  141. 'headers' => ['User-agent' => 'foo'],
  142. 'handler' => $mock,
  143. ]);
  144. $request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
  145. $c->send($request);
  146. self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
  147. }
  148. public function testDoesOverwriteHeaderWithSetRequestOption()
  149. {
  150. $mock = new MockHandler([new Response()]);
  151. $c = new Client([
  152. 'headers' => ['User-agent' => 'foo'],
  153. 'handler' => $mock,
  154. ]);
  155. $request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
  156. $c->send($request, ['headers' => ['User-Agent' => 'YO']]);
  157. self::assertSame('YO', $mock->getLastRequest()->getHeaderLine('User-Agent'));
  158. }
  159. public function testCanUnsetRequestOptionWithNull()
  160. {
  161. $mock = new MockHandler([new Response()]);
  162. $c = new Client([
  163. 'headers' => ['foo' => 'bar'],
  164. 'handler' => $mock,
  165. ]);
  166. $c->get('http://example.com', ['headers' => null]);
  167. self::assertFalse($mock->getLastRequest()->hasHeader('foo'));
  168. }
  169. public function testAllowRedirectsCanBeTrue()
  170. {
  171. $mock = new MockHandler([new Response(200, [], 'foo')]);
  172. $handler = HandlerStack::create($mock);
  173. $client = new Client(['handler' => $handler]);
  174. $client->get('http://foo.com', ['allow_redirects' => true]);
  175. self::assertIsArray($mock->getLastOptions()['allow_redirects']);
  176. }
  177. public function testValidatesAllowRedirects()
  178. {
  179. $mock = new MockHandler([new Response(200, [], 'foo')]);
  180. $handler = HandlerStack::create($mock);
  181. $client = new Client(['handler' => $handler]);
  182. $this->expectException(\InvalidArgumentException::class);
  183. $this->expectExceptionMessage('allow_redirects must be true, false, or array');
  184. $client->get('http://foo.com', ['allow_redirects' => 'foo']);
  185. }
  186. public function testThrowsHttpErrorsByDefault()
  187. {
  188. $mock = new MockHandler([new Response(404)]);
  189. $handler = HandlerStack::create($mock);
  190. $client = new Client(['handler' => $handler]);
  191. $this->expectException(\GuzzleHttp\Exception\ClientException::class);
  192. $client->get('http://foo.com');
  193. }
  194. public function testValidatesCookies()
  195. {
  196. $mock = new MockHandler([new Response(200, [], 'foo')]);
  197. $handler = HandlerStack::create($mock);
  198. $client = new Client(['handler' => $handler]);
  199. $this->expectException(\InvalidArgumentException::class);
  200. $this->expectExceptionMessage('cookies must be an instance of GuzzleHttp\\Cookie\\CookieJarInterface');
  201. $client->get('http://foo.com', ['cookies' => 'foo']);
  202. }
  203. public function testSetCookieToTrueUsesSharedJar()
  204. {
  205. $mock = new MockHandler([
  206. new Response(200, ['Set-Cookie' => 'foo=bar']),
  207. new Response(),
  208. ]);
  209. $handler = HandlerStack::create($mock);
  210. $client = new Client(['handler' => $handler, 'cookies' => true]);
  211. $client->get('http://foo.com');
  212. $client->get('http://foo.com');
  213. self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
  214. }
  215. public function testSetCookieToJar()
  216. {
  217. $mock = new MockHandler([
  218. new Response(200, ['Set-Cookie' => 'foo=bar']),
  219. new Response(),
  220. ]);
  221. $handler = HandlerStack::create($mock);
  222. $client = new Client(['handler' => $handler]);
  223. $jar = new CookieJar();
  224. $client->get('http://foo.com', ['cookies' => $jar]);
  225. $client->get('http://foo.com', ['cookies' => $jar]);
  226. self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
  227. }
  228. public function testCanDisableContentDecoding()
  229. {
  230. $mock = new MockHandler([new Response()]);
  231. $client = new Client(['handler' => $mock]);
  232. $client->get('http://foo.com', ['decode_content' => false]);
  233. $last = $mock->getLastRequest();
  234. self::assertFalse($last->hasHeader('Accept-Encoding'));
  235. self::assertFalse($mock->getLastOptions()['decode_content']);
  236. }
  237. public function testCanSetContentDecodingToValue()
  238. {
  239. $mock = new MockHandler([new Response()]);
  240. $client = new Client(['handler' => $mock]);
  241. $client->get('http://foo.com', ['decode_content' => 'gzip']);
  242. $last = $mock->getLastRequest();
  243. self::assertSame('gzip', $last->getHeaderLine('Accept-Encoding'));
  244. self::assertSame('gzip', $mock->getLastOptions()['decode_content']);
  245. }
  246. public function testAddsAcceptEncodingbyCurl()
  247. {
  248. $client = new Client(['curl' => [\CURLOPT_ENCODING => '']]);
  249. Server::flush();
  250. Server::enqueue([new Response()]);
  251. $client->get(Server::$url);
  252. $sent = Server::received()[0];
  253. self::assertTrue($sent->hasHeader('Accept-Encoding'));
  254. $mock = new MockHandler([new Response()]);
  255. $client->get('http://foo.com', ['handler' => $mock]);
  256. self::assertSame([\CURLOPT_ENCODING => ''], $mock->getLastOptions()['curl']);
  257. }
  258. public function testValidatesHeaders()
  259. {
  260. $mock = new MockHandler();
  261. $client = new Client(['handler' => $mock]);
  262. $this->expectException(\InvalidArgumentException::class);
  263. $client->get('http://foo.com', ['headers' => 'foo']);
  264. }
  265. public function testAddsBody()
  266. {
  267. $mock = new MockHandler([new Response()]);
  268. $client = new Client(['handler' => $mock]);
  269. $request = new Request('PUT', 'http://foo.com');
  270. $client->send($request, ['body' => 'foo']);
  271. $last = $mock->getLastRequest();
  272. self::assertSame('foo', (string) $last->getBody());
  273. }
  274. public function testValidatesQuery()
  275. {
  276. $mock = new MockHandler();
  277. $client = new Client(['handler' => $mock]);
  278. $request = new Request('PUT', 'http://foo.com');
  279. $this->expectException(\InvalidArgumentException::class);
  280. $client->send($request, ['query' => false]);
  281. }
  282. public function testQueryCanBeString()
  283. {
  284. $mock = new MockHandler([new Response()]);
  285. $client = new Client(['handler' => $mock]);
  286. $request = new Request('PUT', 'http://foo.com');
  287. $client->send($request, ['query' => 'foo']);
  288. self::assertSame('foo', $mock->getLastRequest()->getUri()->getQuery());
  289. }
  290. public function testQueryCanBeArray()
  291. {
  292. $mock = new MockHandler([new Response()]);
  293. $client = new Client(['handler' => $mock]);
  294. $request = new Request('PUT', 'http://foo.com');
  295. $client->send($request, ['query' => ['foo' => 'bar baz']]);
  296. self::assertSame('foo=bar%20baz', $mock->getLastRequest()->getUri()->getQuery());
  297. }
  298. public function testCanAddJsonData()
  299. {
  300. $mock = new MockHandler([new Response()]);
  301. $client = new Client(['handler' => $mock]);
  302. $request = new Request('PUT', 'http://foo.com');
  303. $client->send($request, ['json' => ['foo' => 'bar']]);
  304. $last = $mock->getLastRequest();
  305. self::assertSame('{"foo":"bar"}', (string) $mock->getLastRequest()->getBody());
  306. self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
  307. }
  308. public function testCanAddJsonDataWithoutOverwritingContentType()
  309. {
  310. $mock = new MockHandler([new Response()]);
  311. $client = new Client(['handler' => $mock]);
  312. $request = new Request('PUT', 'http://foo.com');
  313. $client->send($request, [
  314. 'headers' => ['content-type' => 'foo'],
  315. 'json' => 'a',
  316. ]);
  317. $last = $mock->getLastRequest();
  318. self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
  319. self::assertSame('foo', $last->getHeaderLine('Content-Type'));
  320. }
  321. public function testCanAddJsonDataWithNullHeader()
  322. {
  323. $mock = new MockHandler([new Response()]);
  324. $client = new Client(['handler' => $mock]);
  325. $request = new Request('PUT', 'http://foo.com');
  326. $client->send($request, [
  327. 'headers' => null,
  328. 'json' => 'a',
  329. ]);
  330. $last = $mock->getLastRequest();
  331. self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
  332. self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
  333. }
  334. public function testAuthCanBeTrue()
  335. {
  336. $mock = new MockHandler([new Response()]);
  337. $client = new Client(['handler' => $mock]);
  338. $client->get('http://foo.com', ['auth' => false]);
  339. $last = $mock->getLastRequest();
  340. self::assertFalse($last->hasHeader('Authorization'));
  341. }
  342. public function testAuthCanBeArrayForBasicAuth()
  343. {
  344. $mock = new MockHandler([new Response()]);
  345. $client = new Client(['handler' => $mock]);
  346. $client->get('http://foo.com', ['auth' => ['a', 'b']]);
  347. $last = $mock->getLastRequest();
  348. self::assertSame('Basic YTpi', $last->getHeaderLine('Authorization'));
  349. }
  350. public function testAuthCanBeArrayForDigestAuth()
  351. {
  352. $mock = new MockHandler([new Response()]);
  353. $client = new Client(['handler' => $mock]);
  354. $client->get('http://foo.com', ['auth' => ['a', 'b', 'digest']]);
  355. $last = $mock->getLastOptions();
  356. self::assertSame([
  357. \CURLOPT_HTTPAUTH => 2,
  358. \CURLOPT_USERPWD => 'a:b',
  359. ], $last['curl']);
  360. }
  361. public function testAuthCanBeArrayForNtlmAuth()
  362. {
  363. $mock = new MockHandler([new Response()]);
  364. $client = new Client(['handler' => $mock]);
  365. $client->get('http://foo.com', ['auth' => ['a', 'b', 'ntlm']]);
  366. $last = $mock->getLastOptions();
  367. self::assertSame([
  368. \CURLOPT_HTTPAUTH => 8,
  369. \CURLOPT_USERPWD => 'a:b',
  370. ], $last['curl']);
  371. }
  372. public function testAuthCanBeCustomType()
  373. {
  374. $mock = new MockHandler([new Response()]);
  375. $client = new Client(['handler' => $mock]);
  376. $client->get('http://foo.com', ['auth' => 'foo']);
  377. $last = $mock->getLastOptions();
  378. self::assertSame('foo', $last['auth']);
  379. }
  380. public function testCanAddFormParams()
  381. {
  382. $mock = new MockHandler([new Response()]);
  383. $client = new Client(['handler' => $mock]);
  384. $client->post('http://foo.com', [
  385. 'form_params' => [
  386. 'foo' => 'bar bam',
  387. 'baz' => ['boo' => 'qux'],
  388. ],
  389. ]);
  390. $last = $mock->getLastRequest();
  391. self::assertSame(
  392. 'application/x-www-form-urlencoded',
  393. $last->getHeaderLine('Content-Type')
  394. );
  395. self::assertSame(
  396. 'foo=bar+bam&baz%5Bboo%5D=qux',
  397. (string) $last->getBody()
  398. );
  399. }
  400. public function testFormParamsEncodedProperly()
  401. {
  402. $separator = \ini_get('arg_separator.output');
  403. \ini_set('arg_separator.output', '&amp;');
  404. $mock = new MockHandler([new Response()]);
  405. $client = new Client(['handler' => $mock]);
  406. $client->post('http://foo.com', [
  407. 'form_params' => [
  408. 'foo' => 'bar bam',
  409. 'baz' => ['boo' => 'qux'],
  410. ],
  411. ]);
  412. $last = $mock->getLastRequest();
  413. self::assertSame(
  414. 'foo=bar+bam&baz%5Bboo%5D=qux',
  415. (string) $last->getBody()
  416. );
  417. \ini_set('arg_separator.output', $separator);
  418. }
  419. public function testEnsuresThatFormParamsAndMultipartAreExclusive()
  420. {
  421. $client = new Client(['handler' => static function () {
  422. }]);
  423. $this->expectException(\InvalidArgumentException::class);
  424. $client->post('http://foo.com', [
  425. 'form_params' => ['foo' => 'bar bam'],
  426. 'multipart' => [],
  427. ]);
  428. }
  429. public function testCanSendMultipart()
  430. {
  431. $mock = new MockHandler([new Response()]);
  432. $client = new Client(['handler' => $mock]);
  433. $client->post('http://foo.com', [
  434. 'multipart' => [
  435. [
  436. 'name' => 'foo',
  437. 'contents' => 'bar',
  438. ],
  439. [
  440. 'name' => 'test',
  441. 'contents' => \fopen(__FILE__, 'r'),
  442. ],
  443. ],
  444. ]);
  445. $last = $mock->getLastRequest();
  446. self::assertStringContainsString(
  447. 'multipart/form-data; boundary=',
  448. $last->getHeaderLine('Content-Type')
  449. );
  450. self::assertStringContainsString(
  451. 'Content-Disposition: form-data; name="foo"',
  452. (string) $last->getBody()
  453. );
  454. self::assertStringContainsString('bar', (string) $last->getBody());
  455. self::assertStringContainsString(
  456. 'Content-Disposition: form-data; name="foo"'."\r\n",
  457. (string) $last->getBody()
  458. );
  459. self::assertStringContainsString(
  460. 'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
  461. (string) $last->getBody()
  462. );
  463. }
  464. public function testCanSendMultipartWithExplicitBody()
  465. {
  466. $mock = new MockHandler([new Response()]);
  467. $client = new Client(['handler' => $mock]);
  468. $client->send(
  469. new Request(
  470. 'POST',
  471. 'http://foo.com',
  472. [],
  473. new Psr7\MultipartStream(
  474. [
  475. [
  476. 'name' => 'foo',
  477. 'contents' => 'bar',
  478. ],
  479. [
  480. 'name' => 'test',
  481. 'contents' => \fopen(__FILE__, 'r'),
  482. ],
  483. ]
  484. )
  485. )
  486. );
  487. $last = $mock->getLastRequest();
  488. self::assertStringContainsString(
  489. 'multipart/form-data; boundary=',
  490. $last->getHeaderLine('Content-Type')
  491. );
  492. self::assertStringContainsString(
  493. 'Content-Disposition: form-data; name="foo"',
  494. (string) $last->getBody()
  495. );
  496. self::assertStringContainsString('bar', (string) $last->getBody());
  497. self::assertStringContainsString(
  498. 'Content-Disposition: form-data; name="foo"'."\r\n",
  499. (string) $last->getBody()
  500. );
  501. self::assertStringContainsString(
  502. 'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
  503. (string) $last->getBody()
  504. );
  505. }
  506. public function testUsesProxyEnvironmentVariables()
  507. {
  508. unset($_SERVER['HTTP_PROXY'], $_SERVER['HTTPS_PROXY'], $_SERVER['NO_PROXY']);
  509. \putenv('HTTP_PROXY=');
  510. \putenv('HTTPS_PROXY=');
  511. \putenv('NO_PROXY=');
  512. try {
  513. $client = new Client();
  514. $config = Helpers::readObjectAttribute($client, 'config');
  515. self::assertArrayNotHasKey('proxy', $config);
  516. \putenv('HTTP_PROXY=127.0.0.1');
  517. $client = new Client();
  518. $config = Helpers::readObjectAttribute($client, 'config');
  519. self::assertArrayHasKey('proxy', $config);
  520. self::assertSame(['http' => '127.0.0.1'], $config['proxy']);
  521. \putenv('HTTPS_PROXY=127.0.0.2');
  522. \putenv('NO_PROXY=127.0.0.3, 127.0.0.4');
  523. $client = new Client();
  524. $config = Helpers::readObjectAttribute($client, 'config');
  525. self::assertArrayHasKey('proxy', $config);
  526. self::assertSame(
  527. ['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3', '127.0.0.4']],
  528. $config['proxy']
  529. );
  530. } finally {
  531. \putenv('HTTP_PROXY=');
  532. \putenv('HTTPS_PROXY=');
  533. \putenv('NO_PROXY=');
  534. }
  535. }
  536. public function testRequestSendsWithSync()
  537. {
  538. $mock = new MockHandler([new Response()]);
  539. $client = new Client(['handler' => $mock]);
  540. $client->request('GET', 'http://foo.com');
  541. self::assertTrue($mock->getLastOptions()['synchronous']);
  542. }
  543. public function testSendSendsWithSync()
  544. {
  545. $mock = new MockHandler([new Response()]);
  546. $client = new Client(['handler' => $mock]);
  547. $client->send(new Request('GET', 'http://foo.com'));
  548. self::assertTrue($mock->getLastOptions()['synchronous']);
  549. }
  550. public function testSendWithInvalidHeader()
  551. {
  552. $mock = new MockHandler([new Response()]);
  553. $client = new Client(['handler' => $mock]);
  554. $request = new Request('GET', 'http://foo.com');
  555. $this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class);
  556. $client->send($request, ['headers' => ['X-Foo: Bar']]);
  557. }
  558. public function testSendWithInvalidHeaders()
  559. {
  560. $mock = new MockHandler([new Response()]);
  561. $client = new Client(['handler' => $mock]);
  562. $request = new Request('GET', 'http://foo.com');
  563. $this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class);
  564. $client->send($request, ['headers' => ['X-Foo: Bar', 'X-Test: Fail']]);
  565. }
  566. public function testCanSetCustomHandler()
  567. {
  568. $mock = new MockHandler([new Response(500)]);
  569. $client = new Client(['handler' => $mock]);
  570. $mock2 = new MockHandler([new Response(200)]);
  571. self::assertSame(
  572. 200,
  573. $client->send(new Request('GET', 'http://foo.com'), [
  574. 'handler' => $mock2,
  575. ])->getStatusCode()
  576. );
  577. }
  578. public function testProperlyBuildsQuery()
  579. {
  580. $mock = new MockHandler([new Response()]);
  581. $client = new Client(['handler' => $mock]);
  582. $request = new Request('PUT', 'http://foo.com');
  583. $client->send($request, ['query' => ['foo' => 'bar', 'john' => 'doe']]);
  584. self::assertSame('foo=bar&john=doe', $mock->getLastRequest()->getUri()->getQuery());
  585. }
  586. public function testSendSendsWithIpAddressAndPortAndHostHeaderInRequestTheHostShouldBePreserved()
  587. {
  588. $mockHandler = new MockHandler([new Response()]);
  589. $client = new Client(['base_uri' => 'http://127.0.0.1:8585', 'handler' => $mockHandler]);
  590. $request = new Request('GET', '/test', ['Host' => 'foo.com']);
  591. $client->send($request);
  592. self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
  593. }
  594. public function testSendSendsWithDomainAndHostHeaderInRequestTheHostShouldBePreserved()
  595. {
  596. $mockHandler = new MockHandler([new Response()]);
  597. $client = new Client(['base_uri' => 'http://foo2.com', 'handler' => $mockHandler]);
  598. $request = new Request('GET', '/test', ['Host' => 'foo.com']);
  599. $client->send($request);
  600. self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
  601. }
  602. public function testValidatesSink()
  603. {
  604. $mockHandler = new MockHandler([new Response()]);
  605. $client = new Client(['handler' => $mockHandler]);
  606. $this->expectException(\InvalidArgumentException::class);
  607. $client->get('http://test.com', ['sink' => true]);
  608. }
  609. public function testHttpDefaultSchemeIfUriHasNone()
  610. {
  611. $mockHandler = new MockHandler([new Response()]);
  612. $client = new Client(['handler' => $mockHandler]);
  613. $client->request('GET', '//example.org/test');
  614. self::assertSame('http://example.org/test', (string) $mockHandler->getLastRequest()->getUri());
  615. }
  616. public function testOnlyAddSchemeWhenHostIsPresent()
  617. {
  618. $mockHandler = new MockHandler([new Response()]);
  619. $client = new Client(['handler' => $mockHandler]);
  620. $client->request('GET', 'baz');
  621. self::assertSame(
  622. 'baz',
  623. (string) $mockHandler->getLastRequest()->getUri()
  624. );
  625. }
  626. public function testThatVersionIsOverwrittenWhenSendingARequest()
  627. {
  628. $mockHandler = new MockHandler([new Response(), new Response()]);
  629. $client = new Client(['handler' => $mockHandler]);
  630. $request = new Request('get', '/bar', [], null, '1.1');
  631. $client->send($request, [RequestOptions::VERSION => '1.0']);
  632. self::assertSame(
  633. '1.0',
  634. $mockHandler->getLastRequest()->getProtocolVersion()
  635. );
  636. $request = new Request('get', '/bar', [], null, '1.0');
  637. $client->send($request, [RequestOptions::VERSION => '1.1']);
  638. self::assertSame(
  639. '1.1',
  640. $mockHandler->getLastRequest()->getProtocolVersion()
  641. );
  642. }
  643. public function testHandlerIsCallable()
  644. {
  645. $this->expectException(\InvalidArgumentException::class);
  646. new Client(['handler' => 'not_cllable']);
  647. }
  648. public function testResponseBodyAsString()
  649. {
  650. $responseBody = '{ "package": "guzzle" }';
  651. $mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
  652. $client = new Client(['handler' => $mock]);
  653. $request = new Request('GET', 'http://foo.com');
  654. $response = $client->send($request, ['json' => ['a' => 'b']]);
  655. self::assertSame($responseBody, (string) $response->getBody());
  656. }
  657. public function testResponseContent()
  658. {
  659. $responseBody = '{ "package": "guzzle" }';
  660. $mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
  661. $client = new Client(['handler' => $mock]);
  662. $request = new Request('POST', 'http://foo.com');
  663. $response = $client->send($request, ['json' => ['a' => 'b']]);
  664. self::assertSame($responseBody, $response->getBody()->getContents());
  665. }
  666. public function testIdnSupportDefaultValue()
  667. {
  668. $mockHandler = new MockHandler([new Response()]);
  669. $client = new Client(['handler' => $mockHandler]);
  670. $config = Helpers::readObjectAttribute($client, 'config');
  671. self::assertFalse($config['idn_conversion']);
  672. }
  673. /**
  674. * @requires extension idn
  675. */
  676. public function testIdnIsTranslatedToAsciiWhenConversionIsEnabled()
  677. {
  678. $mockHandler = new MockHandler([new Response()]);
  679. $client = new Client(['handler' => $mockHandler]);
  680. $client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => true]);
  681. $request = $mockHandler->getLastRequest();
  682. self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
  683. self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
  684. }
  685. public function testIdnStaysTheSameWhenConversionIsDisabled()
  686. {
  687. $mockHandler = new MockHandler([new Response()]);
  688. $client = new Client(['handler' => $mockHandler]);
  689. $client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => false]);
  690. $request = $mockHandler->getLastRequest();
  691. self::assertSame('https://яндекс.рф/images', (string) $request->getUri());
  692. self::assertSame('яндекс.рф', (string) $request->getHeaderLine('Host'));
  693. }
  694. /**
  695. * @requires extension idn
  696. */
  697. public function testExceptionOnInvalidIdn()
  698. {
  699. $mockHandler = new MockHandler([new Response()]);
  700. $client = new Client(['handler' => $mockHandler]);
  701. $this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class);
  702. $this->expectExceptionMessage('IDN conversion failed');
  703. $client->request('GET', 'https://-яндекс.рф/images', ['idn_conversion' => true]);
  704. }
  705. /**
  706. * @depends testCanUseRelativeUriWithSend
  707. *
  708. * @requires extension idn
  709. */
  710. public function testIdnBaseUri()
  711. {
  712. $mock = new MockHandler([new Response()]);
  713. $client = new Client([
  714. 'handler' => $mock,
  715. 'base_uri' => 'http://яндекс.рф',
  716. 'idn_conversion' => true,
  717. ]);
  718. $config = Helpers::readObjectAttribute($client, 'config');
  719. self::assertSame('http://яндекс.рф', (string) $config['base_uri']);
  720. $request = new Request('GET', '/baz');
  721. $client->send($request);
  722. self::assertSame('http://xn--d1acpjx3f.xn--p1ai/baz', (string) $mock->getLastRequest()->getUri());
  723. self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $mock->getLastRequest()->getHeaderLine('Host'));
  724. }
  725. /**
  726. * @requires extension idn
  727. */
  728. public function testIdnWithRedirect()
  729. {
  730. $mockHandler = new MockHandler([
  731. new Response(302, ['Location' => 'http://www.tést.com/whatever']),
  732. new Response(),
  733. ]);
  734. $handler = HandlerStack::create($mockHandler);
  735. $requests = [];
  736. $handler->push(Middleware::history($requests));
  737. $client = new Client(['handler' => $handler]);
  738. $client->request('GET', 'https://яндекс.рф/images', [
  739. RequestOptions::ALLOW_REDIRECTS => [
  740. 'referer' => true,
  741. 'track_redirects' => true,
  742. ],
  743. 'idn_conversion' => true,
  744. ]);
  745. $request = $mockHandler->getLastRequest();
  746. self::assertSame('http://www.xn--tst-bma.com/whatever', (string) $request->getUri());
  747. self::assertSame('www.xn--tst-bma.com', (string) $request->getHeaderLine('Host'));
  748. $request = $requests[0]['request'];
  749. self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
  750. self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
  751. }
  752. }