Passed
Push — issue#752 ( 5ac0d2...4f5583 )
by Guilherme
13:00 queued 04:09
created

testGetSystemInitials()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 16
c 2
b 1
f 0
nc 1
nop 0
dl 0
loc 23
rs 9.0856
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 testGetSystemOwners()
143
    {
144
        $client = new Client();
145
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
146
147
        $registry = $this->getRegistry();
148
        $owners = $registry->getSystemOwners($client);
149
150
        $this->assertNotEmpty($owners);
151
    }
152
153
    public function testGetSystemOwnersNotFound()
154
    {
155
        $client = new Client();
156
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
157
158
        $httpClient = $this->getHttpClient();
159
        $httpClient->expects($this->atLeastOnce())->method('get')
160
            ->willReturnCallback(function () {
161
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
162
                    ->disableOriginalConstructor()->getMock();
163
                $e->expects($this->exactly(2))->method('getResponse')
164
                    ->willReturn($this->getResponse(['error' => 'Not found!'], 404));
165
166
                throw $e;
167
            });
168
169
        $registry = $this->getRegistry($httpClient);
170
        $owners = $registry->getSystemOwners($client);
171
172
        $this->assertEmpty($owners);
173
    }
174
175
    public function testFetchLinked()
176
    {
177
        $client = new Client();
178
        $client->setId(123);
179
180
        $link = new ProcergsLink();
181
        $link->setClient($client)
182
            ->setSystemType(ProcergsLink::TYPE_INTERNAL);
183
184
        $repoClass = 'PROCERGS\LoginCidadao\AccountingBundle\Entity\ProcergsLinkRepository';
185
        $repo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
186
        $repo->expects($this->once())->method('findBy')->willReturn([$link]);
187
188
        $emptyRepo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
189
        $emptyRepo->expects($this->once())->method('findBy')->willReturn([]);
190
191
        $registry = $this->getRegistry($this->getHttpClient());
192
        $empty = $registry->fetchLinked([$client], $emptyRepo);
193
        $this->assertEmpty($empty);
194
195
        $links = $registry->fetchLinked([$client], $repo);
196
        $this->assertNotEmpty($links);
197
    }
198
199
    private function getHttpClient()
200
    {
201
        return $this->getMock('GuzzleHttp\ClientInterface');
202
    }
203
204
    private function getRegistry($client = null, $options = null)
205
    {
206
        if (!$client) {
207
            $client = $this->getHttpClient();
208
            $client->expects($this->any())->method('get')->willReturn($this->getResponse([
209
                [
210
                    'sistema' => 'XPTO',
211
                    'clienteDono' => 'CLIENT',
212
                    'urls' => [
213
                        'url' => 'https://url.tld/',
214
                        'ambiente' => 'Produção',
215
                    ],
216
                ],
217
            ]));
218
        }
219
220
        if (!$options) {
221
            $options = $this->config;
222
        }
223
224
        return new SystemsRegistryService($client, $options);
225
    }
226
227
    /**
228
     * @param $json
229
     * @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...
230
     * @return RequestInterface|\PHPUnit_Framework_MockObject_MockObject
231
     */
232
    private function getResponse($json = null, $statusCode = null)
233
    {
234
        $response = $this->getMock('GuzzleHttp\Message\ResponseInterface');
235
        if ($json) {
236
            $response->expects($this->atLeastOnce())->method('json')->willReturn($json);
237
        }
238
239
        if ($statusCode) {
240
            $response->expects($this->once())->method('getStatusCode')
241
                ->willReturn($statusCode);
242
        }
243
244
        return $response;
245
    }
246
247
    /**
248
     * @param ClientInterface|\PHPUnit_Framework_MockObject_MockObject $httpClient
249
     * @param $queries
250
     * @param $count
251
     */
252
    private function httpClientExpectGet(&$httpClient, &$queries, $count)
253
    {
254
        $httpClient->expects($this->exactly($count))->method('get')
255
            ->willReturnCallback(function ($url, $options) use (&$queries) {
256
                $queries[] = str_replace('https://api.uri/', '', $url);
257
258
                $headers = $options['headers'];
259
                $this->assertEquals($this->config['organization'], $headers['organizacao']);
260
261
                $response = $this->getResponse([['sistema' => 'XPTO']]);
262
263
                return $response;
264
            });
265
    }
266
}
267