Completed
Push — master ( c4731e...d2572c )
by Alex
02:29
created

ServiceTests::prepareGetOptions()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 3
nc 4
nop 0
1
<?php
2
namespace Mezon\Service\Tests;
3
4
/**
5
 * Class ServiceTests
6
 *
7
 * @package Service
8
 * @subpackage ServiceTests
9
 * @author Dodonov A.A.
10
 * @version v.1.0 (2019/08/17)
11
 * @copyright Copyright (c) 2019, aeon.org
12
 */
13
14
/**
15
 * Predefined set of tests for service
16
 *
17
 * @author Dodonov A.A.
18
 * @group baseTests
19
 */
20
class ServiceTests extends \PHPUnit\Framework\TestCase
21
{
22
23
    /**
24
     * Session id.
25
     */
26
    protected $sessionId = false;
27
28
    /**
29
     * Server path.
30
     */
31
    protected $serverPath = false;
32
33
    /**
34
     * Headers.
35
     *
36
     * @var string
37
     */
38
    protected $headers = false;
39
40
    /**
41
     * Constructor.
42
     *
43
     * @param string $service
44
     *            - Service name.
45
     */
46
    public function __construct(string $service)
47
    {
48
        parent::__construct();
49
50
        $this->serverPath = \Mezon\DnsClient\DnsClient::resolveHost($service);
51
    }
52
53
    /**
54
     * Method asserts for errors and warnings in the html code.
55
     *
56
     * @param string $content
57
     *            - Asserting content.
58
     * @param string $message
59
     *            - Message to be displayed in case of error.
60
     */
61
    protected function assertErrors($content, $message)
62
    {
63
        if (strpos($content, 'Warning') !== false || strpos($content, 'Error') !== false ||
64
            strpos($content, 'Fatal error') !== false || strpos($content, 'Access denied') !== false ||
65
            strpos($content, "doesn't exist in statement") !== false) {
66
            throw (new \Exception($message . "\r\n" . $content));
67
        }
68
69
        $this->addToAssertionCount(1);
70
    }
71
72
    /**
73
     * Method asserts JSON.
74
     *
75
     * @param mixed $jsonResult
76
     *            - Result of the call;
77
     * @param string $result
78
     *            - Raw result of the call.
79
     */
80
    protected function assertJsonResponse($jsonResult, string $result)
81
    {
82
        if ($jsonResult === null && $result !== '') {
83
            throw (new \Exception("JSON result is invalid because of:\r\n$result"));
84
        }
85
86
        if (isset($jsonResult->message)) {
87
            throw (new \Exception($jsonResult->message, $jsonResult->code));
88
        }
89
    }
90
91
    /**
92
     * Method sends post request.
93
     *
94
     * @param array $data
95
     *            - Request data;
96
     * @param string $url
97
     *            - Requesting endpoint.
98
     * @return mixed Request result.
99
     */
100
    protected function postHttpRequest(array $data, string $url)
101
    {
102
        $options = [
103
            'http' => [
104
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
105
                "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\r\n" .
106
                ($this->sessionId !== false ? "Cgi-Authorization: Basic " . $this->sessionId . "\r\n" : '') .
0 ignored issues
show
Bug introduced by
Are you sure $this->sessionId of type true can be used in concatenation? ( Ignorable by Annotation )

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

106
                ($this->sessionId !== false ? "Cgi-Authorization: Basic " . /** @scrutinizer ignore-type */ $this->sessionId . "\r\n" : '') .
Loading history...
107
                ($this->headers !== false ? implode("\r\n", $this->headers) . "\r\n" : ''),
0 ignored issues
show
Bug introduced by
$this->headers of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

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

107
                ($this->headers !== false ? implode("\r\n", /** @scrutinizer ignore-type */ $this->headers) . "\r\n" : ''),
Loading history...
introduced by
The condition $this->headers !== false is always true.
Loading history...
108
                'method' => 'POST',
109
                'content' => http_build_query($data)
110
            ]
111
        ];
112
113
        $context = stream_context_create($options);
114
        $result = file_get_contents($url, false, $context);
115
116
        $this->assertErrors($result, 'Request have returned warnings/errors');
117
118
        $jsonResult = json_decode($result);
119
120
        $this->assertJsonResponse($jsonResult, $result);
121
122
        return $jsonResult;
123
    }
124
125
    /**
126
     * Method prepares GET request options.
127
     */
128
    protected function prepareGetOptions()
129
    {
130
        return [
131
            'http' => [
132
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
133
                "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\r\n" .
134
                ($this->sessionId !== false ? "Cgi-Authorization: Basic " . $this->sessionId . "\r\n" : '') .
0 ignored issues
show
Bug introduced by
Are you sure $this->sessionId of type true can be used in concatenation? ( Ignorable by Annotation )

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

134
                ($this->sessionId !== false ? "Cgi-Authorization: Basic " . /** @scrutinizer ignore-type */ $this->sessionId . "\r\n" : '') .
Loading history...
135
                ($this->headers !== false ? implode("\r\n", $this->headers) . "\r\n" : ''),
0 ignored issues
show
introduced by
The condition $this->headers !== false is always true.
Loading history...
Bug introduced by
$this->headers of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

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

135
                ($this->headers !== false ? implode("\r\n", /** @scrutinizer ignore-type */ $this->headers) . "\r\n" : ''),
Loading history...
136
                'method' => 'GET'
137
            ]
138
        ];
139
    }
140
141
    /**
142
     * Method sends GET request
143
     *
144
     * @param string $url
145
     *            Requesting URL
146
     * @return mixed Result off the request
147
     */
148
    protected function getHttpRequest(string $url)
149
    {
150
        $options = $this->prepareGetOptions();
151
152
        $context = stream_context_create($options);
153
        $result = file_get_contents($url, false, $context);
154
155
        $this->assertErrors($result, 'Request have returned warnings/errors');
156
157
        $jsonResult = json_decode($result);
158
159
        $this->assertJsonResponse($jsonResult, $result);
160
161
        return $jsonResult;
162
    }
163
164
    /**
165
     * Method returns test data
166
     *
167
     * @return array Test data
168
     */
169
    protected function getUserData(): array
170
    {
171
        return [
172
            'login' => '[email protected]',
173
            'password' => 'root'
174
        ];
175
    }
176
177
    /**
178
     * Method performs valid connect.
179
     *
180
     * @return mixed Result of the connection.
181
     */
182
    protected function validConnect()
183
    {
184
        $data = $this->getUserData();
185
186
        $url = $this->serverPath . '/connect/';
187
188
        $result = $this->postHttpRequest($data, $url);
189
190
        if (isset($result->session_id) !== false) {
191
            $this->sessionId = $result->session_id;
192
        }
193
194
        return $result;
195
    }
196
197
    /**
198
     * Testing API connection.
199
     */
200
    public function testValidConnect()
201
    {
202
        // authorization
203
        $result = $this->validConnect();
204
205
        $this->assertNotEquals($result, null, 'Connection failed');
206
207
        if (isset($result->session_id) === false) {
208
            $this->assertEquals(true, false, 'Field "session_id" was not set');
209
        }
210
211
        $this->sessionId = $result->session_id;
212
    }
213
214
    /**
215
     * Testing API invalid connection.
216
     */
217
    public function testInvalidConnect()
218
    {
219
        // authorization
220
        $data = $this->getUserData();
221
        $data['password'] = '1234';
222
223
        $url = $this->serverPath . '/connect/';
224
225
        $this->expectException(\Exception::class);
226
        $this->postHttpRequest($data, $url);
227
    }
228
229
    /**
230
     * Testing setting valid token.
231
     */
232
    public function testSetValidToken()
233
    {
234
        $this->testValidConnect();
235
236
        $data = [
237
            'token' => $this->sessionId
238
        ];
239
240
        $url = $this->serverPath . '/token/' . $this->sessionId . '/';
241
242
        $result = $this->postHttpRequest($data, $url);
243
244
        $this->assertEquals(isset($result->session_id), true, 'Connection failed');
245
    }
246
247
    /**
248
     * Testing setting invalid token.
249
     */
250
    public function testSetInvalidToken()
251
    {
252
        try {
253
            $this->testValidConnect();
254
255
            $data = [
256
                'token' => ''
257
            ];
258
259
            $url = $this->serverPath . '/token/unexisting/';
260
261
            $this->postHttpRequest($data, $url);
262
        } catch (\Exception $e) {
263
            // set token method either throws exception or not
264
            // both is correct behaviour
265
            $this->assertEquals($e->getMessage(), 'Invalid session token', 'Invalid error message');
266
            $this->assertEquals($e->getCode(), 2, 'Invalid error code');
267
        }
268
    }
269
270
    /**
271
     * Testing login under another user
272
     */
273
    public function testLoginAs()
274
    {
275
        // setup
276
        $this->testValidConnect();
277
278
        // test body
279
        $data = [
280
            'login' => '[email protected]'
281
        ];
282
283
        $url = $this->serverPath . '/login-as/';
284
285
        $this->postHttpRequest($data, $url);
286
287
        // assertions
288
        $url = $this->serverPath . '/self/login/';
289
290
        $result = $this->get_html_request($url);
0 ignored issues
show
Bug introduced by
The method get_html_request() does not exist on Mezon\Service\Tests\ServiceTests. ( Ignorable by Annotation )

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

290
        /** @scrutinizer ignore-call */ 
291
        $result = $this->get_html_request($url);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
291
292
        $this->assertEquals(
293
            '[email protected]',
294
            \Mezon\Functional\Fetcher::getField($result, 'login'),
295
            'Session user must be [email protected]');
296
    }
297
}
298