Completed
Push — master ( 1c642a...c282cc )
by Steven
01:53
created

InstagramTest::tearDown()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
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()
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 tearDown()
22
    {
23
        m::close();
24
        parent::tearDown();
25
    }
26
27
    public function testAuthorizationUrl()
28
    {
29
        $url = $this->provider->getAuthorizationUrl();
30
        $uri = parse_url($url);
31
        parse_str($uri['query'], $query);
32
33
        $this->assertArrayHasKey('client_id', $query);
0 ignored issues
show
Bug introduced by Steven Maguire
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...
34
        $this->assertArrayHasKey('redirect_uri', $query);
0 ignored issues
show
Bug introduced by Steven Maguire
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...
35
        $this->assertArrayHasKey('state', $query);
0 ignored issues
show
Bug introduced by Steven Maguire
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...
36
        $this->assertArrayHasKey('scope', $query);
0 ignored issues
show
Bug introduced by Steven Maguire
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...
37
        $this->assertArrayHasKey('response_type', $query);
0 ignored issues
show
Bug introduced by Steven Maguire
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...
38
        $this->assertArrayHasKey('approval_prompt', $query);
0 ignored issues
show
Bug introduced by Steven Maguire
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...
39
        $this->assertNotNull($this->provider->getState());
40
    }
41
42
    public function testSetHostInConfig()
43
    {
44
        $host = uniqid();
45
46
        $provider = new \League\OAuth2\Client\Provider\Instagram([
47
            'clientId' => 'mock_client_id',
48
            'clientSecret' => 'mock_secret',
49
            'redirectUri' => 'none',
50
            'host' => $host
51
        ]);
52
53
        $this->assertEquals($host, $provider->getHost());
54
    }
55
56
    public function testSetHostAfterConfig()
57
    {
58
        $host = uniqid();
59
60
        $this->provider->setHost($host);
61
62
        $this->assertEquals($host, $this->provider->getHost());
63
    }
64
65
    public function testScopes()
66
    {
67
        $scopeSeparator = ' ';
68
        $options = ['scope' => [uniqid(), uniqid()]];
69
        $query = ['scope' => implode($scopeSeparator, $options['scope'])];
70
        $url = $this->provider->getAuthorizationUrl($options);
71
        $encodedScope = $this->buildQueryString($query);
72
        $this->assertContains($encodedScope, $url);
73
    }
74
75
    public function testGetAuthorizationUrl()
76
    {
77
        $url = $this->provider->getAuthorizationUrl();
78
        $uri = parse_url($url);
79
80
        $this->assertEquals('/oauth/authorize', $uri['path']);
81
    }
82
83
    public function testGetBaseAccessTokenUrl()
84
    {
85
        $params = [];
86
87
        $url = $this->provider->getBaseAccessTokenUrl($params);
88
        $uri = parse_url($url);
89
90
        $this->assertEquals('/oauth/access_token', $uri['path']);
91
    }
92
93
    public function testGetAccessToken()
94
    {
95
        $response = m::mock('Psr\Http\Message\ResponseInterface');
96
        $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token","user": {"id": "123","username": "snoopdogg","full_name": "Snoop Dogg","profile_picture": "..."}}');
97
        $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
98
99
        $client = m::mock('GuzzleHttp\ClientInterface');
100
        $client->shouldReceive('send')->times(1)->andReturn($response);
101
        $this->provider->setHttpClient($client);
102
103
        $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
104
105
        $this->assertEquals('mock_access_token', $token->getToken());
106
        $this->assertNull($token->getExpires());
107
        $this->assertNull($token->getRefreshToken());
108
        $this->assertEquals('123', $token->getResourceOwnerId());
109
    }
110
111
    public function testUserData()
112
    {
113
        $userId = rand(1000,9999);
114
        $name = uniqid();
115
        $nickname = uniqid();
116
        $picture = uniqid();
117
        $description = uniqid();
118
119
        $postResponse = m::mock('Psr\Http\Message\ResponseInterface');
120
        $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token","user": {"id": "1574083","username": "snoopdogg","full_name": "Snoop Dogg","profile_picture": "..."}}');
121
        $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
122
123
        $userResponse = m::mock('Psr\Http\Message\ResponseInterface');
124
        $userResponse->shouldReceive('getBody')->andReturn('{"data": {"id": "'.$userId.'", "username": "'.$nickname.'", "full_name": "'.$name.'", "bio": "'.$description.'", "profile_picture": "'.$picture.'"}}');
125
        $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
126
127
        $client = m::mock('GuzzleHttp\ClientInterface');
128
        $client->shouldReceive('send')
129
            ->times(2)
130
            ->andReturn($postResponse, $userResponse);
131
        $this->provider->setHttpClient($client);
132
133
        $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
134
        $user = $this->provider->getResourceOwner($token);
0 ignored issues
show
Compatibility introduced by Steven Maguire
$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...
135
136
        $this->assertEquals($userId, $user->getId());
137
        $this->assertEquals($userId, $user->toArray()['id']);
138
        $this->assertEquals($name, $user->getName());
139
        $this->assertEquals($name, $user->toArray()['full_name']);
140
        $this->assertEquals($nickname, $user->getNickname());
141
        $this->assertEquals($nickname, $user->toArray()['username']);
142
        $this->assertEquals($picture, $user->getImageurl());
143
        $this->assertEquals($picture, $user->toArray()['profile_picture']);
144
        $this->assertEquals($description, $user->getDescription());
145
        $this->assertEquals($description, $user->toArray()['bio']);
146
    }
147
148
    /**
149
     * @expectedException League\OAuth2\Client\Provider\Exception\IdentityProviderException
150
     **/
151
    public function testExceptionThrownWhenErrorObjectReceived()
152
    {
153
        $message = uniqid();
154
        $status = rand(400,600);
155
        $postResponse = m::mock('Psr\Http\Message\ResponseInterface');
156
        $postResponse->shouldReceive('getBody')->andReturn('{"meta": {"error_type": "OAuthException","code": '.$status.',"error_message": "'.$message.'"}}');
157
        $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
158
        $postResponse->shouldReceive('getReasonPhrase');
159
        $postResponse->shouldReceive('getStatusCode')->andReturn($status);
160
161
        $client = m::mock('GuzzleHttp\ClientInterface');
162
        $client->shouldReceive('send')
163
            ->times(1)
164
            ->andReturn($postResponse);
165
        $this->provider->setHttpClient($client);
166
        $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
167
    }
168
169
    /**
170
     * @expectedException League\OAuth2\Client\Provider\Exception\IdentityProviderException
171
     **/
172
    public function testExceptionThrownWhenAuthErrorObjectReceived()
173
    {
174
        $message = uniqid();
175
        $status = rand(400,600);
176
        $postResponse = m::mock('Psr\Http\Message\ResponseInterface');
177
        $postResponse->shouldReceive('getBody')->andReturn('{"error_type": "OAuthException","code": '.$status.',"error_message": "'.$message.'"}');
178
        $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
179
        $postResponse->shouldReceive('getReasonPhrase');
180
        $postResponse->shouldReceive('getStatusCode')->andReturn($status);
181
182
        $client = m::mock('GuzzleHttp\ClientInterface');
183
        $client->shouldReceive('send')
184
            ->times(1)
185
            ->andReturn($postResponse);
186
        $this->provider->setHttpClient($client);
187
        $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
188
    }
189
190
    public function testGetAuthenticatedRequest()
191
    {
192
        $method = 'GET';
193
        $url = 'https://api.instagram.com/v1/users/self/feed';
194
195
        $accessTokenResponse = m::mock('Psr\Http\Message\ResponseInterface');
196
        $accessTokenResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token","user": {"id": "1574083","username": "snoopdogg","full_name": "Snoop Dogg","profile_picture": "..."}}');
197
        $accessTokenResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']);
198
199
        $client = m::mock('GuzzleHttp\ClientInterface');
200
        $client->shouldReceive('send')
201
            ->times(1)
202
            ->andReturn($accessTokenResponse);
203
        $this->provider->setHttpClient($client);
204
205
        $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']);
206
207
        $authenticatedRequest = $this->provider->getAuthenticatedRequest($method, $url, $token);
208
209
        $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $authenticatedRequest);
210
        $this->assertEquals($method, $authenticatedRequest->getMethod());
211
        $this->assertContains('access_token=mock_access_token', $authenticatedRequest->getUri()->getQuery());
212
    }
213
}
214