Completed
Pull Request — master (#757)
by Guilherme
22:18 queued 13:34
created

testGetSystemInitialsFromCache()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 20
c 2
b 1
f 0
nc 1
nop 0
dl 0
loc 32
rs 8.8571
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace PROCERGS\LoginCidadao\AccountingBundle\Tests\Service;
12
13
use GuzzleHttp\ClientInterface;
14
use GuzzleHttp\Message\RequestInterface;
15
use LoginCidadao\OAuthBundle\Entity\Client;
16
use PROCERGS\LoginCidadao\AccountingBundle\Entity\ProcergsLink;
17
use PROCERGS\LoginCidadao\AccountingBundle\Service\SystemsRegistryService;
18
19
/**
20
 * @codeCoverageIgnore
21
 */
22
class SystemsRegistryServiceTest extends \PHPUnit_Framework_TestCase
23
{
24
    private $config = [
25
        'apiUri' => 'https://api.uri/{host}',
26
        'organization' => 'MyOrganization',
27
        'registration_number' => 1234,
28
        'password' => 'ultra_top_secret_password',
29
    ];
30
31
    public function testGetSystemInitials()
32
    {
33
        $client = new Client();
34
        $client->setSiteUrl('http://host1/path');
35
        $client->setRedirectUris([
36
            'http://host1/path',
37
            'http://host2/path',
38
            'http://host2/path2',
39
        ]);
40
41
        $queries = [];
42
        $httpClient = $this->getHttpClient();
43
        $this->httpClientExpectGet($httpClient, $queries, 3);
44
45
        $registry = $this->getRegistry($httpClient);
46
47
        $initials = $registry->getSystemInitials($client);
48
49
        $this->assertContains('http://host1/path', $queries);
50
        $this->assertContains('http://host2/path', $queries);
51
        $this->assertContains('http://host2/path2', $queries);
52
        $this->assertCount(3, $queries);
53
        $this->assertContains('XPTO', $initials);
54
    }
55
56
    public function testGetSystemInitialsFromCache()
57
    {
58
        $client = new Client();
59
        $client->setSiteUrl('http://host1/path');
60
        $client->setRedirectUris([
61
            'http://host1/path',
62
            'http://host2/path',
63
            'http://host2/path2',
64
        ]);
65
66
        $queries = [];
67
        $httpClient = $this->getHttpClient();
68
        $this->httpClientExpectGet($httpClient, $queries, 3);
69
70
        $logger = $this->getMock('Psr\Log\LoggerInterface');
71
        // Logger should be called 11 times:
72
        //      2 for 'Fetching PROCERGS's system initials for client_id'
73
        //      6 for 'Searching for ...'
74
        //      3 for 'Returning cached result for ...'
75
        $logger->expects($this->exactly(11))->method('log')->with('info');
76
77
        $registry = $this->getRegistry($httpClient);
78
        $registry->setLogger($logger);
79
80
        $initials = $registry->getSystemInitials($client);
81
        $registry->getSystemInitials($client);
82
83
        $this->assertContains('http://host1/path', $queries);
84
        $this->assertContains('http://host2/path', $queries);
85
        $this->assertContains('http://host2/path2', $queries);
86
        $this->assertCount(3, $queries);
87
        $this->assertContains('XPTO', $initials);
88
    }
89
90
    public function testGetSystemInitialsNotFound()
91
    {
92
        $client = new Client();
93
        $client->setSiteUrl('http://host1/path');
94
95
        $queries = [];
96
        $httpClient = $this->getHttpClient();
97
        $httpClient->expects($this->once())->method('get')
98
            ->willReturnCallback(function ($url, $options) use (&$queries) {
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

98
            ->willReturnCallback(function ($url, /** @scrutinizer ignore-unused */ $options) use (&$queries) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
99
                $queries[] = str_replace('https://api.uri/', '', $url);
100
101
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
102
                    ->disableOriginalConstructor()->getMock();
103
                $e->expects($this->exactly(2))->method('getResponse')
104
                    ->willReturn($this->getResponse(['error' => 'Not found!'], 404));
105
106
                throw $e;
107
            });
108
109
        $registry = $this->getRegistry($httpClient);
110
        $registry->getSystemInitials($client);
111
112
        $this->assertContains('http://host1/path', $queries);
113
        $this->assertCount(1, $queries);
114
    }
115
116
    public function testGetSystemInitialsServerError()
117
    {
118
        // Since this is a batch job, we do not handle errors so that the job can fail and alert us.
119
        $this->setExpectedException('GuzzleHttp\Exception\ClientException');
120
121
        $client = new Client();
122
        $client->setRedirectUris(['http://host1/path']);
123
124
        $queries = [];
125
        $httpClient = $this->getHttpClient();
126
        $httpClient->expects($this->once())->method('get')
127
            ->willReturnCallback(function ($url) use (&$queries) {
128
                $queries[] = str_replace('https://api.uri/', '', $url);
129
130
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
131
                    ->disableOriginalConstructor()->getMock();
132
                $e->expects($this->once())->method('getResponse')
133
                    ->willReturn($this->getResponse(null, 500));
134
135
                throw $e;
136
            });
137
138
        $registry = $this->getRegistry($httpClient);
139
        $registry->getSystemInitials($client);
140
    }
141
142
    public function testGetSystemInitialsIgnoreInactiveSystemsWithoutDecommissionDate()
143
    {
144
        $queries = [];
145
        $httpClient = $this->getHttpClient();
146
        $this->httpClientExpectGet($httpClient, $queries, 1, [
147
            ['sistema' => 'XPTO1', 'situacao' => 'Implantado'],
148
            ['sistema' => 'XPTO2', 'situacao' => 'Not Implantado'],
149
        ]);
150
151
        $client = new Client();
152
        $client->setSiteUrl('http://host1/path');
153
154
        $registry = $this->getRegistry($httpClient);
155
        $initials = $registry->getSystemInitials($client, new \DateTime());
156
157
        $this->assertNotEmpty($initials);
158
        $this->assertContains('XPTO1', $initials);
159
        $this->assertNotContains('XPTO2', $initials);
160
    }
161
162
    public function testGetSystemInitialsIgnoreInactiveSystemsWithDecommissionDate()
163
    {
164
        $queries = [];
165
        $httpClient = $this->getHttpClient();
166
        $this->httpClientExpectGet($httpClient, $queries, 1, [
167
            ['sistema' => 'XPTO1', 'decommissionedOn' => '2018-02-03'],
168
            ['sistema' => 'XPTO2', 'decommissionedOn' => '2018-01-31'],
169
        ]);
170
171
        $client = new Client();
172
        $client->setSiteUrl('http://host1/path');
173
174
        $registry = $this->getRegistry($httpClient);
175
        $initials = $registry->getSystemInitials($client, \DateTime::createFromFormat('Y-m-d', '2018-02-01'));
0 ignored issues
show
Bug introduced by
It seems like DateTime::createFromFormat('Y-m-d', '2018-02-01') can also be of type false; however, parameter $activeAfter of PROCERGS\LoginCidadao\Ac...ce::getSystemInitials() does only seem to accept null|DateTime, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

175
        $initials = $registry->getSystemInitials($client, /** @scrutinizer ignore-type */ \DateTime::createFromFormat('Y-m-d', '2018-02-01'));
Loading history...
176
177
        $this->assertNotEmpty($initials);
178
        $this->assertContains('XPTO1', $initials);
179
        $this->assertNotContains('XPTO2', $initials);
180
    }
181
182
    public function testGetSystemOwners()
183
    {
184
        $client = new Client();
185
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
186
187
        $registry = $this->getRegistry();
188
        $owners = $registry->getSystemOwners($client);
189
190
        $this->assertNotEmpty($owners);
191
    }
192
193
    public function testGetSystemOwnersNotFound()
194
    {
195
        $client = new Client();
196
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
197
198
        $httpClient = $this->getHttpClient();
199
        $httpClient->expects($this->atLeastOnce())->method('get')
200
            ->willReturnCallback(function () {
201
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
202
                    ->disableOriginalConstructor()->getMock();
203
                $e->expects($this->exactly(2))->method('getResponse')
204
                    ->willReturn($this->getResponse(['error' => 'Not found!'], 404));
205
206
                throw $e;
207
            });
208
209
        $registry = $this->getRegistry($httpClient);
210
        $owners = $registry->getSystemOwners($client);
211
212
        $this->assertEmpty($owners);
213
    }
214
215
    public function testFetchLinked()
216
    {
217
        $client = new Client();
218
        $client->setId(123);
219
220
        $link = new ProcergsLink();
221
        $link->setClient($client)
222
            ->setSystemType(ProcergsLink::TYPE_INTERNAL);
223
224
        $repoClass = 'PROCERGS\LoginCidadao\AccountingBundle\Entity\ProcergsLinkRepository';
225
        $repo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
226
        $repo->expects($this->once())->method('findBy')->willReturn([$link]);
227
228
        $emptyRepo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
229
        $emptyRepo->expects($this->once())->method('findBy')->willReturn([]);
230
231
        $registry = $this->getRegistry($this->getHttpClient());
232
        $empty = $registry->fetchLinked([$client], $emptyRepo);
233
        $this->assertEmpty($empty);
234
235
        $links = $registry->fetchLinked([$client], $repo);
236
        $this->assertNotEmpty($links);
237
    }
238
239
    private function getHttpClient()
240
    {
241
        return $this->getMock('GuzzleHttp\ClientInterface');
242
    }
243
244
    private function getRegistry($client = null, $options = null)
245
    {
246
        if (!$client) {
247
            $client = $this->getHttpClient();
248
            $client->expects($this->any())->method('get')->willReturn($this->getResponse([
249
                [
250
                    'sistema' => 'XPTO',
251
                    'clienteDono' => 'CLIENT',
252
                    'urls' => [
253
                        'url' => 'https://url.tld/',
254
                        'ambiente' => 'Produção',
255
                    ],
256
                ],
257
            ]));
258
        }
259
260
        if (!$options) {
261
            $options = $this->config;
262
        }
263
264
        return new SystemsRegistryService($client, $options);
265
    }
266
267
    /**
268
     * @param $json
269
     * @param null $statusCode
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $statusCode is correct as it would always require null to be passed?
Loading history...
270
     * @return RequestInterface|\PHPUnit_Framework_MockObject_MockObject
271
     */
272
    private function getResponse($json = null, $statusCode = null)
273
    {
274
        $response = $this->getMock('GuzzleHttp\Message\ResponseInterface');
275
        if ($json) {
276
            $response->expects($this->atLeastOnce())->method('json')->willReturn($json);
277
        }
278
279
        if ($statusCode) {
280
            $response->expects($this->once())->method('getStatusCode')
281
                ->willReturn($statusCode);
282
        }
283
284
        return $response;
285
    }
286
287
    /**
288
     * @param ClientInterface|\PHPUnit_Framework_MockObject_MockObject $httpClient
289
     * @param $queries
290
     * @param $count
291
     * @param array|null $payload
292
     */
293
    private function httpClientExpectGet(&$httpClient, &$queries, $count, $payload = null)
294
    {
295
        $httpClient->expects($this->exactly($count))->method('get')
296
            ->willReturnCallback(function ($url, $options) use (&$queries, $payload) {
297
                $queries[] = str_replace('https://api.uri/', '', $url);
298
299
                $headers = $options['headers'];
300
                $this->assertEquals($this->config['organization'], $headers['organizacao']);
301
302
                $response = $this->getResponse($payload ?: [['sistema' => 'XPTO']]);
303
304
                return $response;
305
            });
306
    }
307
}
308