PageRenderTime 24ms CodeModel.GetById 12ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Google/vendor/google/auth/tests/Middleware/AuthTokenMiddlewareTest.php

https://gitlab.com/vangtrangbac123/zinkaiuit.tk
PHP | 344 lines | 296 code | 26 blank | 22 comment | 0 complexity | 4af9890f509bd8e5fb6407ef7cf13d3e MD5 | raw file
  1<?php
  2/*
  3 * Copyright 2015 Google Inc.
  4 *
  5 * Licensed under the Apache License, Version 2.0 (the "License");
  6 * you may not use this file except in compliance with the License.
  7 * You may obtain a copy of the License at
  8 *
  9 *     http://www.apache.org/licenses/LICENSE-2.0
 10 *
 11 * Unless required by applicable law or agreed to in writing, software
 12 * distributed under the License is distributed on an "AS IS" BASIS,
 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14 * See the License for the specific language governing permissions and
 15 * limitations under the License.
 16 */
 17
 18namespace Google\Auth\Tests;
 19
 20use Google\Auth\FetchAuthTokenCache;
 21use Google\Auth\Middleware\AuthTokenMiddleware;
 22use GuzzleHttp\Handler\MockHandler;
 23use GuzzleHttp\Psr7\Response;
 24
 25class AuthTokenMiddlewareTest extends BaseTest
 26{
 27    private $mockFetcher;
 28    private $mockCacheItem;
 29    private $mockCache;
 30    private $mockRequest;
 31
 32    protected function setUp()
 33    {
 34        $this->onlyGuzzle6();
 35
 36        $this->mockFetcher =
 37            $this
 38                ->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
 39                ->getMock();
 40        $this->mockCacheItem =
 41            $this
 42                ->getMockBuilder('Psr\Cache\CacheItemInterface')
 43                ->getMock();
 44        $this->mockCache =
 45            $this
 46                ->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
 47                ->getMock();
 48        $this->mockRequest =
 49            $this
 50                ->getMockBuilder('GuzzleHttp\Psr7\Request')
 51                ->disableOriginalConstructor()
 52                ->getMock();
 53    }
 54
 55    public function testOnlyTouchesWhenAuthConfigScoped()
 56    {
 57        $this->mockFetcher
 58            ->expects($this->any())
 59            ->method('fetchAuthToken')
 60            ->will($this->returnValue([]));
 61        $this->mockRequest
 62            ->expects($this->never())
 63            ->method('withHeader');
 64
 65        $middleware = new AuthTokenMiddleware($this->mockFetcher);
 66        $mock = new MockHandler([new Response(200)]);
 67        $callable = $middleware($mock);
 68        $callable($this->mockRequest, ['auth' => 'not_google_auth']);
 69    }
 70
 71    public function testAddsTheTokenAsAnAuthorizationHeader()
 72    {
 73        $authResult = ['access_token' => '1/abcdef1234567890'];
 74        $this->mockFetcher
 75            ->expects($this->once())
 76            ->method('fetchAuthToken')
 77            ->will($this->returnValue($authResult));
 78        $this->mockRequest
 79            ->expects($this->once())
 80            ->method('withHeader')
 81            ->with('authorization', 'Bearer ' . $authResult['access_token'])
 82            ->will($this->returnValue($this->mockRequest));
 83
 84        // Run the test.
 85        $middleware = new AuthTokenMiddleware($this->mockFetcher);
 86        $mock = new MockHandler([new Response(200)]);
 87        $callable = $middleware($mock);
 88        $callable($this->mockRequest, ['auth' => 'google_auth']);
 89    }
 90
 91    public function testDoesNotAddAnAuthorizationHeaderOnNoAccessToken()
 92    {
 93        $authResult = ['not_access_token' => '1/abcdef1234567890'];
 94        $this->mockFetcher
 95            ->expects($this->once())
 96            ->method('fetchAuthToken')
 97            ->will($this->returnValue($authResult));
 98        $this->mockRequest
 99            ->expects($this->once())
100            ->method('withHeader')
101            ->with('authorization', 'Bearer ')
102            ->will($this->returnValue($this->mockRequest));
103
104        // Run the test.
105        $middleware = new AuthTokenMiddleware($this->mockFetcher);
106        $mock = new MockHandler([new Response(200)]);
107        $callable = $middleware($mock);
108        $callable($this->mockRequest, ['auth' => 'google_auth']);
109    }
110
111    public function testUsesCachedAuthToken()
112    {
113        $cacheKey = 'myKey';
114        $cachedValue = '2/abcdef1234567890';
115        $this->mockCacheItem
116            ->expects($this->once())
117            ->method('isHit')
118            ->will($this->returnValue(true));
119        $this->mockCacheItem
120            ->expects($this->once())
121            ->method('get')
122            ->will($this->returnValue($cachedValue));
123        $this->mockCache
124            ->expects($this->once())
125            ->method('getItem')
126            ->with($this->equalTo($cacheKey))
127            ->will($this->returnValue($this->mockCacheItem));
128        $this->mockFetcher
129            ->expects($this->never())
130            ->method('fetchAuthToken');
131        $this->mockFetcher
132            ->expects($this->any())
133            ->method('getCacheKey')
134            ->will($this->returnValue($cacheKey));
135        $this->mockRequest
136            ->expects($this->once())
137            ->method('withHeader')
138            ->with('authorization', 'Bearer ' . $cachedValue)
139            ->will($this->returnValue($this->mockRequest));
140
141        // Run the test.
142        $cachedFetcher = new FetchAuthTokenCache(
143            $this->mockFetcher,
144            null,
145            $this->mockCache
146        );
147        $middleware = new AuthTokenMiddleware($cachedFetcher);
148        $mock = new MockHandler([new Response(200)]);
149        $callable = $middleware($mock);
150        $callable($this->mockRequest, ['auth' => 'google_auth']);
151    }
152
153    public function testGetsCachedAuthTokenUsingCacheOptions()
154    {
155        $prefix = 'test_prefix_';
156        $cacheKey = 'myKey';
157        $cachedValue = '2/abcdef1234567890';
158        $this->mockCacheItem
159            ->expects($this->once())
160            ->method('isHit')
161            ->will($this->returnValue(true));
162        $this->mockCacheItem
163            ->expects($this->once())
164            ->method('get')
165            ->will($this->returnValue($cachedValue));
166        $this->mockCache
167            ->expects($this->once())
168            ->method('getItem')
169            ->with($this->equalTo($prefix . $cacheKey))
170            ->will($this->returnValue($this->mockCacheItem));
171        $this->mockFetcher
172            ->expects($this->never())
173            ->method('fetchAuthToken');
174        $this->mockFetcher
175            ->expects($this->any())
176            ->method('getCacheKey')
177            ->will($this->returnValue($cacheKey));
178        $this->mockRequest
179            ->expects($this->once())
180            ->method('withHeader')
181            ->with('authorization', 'Bearer ' . $cachedValue)
182            ->will($this->returnValue($this->mockRequest));
183
184        // Run the test.
185        $cachedFetcher = new FetchAuthTokenCache(
186            $this->mockFetcher,
187            ['prefix' => $prefix],
188            $this->mockCache
189        );
190        $middleware = new AuthTokenMiddleware($cachedFetcher);
191        $mock = new MockHandler([new Response(200)]);
192        $callable = $middleware($mock);
193        $callable($this->mockRequest, ['auth' => 'google_auth']);
194    }
195
196    public function testShouldSaveValueInCacheWithSpecifiedPrefix()
197    {
198        $prefix = 'test_prefix_';
199        $lifetime = '70707';
200        $cacheKey = 'myKey';
201        $token = '1/abcdef1234567890';
202        $authResult = ['access_token' => $token];
203        $this->mockCacheItem
204            ->expects($this->any())
205            ->method('get')
206            ->will($this->returnValue(null));
207        $this->mockCacheItem
208            ->expects($this->once())
209            ->method('set')
210            ->with($this->equalTo($token))
211            ->will($this->returnValue(false));
212        $this->mockCacheItem
213            ->expects($this->once())
214            ->method('expiresAfter')
215            ->with($this->equalTo($lifetime));
216        $this->mockCache
217            ->expects($this->any())
218            ->method('getItem')
219            ->with($this->equalTo($prefix . $cacheKey))
220            ->will($this->returnValue($this->mockCacheItem));
221        $this->mockFetcher
222            ->expects($this->any())
223            ->method('getCacheKey')
224            ->will($this->returnValue($cacheKey));
225        $this->mockFetcher
226            ->expects($this->once())
227            ->method('fetchAuthToken')
228            ->will($this->returnValue($authResult));
229        $this->mockRequest
230            ->expects($this->once())
231            ->method('withHeader')
232            ->with('authorization', 'Bearer ' . $token)
233            ->will($this->returnValue($this->mockRequest));
234
235        // Run the test.
236        $cachedFetcher = new FetchAuthTokenCache(
237            $this->mockFetcher,
238            ['prefix' => $prefix, 'lifetime' => $lifetime],
239            $this->mockCache
240        );
241        $middleware = new AuthTokenMiddleware($cachedFetcher);
242        $mock = new MockHandler([new Response(200)]);
243        $callable = $middleware($mock);
244        $callable($this->mockRequest, ['auth' => 'google_auth']);
245    }
246
247    /** @dataProvider provideShouldNotifyTokenCallback */
248    public function testShouldNotifyTokenCallback(callable $tokenCallback)
249    {
250        $prefix = 'test_prefix_';
251        $cacheKey = 'myKey';
252        $token = '1/abcdef1234567890';
253        $authResult = ['access_token' => $token];
254        $this->mockCacheItem
255            ->expects($this->any())
256            ->method('get')
257            ->will($this->returnValue(null));
258        $this->mockCache
259            ->expects($this->any())
260            ->method('getItem')
261            ->with($this->equalTo($prefix . $cacheKey))
262            ->will($this->returnValue($this->mockCacheItem));
263        $this->mockFetcher
264            ->expects($this->any())
265            ->method('getCacheKey')
266            ->will($this->returnValue($cacheKey));
267        $this->mockFetcher
268            ->expects($this->once())
269            ->method('fetchAuthToken')
270            ->will($this->returnValue($authResult));
271        $this->mockRequest
272            ->expects($this->once())
273            ->method('withHeader')
274            ->will($this->returnValue($this->mockRequest));
275
276        MiddlewareCallback::$expectedKey = $this->getValidKeyName($prefix . $cacheKey);
277        MiddlewareCallback::$expectedValue = $token;
278        MiddlewareCallback::$called = false;
279
280        // Run the test.
281        $cachedFetcher = new FetchAuthTokenCache(
282            $this->mockFetcher,
283            ['prefix' => $prefix],
284            $this->mockCache
285        );
286        $middleware = new AuthTokenMiddleware(
287            $cachedFetcher,
288            null,
289            $tokenCallback
290        );
291        $mock = new MockHandler([new Response(200)]);
292        $callable = $middleware($mock);
293        $callable($this->mockRequest, ['auth' => 'google_auth']);
294        $this->assertTrue(MiddlewareCallback::$called);
295    }
296
297    public function provideShouldNotifyTokenCallback()
298    {
299        MiddlewareCallback::$phpunit = $this;
300        $anonymousFunc = function ($key, $value) {
301            MiddlewareCallback::staticInvoke($key, $value);
302        };
303        return [
304            ['Google\Auth\Tests\MiddlewareCallbackFunction'],
305            ['Google\Auth\Tests\MiddlewareCallback::staticInvoke'],
306            [['Google\Auth\Tests\MiddlewareCallback', 'staticInvoke']],
307            [$anonymousFunc],
308            [[new MiddlewareCallback, 'staticInvoke']],
309            [[new MiddlewareCallback, 'methodInvoke']],
310            [new MiddlewareCallback],
311        ];
312    }
313}
314
315class MiddlewareCallback
316{
317    public static $phpunit;
318    public static $expectedKey;
319    public static $expectedValue;
320    public static $called = false;
321
322    public function __invoke($key, $value)
323    {
324        self::$phpunit->assertEquals(self::$expectedKey, $key);
325        self::$phpunit->assertEquals(self::$expectedValue, $value);
326        self::$called = true;
327    }
328
329    public function methodInvoke($key, $value)
330    {
331        return $this($key, $value);
332    }
333
334    public static function staticInvoke($key, $value)
335    {
336        $instance = new self();
337        return $instance($key, $value);
338    }
339}
340
341function MiddlewareCallbackFunction($key, $value)
342{
343    return MiddlewareCallback::staticInvoke($key, $value);
344}