Passed
Push — issue#752 ( 8960ee...e0b46f )
by Guilherme
08:46
created

testGetSystemInitialsServerError()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 15
nc 1
nop 0
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
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\Message\RequestInterface;
14
use LoginCidadao\OAuthBundle\Entity\Client;
15
use PROCERGS\LoginCidadao\AccountingBundle\Entity\ProcergsLink;
16
use PROCERGS\LoginCidadao\AccountingBundle\Service\SystemsRegistryService;
17
18
/**
19
 * @codeCoverageIgnore
20
 */
21
class SystemsRegistryServiceTest extends \PHPUnit_Framework_TestCase
22
{
23
    private $config = [
24
        'apiUri' => 'https://api.uri/{host}',
25
        'organization' => 'MyOrganization',
26
        'registration_number' => 1234,
27
        'password' => 'ultra_top_secret_password',
28
    ];
29
30
    public function testGetSystemInitials()
31
    {
32
        $client = new Client();
33
        $client->setSiteUrl('http://host1/path');
34
        $client->setRedirectUris([
35
            'http://host1/path',
36
            'http://host2/path',
37
            'http://host2/path2',
38
        ]);
39
40
        $queries = [];
41
        $httpClient = $this->getHttpClient();
42
        $httpClient->expects($this->exactly(3))->method('get')
43
            ->willReturnCallback(function ($url, $options) use (&$queries) {
44
                $queries[] = str_replace('https://api.uri/', '', $url);
45
46
                $headers = $options['headers'];
47
                $this->assertEquals($this->config['organization'], $headers['organizacao']);
48
49
                $response = $this->getResponse([['sistema' => 'XPTO']]);
50
51
                return $response;
52
            });
53
54
        $registry = $this->getRegistry($httpClient);
55
56
        $initials = $registry->getSystemInitials($client);
57
58
        $this->assertContains('http://host1/path', $queries);
59
        $this->assertContains('http://host2/path', $queries);
60
        $this->assertContains('http://host2/path2', $queries);
61
        $this->assertCount(3, $queries);
62
        $this->assertContains('XPTO', $initials);
63
    }
64
65
    public function testGetSystemInitialsFromCache()
66
    {
67
        $client = new Client();
68
        $client->setSiteUrl('http://host1/path');
69
        $client->setRedirectUris([
70
            'http://host1/path',
71
            'http://host2/path',
72
            'http://host2/path2',
73
        ]);
74
75
        $queries = [];
76
        $httpClient = $this->getHttpClient();
77
        $httpClient->expects($this->exactly(3))->method('get')
78
            ->willReturnCallback(function ($url, $options) use (&$queries) {
79
                $queries[] = str_replace('https://api.uri/', '', $url);
80
81
                $headers = $options['headers'];
82
                $this->assertEquals($this->config['organization'], $headers['organizacao']);
83
84
                $response = $this->getResponse([['sistema' => 'XPTO']]);
85
86
                return $response;
87
            });
88
89
        $logger = $this->getMock('Psr\Log\LoggerInterface');
90
        // Logger should be called 11 times:
91
        //      2 for 'Fetching PROCERGS's system initials for client_id'
92
        //      6 for 'Searching for ...'
93
        //      3 for 'Returning cached result for ...'
94
        $logger->expects($this->exactly(11))->method('log')->with('info');
95
96
        $registry = $this->getRegistry($httpClient);
97
        $registry->setLogger($logger);
98
99
        $initials = $registry->getSystemInitials($client);
100
        $registry->getSystemInitials($client);
101
102
        $this->assertContains('http://host1/path', $queries);
103
        $this->assertContains('http://host2/path', $queries);
104
        $this->assertContains('http://host2/path2', $queries);
105
        $this->assertCount(3, $queries);
106
        $this->assertContains('XPTO', $initials);
107
    }
108
109
    public function testGetSystemInitialsNotFound()
110
    {
111
        $client = new Client();
112
        $client->setSiteUrl('http://host1/path');
113
114
        $queries = [];
115
        $httpClient = $this->getHttpClient();
116
        $httpClient->expects($this->once())->method('get')
117
            ->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

117
            ->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...
118
                $queries[] = str_replace('https://api.uri/', '', $url);
119
120
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
121
                    ->disableOriginalConstructor()->getMock();
122
                $e->expects($this->exactly(2))->method('getResponse')
123
                    ->willReturn($this->getResponse(['error' => 'Not found!'], 404));
124
125
                throw $e;
126
            });
127
128
        $registry = $this->getRegistry($httpClient);
129
        $registry->getSystemInitials($client);
130
131
        $this->assertContains('http://host1/path', $queries);
132
        $this->assertCount(1, $queries);
133
    }
134
135
    public function testGetSystemInitialsServerError()
136
    {
137
        // Since this is a batch job, we do not handle errors so that the job can fail and alert us.
138
        $this->setExpectedException('GuzzleHttp\Exception\ClientException');
139
140
        $client = new Client();
141
        $client->setRedirectUris(['http://host1/path']);
142
143
        $queries = [];
144
        $httpClient = $this->getHttpClient();
145
        $httpClient->expects($this->once())->method('get')
146
            ->willReturnCallback(function ($url) use (&$queries) {
147
                $queries[] = str_replace('https://api.uri/', '', $url);
148
149
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
150
                    ->disableOriginalConstructor()->getMock();
151
                $e->expects($this->once())->method('getResponse')
152
                    ->willReturn($this->getResponse(null, 500));
153
154
                throw $e;
155
            });
156
157
        $registry = $this->getRegistry($httpClient);
158
        $registry->getSystemInitials($client);
159
    }
160
161
    public function testGetSystemOwners()
162
    {
163
        $client = new Client();
164
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
165
166
        $registry = $this->getRegistry();
167
        $owners = $registry->getSystemOwners($client);
168
169
        $this->assertNotEmpty($owners);
170
    }
171
172
    public function testGetSystemOwnersNotFound()
173
    {
174
        $client = new Client();
175
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
176
177
        $httpClient = $this->getHttpClient();
178
        $httpClient->expects($this->atLeastOnce())->method('get')
179
            ->willReturnCallback(function () {
180
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
181
                    ->disableOriginalConstructor()->getMock();
182
                $e->expects($this->exactly(2))->method('getResponse')
183
                    ->willReturn($this->getResponse(['error' => 'Not found!'], 404));
184
185
                throw $e;
186
            });
187
188
        $registry = $this->getRegistry($httpClient);
189
        $owners = $registry->getSystemOwners($client);
190
191
        $this->assertEmpty($owners);
192
    }
193
194
    public function testFetchLinked()
195
    {
196
        $client = new Client();
197
        $client->setId(123);
198
199
        $link = new ProcergsLink();
200
        $link->setClient($client)
201
            ->setSystemType(ProcergsLink::TYPE_INTERNAL);
202
203
        $repoClass = 'PROCERGS\LoginCidadao\AccountingBundle\Entity\ProcergsLinkRepository';
204
        $repo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
205
        $repo->expects($this->once())->method('findBy')->willReturn([$link]);
206
207
        $emptyRepo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
208
        $emptyRepo->expects($this->once())->method('findBy')->willReturn([]);
209
210
        $registry = $this->getRegistry($this->getHttpClient());
211
        $empty = $registry->fetchLinked([$client], $emptyRepo);
212
        $this->assertEmpty($empty);
213
214
        $links = $registry->fetchLinked([$client], $repo);
215
        $this->assertNotEmpty($links);
216
    }
217
218
    private function getHttpClient()
219
    {
220
        return $this->getMock('GuzzleHttp\ClientInterface');
221
    }
222
223
    private function getRegistry($client = null, $options = null)
224
    {
225
        if (!$client) {
226
            $client = $this->getHttpClient();
227
            $client->expects($this->any())->method('get')->willReturn($this->getResponse([
228
                [
229
                    'sistema' => 'XPTO',
230
                    'clienteDono' => 'CLIENT',
231
                    'urls' => [
232
                        'url' => 'https://url.tld/',
233
                        'ambiente' => 'Produção',
234
                    ],
235
                ],
236
            ]));
237
        }
238
239
        if (!$options) {
240
            $options = $this->config;
241
        }
242
243
        return new SystemsRegistryService($client, $options);
244
    }
245
246
    /**
247
     * @param $json
248
     * @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...
249
     * @return RequestInterface|\PHPUnit_Framework_MockObject_MockObject
250
     */
251
    private function getResponse($json = null, $statusCode = null)
252
    {
253
        $response = $this->getMock('GuzzleHttp\Message\ResponseInterface');
254
        if ($json) {
255
            $response->expects($this->atLeastOnce())->method('json')->willReturn($json);
256
        }
257
258
        if ($statusCode) {
259
            $response->expects($this->once())->method('getStatusCode')
260
                ->willReturn($statusCode);
261
        }
262
263
        return $response;
264
    }
265
}
266