Completed
Push — master ( 24f6ce...c3efa2 )
by Guilherme
05:36
created

SystemsRegistryServiceTest::testGetSystemOwners()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 10
rs 9.4285
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
        // We have 2 hosts and 3 URIs, so we need 3 requests since the 3 URIs use only 2 hosts
43
        $httpClient->expects($this->exactly(3))->method('get')
44
            ->willReturnCallback(function ($url, $options) use (&$queries) {
45
                $queries[] = str_replace('https://api.uri/', '', $url);
46
47
                $headers = $options['headers'];
48
                $this->assertEquals($this->config['organization'], $headers['organizacao']);
49
50
                $response = $this->getResponse([['sistema' => 'XPTO']]);
51
52
                return $response;
53
            });
54
55
        $registry = $this->getRegistry($httpClient);
56
57
        $initials = $registry->getSystemInitials($client);
58
59
        $this->assertContains('host1', $queries);
60
        $this->assertContains('host2', $queries);
61
        $this->assertContains('http://host1/path', $queries);
62
        $this->assertContains('XPTO', $initials);
63
    }
64
65
    public function testGetSystemInitialsNotFound()
66
    {
67
        $client = new Client();
68
        $client->setSiteUrl('http://host1/path');
69
70
        $queries = [];
71
        $httpClient = $this->getHttpClient();
72
        $httpClient->expects($this->exactly(2))->method('get')
73
            ->willReturnCallback(function ($url, $options) use (&$queries) {
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

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

Loading history...
74
                $queries[] = str_replace('https://api.uri/', '', $url);
75
76
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
77
                    ->disableOriginalConstructor()->getMock();
78
                $e->expects($this->exactly(2))->method('getResponse')
79
                    ->willReturn($this->getResponse(['error' => 'Not found!'], 404));
80
81
                throw $e;
82
            });
83
84
        $registry = $this->getRegistry($httpClient);
85
        $registry->getSystemInitials($client);
86
87
        $this->assertContains('host1', $queries);
88
        $this->assertContains('http://host1/path', $queries);
89
    }
90
91
    public function testGetSystemInitialsServerError()
92
    {
93
        // Since this is a batch job, we do not handle errors so that the job can fail and alert us.
94
        $this->setExpectedException('GuzzleHttp\Exception\ClientException');
95
96
        $client = new Client();
97
        $client->setRedirectUris(['http://host1/path']);
98
99
        $queries = [];
100
        $httpClient = $this->getHttpClient();
101
        $httpClient->expects($this->once())->method('get')
102
            ->willReturnCallback(function ($url) use (&$queries) {
103
                $queries[] = str_replace('https://api.uri/', '', $url);
104
105
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
106
                    ->disableOriginalConstructor()->getMock();
107
                $e->expects($this->once())->method('getResponse')
108
                    ->willReturn($this->getResponse(null, 500));
109
110
                throw $e;
111
            });
112
113
        $registry = $this->getRegistry($httpClient);
114
        $registry->getSystemInitials($client);
115
    }
116
117
    public function testGetSystemOwners()
118
    {
119
        $client = new Client();
120
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
121
122
        $registry = $this->getRegistry();
123
        $owners = $registry->getSystemOwners($client);
124
125
        $this->assertNotEmpty($owners);
126
    }
127
128
    public function testGetSystemOwnersNotFound()
129
    {
130
        $client = new Client();
131
        $client->setRedirectUris(['https://host1/path', 'https://host2/path']);
132
133
        $httpClient = $this->getHttpClient();
134
        $httpClient->expects($this->atLeastOnce())->method('get')
135
            ->willReturnCallback(function () {
136
                $e = $this->getMockBuilder('GuzzleHttp\Exception\ClientException')
137
                    ->disableOriginalConstructor()->getMock();
138
                $e->expects($this->exactly(2))->method('getResponse')
139
                    ->willReturn($this->getResponse(['error' => 'Not found!'], 404));
140
141
                throw $e;
142
            });
143
144
        $registry = $this->getRegistry($httpClient);
145
        $owners = $registry->getSystemOwners($client);
146
147
        $this->assertEmpty($owners);
148
    }
149
150
    public function testFetchLinked()
151
    {
152
        $client = new Client();
153
        $client->setId(123);
154
155
        $link = new ProcergsLink();
156
        $link->setClient($client)
157
            ->setSystemType(ProcergsLink::TYPE_INTERNAL);
158
159
        $repoClass = 'PROCERGS\LoginCidadao\AccountingBundle\Entity\ProcergsLinkRepository';
160
        $repo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
161
        $repo->expects($this->once())->method('findBy')->willReturn([$link]);
162
163
        $emptyRepo = $this->getMockBuilder($repoClass)->disableOriginalConstructor()->getMock();
164
        $emptyRepo->expects($this->once())->method('findBy')->willReturn([]);
165
166
        $registry = $this->getRegistry($this->getHttpClient());
167
        $empty = $registry->fetchLinked([$client], $emptyRepo);
168
        $this->assertEmpty($empty);
169
170
        $links = $registry->fetchLinked([$client], $repo);
171
        $this->assertNotEmpty($links);
172
    }
173
174
    private function getHttpClient()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
175
    {
176
        return $this->getMock('GuzzleHttp\ClientInterface');
177
    }
178
179
    private function getRegistry($client = null, $options = null)
180
    {
181
        if (!$client) {
182
            $client = $this->getHttpClient();
183
            $client->expects($this->any())->method('get')->willReturn($this->getResponse([
184
                [
185
                    'sistema' => 'XPTO',
186
                    'clienteDono' => 'CLIENT',
187
                    'urls' => [
188
                        'url' => 'https://url.tld/',
189
                        'ambiente' => 'Produção',
190
                    ],
191
                ],
192
            ]));
193
        }
194
195
        if (!$options) {
196
            $options = $this->config;
197
        }
198
199
        return new SystemsRegistryService($client, $options);
200
    }
201
202
    /**
203
     * @param $json
204
     * @param null $statusCode
205
     * @return RequestInterface|\PHPUnit_Framework_MockObject_MockObject
206
     */
207
    private function getResponse($json = null, $statusCode = null)
208
    {
209
        $response = $this->getMock('GuzzleHttp\Message\ResponseInterface');
210
        if ($json) {
211
            $response->expects($this->atLeastOnce())->method('json')->willReturn($json);
212
        }
213
214
        if ($statusCode) {
215
            $response->expects($this->once())->method('getStatusCode')
216
                ->willReturn($statusCode);
217
        }
218
219
        return $response;
220
    }
221
}
222