1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace IBM\Watson\Common\Tests; |
5
|
|
|
|
6
|
|
|
use GuzzleHttp\Client; |
7
|
|
|
use GuzzleHttp\Handler\MockHandler; |
8
|
|
|
use GuzzleHttp\HandlerStack; |
9
|
|
|
use GuzzleHttp\Middleware; |
10
|
|
|
use GuzzleHttp\Psr7\Response; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class TestCase |
14
|
|
|
* @package IBM\Watson\Common\Tests |
15
|
|
|
*/ |
16
|
|
|
abstract class TestCase extends \PHPUnit_Framework_TestCase |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var \GuzzleHttp\Client |
20
|
|
|
*/ |
21
|
|
|
private $httpClient; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param string $path Mock response file |
25
|
|
|
* @param int $code Response code |
26
|
|
|
* @return Response |
27
|
|
|
*/ |
28
|
|
|
public function getMockHttpResponse($path, $code = 200) |
29
|
|
|
{ |
30
|
|
|
if ($path instanceof Response) { |
31
|
|
|
return $path; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$ref = new \ReflectionObject($this); |
35
|
|
|
$dir = dirname($ref->getFileName()); |
36
|
|
|
|
37
|
|
|
// if mock file doesn't exist, check parent directory |
38
|
|
|
if (!file_exists($dir . '/Mock/' . $path) && file_exists($dir . '/../Mock/' . $path)) { |
39
|
|
|
return new Response($code, [], file_get_contents($dir . '/../Mock/' . $path)); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return new Response($code, [], file_get_contents($dir . '/Mock/' . $path)); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Get a mock HTTP client with history and mock responses |
47
|
|
|
* |
48
|
|
|
* @param mixed $container Responses container |
49
|
|
|
* @param $responses |
50
|
|
|
* @return Client |
51
|
|
|
*/ |
52
|
|
|
public function getMockHttpClientWithHistoryAndResponses(&$container, $responses) |
53
|
|
|
{ |
54
|
|
|
$mock = new MockHandler($responses); |
55
|
|
|
|
56
|
|
|
$stack = HandlerStack::create($mock); |
57
|
|
|
$history = Middleware::history($container); |
58
|
|
|
$stack->push($history); |
59
|
|
|
|
60
|
|
|
return new Client(['handler' => $stack]); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Get HTTP client |
65
|
|
|
* |
66
|
|
|
* @return Client |
67
|
|
|
*/ |
68
|
|
|
public function getHttpClient() |
69
|
|
|
{ |
70
|
|
|
if (null === $this->httpClient) { |
71
|
|
|
$this->httpClient = new Client; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $this->httpClient; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|