Completed
Push — master ( e1abb2...22bdbf )
by Alex
01:59
created

Tests/ServiceClientUnitTests.php (1 issue)

Severity
1
<?php
2
namespace Mezon\Service\Tests;
3
4
/**
5
 * Class ServiceClientUnitTests
6
 *
7
 * @package ServiceClient
8
 * @subpackage ServiceClientUnitTests
9
 * @author Dodonov A.A.
10
 * @version v.1.0 (2019/09/20)
11
 * @copyright Copyright (c) 2019, aeon.org
12
 */
13
class TestingServiceClient extends \Mezon\Service\ServiceClient
14
{
15
16
    /**
17
     * Method returns concrete url by it's locator
18
     *
19
     * @param string $urlLocator
20
     *            url locator
21
     * @return string concrete URL
22
     */
23
    public function getRequestUriPublic(string $urlLocator): string
24
    {
25
        return $this->getRequestUrl($urlLocator);
26
    }
27
28
    /**
29
     * Result of the sendRequest method
30
     *
31
     * @var array
32
     */
33
    public $sendRequestResult = [
34
        'body',
35
        1
36
    ];
37
38
    /**
39
     *
40
     * @param string $url
41
     *            URL
42
     * @param array $headers
43
     *            Headers
44
     * @param string $method
45
     *            Request HTTP Method
46
     * @param array $data
47
     *            Request data
48
     * @return array Response body and HTTP code
49
     * @codeCoverageIgnore
50
     */
51
    protected function sendRequest(string $url, array $headers, string $method, array $data = []): array
52
    {
53
        return $this->sendRequestResult;
54
    }
55
}
56
57
/**
58
 * Basic tests for service client
59
 *
60
 * @author Dodonov A.
61
 * @group baseTests
62
 * @codeCoverageIgnore
63
 */
64
class ServiceClientUnitTests extends \PHPUnit\Framework\TestCase
65
{
66
67
    /**
68
     * Client class name
69
     */
70
    protected $clientClassName = \Mezon\Service\ServiceClient::class;
71
72
    /**
73
     * Common setup for all tests
74
     */
75
    public function setUp(): void
76
    {
77
        \Mezon\DnsClient\DnsClient::clear();
78
        \Mezon\DnsClient\DnsClient::setService('existing-service', 'https://existing-service.com');
79
    }
80
81
    /**
82
     * Method creates mock for the service client
83
     *
84
     * @param array $methods
85
     *            mocking methods
86
     * @return object Mock
87
     */
88
    protected function getServiceClientRawMock(
89
        array $methods = [
90
            'sendPostRequest',
91
            'sendGetRequest',
92
            'sendPutRequest',
93
            'sendDeleteRequest'
94
        ]): object
95
    {
96
        return $this->getMockBuilder($this->clientClassName)
0 ignored issues
show
Deprecated Code introduced by
The function PHPUnit\Framework\MockOb...ckBuilder::setMethods() has been deprecated: https://github.com/sebastianbergmann/phpunit/pull/3687 ( Ignorable by Annotation )

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

96
        return /** @scrutinizer ignore-deprecated */ $this->getMockBuilder($this->clientClassName)

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
97
            ->setMethods($methods)
98
            ->disableOriginalConstructor()
99
            ->getMock();
100
    }
101
102
    /**
103
     * Method creates mock with setup
104
     *
105
     * @param string $dataFile
106
     *            File name with testing data
107
     * @return object Mock object
108
     */
109
    protected function getServiceClientMock(string $dataFile = 'login-with-invalid-session-id'): object
110
    {
111
        $mock = $this->getServiceClientRawMock([
112
            'sendRequest'
113
        ]);
114
115
        $mock->method('sendRequest')->will(
116
            $this->returnValue(json_decode(file_get_contents(__DIR__ . '/Conf/' . $dataFile . '.json'), true)));
117
118
        return $mock;
119
    }
120
121
    /**
122
     * Testing construction with login and password
123
     */
124
    public function testConstructWithLogin(): void
125
    {
126
        // setup
127
        $mock = $this->getServiceClientMock('construct-with-login');
128
129
        // test body
130
        $mock->__construct('http://example.com/', 'login', 'password');
131
132
        // assertions
133
        $this->assertEquals('login', $mock->getStoredLogin(), 'Login was not set');
134
        $this->assertEquals('session id', $mock->getToken(), 'SessionId was not set');
135
    }
136
137
    /**
138
     * Testing constructor
139
     */
140
    public function testSetHeader(): void
141
    {
142
        // setup
143
        $client = new $this->clientClassName('http://example.com/');
144
145
        // test body and assertions
146
        $this->assertEquals('', $client->getService(), 'Field was init but it must not');
147
    }
148
149
    /**
150
     * Checking exception throwing if the service was not found
151
     */
152
    public function testNoServiceFound(): void
153
    {
154
        $this->expectException(\Exception::class);
155
156
        new $this->clientClassName('auth');
157
    }
158
159
    /**
160
     * Testing that service was found.
161
     */
162
    public function testServiceFound(): void
163
    {
164
        $client = new $this->clientClassName('existing-service');
165
166
        $this->assertEquals('existing-service', $client->getService(), 'Field was init but it must not');
167
    }
168
169
    /**
170
     * Data provider for the test testSendRequest
171
     *
172
     * @return array test data
173
     */
174
    public function sendRequestDataProvider(): array
175
    {
176
        return [
177
            [
178
                'sendGetRequest'
179
            ],
180
            [
181
                'sendPostRequest'
182
            ],
183
            [
184
                'sendPutRequest'
185
            ],
186
            [
187
                'sendDeleteRequest'
188
            ]
189
        ];
190
    }
191
192
    /**
193
     * Testing send[Post|Get|Put|Delete]Request
194
     *
195
     * @param string $methodName
196
     *            testing method name
197
     * @dataProvider sendRequestDataProvider
198
     */
199
    public function testSendRequest(string $methodName): void
200
    {
201
        $mock = $this->getServiceClientMock('test-request');
202
203
        $result = $mock->$methodName('http://ya.ru', []);
204
205
        $this->assertEquals(1, $result->result);
206
    }
207
208
    /**
209
     * Testing setToken method
210
     */
211
    public function testSetToken(): void
212
    {
213
        // setup
214
        $mock = $this->getServiceClientRawMock(); // we need this function, as we need mock without any extra setup
215
216
        // test body
217
        $mock->setToken('token', 'login');
218
219
        // assertions
220
        $this->assertEquals('token', $mock->getToken(), 'SessionId was not set');
221
        $this->assertEquals('login', $mock->getStoredLogin(), 'Login was not set');
222
    }
223
224
    /**
225
     * Testing getToken method
226
     */
227
    public function testGetToken(): void
228
    {
229
        // setup
230
        $mock = $this->getServiceClientRawMock(); // we need this function, as we need mock without any extra setup
231
232
        // test body
233
        $sessionId = $mock->getToken();
234
235
        // assertions
236
        $this->assertEquals('', $sessionId, 'Invalid session id');
237
    }
238
239
    /**
240
     * Testing setToken method
241
     */
242
    public function testSetTokenException(): void
243
    {
244
        // setup
245
        $mock = $this->getServiceClientRawMock(); // we need this function, as we need mock without any extra setup
246
247
        // test body and assertions
248
        $this->expectException(\Exception::class);
249
        $mock->setToken('');
250
    }
251
252
    /**
253
     * Testing getSelfId method
254
     */
255
    public function testGetSelfId(): void
256
    {
257
        // setup
258
        $mock = $this->getServiceClientMock('self-id');
259
260
        // test body
261
        $selfId = $mock->getSelfId();
262
263
        // assertions
264
        $this->assertEquals('123', $selfId, 'Invalid self id');
265
    }
266
267
    /**
268
     * Testing getSelfLogin method
269
     */
270
    public function testGetSelfLogin(): void
271
    {
272
        // setup
273
        $mock = $this->getServiceClientMock('self-login');
274
275
        // test body
276
        $selfLogin = $mock->getSelfLogin();
277
278
        // assertions
279
        $this->assertEquals('admin', $selfLogin, 'Invalid self login');
280
    }
281
282
    /**
283
     * Testing loginAs method
284
     */
285
    public function testLoginAsWithInvalidSessionId(): void
286
    {
287
        // setup
288
        $mock = $this->getServiceClientMock();
289
290
        // test body and assertions
291
        $this->expectException(\Exception::class);
292
293
        $mock->loginAs('registered-user', 'login');
294
    }
295
296
    /**
297
     * Testing loginAs method
298
     */
299
    public function testLoginAsWithInvalidSessionId2(): void
300
    {
301
        // setup
302
        $mock = $this->getServiceClientMock();
303
304
        // test body
305
        $mock->loginAs('registered', 'id');
306
307
        // assertions
308
        $this->assertEquals('', $mock->getStoredLogin());
309
    }
310
311
    /**
312
     * Testing loginAs method
313
     */
314
    public function testLoginAs(): void
315
    {
316
        // setup
317
        $mock = $this->getServiceClientMock('login-as');
318
319
        // test body
320
        $mock->loginAs('registered', 'login');
321
322
        // assertions
323
        $this->assertEquals('session-id', $mock->getToken(), 'Invalid self login');
324
    }
325
326
    /**
327
     * Testing construction with login and password and invalid session_id
328
     */
329
    public function testConstructWithLoginAndInvalidSessionId(): void
330
    {
331
        // setup
332
        $mock = $this->getServiceClientMock();
333
334
        // test body and assertions
335
        $this->expectException(\Exception::class);
336
        $mock->__construct('http://example.com/', 'login', 'password');
337
    }
338
339
    /**
340
     * Testing setting and getting rewrite mode
341
     */
342
    public function testRewriteMode(): void
343
    {
344
        // setup
345
        $mock = $this->getServiceClientMock();
346
347
        // test body and assertions
348
        $mock->setRewriteMode(true);
349
        $this->assertTrue($mock->getRewriteMode());
350
351
        $mock->setRewriteMode(false);
352
        $this->assertFalse($mock->getRewriteMode());
353
    }
354
355
    /**
356
     * Testing authentication headers
357
     */
358
    public function testAuthenticationHeaders(): void
359
    {
360
        // setup and assertions
361
        $client = $this->getServiceClientRawMock([
362
            'sendRequest'
363
        ]);
364
        $client->method('sendRequest')
365
            ->with(
366
            $this->callback(function () {
367
                return true;
368
            }),
369
            $this->callback(
370
                function ($headers) {
371
                    $this->assertContains('Authentication: Basic some-token', $headers);
372
                    $this->assertContains('Cgi-Authorization: Basic some-token', $headers);
373
                    return true;
374
                }))
375
            ->willReturn([
376
            "{\"session_id\":\"some-password\"}",
377
            200
378
        ]);
379
        $client->setToken('some-token');
380
381
        // test body
382
        $client->connect('some-login', 'some-password');
383
    }
384
385
    /**
386
     * Testing method
387
     */
388
    public function testGetRequestUrlException(): void
389
    {
390
        // setup and assertions
391
        $this->expectException(\Exception::class);
392
        $client = new TestingServiceClient('https://some-service');
393
394
        // test body
395
        $client->getRequestUriPublic('unexistingUri');
396
    }
397
398
    /**
399
     * Testing exception throwing if error response was got
400
     */
401
    public function testGetReuqetsUrlWithHandlingError(): void
402
    {
403
        // setup and assertions
404
        $this->expectException(\Exception::class);
405
        $client = new TestingServiceClient('https://some-service');
406
        $client->sendRequestResult = [
407
            '{"message":"", "code": 1}',
408
            200
409
        ];
410
411
        // test body
412
        $client->sendGetRequest('some endpoint');
413
    }
414
415
    /**
416
     * Mtrhod tests case when sendRequest method have returned invalid json
417
     */
418
    public function testInvalidJsonReturnedFromSendRequest():void{
419
        // setup and assertions
420
        $this->expectException(\Mezon\Rest\Exception::class);
421
        $client = new TestingServiceClient('https://some-service');
422
        $client->sendRequestResult = [
423
            'some crap',
424
            200
425
        ];
426
427
        // test body
428
        $client->sendGetRequest('some endpoint');
429
    }
430
}
431