/
StaticTest.php
659 lines (573 loc) · 19.5 KB
/
StaticTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
<?php
/**
* @see https://github.com/laminas/laminas-http for the canonical source repository
* @copyright https://github.com/laminas/laminas-http/blob/master/COPYRIGHT.md
* @license https://github.com/laminas/laminas-http/blob/master/LICENSE.md New BSD License
*/
namespace LaminasTest\Http\Client;
use Laminas\Config\Config;
use Laminas\Http\Client\Adapter\Exception as ClientAdapterException;
use Laminas\Http\Client\Adapter\Test;
use Laminas\Http\Client as HTTPClient;
use Laminas\Http\Client\Exception as ClientException;
use Laminas\Http\Exception\InvalidArgumentException;
use Laminas\Http\Exception\RuntimeException;
use Laminas\Http\Header\SetCookie;
use Laminas\Uri\Http as UriHttp;
use LaminasTest\Http\Client\TestAsset\MockAdapter;
use LaminasTest\Http\Client\TestAsset\MockClient;
use PHPUnit\Framework\TestCase;
use stdClass;
/**
* This Testsuite includes all Laminas_Http_Client tests that do not rely
* on performing actual requests to an HTTP server. These tests can be
* executed once, and do not need to be tested with different servers /
* client setups.
*
* @group Laminas_Http
* @group Laminas_Http_Client
*/
class StaticTest extends TestCase
{
// @codingStandardsIgnoreStart
/**
* Common HTTP client
*
* @var HTTPClient
*/
protected $_client;
// @codingStandardsIgnoreEnd
/**
* Set up the test suite before each test
*/
public function setUp(): void
{
$this->_client = new MockClient('http://www.example.com');
}
/**
* Clean up after running a test
*/
public function tearDown(): void
{
$this->_client = null;
}
/**
* URI Tests
*/
/**
* Test we can SET and GET a URI as string
*/
public function testSetGetUriString()
{
$uristr = 'https://www.zend.com:80/';
$this->_client->setUri($uristr);
$uri = $this->_client->getUri();
$this->assertInstanceOf(UriHttp::class, $uri, 'Returned value is not a Uri object as expected');
$this->assertEquals($uri->__toString(), $uristr, 'Returned Uri object does not hold the expected URI');
$uri = $this->_client->getUri()->toString();
$this->assertIsString(
$uri,
'Returned value expected to be a string, ' . gettype($uri) . ' returned'
);
$this->assertEquals($uri, $uristr, 'Returned string is not the expected URI');
}
/**
* Test we can SET and GET a URI as object
*/
public function testSetGetUriObject()
{
$uriobj = new UriHttp('https://www.zend.com:80/');
$this->_client->setUri($uriobj);
$uri = $this->_client->getUri();
$this->assertInstanceOf(UriHttp::class, $uri, 'Returned value is not a Uri object as expected');
$this->assertEquals($uri, $uriobj, 'Returned object is not the excepted Uri object');
}
/**
* Test that setting the same parameter twice in the query string does not
* get reduced to a single value only.
*/
public function testDoubleGetParameter()
{
$qstr = 'foo=bar&foo=baz';
$this->_client->setUri('http://example.com/test/?' . $qstr);
$this->_client->setAdapter(Test::class);
$this->_client->setMethod('GET');
$this->_client->send();
$this->assertStringContainsString(
$qstr,
$this->_client->getLastRawRequest(),
'Request is expected to contain the entire query string'
);
}
/**
* Header Tests
*/
/**
* Test we can get already set headers
*/
public function testGetHeader()
{
$this->_client->setHeaders([
'Accept-encoding' => 'gzip,deflate',
'Accept-language' => 'en,de,*',
]);
$this->assertEquals(
$this->_client->getHeader('Accept-encoding'),
'gzip, deflate',
'Returned value of header is not as expected'
);
$this->assertEquals(
$this->_client->getHeader('X-Fake-Header'),
null,
'Non-existing header should not return a value'
);
}
/**
* Authentication tests
*/
/**
* Test setAuth (dynamic method) fails when trying to use an unsupported
* authentication scheme
*/
public function testExceptUnsupportedAuthDynamic()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid or not supported authentication type: \'SuperStrongAlgo\'');
$this->_client->setAuth('shahar', '1234', 'SuperStrongAlgo');
}
/**
* Cookie and Cookie Jar tests
*/
/**
* Test we can properly set a new cookies
*/
public function testSetNewCookies()
{
$this->_client->addCookie('cookie', 'value');
$this->_client->addCookie('chocolate', 'chips');
$cookies = $this->_client->getCookies();
// Check we got the right cookiejar
$this->assertIsArray($cookies);
$this->assertContainsOnlyInstancesOf(SetCookie::class, $cookies);
$this->assertCount(2, $cookies);
}
/**
* Test we can unset a cookie jar
*/
public function testUnsetCookies()
{
// Set the cookie jar just like in testSetNewCookieJar
$this->_client->addCookie('cookie', 'value');
$this->_client->addCookie('chocolate', 'chips');
$cookies = $this->_client->getCookies();
// Try unsetting the cookies
$this->_client->clearCookies();
$cookies = $this->_client->getCookies();
$this->assertEquals([], $cookies, 'Cookies are expected to be an empty array but it is not');
}
/**
* Make sure using an invalid cookie jar object throws an exception
*/
public function testSetInvalidCookies()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid parameter type passed as Cookie');
$this->_client->addCookie('cookie');
}
/**
* Configuration Handling
*/
/**
* Test that we can set a valid configuration array with some options
*/
public function testConfigSetAsArray()
{
$config = [
'timeout' => 500,
'someoption' => 'hasvalue',
];
$this->_client->setOptions($config);
$hasConfig = $this->_client->config;
foreach ($config as $k => $v) {
$this->assertEquals($v, $hasConfig[$k]);
}
}
/**
* Test that a Laminas_Config object can be used to set configuration
*
* @link https://getlaminas.org/issues/browse/Laminas-5577
*/
public function testConfigSetAsLaminasConfig()
{
$config = new Config([
'timeout' => 400,
'nested' => [
'item' => 'value',
],
]);
$this->_client->setOptions($config);
$hasConfig = $this->_client->config;
$this->assertEquals($config->timeout, $hasConfig['timeout']);
$this->assertEquals($config->nested->item, $hasConfig['nested']['item']);
}
/**
* Test that passing invalid variables to setConfig() causes an exception
*
* @dataProvider invalidConfigProvider
*
* @param mixed $config
*/
public function testConfigSetInvalid($config)
{
$this->expectException(ClientException\InvalidArgumentException::class);
$this->expectExceptionMessage('Config parameter is not valid');
$this->_client->setOptions($config);
}
/**
* Test that configuration options are passed to the adapter after the
* adapter is instantiated
*
* @group Laminas-4557
*/
public function testConfigPassToAdapterLaminas4557()
{
$adapter = new MockAdapter();
// test that config passes when we set the adapter
$this->_client->setOptions(['param' => 'value1']);
$this->_client->setAdapter($adapter);
$adapterCfg = $adapter->config;
$this->assertEquals('value1', $adapterCfg['param']);
// test that adapter config value changes when we set client config
$this->_client->setOptions(['param' => 'value2']);
$adapterCfg = $adapter->config;
$this->assertEquals('value2', $adapterCfg['param']);
}
/**
* Other Tests
*/
/**
* Test the getLastRawResponse() method actually returns the last response
*/
public function testGetLastRawResponse()
{
// First, make sure we get null before the request
$this->assertEquals(
null,
$this->_client->getLastRawResponse(),
'getLastRawResponse() is still expected to return null'
);
// Now, test we get a proper response after the request
$this->_client->setUri('http://example.com/foo/bar');
$this->_client->setAdapter(Test::class);
$response = $this->_client->send();
$this->assertSame(
$response,
$this->_client->getResponse(),
'Response is expected to be identical to the result of getResponse()'
);
}
/**
* Test that getLastRawResponse returns null when not storing
*/
public function testGetLastRawResponseWhenNotStoring()
{
// Now, test we get a proper response after the request
$this->_client->setUri('http://example.com/foo/bar');
$this->_client->setAdapter(Test::class);
$this->_client->setOptions(['storeresponse' => false]);
$this->_client->send();
$this->assertNull(
$this->_client->getLastRawResponse(),
'getLastRawResponse is expected to be null when not storing'
);
}
/**
* Check we get an exception when trying to send a POST request with an
* invalid content-type header
*/
public function testInvalidPostContentType()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Cannot handle content type \'x-foo/something-fake\' automatically');
$this->_client->setEncType('x-foo/something-fake');
$this->_client->setParameterPost(['parameter' => 'value']);
$this->_client->setMethod('POST');
// This should throw an exception
$this->_client->send();
}
/**
* Check we get an exception if there's an error in the socket
*/
public function testSocketErrorException()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->expectException(ClientAdapterException\RuntimeException::class);
$this->expectExceptionMessage('Unable to connect to 255.255.255.255:80');
// Try to connect to an invalid host
$this->_client->setUri('http://255.255.255.255');
// Reduce timeout to 3 seconds to avoid waiting
$this->_client->setOptions(['timeout' => 3]);
// This call should cause an exception
$this->_client->send();
}
/**
* Check that an exception is thrown if non-word characters are used in
* the request method.
*
* @dataProvider invalidMethodProvider
*
* @param string $method
*/
public function testSettingInvalidMethodThrowsException($method)
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid HTTP method passed');
$this->_client->setMethod($method);
}
/**
* Test that POST data with multi-dimentional array is properly encoded as
* multipart/form-data
*/
public function testFormDataEncodingWithMultiArrayLaminas7038()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->setAdapter(Test::class);
$this->_client->setUri('http://example.com');
$this->_client->setEncType(HTTPClient::ENC_FORMDATA);
$this->_client->setParameterPost([
'test' => [
'v0.1',
'v0.2',
'k1' => 'v1.0',
'k2' => [
'v2.1',
'k2.1' => 'v2.1.0',
],
],
]);
$this->_client->setMethod('POST');
$this->_client->send();
$expectedLines = file(__DIR__ . '/_files/Laminas7038-multipartarrayrequest.txt');
$gotLines = explode("\n", $this->_client->getLastRawRequest());
$this->assertEquals(count($expectedLines), count($gotLines));
while (($expected = array_shift($expectedLines))
&& ($got = array_shift($gotLines))
) {
$expected = trim($expected);
$got = trim($got);
$this->assertRegExp(sprintf('/^%s$/', $expected), $got);
}
}
/**
* Test that we properly calculate the content-length of multibyte-encoded
* request body
*
* This may file in case that mbstring overloads the substr and strlen
* functions, and the mbstring internal encoding is a multibyte encoding.
*
* @link https://getlaminas.org/issues/browse/Laminas-2098
*/
public function testMultibyteRawPostDataLaminas2098()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->setAdapter(Test::class);
$this->_client->setUri('http://example.com');
$bodyFile = __DIR__ . '/_files/Laminas2098-multibytepostdata.txt';
$this->_client->setRawBody(file_get_contents($bodyFile));
$this->_client->setEncType('text/plain');
$this->_client->setMethod('POST');
$this->_client->send();
$request = $this->_client->getLastRawRequest();
if (! preg_match('/^content-length:\s+(\d+)/mi', $request, $match)) {
$this->fail('Unable to find content-length header in request');
}
$this->assertEquals(filesize($bodyFile), (int) $match[1]);
}
/**
* Testing if the connection isn't closed
*
* @group Laminas-9685
*/
public function testOpenTempStreamWithValidFileDoesntThrowsException()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$url = 'http://www.example.com/';
$config = [
'outputstream' => realpath(__DIR__ . '/_files/laminas_http_client_stream.file'),
];
$client = new HTTPClient($url, $config);
$result = $client->send();
// we can safely return until we can verify link is still active
// @todo verify link is still active
}
/**
* Test if a downloaded file can be deleted
*
* @group Laminas-9685
*/
public function testDownloadedFileCanBeDeleted()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped('Laminas\Http\Client online tests are not enabled');
}
$url = 'http://www.example.com/';
$outputFile = @tempnam(@sys_get_temp_dir(), 'zht');
if (! is_file($outputFile)) {
$this->markTestSkipped('Failed to create a temporary file');
}
$config = [
'outputstream' => $outputFile,
];
$client = new HTTPClient($url, $config);
$result = $client->send();
$this->assertInstanceOf('Laminas\Http\Response\Stream', $result);
if (DIRECTORY_SEPARATOR === '\\') {
$this->assertFalse(@unlink($outputFile), 'Deleting an open file should fail on Windows');
}
fclose($result->getStream());
$this->assertTrue(@unlink($outputFile), 'Failed to delete downloaded file');
}
/**
* Testing if the connection can be closed
*
* @group Laminas-9685
*/
public function testOpenTempStreamWithBogusFileClosesTheConnection()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$url = 'http://www.example.com';
$config = [
'outputstream' => '/path/to/bogus/file.ext',
];
$client = new HTTPClient($url, $config);
$client->setMethod('GET');
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Could not open temp file /path/to/bogus/file.ext');
$client->send();
}
/**
* Test sending cookie with encoded value
*
* @group fix-double-encoding-problem-about-cookie-value
*/
public function testEncodedCookiesInRequestHeaders()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->addCookie('foo', 'bar=baz');
$this->_client->send();
$cookieValue = 'Cookie: foo=' . urlencode('bar=baz');
$this->assertStringContainsString(
$cookieValue,
$this->_client->getLastRawRequest(),
'Request is expected to contain the entire cookie "keyname=encoded_value"'
);
}
/**
* Test sending cookie header with raw value
*
* @group fix-double-encoding-problem-about-cookie-value
*/
public function testRawCookiesInRequestHeaders()
{
if (! getenv('TESTS_LAMINAS_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->setOptions(['encodecookies' => false]);
$this->_client->addCookie('foo', 'bar=baz');
$this->_client->send();
$cookieValue = 'Cookie: foo=bar=baz';
$this->assertStringContainsString(
$cookieValue,
$this->_client->getLastRawRequest(),
'Request is expected to contain the entire cookie "keyname=raw_value"'
);
}
/**
* Data providers
*/
/**
* Data provider of valid non-standard HTTP methods
*
* @return array
*/
public static function validMethodProvider()
{
return [
['OPTIONS'],
['POST'],
['DOSOMETHING'],
['PROPFIND'],
['Some_Characters'],
['X-MS-ENUMATTS'],
];
}
/**
* Data provider of invalid HTTP methods
*
* @return array
*/
public static function invalidMethodProvider()
{
return [
['N@5TYM3T#0D'],
['TWO WORDS'],
['GET http://foo.com/?'],
['Injected' . "\n" . 'newline'],
];
}
/**
* Data provider for invalid configuration containers
*
* @return array
*/
public static function invalidConfigProvider()
{
return [
[false],
['foobar'],
['foo' => 'bar'],
[null],
[new stdClass()],
[55],
];
}
}