Completed
Push — master ( 0abcf2...c12050 )
by Dan Michael O.
03:13
created

ClientSpec::it_can_post_and_parse_JSON()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace spec\Scriptotek\Alma;
4
5
use GuzzleHttp\Psr7\Response;
6
use Http\Client\Common\Exception\ClientErrorException;
7
use Http\Client\Common\Exception\ServerErrorException;
8
use Http\Mock\Client as MockHttp;
9
use PhpSpec\ObjectBehavior;
10
use Scriptotek\Alma\Exception\InvalidApiKey;
11
use Scriptotek\Alma\Exception\RequestFailed;
12
use Scriptotek\Alma\Exception\ResourceNotFound;
13
use Scriptotek\Alma\Zones;
14
15
function str_random()
16
{
17
    return strval(rand(10000, 99999));
18
}
19
20
class ClientSpec extends ObjectBehavior
21
{
22
    public function let()
23
    {
24
        $http = new MockHttp();
25
        $apiKey = 'DummyApiKey';
26
        $region = 'eu';
27
        $this->beConstructedWith($apiKey, $region, Zones::INSTITUTION, $http);
28
29
        return $http;
30
    }
31
32
    protected function httpWithResponseBody($body, $statusCode = 200, $headers = [])
33
    {
34
        $http = $this->let();
35
        $http->addResponse(new Response($statusCode, $headers, $body));
36
37
        return $http;
38
    }
39
40
    public function it_is_initializable()
41
    {
42
        $this->shouldHaveType('Scriptotek\Alma\Client');
43
    }
44
45
    public function it_only_accepts_valid_regions()
46
    {
47
        $this->shouldThrow('Scriptotek\Alma\Exception\ClientException')
48
            ->duringSetRegion('ux');
49
    }
50
51
    public function it_can_make_GET_requests()
52
    {
53
        $responseBody = str_random();
54
        $this->httpWithResponseBody($responseBody);
55
        $this->get(str_random())->shouldBe($responseBody);
56
    }
57
58
    public function it_sends_an_API_key_with_each_request()
59
    {
60
        $http = $this->httpWithResponseBody(str_random());
61
        $this->getJSON(str_random());
62
63
        // Query string should include apikey
64
        expect($http->getRequests()[0])->getUri()->getQuery()->toContain('apikey=DummyApiKey');
65
    }
66
67
    public function it_can_request_and_parse_JSON()
68
    {
69
        $responseBody = json_encode(['some_key' => 'some_value']);
70
        $http = $this->httpWithResponseBody($responseBody);
71
72
        $this->getJSON(str_random())->some_key->shouldBe('some_value');
73
74
        $request = $http->getRequests()[0];
75
        expect($request->getHeader('Accept')[0])->toBe('application/json');
76
    }
77
78
    public function it_can_post_and_parse_JSON()
79
    {
80
        $http = $this->httpWithResponseBody(SpecHelper::getDummyData('create_loan_response.json', false));
81
82
        $this->postJSON(str_random())->loan_id->shouldBe('7329587120002204');
83
84
        $request = $http->getRequests()[0];
85
        expect($request->getHeader('Content-Type')[0])->toBe('application/json');
86
        expect($request->getHeader('Accept')[0])->toBe('application/json');
87
    }
88
89
    public function it_can_request_and_parse_XML()
90
    {
91
        $responseBody = "<?xml version=\"1.0\"?>\n<some_key>some_value</some_key>\n";
92
        $http = $this->httpWithResponseBody($responseBody);
93
94
        $xml = $this->getXML(str_random());
95
96
        // Request headers should include Accept: application/xml
97
        expect($http->getRequests()[0])->getHeader('Accept')[0]->toBe('application/xml');
98
99
        // Response should be of type QuiteSimpleXMLElement
100
        $xml->shouldHaveType('Danmichaelo\QuiteSimpleXMLElement\QuiteSimpleXMLElement');
101
102
        // and have the expected value
103
        $xml->asXML()->shouldBe($responseBody);
104
    }
105
106
    public function it_can_make_PUT_requests()
107
    {
108
        $responseBody = str_random();
109
        $http = $this->httpWithResponseBody($responseBody);
110
111
        $this->put(str_random(), str_random(), 'application/json')->shouldBe($responseBody);
112
113
        expect($http->getRequests())->toHaveCount(1);
114
        expect($http->getRequests()[0])->getMethod()->toBe('PUT');
115
    }
116
117
    public function it_can_get_redirect_locations()
118
    {
119
        $http = $this->let();
120
        $response = new Response();
121
        $response = $response->withHeader('Location', 'http://test.test');
122
        $http->addResponse($response);
123
124
        $this->getRedirectLocation('/')->shouldBe('http://test.test');
125
    }
126
127 View Code Duplication
    public function it_processes_json_error_responses(ClientErrorException $exception)
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...
128
    {
129
        $exception->getResponse()->willReturn(new Response(
130
            400,
131
            ['Content-Type' => 'application/json;charset=utf-8'],
132
            SpecHelper::getDummyData('error_response.json', false)
133
        ));
134
135
        $http = $this->let();
136
        $http->addException($exception->getWrappedObject());
137
138
        $this->shouldThrow(new RequestFailed(
139
            'Mandatory field is missing: library',
140
            '401664'
141
        ))->during('getJSON', ['/items/123']);
142
143
        expect($http->getRequests())->toHaveCount(1);
144
    }
145
146 View Code Duplication
    public function it_processes_xml_error_responses(ClientErrorException $exception)
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...
147
    {
148
        $exception->getResponse()->willReturn(new Response(
149
            400,
150
            ['Content-Type' => 'application/xml;charset=utf-8'],
151
            SpecHelper::getDummyData('error_response.xml', false)
152
        ));
153
154
        $http = $this->let();
155
        $http->addException($exception->getWrappedObject());
156
157
        $this->shouldThrow(new RequestFailed(
158
            'Mandatory field is missing: library',
159
            '401664'
160
        ))->during('getXML', ['/items/123']);
161
162
        expect($http->getRequests())->toHaveCount(1);
163
    }
164
165 View Code Duplication
    public function it_can_throw_resource_not_found(ClientErrorException $exception)
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...
166
    {
167
        $exception->getResponse()->willReturn(new Response(
168
            400,
169
            ['Content-Type' => 'application/json;charset=utf-8'],
170
            SpecHelper::getDummyData('item_barcode_error_response.json', false)
171
        ));
172
173
        $http = $this->let();
174
        $http->addException($exception->getWrappedObject());
175
176
        $this->shouldThrow(new ResourceNotFound('No items found for barcode 123.', '401689'))
177
            ->during('getJSON', ['/items/123']);
178
179
        expect($http->getRequests())->toHaveCount(1);
180
    }
181
182 View Code Duplication
    public function it_can_throw_resource_not_found_for_500_errors_too(ServerErrorException $exception)
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...
183
    {
184
        // For Analytics reports, Alma will return 500, not 4xx
185
        $exception->getResponse()->willReturn(new Response(
186
            500,
187
            ['Content-Type' => 'application/xml;charset=utf-8'],
188
            SpecHelper::getDummyData('report_not_found_response.xml', false)
189
        ));
190
191
        $http = $this->let();
192
        $http->addException($exception->getWrappedObject());
193
194
        $this->shouldThrow(new ResourceNotFound('Path not found (/test/path)', 'INTERNAL_SERVER_ERROR'))
195
            ->during('getXML', ['/analytics/reports', ['path' => '/test/path']]);
196
197
        expect($http->getRequests())->toHaveCount(1);
198
    }
199
200 View Code Duplication
    public function it_can_throw_invalid_api_key(ClientErrorException $exception)
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...
201
    {
202
        $exception->getResponse()->willReturn(new Response(
203
            400,
204
            ['Content-Type' => 'text/plain;charset=UTF-8'],
205
            'Invalid API Key'
206
        ));
207
208
        $http = $this->let();
209
        $http->addException($exception->getWrappedObject());
210
211
        $this->shouldThrow(new InvalidApiKey('Invalid API Key', 0))
212
           ->during('getJSON', ['/items/123']);
213
214
        expect($http->getRequests())->toHaveCount(1);
215
    }
216
217
    public function it_will_retry_when_reaching_rate_limit(ClientErrorException $exception)
218
    {
219
        $exception->getResponse()->willReturn(new Response(
220
            400,
221
            ['Content-Type' => 'application/json;charset=utf-8'],
222
            SpecHelper::getDummyData('per_second_threshold_error_response.json', false)
223
        ));
224
225
        $http = $this->let();
226
        $http->addException($exception->getWrappedObject());
227
228
        $this->getJSON('/items/123');
229
230
        expect($http->getRequests())->toHaveCount(2);
231
    }
232
}
233