Passed
Pull Request — master (#28)
by Fran
08:31
created

ServiceTest::testAuthorizedCall()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 38
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 29
nc 7
nop 0
dl 0
loc 38
rs 9.1448
c 0
b 0
f 0
1
<?php
2
3
namespace PSFS\tests\base;
4
5
use PHPUnit\Framework\TestCase;
6
use PSFS\base\Logger;
7
use PSFS\base\Service;
8
use PSFS\base\Singleton;
9
use PSFS\base\types\CurlService;
10
11
/**
12
 * Class ServiceTest
13
 * @package PSFS\tests
14
 */
15
class ServiceTest extends TestCase
16
{
17
18
//    /** @var Process */
19
//    private static Process $process;
20
//
21
//
22
//    public static function setUpBeforeClass(): void
23
//    {
24
//        self::$process = new Process(["php", "-S", "0.0.0.0:8888", "-t", realpath(WEB_DIR)]);
25
//        self::$process->setIdleTimeout(0.0);
26
//        self::$process->setTimeout(0.0);
27
//        self::$process->enableOutput();
28
//        self::$process->start();
29
//        usleep(1000);
30
//    }
31
//
32
//    public static function tearDownAfterClass(): void
33
//    {
34
//        self::$process->stop();
35
//    }
36
37
    private function hasInternet()
38
    {
39
        // use 80 for http or 443 for https protocol
40
        $connected = @fsockopen("https://github.com", 443);
41
        if ($connected) {
0 ignored issues
show
introduced by
$connected is of type false|resource, thus it always evaluated to false.
Loading history...
42
            fclose($connected);
43
            return true;
44
        }
45
        return false;
46
    }
47
48
    protected function getServiceInstance(): Service
49
    {
50
        $srv = Service::getInstance();
51
        // Check instance
52
        $this->assertInstanceOf(Service::class, $srv, '$srv is not a Service class');
53
        // Check Singleton
54
        $this->assertInstanceOf(Singleton::class, $srv, '$srv is not a Singleton class');
55
        // Check initialization
56
        $this->assertNull($srv->getUrl(), 'Service has previous url set');
57
        $srv->setUrl('www.example.com');
58
        $this->assertNotEmpty($srv->getUrl(), 'Service has empty url');
59
        $srv->setUrl('www.google.com');
60
        $this->assertNotEquals('www.example.com', $srv->getUrl(), 'Service does not update url');
61
        return $srv;
62
    }
63
64
    protected function checkParams(Service $srv)
65
    {
66
        $paramName = uniqid('test');
67
        $paramValue = microtime(true);
68
        // CHeck when param didn't exist
69
        $param = $srv->getParam($paramName);
70
        $this->assertNull($param, 'Param exists before test');
71
        // Set params with bulk method
72
        $srv->setParams([$paramName => $paramValue]);
73
        $this->assertNotEmpty($srv->getParams(), 'Service params are empty');
74
        $param = $srv->getParam($paramName);
75
        $this->assertNotNull($param, 'Param did not exists');
76
        // Check to remove params
77
        $count = count($srv->getParams());
78
        $srv->dropParam($paramName);
79
        $this->assertNotEquals(count($srv->getParams()), $count, 'Param not dropped');
80
        // Check adding one param
81
        $srv->addParam($paramName, $paramValue);
82
        $param = $srv->getParam($paramName);
83
        $this->assertNotNull($param, 'Param did not exists');
84
        $this->assertEquals($paramValue, $param, 'Different param value');
85
    }
86
87
    protected function checkOptions(Service $srv)
88
    {
89
        // Clean data
90
        $srv->setOptions([]);
91
        // CHeck when option didn't exist
92
        $option = $srv->getOption(CURLOPT_CONNECTTIMEOUT);
93
        $this->assertNull($option, 'Option exists before test');
94
        // Set option with bulk method
95
        $srv->setOptions([CURLOPT_CONNECTTIMEOUT => 30]);
96
        $this->assertNotEmpty($srv->getOptions(), 'Service options are empty');
97
        $option = $srv->getOption(CURLOPT_CONNECTTIMEOUT);
98
        $this->assertNotNull($option, 'Option did not exists');
99
        // Check to remove options
100
        $count = count($srv->getOptions());
101
        $srv->dropOption(CURLOPT_CONNECTTIMEOUT);
102
        $this->assertNotEquals(count($srv->getOptions()), $count, 'Option not dropped');
103
        // Check adding one option
104
        $srv->addOption(CURLOPT_CONNECTTIMEOUT, 30);
105
        $option = $srv->getOption(CURLOPT_CONNECTTIMEOUT);
106
        $this->assertNotNull($option, 'Option did not exists');
107
        $this->assertEquals(30, $option, 'Different option value');
108
    }
109
110
    /**
111
     * @return void
112
     */
113
    public function testServiceTraits()
114
    {
115
        $srv = $this->getServiceInstance();
116
        $this->assertInstanceOf(Service::class, $srv, '$srv is not a Service class');
117
        $this->checkParams($srv);
118
        $this->checkOptions($srv);
119
120
        // Initialize url, with default second param, the service has to clean all variables
121
        $srv->setUrl('https://example.com');
122
123
        // Tests has to be passed again
124
        $this->checkParams($srv);
125
126
        // Initialize service without cleaning params and options
127
        $srv->setUrl('https://google.com', false);
128
        $this->assertNotEquals('https://example.com', $srv->getUrl(), 'Service does not update url');
129
        $this->assertEquals('https://google.com', $srv->getUrl(), 'Service does not update url');
130
        $this->assertNotEmpty($srv->getParams(), 'Params are empty');
131
        $this->assertNotEmpty($srv->getOptions(), 'Options are empty');
132
        $this->assertInstanceOf(Logger::class, $srv->getLog(), 'Logger not instantiated');
133
    }
134
135
    /**
136
     * @return void
137
     */
138
    public function testSimpleCall()
139
    {
140
        if ($this->hasInternet()) {
141
            $this->markTestIncomplete('Pending make tests');
142
        } else {
143
            $this->assertTrue(true, 'Not connected to internet');
144
        }
145
    }
146
147
    /**
148
     * @return void
149
     */
150
    public function testAuthorizedCall()
151
    {
152
        $authSrv = \PSFS\tests\examples\AuthServiceTestExample::getInstance();
153
        // Generate random user and password
154
        $user = uniqid('user');
155
        $password = sha1(microtime(true));
156
        $basicAuth = "{$user}:{$password}";
157
        // Apply auth to a example service
158
        $authSrv->test($user, $password);
159
        // Check options created into curl resource
160
        $curl = $authSrv->getCon();
161
        $this->assertInstanceOf(\CurlHandle::class, $curl, 'Curl resource was not created');
162
        $callInfo = $authSrv->getCallInfo();
163
        $jsonResponse = $authSrv->getResult();
164
        // Get specific curl options that have to be set
165
        $authType = $authSrv->getOption(CURLOPT_HTTPAUTH);
166
        $this->assertNotNull($authType, 'Auth not set');
167
        $this->assertEquals(CURLAUTH_BASIC, $authType, 'Auth basic not set');
168
        $authString = $authSrv->getOption(CURLOPT_USERPWD);
169
        $this->assertNotNull($authString, 'Basic auth string not set');
170
        $this->assertEquals($basicAuth, $authString, 'Different auth string');
171
        // Check request response
172
        $this->assertIsArray($jsonResponse, 'Bad json decoding');
173
        $this->assertArrayHasKey('request_header', $callInfo, 'Verbose mode not activated');
174
        if (array_key_exists('request_header', $callInfo)) {
175
            $rawHeaders = explode("\r\n", $callInfo['request_header']);
176
            $headers = [];
177
            foreach ($rawHeaders as $rawHeader) {
178
                $data = explode(": ", $rawHeader, 2);
179
                if (count($data) === 2) {
180
                    $headers[strtolower($data[0])] = $data[1];
181
                }
182
            }
183
            $this->assertArrayHasKey(strtolower('Authorization'), $headers, 'Auth header not set');
184
            $this->assertArrayHasKey(strtolower(CurlService::PSFS_AUTH_HEADER), $headers, 'PSFS Security header not set');
185
            if (array_key_exists(strtolower('Authorization'), $headers)) {
186
                $authorization = base64_decode(str_replace('Basic ', '', $headers[strtolower('Authorization')]));
187
                $this->assertEquals($basicAuth, $authorization, 'Basic header different than expected');
188
            }
189
        }
190
    }
191
192
//    public function testAccessToAdminWithoutCredentials()
193
//    {
194
//        $curl = Service::getInstance();
195
//        $curl->setUrl('http://localhost:8888/admin');
196
//        $curl->setType('GET');
197
//        $curl->setIsJson(false);
198
//        $curl->setDebug(true);
199
//        $curl->callSrv();
200
//        $info = $curl->getInfo();
201
//        $response = $curl->getResult();
202
//        $this->assertNotNull($response, 'Empty response');
203
//        $this->assertEquals(401, $info['http_code'], 'Can access to admin zone without credentials');
204
//    }
205
//
206
//    public function testAccessToAdminWithWrongCredentials()
207
//    {
208
//        $curl = Service::getInstance();
209
//        $curl->setUrl('http://localhost:8888/admin');
210
//        $curl->addHeader('Authorization', 'Basic ' . base64_encode("demo:test"));
211
//        $curl->setType('GET');
212
//        $curl->setIsJson(false);
213
//        $curl->callSrv();
214
//        $info = $curl->getInfo();
215
//        $response = $curl->getResult();
216
//        $this->assertNotNull($response, 'Empty response');
217
//        $this->assertEquals(401, $info['http_code'], 'Can access to admin zone without right credentials');
218
//    }
219
//
220
//    public function testAccessToAdminWithCredentials()
221
//    {
222
//        Security::save([
223
//            'username' => 'demo',
224
//            'password' => 'demo',
225
//            'profile' => AuthHelper::ADMIN_ID_TOKEN,
226
//        ]);
227
//        $curl = Service::getInstance();
228
//        $curl->setUrl('http://localhost:8888/admin');
229
//        $curl->addHeader('Authorization', 'Basic ' . base64_encode("demo:demo"));
230
//        $curl->setType('GET');
231
//        $curl->setIsJson(false);
232
//        $curl->callSrv();
233
//        $info = $curl->getInfo();
234
//        $response = $curl->getResult();
235
//        $this->assertNotNull($response, 'Empty response');
236
//        $this->assertEquals(200, $info['http_code'], 'Can access to admin zone without right credentials');
237
//    }
238
}
239