Completed
Push — master ( 16ef67...a8e8f2 )
by Marcelo
02:33
created

JsonTest::assertFooBarResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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 View Code Duplication
    public function canResolvePathWithNonLeadingSlash()
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...
56
    {
57
        $query = ['foo' => 'bar'];
58
59
        $this->mockClient()
60
            ->request(
61
                'GET',
62
                $this->url('/foo'),
63
                ['query' => $query]
64
            )
65
            ->willReturn($this->fooBarResponse());
66
67
        $data = $this->client->get('foo', $query);
68
69
        $this->assertFooBarResponse($data);
70
    }
71
72
73
    /**
74
     * @test
75
     */
76
    public function canMutateEndpoint()
77
    {
78
        $this->client = new Json(['endpoint' => 'https://test.foo.bar/v3/']);
79
        $this->assertEquals('https://test.foo.bar/v3', $this->client->getEndpoint());
80
    }
81
82
    /**
83
     * @test
84
     */
85 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...
86
    {
87
        $query = ['foo' => 'bar'];
88
89
        $this->mockClient()->request(
90
            'GET',
91
            $this->url('/foo'),
92
            [
93
                'query' => $query,
94
            ]
95
        )->willReturn($this->fooBarResponse());
96
97
        $data = $this->client->get('/foo', $query);
98
99
        $this->assertFooBarResponse($data);
100
    }
101
102
    /**
103
     * @test
104
     */
105 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...
106
    {
107
        $this->setClient(['authToken' => 'myToken']);
108
109
        $query = ['foo' => 'bar'];
110
111
        $this->mockClient()->request(
112
            'GET',
113
            $this->url('/foo'),
114
            [
115
                'auth'  => ['myToken', ''],
116
                'query' => $query,
117
            ]
118
        )->willReturn($this->fooBarResponse());
119
120
        $data = $this->client->get('/foo', $query);
121
122
        $this->assertFooBarResponse($data);
123
    }
124
125
    /**
126
     * @test
127
     */
128 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...
129
    {
130
        $this->setClient(['basicAuth' => ['username', 'password']]);
131
132
        $query = ['foo' => 'bar'];
133
134
        $this->mockClient()->request(
135
            'GET',
136
            $this->url('/foo'),
137
            [
138
                'auth'  => ['username', 'password'],
139
                'query' => $query,
140
            ]
141
        )->willReturn($this->fooBarResponse());
142
143
        $data = $this->client->get('/foo', $query);
144
145
        $this->assertFooBarResponse($data);
146
    }
147
148
    /**
149
     * @test
150
     */
151 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...
152
    {
153
        $postData = ['foo' => 'bar'];
154
155
        $this->mockClient()->request(
156
            'POST',
157
            $this->url('/foo'),
158
            [
159
                'form_params' => $postData,
160
            ]
161
        )->willReturn($this->fooBarResponse());
162
163
        $data = $this->client->post('/foo', $postData);
164
165
        $this->assertFooBarResponse($data);
166
    }
167
168
    /**
169
     * @test
170
     */
171 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...
172
    {
173
        $putData = ['foo' => 'bar'];
174
175
        $this->mockClient()->request(
176
            'PUT',
177
            $this->url('/foo'),
178
            [
179
                'json' => $putData,
180
            ]
181
        )->willReturn($this->fooBarResponse());
182
183
        $data = $this->client->put('/foo', $putData);
184
185
        $this->assertFooBarResponse($data);
186
    }
187
188
    /**
189
     * @test
190
     * @expectedException \BadMethodCallException
191
     */
192
    public function deleteIsNotImplemented()
193
    {
194
        $this->client->delete('endpoint');
195
    }
196
197
    /**
198
     * @test
199
     * @expectedException \BadMethodCallException
200
     */
201
    public function patchIsNotImplemented()
202
    {
203
        $this->client->patch('endpoint');
204
    }
205
206
    /**
207
     * @test
208
     */
209
    public function convertsGuzzleResponseExceptionsIntoFriendlyClientExceptions()
210
    {
211
        $request = $this->prophesize(RequestInterface::class);
212
        $response = $this->getMockResponse(['message' => 'theMessage']);
213
        $response->getStatusCode()->willReturn(200);
214
215
        $originalException = new RequestException(
216
            'exception message',
217
            $request->reveal(),
218
            $response->reveal()
219
        );
220
221
        $this->mockClient()
222
            ->request('GET', $this->url('/foo'), ['query' => []])
223
            ->willThrow($originalException);
224
225
        try {
226
            $this->client->get('/foo');
227
            $this->fail('Should have thrown exception');
228
        } catch (\Exception $e) {
229
            $this->assertInstanceOf(Exception::class, $e);
230
            $this->assertEquals('theMessage', $e->getMessage());
231
            $this->assertSame($originalException, $e->getPrevious());
232
        }
233
    }
234
235
    /**
236
     * @test
237
     * @expectedException \Brofist\ApiClient\InvalidJsonResponseBodyException
238
     */
239
    public function throwsInvalidJsonResponse()
240
    {
241
        $this->mockClient()->request('GET', $this->url('/foo'), ['query' => []])
242
            ->willReturn($this->mockResponseBody('invalid')->reveal());
243
244
        $this->client->get('/foo');
245
    }
246
247
    /**
248
     * @return \Prophecy\Prophecy\ObjectProphecy
249
     */
250
    private function mockClient()
251
    {
252
        if ($this->mockClient === null) {
253
            $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...
254
        }
255
256
        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 256 which is incompatible with the return type documented by BrofistTest\ApiClient\JsonTest::mockClient of type Prophecy\Prophecy\ObjectProphecy.
Loading history...
257
    }
258
259
    /**
260
     * @param string $path
261
     *
262
     * @return string
263
     */
264
    private function url($path = '/')
265
    {
266
        return 'https://endpoint/v1' . $path;
267
    }
268
269
    private function fooBarResponse()
270
    {
271
        return $this->mockResponseBody('{"foo":"bar"}')->reveal();
272
    }
273
274
    private function mockResponseBody($responseBody)
275
    {
276
        $response = $this->prophesize(ResponseInterface::class);
277
        $response->getBody()->willReturn($responseBody);
278
279
        return $response;
280
    }
281
282
    private function getMockResponse(array $data = [])
283
    {
284
        return $this->mockResponseBody(json_encode($data));
285
    }
286
287
    /**
288
     * @param array $data
289
     */
290
    private function assertFooBarResponse($data)
291
    {
292
        $this->assertEquals(['foo' => 'bar'], $data);
293
    }
294
295
    private function setClient(array $params = [])
296
    {
297
        $default = [
298
            'endpoint'   => 'https://endpoint/v1/',
299
            'httpClient' => $this->mockClient()->reveal(),
300
        ];
301
        $this->client = new Json(array_merge($default, $params));
302
    }
303
}
304