Completed
Pull Request — master (#27)
by Harry
06:09
created

testUidSignatureWhenInvalidSignatureThrowsAnException()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 11

Duplication

Lines 26
Ratio 100 %

Importance

Changes 0
Metric Value
dl 26
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
/**
3
 * This file is part of graze/gigya-client
4
 *
5
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/gigya-client/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/gigya-client
12
 */
13
14
namespace Graze\Gigya\Test\Integration;
15
16
use Graze\Gigya\Exception\InvalidTimestampException;
17
use Graze\Gigya\Exception\InvalidUidSignatureException;
18
use Graze\Gigya\Gigya;
19
use Graze\Gigya\Test\TestCase;
20
use Graze\Gigya\Test\TestFixtures;
21
use Graze\Gigya\Validation\Signature;
22
use GuzzleHttp\Handler\MockHandler;
23
use GuzzleHttp\HandlerStack;
24
use GuzzleHttp\Middleware;
25
use GuzzleHttp\Psr7\Response;
26
use Illuminate\Support\Collection;
27
use Mockery as m;
28
use Psr\Http\Message\RequestInterface;
29
30
class GigyaTest extends TestCase
31
{
32
    /**
33
     * @param string|null $body Optional body text
34
     *
35
     * @return HandlerStack
36
     */
37
    public function setupHandler($body = null)
38
    {
39
        $mockHandler = new MockHandler(array_pad(
40
            [],
41
            3,
42
            new Response(
43
                '200',
44
                [],
45
                $body ?: TestFixtures::getFixture('basic')
46
            )
47
        ));
48
49
        return new HandlerStack($mockHandler);
50
    }
51
52
    public function testAuthInjectsKeyAndSecretIntoParams()
53
    {
54
        $handler = $this->setupHandler();
55
        $client = new Gigya('key', 'secret', null, null, ['guzzle' => ['handler' => $handler]]);
56
        $store = [];
57
        $handler->push(Middleware::history($store));
58
59
        $response = $client->accounts()->getAccountInfo();
60
61
        static::assertEquals(0, $response->getErrorCode());
62
        static::assertCount(1, $store);
63
        $log = array_pop($store);
64
        static::assertEquals(
65
            'https://accounts.eu1.gigya.com/accounts.getAccountInfo',
66
            $log['request']->getUri()->__toString()
67
        );
68
        static::assertEquals(
69
            'apiKey=key&secret=secret',
70
            $log['request']->getBody()->__toString()
71
        );
72
        static::assertEquals(['application/x-www-form-urlencoded'], $log['request']->getHeader('Content-Type'));
73
    }
74
75
    public function testAuthInjectsKeySecretAndUserKeyIntoParams()
76
    {
77
        $handler = $this->setupHandler();
78
        $client = new Gigya('key', 'secret', null, 'userKey', ['guzzle' => ['handler' => $handler]]);
79
        $store = [];
80
        $handler->push(Middleware::history($store));
81
82
        $response = $client->accounts()->getAccountInfo();
83
84
        static::assertEquals(0, $response->getErrorCode());
85
        static::assertCount(1, $store);
86
        $log = array_pop($store);
87
        static::assertArrayHasKey('request', $log);
88
        /** @var RequestInterface $request */
89
        $request = $log['request'];
90
        static::assertInstanceOf(RequestInterface::class, $request);
91
        static::assertEquals(
92
            'https://accounts.eu1.gigya.com/accounts.getAccountInfo',
93
            $request->getUri()->__toString()
94
        );
95
        static::assertEquals(
96
            'apiKey=key&secret=secret&userKey=userKey',
97
            $log['request']->getBody()->__toString()
98
        );
99
        static::assertEquals(['application/x-www-form-urlencoded'], $log['request']->getHeader('Content-Type'));
100
    }
101
102
    public function testUidSignatureWhenValidDoesNotThrowException()
103
    {
104
        $uid = 'diofu90ifgdf';
105
        $timestamp = time();
106
107
        $signatureValidator = new Signature();
108
        $signature = $signatureValidator->calculateSignature($timestamp . '_' . $uid, 'secret');
109
110
        $body = sprintf(
111
            '{
112
            "UID": "%s",
113
            "UIDSignature": "%s",
114
            "signatureTimestamp": "%d",
115
            "statusCode": 200,
116
            "errorCode": 0,
117
            "statusReason": "OK",
118
            "callId": "123456",
119
            "time": "2015-03-22T11:42:25.943Z"
120
        }',
121
            $uid,
122
            $signature,
123
            $timestamp
124
        );
125
126
        $handler = $this->setupHandler($body);
127
        $client = new Gigya('key', 'secret', null, null, ['guzzle' => ['handler' => $handler]]);
128
        $store = [];
129
        $handler->push(Middleware::history($store));
130
131
        $response = $client->accounts()->getAccountInfo(['uid' => $uid]);
132
        static::assertEquals(0, $response->getErrorCode());
133
        static::assertCount(1, $store);
134
        $log = array_pop($store);
135
        static::assertEquals(
136
            "https://accounts.eu1.gigya.com/accounts.getAccountInfo",
137
            $log['request']->getUri()->__toString()
138
        );
139
        static::assertEquals(
140
            "uid=$uid&apiKey=key&secret=secret",
141
            $log['request']->getBody()->__toString()
142
        );
143
        static::assertEquals(['application/x-www-form-urlencoded'], $log['request']->getHeader('Content-Type'));
144
145
        $data = $response->getData();
146
        static::assertEquals($uid, $data->get('UID'));
147
        static::assertEquals($signature, $data->get('UIDSignature'));
148
        static::assertEquals($timestamp, $data->get('signatureTimestamp'));
149
    }
150
151
    /**
152
     * @expectedException \Graze\Gigya\Exception\InvalidTimestampException
153
     */
154
    public function testUidSignatureWhenIncorrectTimestampThrowsAnException()
155
    {
156
        $uid = 'diofu90ifgdf';
157
        $timestamp = time() - 181;
158
159
        $signatureValidator = new Signature();
160
        $signature = $signatureValidator->calculateSignature($timestamp . '_' . $uid, 'secret');
161
162
        $body = sprintf(
163
            '{
164
            "UID": "%s",
165
            "UIDSignature": "%s",
166
            "signatureTimestamp": "%d",
167
            "statusCode": 200,
168
            "errorCode": 0,
169
            "statusReason": "OK",
170
            "callId": "123456",
171
            "time": "2015-03-22T11:42:25.943Z"
172
        }',
173
            $uid,
174
            $signature,
175
            $timestamp
176
        );
177
178
        $handler = $this->setupHandler($body);
179
        $client = new Gigya('key', 'secret', null, null, ['guzzle' => ['handler' => $handler]]);
180
181
        $client->accounts()->getAccountInfo(['uid' => $uid]);
182
    }
183
184
    /**
185
     * @expectedException \Graze\Gigya\Exception\InvalidUidSignatureException
186
     */
187 View Code Duplication
    public function testUidSignatureWhenInvalidSignatureThrowsAnException()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
    {
189
        $uid = 'diofu90ifgdf';
190
        $timestamp = time();
191
192
        $body = sprintf(
193
            '{
194
            "UID": "%s",
195
            "UIDSignature": "%s",
196
            "signatureTimestamp": "%d",
197
            "statusCode": 200,
198
            "errorCode": 0,
199
            "statusReason": "OK",
200
            "callId": "123456",
201
            "time": "2015-03-22T11:42:25.943Z"
202
        }',
203
            $uid,
204
            'invalid',
205
            $timestamp
206
        );
207
208
        $handler = $this->setupHandler($body);
209
        $client = new Gigya('key', 'secret', null, null, ['guzzle' => ['handler' => $handler]]);
210
211
        $client->accounts()->getAccountInfo(['uid' => $uid]);
212
    }
213
214
    /**
215
     * @expectedException \Graze\Gigya\Exception\InvalidTimestampException
216
     */
217 View Code Duplication
    public function testRequestWillThrowTimestampExceptionWhenBothTimestampAndSignatureAreInvalid()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
218
    {
219
        $uid = 'diofu90ifgdf';
220
        $timestamp = time() - 181;
221
222
        $body = sprintf(
223
            '{
224
            "UID": "%s",
225
            "UIDSignature": "%s",
226
            "signatureTimestamp": "%d",
227
            "statusCode": 200,
228
            "errorCode": 0,
229
            "statusReason": "OK",
230
            "callId": "123456",
231
            "time": "2015-03-22T11:42:25.943Z"
232
        }',
233
            $uid,
234
            'invalid',
235
            $timestamp
236
        );
237
238
        $handler = $this->setupHandler($body);
239
        $client = new Gigya('key', 'secret', null, null, ['guzzle' => ['handler' => $handler]]);
240
241
        $client->accounts()->getAccountInfo(['uid' => $uid]);
242
    }
243
244
    public function testGigyaWillTriggerSubscriberOnlyWhenItIsAddedInARequest()
245
    {
246
        $handler = $this->setupHandler();
247
        $client = new Gigya('key', 'secret', null, null, ['guzzle' => ['handler' => $handler]]);
248
249
        $client->accounts()->getAccountInfo();
250
251
        $called = 0;
252
253
        $fn = function (callable $handler) use (&$called) {
254
            return function (RequestInterface $request, $options) use ($handler, &$called) {
255
                $called++;
256
                return $handler($request, $options);
257
            };
258
        };
259
260
        $client->addHandler($fn);
261
262
        $client->accounts()->getAccountInfo();
263
264
        $this->assertEquals(1, $called);
265
266
        $client->removeHandler($fn);
267
268
        $client->accounts()->getAccountInfo();
269
270
        $this->assertEquals(1, $called);
271
    }
272
}
273