Completed
Push — master ( ad6921...16742d )
by Alex
07:56
created

ServiceTests::getUserData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

99
                ($this->sessionId !== false ? "Cgi-Authorization: Basic " . /** @scrutinizer ignore-type */ $this->sessionId . "\r\n" : '') .
Loading history...
100
                ($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

100
                ($this->headers !== false ? implode("\r\n", /** @scrutinizer ignore-type */ $this->headers) . "\r\n" : ''),
Loading history...
101
                'method' => 'POST',
102
                'content' => http_build_query($data)
103
            ]
104
        ];
105
106
        $context = stream_context_create($options);
107
        $result = file_get_contents($url, false, $context);
108
109
        $this->assertErrors($result, 'Request have returned warnings/errors');
110
111
        return json_decode($result);
112
    }
113
114
    /**
115
     * Method prepares GET request options
116
     */
117
    protected function prepareGetOptions()
118
    {
119
        return [
120
            'http' => [
121
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
122
                "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\r\n" .
123
                ($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

123
                ($this->sessionId !== false ? "Cgi-Authorization: Basic " . /** @scrutinizer ignore-type */ $this->sessionId . "\r\n" : '') .
Loading history...
124
                ($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

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