Completed
Push — master ( 2fe9aa...60a03e )
by Steven
01:34
created

InstagramTest::tearDown()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php namespace League\OAuth2\Client\Test\Provider;
2
3
use League\OAuth2\Client\Tool\QueryBuilderTrait;
4
use Mockery as m;
5
6
class InstagramTest extends \PHPUnit\Framework\TestCase
7
{
8
    use QueryBuilderTrait;
9
10
    protected $provider;
11
12
    protected function setUp(): void
13
    {
14
        $this->provider = new \League\OAuth2\Client\Provider\Instagram([
15
            'clientId' => 'mock_client_id',
16
            'clientSecret' => 'mock_secret',
17
            'redirectUri' => 'none',
18
        ]);
19
    }
20
21
    public function testAuthorizationUrl()
22
    {
23
        $url = $this->provider->getAuthorizationUrl();
24
        $uri = parse_url($url);
25
        parse_str($uri['query'], $query);
26
27
        $this->assertArrayHasKey('client_id', $query);
0 ignored issues
show
Bug introduced by
It seems like $query can also be of type null; however, PHPUnit\Framework\Assert::assertArrayHasKey() does only seem to accept array|object<ArrayAccess>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
28
        $this->assertArrayHasKey('redirect_uri', $query);
0 ignored issues
show
Bug introduced by
It seems like $query can also be of type null; however, PHPUnit\Framework\Assert::assertArrayHasKey() does only seem to accept array|object<ArrayAccess>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
29
        $this->assertArrayHasKey('state', $query);
0 ignored issues
show
Bug introduced by
It seems like $query can also be of type null; however, PHPUnit\Framework\Assert::assertArrayHasKey() does only seem to accept array|object<ArrayAccess>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
30
        $this->assertArrayHasKey('scope', $query);
0 ignored issues
show
Bug introduced by
It seems like $query can also be of type null; however, PHPUnit\Framework\Assert::assertArrayHasKey() does only seem to accept array|object<ArrayAccess>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
31
        $this->assertArrayHasKey('response_type', $query);
0 ignored issues
show
Bug introduced by
It seems like $query can also be of type null; however, PHPUnit\Framework\Assert::assertArrayHasKey() does only seem to accept array|object<ArrayAccess>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
32
        $this->assertArrayHasKey('approval_prompt', $query);
0 ignored issues
show
Bug introduced by
It seems like $query can also be of type null; however, PHPUnit\Framework\Assert::assertArrayHasKey() does only seem to accept array|object<ArrayAccess>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
33
        $this->assertNotNull($this->provider->getState());
34
    }
35
36
    public function testSetHostInConfig()
37
    {
38
        $host = uniqid();
39
40
        $provider = new \League\OAuth2\Client\Provider\Instagram([
41
            'clientId' => 'mock_client_id',
42
            'clientSecret' => 'mock_secret',
43
            'redirectUri' => 'none',
44
            'host' => $host
45
        ]);
46
47
        $this->assertEquals($host, $provider->getHost());
48
    }
49
50
    public function testSetHostAfterConfig()
51
    {
52
        $host = uniqid();
53
54
        $this->provider->setHost($host);
55
56
        $this->assertEquals($host, $this->provider->getHost());
57
    }
58
59
    public function testScopes()
60
    {
61
        $scopeSeparator = ' ';
62
        $options = ['scope' => [uniqid(), uniqid()]];
63
        $query = ['scope' => implode($scopeSeparator, $options['scope'])];
64
        $url = $this->provider->getAuthorizationUrl($options);
65
        $encodedScope = $this->buildQueryString($query);
66
        $this->assertStringContainsString($encodedScope, $url);
67
    }
68
69
    public function testGetAuthorizationUrl()
70
    {
71
        $url = $this->provider->getAuthorizationUrl();
72
        $uri = parse_url($url);
73
74
        $this->assertEquals('/oauth/authorize', $uri['path']);
75
    }
76
77
    public function testGetBaseAccessTokenUrl()
78
    {
79
        $params = [];
80
81
        $url = $this->provider->getBaseAccessTokenUrl($params);
82
        $uri = parse_url($url);
83
84
        $this->assertEquals('/oauth/access_token', $uri['path']);
85
    }
86
87
    public function testGetAccessToken()
88
    {
89
        $response = m::mock('Psr\Http\Message\ResponseInterface');
90
        $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token","user": {"id": "123","username": "snoopdogg","full_name": "Snoop Dogg","profile_picture": "..."}}');
91
        $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
92
93
        $client = m::mock('GuzzleHttp\ClientInterface');
94
        $client->shouldReceive('send')->times(1)->andReturn($response);
95
        $this->provider->setHttpClient($client);
96
97
        $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
98
99
        $this->assertEquals('mock_access_token', $token->getToken());
100
        $this->assertNull($token->getExpires());
101
        $this->assertNull($token->getRefreshToken());
102
        $this->assertEquals('123', $token->getResourceOwnerId());
103
    }
104
105
    public function testUserData()
106
    {
107
        $userId = rand(1000,9999);
108
        $name = uniqid();
109
        $nickname = uniqid();
110
        $picture = uniqid();
111
        $description = uniqid();
112
113
        $postResponse = m::mock('Psr\Http\Message\ResponseInterface');
114
        $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token","user": {"id": "1574083","username": "snoopdogg","full_name": "Snoop Dogg","profile_picture": "..."}}');
115
        $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
116
117
        $userResponse = m::mock('Psr\Http\Message\ResponseInterface');
118
        $userResponse->shouldReceive('getBody')->andReturn('{"data": {"id": "'.$userId.'", "username": "'.$nickname.'", "full_name": "'.$name.'", "bio": "'.$description.'", "profile_picture": "'.$picture.'"}}');
119
        $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
120
121
        $client = m::mock('GuzzleHttp\ClientInterface');
122
        $client->shouldReceive('send')
123
            ->times(2)
124
            ->andReturn($postResponse, $userResponse);
125
        $this->provider->setHttpClient($client);
126
127
        $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
128
        $user = $this->provider->getResourceOwner($token);
0 ignored issues
show
Compatibility introduced by
$token of type object<League\OAuth2\Cli...n\AccessTokenInterface> is not a sub-type of object<League\OAuth2\Client\Token\AccessToken>. It seems like you assume a concrete implementation of the interface League\OAuth2\Client\Token\AccessTokenInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
129
130
        $this->assertEquals($userId, $user->getId());
131
        $this->assertEquals($userId, $user->toArray()['id']);
132
        $this->assertEquals($name, $user->getName());
133
        $this->assertEquals($name, $user->toArray()['full_name']);
134
        $this->assertEquals($nickname, $user->getNickname());
135
        $this->assertEquals($nickname, $user->toArray()['username']);
136
        $this->assertEquals($picture, $user->getImageurl());
137
        $this->assertEquals($picture, $user->toArray()['profile_picture']);
138
        $this->assertEquals($description, $user->getDescription());
139
        $this->assertEquals($description, $user->toArray()['bio']);
140
    }
141
142
    public function testExceptionThrownWhenErrorObjectReceived()
143
    {
144
        $this->expectException('League\OAuth2\Client\Provider\Exception\IdentityProviderException');
145
        $message = uniqid();
146
        $status = rand(400,600);
147
        $postResponse = m::mock('Psr\Http\Message\ResponseInterface');
148
        $postResponse->shouldReceive('getBody')->andReturn('{"meta": {"error_type": "OAuthException","code": '.$status.',"error_message": "'.$message.'"}}');
149
        $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
150
        $postResponse->shouldReceive('getReasonPhrase');
151
        $postResponse->shouldReceive('getStatusCode')->andReturn($status);
152
153
        $client = m::mock('GuzzleHttp\ClientInterface');
154
        $client->shouldReceive('send')
155
            ->times(1)
156
            ->andReturn($postResponse);
157
        $this->provider->setHttpClient($client);
158
        $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
159
    }
160
161
    public function testExceptionThrownWhenAuthErrorObjectReceived()
162
    {
163
        $this->expectException('League\OAuth2\Client\Provider\Exception\IdentityProviderException');
164
        $message = uniqid();
165
        $status = rand(400,600);
166
        $postResponse = m::mock('Psr\Http\Message\ResponseInterface');
167
        $postResponse->shouldReceive('getBody')->andReturn('{"error_type": "OAuthException","code": '.$status.',"error_message": "'.$message.'"}');
168
        $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
169
        $postResponse->shouldReceive('getReasonPhrase');
170
        $postResponse->shouldReceive('getStatusCode')->andReturn($status);
171
172
        $client = m::mock('GuzzleHttp\ClientInterface');
173
        $client->shouldReceive('send')
174
            ->times(1)
175
            ->andReturn($postResponse);
176
        $this->provider->setHttpClient($client);
177
        $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
178
    }
179
180
    public function testGetAuthenticatedRequest()
181
    {
182
        $method = 'GET';
183
        $url = 'https://api.instagram.com/v1/users/self/feed';
184
185
        $accessTokenResponse = m::mock('Psr\Http\Message\ResponseInterface');
186
        $accessTokenResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token","user": {"id": "1574083","username": "snoopdogg","full_name": "Snoop Dogg","profile_picture": "..."}}');
187
        $accessTokenResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
188
189
        $client = m::mock('GuzzleHttp\ClientInterface');
190
        $client->shouldReceive('send')
191
            ->times(1)
192
            ->andReturn($accessTokenResponse);
193
        $this->provider->setHttpClient($client);
194
195
        $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
196
197
        $authenticatedRequest = $this->provider->getAuthenticatedRequest($method, $url, $token);
198
199
        $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $authenticatedRequest);
200
        $this->assertEquals($method, $authenticatedRequest->getMethod());
201
        $this->assertStringContainsString('access_token=mock_access_token', $authenticatedRequest->getUri()->getQuery());
202
    }
203
}
204