Passed
Push — master ( 145379...16ef67 )
by Marcelo
06:15
created

JsonTest::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
3
namespace BrofistTest\ApiClient;
4
5
use Brofist\ApiClient\Exception;
6
use Brofist\ApiClient\Json;
7
use Brofist\ApiClient\JsonInterface;
8
use GuzzleHttp\Client as HttpClient;
9
use GuzzleHttp\Exception\RequestException;
10
use GuzzleHttp\Psr7\Request;
11
use PHPUnit_Framework_TestCase;
12
use Psr\Http\Message\RequestInterface;
13
use Psr\Http\Message\ResponseInterface;
14
15
/**
16
 * @SuppressWarnings(PHPMD)
17
 */
18
class JsonTest extends PHPUnit_Framework_TestCase
19
{
20
    /** @var Json */
21
    protected $client;
22
23
    /** @var HttpClient | \Prophecy\Prophecy\ObjectProphecy */
24
    protected $mockClient;
25
26
    /**
27
     * @before
28
     */
29
    public function initialize()
30
    {
31
        $this->setClient();
32
    }
33
34
    /**
35
     * @test
36
     * @expectedException \InvalidArgumentException
37
     * @expectedExceptionMessage Endpoint not set
38
     */
39
    public function throwsExceptionWhenNoEndpointIsGiven()
40
    {
41
        new Json();
42
    }
43
44
    /**
45
     * @test
46
     */
47
    public function implementsTheCorrectInterface()
48
    {
49
        $this->assertInstanceOf(JsonInterface::class, $this->client);
50
    }
51
52
    /**
53
     * @test
54
     */
55
    public function canMutateEndpoint()
56
    {
57
        $this->client = new Json(['endpoint' => 'https://test.foo.bar/v3/']);
58
        $this->assertEquals('https://test.foo.bar/v3', $this->client->getEndpoint());
59
    }
60
61
    /**
62
     * @test
63
     */
64 View Code Duplication
    public function canMakeGetRequests()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
65
    {
66
        $query = ['foo' => 'bar'];
67
68
        $this->mockClient()->request(
69
            'GET',
70
            $this->url('/foo'),
71
            [
72
                'query' => $query,
73
            ]
74
        )->willReturn($this->fooBarResponse());
75
76
        $data = $this->client->get('/foo', $query);
77
78
        $this->assertFooBarResponse($data);
79
    }
80
81
    /**
82
     * @test
83
     */
84 View Code Duplication
    public function canMakeGetRequestsWithAuthentication()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
85
    {
86
        $this->setClient(['authToken' => 'myToken']);
87
88
        $query = ['foo' => 'bar'];
89
90
        $this->mockClient()->request(
91
            'GET',
92
            $this->url('/foo'),
93
            [
94
                'auth'  => ['myToken', ''],
95
                'query' => $query,
96
            ]
97
        )->willReturn($this->fooBarResponse());
98
99
        $data = $this->client->get('/foo', $query);
100
101
        $this->assertFooBarResponse($data);
102
    }
103
104
    /**
105
     * @test
106
     */
107 View Code Duplication
    public function canMakeGetRequestsWithBasicAuthentication()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
    {
109
        $this->setClient(['basicAuth' => ['username', 'password']]);
110
111
        $query = ['foo' => 'bar'];
112
113
        $this->mockClient()->request(
114
            'GET',
115
            $this->url('/foo'),
116
            [
117
                'auth'  => ['username', 'password'],
118
                'query' => $query,
119
            ]
120
        )->willReturn($this->fooBarResponse());
121
122
        $data = $this->client->get('/foo', $query);
123
124
        $this->assertFooBarResponse($data);
125
    }
126
127
    /**
128
     * @test
129
     */
130 View Code Duplication
    public function canMakePostRequests()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
    {
132
        $postData = ['foo' => 'bar'];
133
134
        $this->mockClient()->request(
135
            'POST',
136
            $this->url('/foo'),
137
            [
138
                'form_params' => $postData,
139
            ]
140
        )->willReturn($this->fooBarResponse());
141
142
        $data = $this->client->post('/foo', $postData);
143
144
        $this->assertFooBarResponse($data);
145
    }
146
147
    /**
148
     * @test
149
     */
150 View Code Duplication
    public function canMakePutRequest()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
    {
152
        $putData = ['foo' => 'bar'];
153
154
        $this->mockClient()->request(
155
            'PUT',
156
            $this->url('/foo'),
157
            [
158
                'json' => $putData,
159
            ]
160
        )->willReturn($this->fooBarResponse());
161
162
        $data = $this->client->put('/foo', $putData);
163
164
        $this->assertFooBarResponse($data);
165
    }
166
167
    /**
168
     * @test
169
     * @expectedException \BadMethodCallException
170
     */
171
    public function deleteIsNotImplemented()
172
    {
173
        $this->client->delete('endpoint');
174
    }
175
176
    /**
177
     * @test
178
     * @expectedException \BadMethodCallException
179
     */
180
    public function patchIsNotImplemented()
181
    {
182
        $this->client->patch('endpoint');
183
    }
184
185
    /**
186
     * @test
187
     */
188
    public function convertsGuzzleResponseExceptionsIntoFriendlyClientExceptions()
189
    {
190
        $request = $this->prophesize(RequestInterface::class);
191
        $response = $this->getMockResponse(['message' => 'theMessage']);
192
        $response->getStatusCode()->willReturn(200);
193
194
        $originalException = new RequestException(
195
            'exception message',
196
            $request->reveal(),
197
            $response->reveal()
198
        );
199
200
        $this->mockClient()
201
            ->request('GET', $this->url('/foo'), ['query' => []])
202
            ->willThrow($originalException);
203
204
        try {
205
            $this->client->get('/foo');
206
            $this->fail('Should have thrown exception');
207
        } catch (\Exception $e) {
208
            $this->assertInstanceOf(Exception::class, $e);
209
            $this->assertEquals('theMessage', $e->getMessage());
210
            $this->assertSame($originalException, $e->getPrevious());
211
        }
212
    }
213
214
    /**
215
     * @test
216
     * @expectedException \Brofist\ApiClient\InvalidJsonResponseBodyException
217
     */
218
    public function throwsInvalidJsonResponse()
219
    {
220
        $this->mockClient()->request('GET', $this->url('/foo'), ['query' => []])
221
            ->willReturn($this->mockResponseBody('invalid')->reveal());
222
223
        $this->client->get('/foo');
224
    }
225
226
    /**
227
     * @return \Prophecy\Prophecy\ObjectProphecy
228
     */
229
    private function mockClient()
230
    {
231
        if ($this->mockClient === null) {
232
            $this->mockClient = $this->prophesize(HttpClient::class);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->prophesize(\GuzzleHttp\Client::class) of type object<Prophecy\Prophecy\ObjectProphecy> is incompatible with the declared type object<GuzzleHttp\Client> of property $mockClient.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
233
        }
234
235
        return $this->mockClient;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->mockClient; of type Prophecy\Prophecy\ObjectProphecy|GuzzleHttp\Client adds the type GuzzleHttp\Client to the return on line 235 which is incompatible with the return type documented by BrofistTest\ApiClient\JsonTest::mockClient of type Prophecy\Prophecy\ObjectProphecy.
Loading history...
236
    }
237
238
    /**
239
     * @param string $path
240
     *
241
     * @return string
242
     */
243
    private function url($path = '/')
244
    {
245
        return 'https://endpoint/v1' . $path;
246
    }
247
248
    private function fooBarResponse()
249
    {
250
        return $this->mockResponseBody('{"foo":"bar"}')->reveal();
251
    }
252
253
    private function mockResponseBody($responseBody)
254
    {
255
        $response = $this->prophesize(ResponseInterface::class);
256
        $response->getBody()->willReturn($responseBody);
257
258
        return $response;
259
    }
260
261
    private function getMockResponse(array $data = [])
262
    {
263
        return $this->mockResponseBody(json_encode($data));
264
    }
265
266
    /**
267
     * @param array $data
268
     */
269
    private function assertFooBarResponse($data)
270
    {
271
        $this->assertEquals(['foo' => 'bar'], $data);
272
    }
273
274
    private function setClient(array $params = [])
275
    {
276
        $default = [
277
            'endpoint'   => 'https://endpoint/v1/',
278
            'httpClient' => $this->mockClient()->reveal(),
279
        ];
280
        $this->client = new Json(array_merge($default, $params));
281
    }
282
}
283