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