scratch – Blame information for rev 87

Subversion Repositories:
Rev:
Rev Author Line No. Line
87 office 1 <?php
2  
3 namespace GuzzleHttp\Tests;
4  
5 use GuzzleHttp\Adapter\FakeParallelAdapter;
6 use GuzzleHttp\Adapter\MockAdapter;
7 use GuzzleHttp\Client;
8 use GuzzleHttp\Event\BeforeEvent;
9 use GuzzleHttp\Exception\RequestException;
10 use GuzzleHttp\Message\MessageFactory;
11 use GuzzleHttp\Message\Response;
12 use GuzzleHttp\Subscriber\History;
13 use GuzzleHttp\Subscriber\Mock;
14  
15 /**
16 * @covers GuzzleHttp\Client
17 */
18 class ClientTest extends \PHPUnit_Framework_TestCase
19 {
20 public function testProvidesDefaultUserAgent()
21 {
22 $this->assertEquals(1, preg_match('#^Guzzle/.+ curl/.+ PHP/.+$#', Client::getDefaultUserAgent()));
23 }
24  
25 public function testUsesDefaultDefaultOptions()
26 {
27 $client = new Client();
28 $this->assertTrue($client->getDefaultOption('allow_redirects'));
29 $this->assertTrue($client->getDefaultOption('exceptions'));
30 $this->assertContains('cacert.pem', $client->getDefaultOption('verify'));
31 }
32  
33 public function testUsesProvidedDefaultOptions()
34 {
35 $client = new Client([
36 'defaults' => [
37 'allow_redirects' => false,
38 'query' => ['foo' => 'bar']
39 ]
40 ]);
41 $this->assertFalse($client->getDefaultOption('allow_redirects'));
42 $this->assertTrue($client->getDefaultOption('exceptions'));
43 $this->assertContains('cacert.pem', $client->getDefaultOption('verify'));
44 $this->assertEquals(['foo' => 'bar'], $client->getDefaultOption('query'));
45 }
46  
47 public function testCanSpecifyBaseUrl()
48 {
49 $this->assertSame('', (new Client())->getBaseUrl());
50 $this->assertEquals('http://foo', (new Client([
51 'base_url' => 'http://foo'
52 ]))->getBaseUrl());
53 }
54  
55 public function testCanSpecifyBaseUrlUriTemplate()
56 {
57 $client = new Client(['base_url' => ['http://foo.com/{var}/', ['var' => 'baz']]]);
58 $this->assertEquals('http://foo.com/baz/', $client->getBaseUrl());
59 }
60  
61 public function testClientUsesDefaultAdapterWhenNoneIsSet()
62 {
63 $client = new Client();
64 if (!extension_loaded('curl')) {
65 $adapter = 'GuzzleHttp\Adapter\StreamAdapter';
66 } elseif (ini_get('allow_url_fopen')) {
67 $adapter = 'GuzzleHttp\Adapter\StreamingProxyAdapter';
68 } else {
69 $adapter = 'GuzzleHttp\Adapter\Curl\CurlAdapter';
70 }
71 $this->assertInstanceOf($adapter, $this->readAttribute($client, 'adapter'));
72 }
73  
74 /**
75 * @expectedException \Exception
76 * @expectedExceptionMessage Foo
77 */
78 public function testCanSpecifyAdapter()
79 {
80 $adapter = $this->getMockBuilder('GuzzleHttp\Adapter\AdapterInterface')
81 ->setMethods(['send'])
82 ->getMockForAbstractClass();
83 $adapter->expects($this->once())
84 ->method('send')
85 ->will($this->throwException(new \Exception('Foo')));
86 $client = new Client(['adapter' => $adapter]);
87 $client->get('http://httpbin.org');
88 }
89  
90 /**
91 * @expectedException \Exception
92 * @expectedExceptionMessage Foo
93 */
94 public function testCanSpecifyMessageFactory()
95 {
96 $factory = $this->getMockBuilder('GuzzleHttp\Message\MessageFactoryInterface')
97 ->setMethods(['createRequest'])
98 ->getMockForAbstractClass();
99 $factory->expects($this->once())
100 ->method('createRequest')
101 ->will($this->throwException(new \Exception('Foo')));
102 $client = new Client(['message_factory' => $factory]);
103 $client->get();
104 }
105  
106 public function testCanSpecifyEmitter()
107 {
108 $emitter = $this->getMockBuilder('GuzzleHttp\Event\EmitterInterface')
109 ->setMethods(['listeners'])
110 ->getMockForAbstractClass();
111 $emitter->expects($this->once())
112 ->method('listeners')
113 ->will($this->returnValue('foo'));
114  
115 $client = new Client(['emitter' => $emitter]);
116 $this->assertEquals('foo', $client->getEmitter()->listeners());
117 }
118  
119 public function testAddsDefaultUserAgentHeaderWithDefaultOptions()
120 {
121 $client = new Client(['defaults' => ['allow_redirects' => false]]);
122 $this->assertFalse($client->getDefaultOption('allow_redirects'));
123 $this->assertEquals(
124 ['User-Agent' => Client::getDefaultUserAgent()],
125 $client->getDefaultOption('headers')
126 );
127 }
128  
129 public function testAddsDefaultUserAgentHeaderWithoutDefaultOptions()
130 {
131 $client = new Client();
132 $this->assertEquals(
133 ['User-Agent' => Client::getDefaultUserAgent()],
134 $client->getDefaultOption('headers')
135 );
136 }
137  
138 private function getRequestClient()
139 {
140 $client = $this->getMockBuilder('GuzzleHttp\Client')
141 ->setMethods(['send'])
142 ->getMock();
143 $client->expects($this->once())
144 ->method('send')
145 ->will($this->returnArgument(0));
146  
147 return $client;
148 }
149  
150 public function requestMethodProvider()
151 {
152 return [
153 ['GET', false],
154 ['HEAD', false],
155 ['DELETE', false],
156 ['OPTIONS', false],
157 ['POST', 'foo'],
158 ['PUT', 'foo'],
159 ['PATCH', 'foo']
160 ];
161 }
162  
163 /**
164 * @dataProvider requestMethodProvider
165 */
166 public function testClientProvidesMethodShortcut($method, $body)
167 {
168 $client = $this->getRequestClient();
169 if ($body) {
170 $request = $client->{$method}('http://foo.com', [
171 'headers' => ['X-Baz' => 'Bar'],
172 'body' => $body,
173 'query' => ['a' => 'b']
174 ]);
175 } else {
176 $request = $client->{$method}('http://foo.com', [
177 'headers' => ['X-Baz' => 'Bar'],
178 'query' => ['a' => 'b']
179 ]);
180 }
181 $this->assertEquals($method, $request->getMethod());
182 $this->assertEquals('Bar', $request->getHeader('X-Baz'));
183 $this->assertEquals('a=b', $request->getQuery());
184 if ($body) {
185 $this->assertEquals($body, $request->getBody());
186 }
187 }
188  
189 public function testClientMergesDefaultOptionsWithRequestOptions()
190 {
191 $f = $this->getMockBuilder('GuzzleHttp\Message\MessageFactoryInterface')
192 ->setMethods(array('createRequest'))
193 ->getMockForAbstractClass();
194  
195 $o = null;
196 // Intercept the creation
197 $f->expects($this->once())
198 ->method('createRequest')
199 ->will($this->returnCallback(
200 function ($method, $url, array $options = []) use (&$o) {
201 $o = $options;
202 return (new MessageFactory())->createRequest($method, $url, $options);
203 }
204 ));
205  
206 $client = new Client([
207 'message_factory' => $f,
208 'defaults' => [
209 'headers' => ['Foo' => 'Bar'],
210 'query' => ['baz' => 'bam'],
211 'exceptions' => false
212 ]
213 ]);
214  
215 $request = $client->createRequest('GET', 'http://foo.com?a=b', [
216 'headers' => ['Hi' => 'there', '1' => 'one'],
217 'allow_redirects' => false,
218 'query' => ['t' => 1]
219 ]);
220  
221 $this->assertFalse($o['allow_redirects']);
222 $this->assertFalse($o['exceptions']);
223 $this->assertEquals('Bar', $request->getHeader('Foo'));
224 $this->assertEquals('there', $request->getHeader('Hi'));
225 $this->assertEquals('one', $request->getHeader('1'));
226 $this->assertEquals('a=b&baz=bam&t=1', $request->getQuery());
227 }
228  
229 public function testClientMergesDefaultHeadersCaseInsensitively()
230 {
231 $client = new Client(['defaults' => ['headers' => ['Foo' => 'Bar']]]);
232 $request = $client->createRequest('GET', 'http://foo.com?a=b', [
233 'headers' => ['foo' => 'custom', 'user-agent' => 'test']
234 ]);
235 $this->assertEquals('test', $request->getHeader('User-Agent'));
236 $this->assertEquals('custom', $request->getHeader('Foo'));
237 }
238  
239 public function testUsesBaseUrlWhenNoUrlIsSet()
240 {
241 $client = new Client(['base_url' => 'http://www.foo.com/baz?bam=bar']);
242 $this->assertEquals(
243 'http://www.foo.com/baz?bam=bar',
244 $client->createRequest('GET')->getUrl()
245 );
246 }
247  
248 public function testUsesBaseUrlCombinedWithProvidedUrl()
249 {
250 $client = new Client(['base_url' => 'http://www.foo.com/baz?bam=bar']);
251 $this->assertEquals(
252 'http://www.foo.com/bar/bam',
253 $client->createRequest('GET', 'bar/bam')->getUrl()
254 );
255 }
256  
257 public function testUsesBaseUrlCombinedWithProvidedUrlViaUriTemplate()
258 {
259 $client = new Client(['base_url' => 'http://www.foo.com/baz?bam=bar']);
260 $this->assertEquals(
261 'http://www.foo.com/bar/123',
262 $client->createRequest('GET', ['bar/{bam}', ['bam' => '123']])->getUrl()
263 );
264 }
265  
266 public function testSettingAbsoluteUrlOverridesBaseUrl()
267 {
268 $client = new Client(['base_url' => 'http://www.foo.com/baz?bam=bar']);
269 $this->assertEquals(
270 'http://www.foo.com/foo',
271 $client->createRequest('GET', '/foo')->getUrl()
272 );
273 }
274  
275 public function testSettingAbsoluteUriTemplateOverridesBaseUrl()
276 {
277 $client = new Client(['base_url' => 'http://www.foo.com/baz?bam=bar']);
278 $this->assertEquals(
279 'http://goo.com/1',
280 $client->createRequest(
281 'GET',
282 ['http://goo.com/{bar}', ['bar' => '1']]
283 )->getUrl()
284 );
285 }
286  
287 public function testCanSetRelativeUrlStartingWithHttp()
288 {
289 $client = new Client(['base_url' => 'http://www.foo.com']);
290 $this->assertEquals(
291 'http://www.foo.com/httpfoo',
292 $client->createRequest('GET', 'httpfoo')->getUrl()
293 );
294 }
295  
296 public function testClientSendsRequests()
297 {
298 $response = new Response(200);
299 $adapter = new MockAdapter();
300 $adapter->setResponse($response);
301 $client = new Client(['adapter' => $adapter]);
302 $this->assertSame($response, $client->get('http://test.com'));
303 $this->assertEquals('http://test.com', $response->getEffectiveUrl());
304 }
305  
306 public function testSendingRequestCanBeIntercepted()
307 {
308 $response = new Response(200);
309 $response2 = new Response(200);
310 $adapter = new MockAdapter();
311 $adapter->setResponse($response);
312 $client = new Client(['adapter' => $adapter]);
313 $client->getEmitter()->on(
314 'before',
315 function (BeforeEvent $e) use ($response2) {
316 $e->intercept($response2);
317 }
318 );
319 $this->assertSame($response2, $client->get('http://test.com'));
320 $this->assertEquals('http://test.com', $response2->getEffectiveUrl());
321 }
322  
323 /**
324 * @expectedException \GuzzleHttp\Exception\RequestException
325 * @expectedExceptionMessage No response
326 */
327 public function testEnsuresResponseIsPresentAfterSending()
328 {
329 $adapter = $this->getMockBuilder('GuzzleHttp\Adapter\MockAdapter')
330 ->setMethods(['send'])
331 ->getMock();
332 $adapter->expects($this->once())
333 ->method('send');
334 $client = new Client(['adapter' => $adapter]);
335 $client->get('http://httpbin.org');
336 }
337  
338 public function testClientHandlesErrorsDuringBeforeSend()
339 {
340 $client = new Client();
341 $client->getEmitter()->on('before', function ($e) {
342 throw new \Exception('foo');
343 });
344 $client->getEmitter()->on('error', function ($e) {
345 $e->intercept(new Response(200));
346 });
347 $this->assertEquals(200, $client->get('http://test.com')->getStatusCode());
348 }
349  
350 /**
351 * @expectedException \GuzzleHttp\Exception\RequestException
352 * @expectedExceptionMessage foo
353 */
354 public function testClientHandlesErrorsDuringBeforeSendAndThrowsIfUnhandled()
355 {
356 $client = new Client();
357 $client->getEmitter()->on('before', function ($e) {
358 throw new RequestException('foo', $e->getRequest());
359 });
360 $client->get('http://httpbin.org');
361 }
362  
363 /**
364 * @expectedException \GuzzleHttp\Exception\RequestException
365 * @expectedExceptionMessage foo
366 */
367 public function testClientWrapsExceptions()
368 {
369 $client = new Client();
370 $client->getEmitter()->on('before', function ($e) {
371 throw new \Exception('foo');
372 });
373 $client->get('http://httpbin.org');
374 }
375  
376 public function testCanSetDefaultValues()
377 {
378 $client = new Client(['foo' => 'bar']);
379 $client->setDefaultOption('headers/foo', 'bar');
380 $this->assertNull($client->getDefaultOption('foo'));
381 $this->assertEquals('bar', $client->getDefaultOption('headers/foo'));
382 }
383  
384 public function testSendsAllInParallel()
385 {
386 $client = new Client();
387 $client->getEmitter()->attach(new Mock([
388 new Response(200),
389 new Response(201),
390 new Response(202),
391 ]));
392 $history = new History();
393 $client->getEmitter()->attach($history);
394  
395 $requests = [
396 $client->createRequest('GET', 'http://test.com'),
397 $client->createRequest('POST', 'http://test.com'),
398 $client->createRequest('PUT', 'http://test.com')
399 ];
400  
401 $client->sendAll($requests);
402 $requests = array_map(function ($r) { return $r->getMethod(); }, $history->getRequests());
403 $this->assertContains('GET', $requests);
404 $this->assertContains('POST', $requests);
405 $this->assertContains('PUT', $requests);
406 }
407  
408 public function testCanSetCustomParallelAdapter()
409 {
410 $called = false;
411 $pa = new FakeParallelAdapter(new MockAdapter(function () use (&$called) {
412 $called = true;
413 return new Response(203);
414 }));
415 $client = new Client(['parallel_adapter' => $pa]);
416 $client->sendAll([$client->createRequest('GET', 'http://www.foo.com')]);
417 $this->assertTrue($called);
418 }
419  
420 public function testCanDisableAuthPerRequest()
421 {
422 $client = new Client(['defaults' => ['auth' => 'foo']]);
423 $request = $client->createRequest('GET', 'http://test.com');
424 $this->assertEquals('foo', $request->getConfig()['auth']);
425 $request = $client->createRequest('GET', 'http://test.com', ['auth' => null]);
426 $this->assertFalse($request->getConfig()->hasKey('auth'));
427 }
428  
429 /**
430 * @expectedException \PHPUnit_Framework_Error_Deprecated
431 */
432 public function testHasDeprecatedGetEmitter()
433 {
434 $client = new Client();
435 $client->getEventDispatcher();
436 }
437  
438 public function testUsesProxyEnvironmentVariables()
439 {
440 $client = new Client();
441 $this->assertNull($client->getDefaultOption('proxy'));
442  
443 putenv('HTTP_PROXY=127.0.0.1');
444 $client = new Client();
445 $this->assertEquals(
446 ['http' => '127.0.0.1'],
447 $client->getDefaultOption('proxy')
448 );
449  
450 putenv('HTTPS_PROXY=127.0.0.2');
451 $client = new Client();
452 $this->assertEquals(
453 ['http' => '127.0.0.1', 'https' => '127.0.0.2'],
454 $client->getDefaultOption('proxy')
455 );
456  
457 putenv('HTTP_PROXY=');
458 putenv('HTTPS_PROXY=');
459 }
460 }