Completed
Pull Request — master (#594)
by Andreas
03:22
created

FacebookClientTest::testAFacebookRequestValidatesTheAccessTokenWhenOneIsNotProvided()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 7
rs 9.4285
c 1
b 0
f 0
1
<?php
2
/**
3
 * Copyright 2016 Facebook, Inc.
4
 *
5
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
6
 * use, copy, modify, and distribute this software in source code or binary
7
 * form for use in connection with the web services and APIs provided by
8
 * Facebook.
9
 *
10
 * As with any software that integrates with the Facebook platform, your use
11
 * of this software is subject to the Facebook Developer Principles and
12
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
13
 * shall be included in all copies or substantial portions of the software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21
 * DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
namespace Facebook\Tests;
25
26
use Facebook\Exceptions\FacebookSDKException;
27
use Facebook\Facebook;
28
use Facebook\FacebookApp;
29
use Facebook\FacebookRequest;
30
use Facebook\FacebookBatchRequest;
31
use Facebook\FacebookClient;
32
use Facebook\FileUpload\FacebookFile;
33
use Facebook\FileUpload\FacebookVideo;
34
// These are needed when you uncomment the HTTP clients below.
35
use Facebook\HttpClients\FacebookCurlHttpClient;
36
use Facebook\HttpClients\FacebookGuzzleHttpClient;
37
use Facebook\HttpClients\FacebookStreamHttpClient;
38
use Facebook\Tests\Fixtures\MyFooBatchClientHandler;
39
use Facebook\Tests\Fixtures\MyFooClientHandler;
40
41
class FacebookClientTest extends \PHPUnit_Framework_TestCase
42
{
43
    /**
44
     * @var FacebookApp
45
     */
46
    public $fbApp;
47
48
    /**
49
     * @var FacebookClient
50
     */
51
    public $fbClient;
52
53
    /**
54
     * @var FacebookApp
55
     */
56
    public static $testFacebookApp;
57
58
    /**
59
     * @var FacebookClient
60
     */
61
    public static $testFacebookClient;
62
63
    protected function setUp()
64
    {
65
        $this->fbApp = new FacebookApp('id', 'shhhh!');
66
        $this->fbClient = new FacebookClient(new MyFooClientHandler());
67
    }
68
69
    public function testACustomHttpClientCanBeInjected()
70
    {
71
        $handler = new MyFooClientHandler();
72
        $client = new FacebookClient($handler);
73
        $httpHandler = $client->getHttpClientHandler();
74
75
        $this->assertInstanceOf('Facebook\Tests\Fixtures\MyFooClientHandler', $httpHandler);
76
    }
77
78
    public function testTheHttpClientWillFallbackToDefault()
79
    {
80
        $client = new FacebookClient();
81
        $httpHandler = $client->getHttpClientHandler();
82
83
        if (function_exists('curl_init')) {
84
            $this->assertInstanceOf('Facebook\HttpClients\FacebookCurlHttpClient', $httpHandler);
85
        } else {
86
            $this->assertInstanceOf('Facebook\HttpClients\FacebookStreamHttpClient', $httpHandler);
87
        }
88
    }
89
90
    public function testBetaModeCanBeDisabledOrEnabledViaConstructor()
91
    {
92
        $client = new FacebookClient(null, false);
93
        $url = $client->getBaseGraphUrl();
94
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL, $url);
95
96
        $client = new FacebookClient(null, true);
97
        $url = $client->getBaseGraphUrl();
98
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL_BETA, $url);
99
    }
100
101
    public function testBetaModeCanBeDisabledOrEnabledViaMethod()
102
    {
103
        $client = new FacebookClient();
104
        $client->enableBetaMode(false);
105
        $url = $client->getBaseGraphUrl();
106
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL, $url);
107
108
        $client->enableBetaMode(true);
109
        $url = $client->getBaseGraphUrl();
110
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL_BETA, $url);
111
    }
112
113
    public function testGraphVideoUrlCanBeSet()
114
    {
115
        $client = new FacebookClient();
116
        $client->enableBetaMode(false);
117
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
118
        $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL, $url);
119
120
        $client->enableBetaMode(true);
121
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
122
        $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL_BETA, $url);
123
    }
124
125
    public function testAFacebookRequestEntityCanBeUsedToSendARequestToGraph()
126
    {
127
        $fbRequest = new FacebookRequest($this->fbApp, 'token', 'GET', '/foo');
128
        $response = $this->fbClient->sendRequest($fbRequest);
129
130
        $this->assertInstanceOf('Facebook\FacebookResponse', $response);
131
        $this->assertEquals(200, $response->getHttpStatusCode());
132
        $this->assertEquals('{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', $response->getBody());
133
    }
134
135
    public function testAFacebookBatchRequestEntityCanBeUsedToSendABatchRequestToGraph()
136
    {
137
        $fbRequests = [
138
            new FacebookRequest($this->fbApp, 'token', 'GET', '/foo'),
139
            new FacebookRequest($this->fbApp, 'token', 'POST', '/bar'),
140
        ];
141
        $fbBatchRequest = new FacebookBatchRequest($this->fbApp, $fbRequests);
142
143
        $fbBatchClient = new FacebookClient(new MyFooBatchClientHandler());
144
        $response = $fbBatchClient->sendBatchRequest($fbBatchRequest);
145
146
        $this->assertInstanceOf('Facebook\FacebookBatchResponse', $response);
147
        $this->assertEquals('GET', $response[0]->getRequest()->getMethod());
148
        $this->assertEquals('POST', $response[1]->getRequest()->getMethod());
149
    }
150
151
    public function testAFacebookBatchRequestWillProperlyBatchFiles()
152
    {
153
        $fbRequests = [
154
            new FacebookRequest($this->fbApp, 'token', 'POST', '/photo', [
155
                'message' => 'foobar',
156
                'source' => new FacebookFile(__DIR__ . '/foo.txt'),
157
            ]),
158
            new FacebookRequest($this->fbApp, 'token', 'POST', '/video', [
159
                'message' => 'foobar',
160
                'source' => new FacebookVideo(__DIR__ . '/foo.txt'),
161
            ]),
162
        ];
163
        $fbBatchRequest = new FacebookBatchRequest($this->fbApp, $fbRequests);
164
        $fbBatchRequest->prepareRequestsForBatch();
165
166
        list($url, $method, $headers, $body) = $this->fbClient->prepareRequestMessage($fbBatchRequest);
167
168
        $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL . '/' . Facebook::DEFAULT_GRAPH_VERSION, $url);
169
        $this->assertEquals('POST', $method);
170
        $this->assertContains('multipart/form-data; boundary=', $headers['Content-Type']);
171
        $this->assertContains('Content-Disposition: form-data; name="batch"', $body);
172
        $this->assertContains('Content-Disposition: form-data; name="include_headers"', $body);
173
        $this->assertContains('"name":0,"attached_files":', $body);
174
        $this->assertContains('"name":1,"attached_files":', $body);
175
        $this->assertContains('"; filename="foo.txt"', $body);
176
    }
177
178
    public function testARequestOfParamsWillBeUrlEncoded()
179
    {
180
        $fbRequest = new FacebookRequest($this->fbApp, 'token', 'POST', '/foo', ['foo' => 'bar']);
181
        $response = $this->fbClient->sendRequest($fbRequest);
182
183
        $headersSent = $response->getRequest()->getHeaders();
184
185
        $this->assertEquals('application/x-www-form-urlencoded', $headersSent['Content-Type']);
186
    }
187
188
    public function testARequestWithFilesWillBeMultipart()
189
    {
190
        $myFile = new FacebookFile(__DIR__ . '/foo.txt');
191
        $fbRequest = new FacebookRequest($this->fbApp, 'token', 'POST', '/foo', ['file' => $myFile]);
192
        $response = $this->fbClient->sendRequest($fbRequest);
193
194
        $headersSent = $response->getRequest()->getHeaders();
195
196
        $this->assertContains('multipart/form-data; boundary=', $headersSent['Content-Type']);
197
    }
198
199
    public function testAFacebookRequestValidatesTheAccessTokenWhenOneIsNotProvided()
200
    {
201
        $this->setExpectedException('Facebook\Exceptions\FacebookSDKException');
202
203
        $fbRequest = new FacebookRequest($this->fbApp, null, 'GET', '/foo');
204
        $this->fbClient->sendRequest($fbRequest);
205
    }
206
207
    /**
208
     * @group integration
209
     */
210
    public function testCanCreateATestUserAndGetTheProfileAndThenDeleteTheTestUser()
211
    {
212
        $this->initializeTestApp();
213
214
        // Create a test user
215
        $testUserPath = '/' . FacebookTestCredentials::$appId . '/accounts/test-users';
216
        $params = [
217
            'installed' => true,
218
            'name' => 'Foo Phpunit User',
219
            'locale' => 'en_US',
220
            'permissions' => implode(',', ['read_stream', 'user_photos']),
221
        ];
222
223
        $request = new FacebookRequest(
224
            static::$testFacebookApp,
225
            static::$testFacebookApp->getAccessToken(),
226
            'POST',
227
            $testUserPath,
228
            $params
229
        );
230
        $response = static::$testFacebookClient->sendRequest($request)->getGraphNode();
231
232
        $testUserId = $response->getField('id');
233
        $testUserAccessToken = $response->getField('access_token');
234
235
        // Get the test user's profile
236
        $request = new FacebookRequest(
237
            static::$testFacebookApp,
238
            $testUserAccessToken,
239
            'GET',
240
            '/me'
241
        );
242
        $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode();
243
244
        $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphNode);
245
        $this->assertNotNull($graphNode->getField('id'));
246
        $this->assertEquals('Foo Phpunit User', $graphNode->getField('name'));
247
248
        // Delete test user
249
        $request = new FacebookRequest(
250
            static::$testFacebookApp,
251
            static::$testFacebookApp->getAccessToken(),
252
            'DELETE',
253
            '/' . $testUserId
254
        );
255
        $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode();
256
257
        $this->assertTrue($graphNode->getField('success'));
258
    }
259
260
    public function initializeTestApp()
261
    {
262
        if (!file_exists(__DIR__ . '/FacebookTestCredentials.php')) {
263
            throw new FacebookSDKException(
264
                'You must create a FacebookTestCredentials.php file from FacebookTestCredentials.php.dist'
265
            );
266
        }
267
268
        if (!strlen(FacebookTestCredentials::$appId) ||
269
            !strlen(FacebookTestCredentials::$appSecret)
270
        ) {
271
            throw new FacebookSDKException(
272
                'You must fill out FacebookTestCredentials.php'
273
            );
274
        }
275
        static::$testFacebookApp = new FacebookApp(
276
            FacebookTestCredentials::$appId,
277
            FacebookTestCredentials::$appSecret
278
        );
279
280
        // Use default client
281
        $client = null;
282
283
        // Uncomment to enable curl implementation.
284
        //$client = new FacebookCurlHttpClient();
285
286
        // Uncomment to enable stream wrapper implementation.
287
        //$client = new FacebookStreamHttpClient();
288
289
        // Uncomment to enable Guzzle implementation.
290
        //$client = new FacebookGuzzleHttpClient();
291
292
        static::$testFacebookClient = new FacebookClient($client);
293
    }
294
}
295