Completed
Pull Request — master (#594)
by Andreas
03:19
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\Http\GraphRawResponse;
33
use Facebook\HttpClients\FacebookHttpClientInterface;
34
use Facebook\FileUpload\FacebookFile;
35
use Facebook\FileUpload\FacebookVideo;
36
// These are needed when you uncomment the HTTP clients below.
37
use Facebook\HttpClients\FacebookCurlHttpClient;
38
use Facebook\HttpClients\FacebookGuzzleHttpClient;
39
use Facebook\HttpClients\FacebookStreamHttpClient;
40
41
class MyFooClientHandler implements FacebookHttpClientInterface
42
{
43
    public function send($url, $method, $body, array $headers, $timeOut)
44
    {
45
        return new GraphRawResponse(
46
            "HTTP/1.1 200 OK\r\nDate: Mon, 19 May 2014 18:37:17 GMT",
47
            '{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}'
48
        );
49
    }
50
}
51
52
class MyFooBatchClientHandler implements FacebookHttpClientInterface
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
53
{
54
    public function send($url, $method, $body, array $headers, $timeOut)
55
    {
56
        return new GraphRawResponse(
57
            "HTTP/1.1 200 OK\r\nDate: Mon, 19 May 2014 18:37:17 GMT",
58
            '[{"code":"123","body":"Foo"},{"code":"1337","body":"Bar"}]'
59
        );
60
    }
61
}
62
63
class FacebookClientTest extends \PHPUnit_Framework_TestCase
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
64
{
65
    /**
66
     * @var FacebookApp
67
     */
68
    public $fbApp;
69
70
    /**
71
     * @var FacebookClient
72
     */
73
    public $fbClient;
74
75
    /**
76
     * @var FacebookApp
77
     */
78
    public static $testFacebookApp;
79
80
    /**
81
     * @var FacebookClient
82
     */
83
    public static $testFacebookClient;
84
85
    protected function setUp()
86
    {
87
        $this->fbApp = new FacebookApp('id', 'shhhh!');
88
        $this->fbClient = new FacebookClient(new MyFooClientHandler());
89
    }
90
91
    public function testACustomHttpClientCanBeInjected()
92
    {
93
        $handler = new MyFooClientHandler();
94
        $client = new FacebookClient($handler);
95
        $httpHandler = $client->getHttpClientHandler();
96
97
        $this->assertInstanceOf('Facebook\Tests\MyFooClientHandler', $httpHandler);
98
    }
99
100
    public function testTheHttpClientWillFallbackToDefault()
101
    {
102
        $client = new FacebookClient();
103
        $httpHandler = $client->getHttpClientHandler();
104
105
        if (function_exists('curl_init')) {
106
            $this->assertInstanceOf('Facebook\HttpClients\FacebookCurlHttpClient', $httpHandler);
107
        } else {
108
            $this->assertInstanceOf('Facebook\HttpClients\FacebookStreamHttpClient', $httpHandler);
109
        }
110
    }
111
112
    public function testBetaModeCanBeDisabledOrEnabledViaConstructor()
113
    {
114
        $client = new FacebookClient(null, false);
115
        $url = $client->getBaseGraphUrl();
116
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL, $url);
117
118
        $client = new FacebookClient(null, true);
119
        $url = $client->getBaseGraphUrl();
120
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL_BETA, $url);
121
    }
122
123
    public function testBetaModeCanBeDisabledOrEnabledViaMethod()
124
    {
125
        $client = new FacebookClient();
126
        $client->enableBetaMode(false);
127
        $url = $client->getBaseGraphUrl();
128
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL, $url);
129
130
        $client->enableBetaMode(true);
131
        $url = $client->getBaseGraphUrl();
132
        $this->assertEquals(FacebookClient::BASE_GRAPH_URL_BETA, $url);
133
    }
134
135
    public function testGraphVideoUrlCanBeSet()
136
    {
137
        $client = new FacebookClient();
138
        $client->enableBetaMode(false);
139
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
140
        $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL, $url);
141
142
        $client->enableBetaMode(true);
143
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
144
        $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL_BETA, $url);
145
    }
146
147
    public function testAFacebookRequestEntityCanBeUsedToSendARequestToGraph()
148
    {
149
        $fbRequest = new FacebookRequest($this->fbApp, 'token', 'GET', '/foo');
150
        $response = $this->fbClient->sendRequest($fbRequest);
151
152
        $this->assertInstanceOf('Facebook\FacebookResponse', $response);
153
        $this->assertEquals(200, $response->getHttpStatusCode());
154
        $this->assertEquals('{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', $response->getBody());
155
    }
156
157
    public function testAFacebookBatchRequestEntityCanBeUsedToSendABatchRequestToGraph()
158
    {
159
        $fbRequests = [
160
            new FacebookRequest($this->fbApp, 'token', 'GET', '/foo'),
161
            new FacebookRequest($this->fbApp, 'token', 'POST', '/bar'),
162
        ];
163
        $fbBatchRequest = new FacebookBatchRequest($this->fbApp, $fbRequests);
164
165
        $fbBatchClient = new FacebookClient(new MyFooBatchClientHandler());
166
        $response = $fbBatchClient->sendBatchRequest($fbBatchRequest);
167
168
        $this->assertInstanceOf('Facebook\FacebookBatchResponse', $response);
169
        $this->assertEquals('GET', $response[0]->getRequest()->getMethod());
170
        $this->assertEquals('POST', $response[1]->getRequest()->getMethod());
171
    }
172
173
    public function testAFacebookBatchRequestWillProperlyBatchFiles()
174
    {
175
        $fbRequests = [
176
            new FacebookRequest($this->fbApp, 'token', 'POST', '/photo', [
177
                'message' => 'foobar',
178
                'source' => new FacebookFile(__DIR__ . '/foo.txt'),
179
            ]),
180
            new FacebookRequest($this->fbApp, 'token', 'POST', '/video', [
181
                'message' => 'foobar',
182
                'source' => new FacebookVideo(__DIR__ . '/foo.txt'),
183
            ]),
184
        ];
185
        $fbBatchRequest = new FacebookBatchRequest($this->fbApp, $fbRequests);
186
        $fbBatchRequest->prepareRequestsForBatch();
187
188
        list($url, $method, $headers, $body) = $this->fbClient->prepareRequestMessage($fbBatchRequest);
189
190
        $this->assertEquals(FacebookClient::BASE_GRAPH_VIDEO_URL . '/' . Facebook::DEFAULT_GRAPH_VERSION, $url);
191
        $this->assertEquals('POST', $method);
192
        $this->assertContains('multipart/form-data; boundary=', $headers['Content-Type']);
193
        $this->assertContains('Content-Disposition: form-data; name="batch"', $body);
194
        $this->assertContains('Content-Disposition: form-data; name="include_headers"', $body);
195
        $this->assertContains('"name":0,"attached_files":', $body);
196
        $this->assertContains('"name":1,"attached_files":', $body);
197
        $this->assertContains('"; filename="foo.txt"', $body);
198
    }
199
200
    public function testARequestOfParamsWillBeUrlEncoded()
201
    {
202
        $fbRequest = new FacebookRequest($this->fbApp, 'token', 'POST', '/foo', ['foo' => 'bar']);
203
        $response = $this->fbClient->sendRequest($fbRequest);
204
205
        $headersSent = $response->getRequest()->getHeaders();
206
207
        $this->assertEquals('application/x-www-form-urlencoded', $headersSent['Content-Type']);
208
    }
209
210
    public function testARequestWithFilesWillBeMultipart()
211
    {
212
        $myFile = new FacebookFile(__DIR__ . '/foo.txt');
213
        $fbRequest = new FacebookRequest($this->fbApp, 'token', 'POST', '/foo', ['file' => $myFile]);
214
        $response = $this->fbClient->sendRequest($fbRequest);
215
216
        $headersSent = $response->getRequest()->getHeaders();
217
218
        $this->assertContains('multipart/form-data; boundary=', $headersSent['Content-Type']);
219
    }
220
221
    public function testAFacebookRequestValidatesTheAccessTokenWhenOneIsNotProvided()
222
    {
223
        $this->setExpectedException('Facebook\Exceptions\FacebookSDKException');
224
225
        $fbRequest = new FacebookRequest($this->fbApp, null, 'GET', '/foo');
226
        $this->fbClient->sendRequest($fbRequest);
227
    }
228
229
    /**
230
     * @group integration
231
     */
232
    public function testCanCreateATestUserAndGetTheProfileAndThenDeleteTheTestUser()
233
    {
234
        $this->initializeTestApp();
235
236
        // Create a test user
237
        $testUserPath = '/' . FacebookTestCredentials::$appId . '/accounts/test-users';
238
        $params = [
239
            'installed' => true,
240
            'name' => 'Foo Phpunit User',
241
            'locale' => 'en_US',
242
            'permissions' => implode(',', ['read_stream', 'user_photos']),
243
        ];
244
245
        $request = new FacebookRequest(
246
            static::$testFacebookApp,
247
            static::$testFacebookApp->getAccessToken(),
248
            'POST',
249
            $testUserPath,
250
            $params
251
        );
252
        $response = static::$testFacebookClient->sendRequest($request)->getGraphNode();
253
254
        $testUserId = $response->getField('id');
255
        $testUserAccessToken = $response->getField('access_token');
256
257
        // Get the test user's profile
258
        $request = new FacebookRequest(
259
            static::$testFacebookApp,
260
            $testUserAccessToken,
261
            'GET',
262
            '/me'
263
        );
264
        $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode();
265
266
        $this->assertInstanceOf('Facebook\GraphNodes\GraphNode', $graphNode);
267
        $this->assertNotNull($graphNode->getField('id'));
268
        $this->assertEquals('Foo Phpunit User', $graphNode->getField('name'));
269
270
        // Delete test user
271
        $request = new FacebookRequest(
272
            static::$testFacebookApp,
273
            static::$testFacebookApp->getAccessToken(),
274
            'DELETE',
275
            '/' . $testUserId
276
        );
277
        $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode();
278
279
        $this->assertTrue($graphNode->getField('success'));
280
    }
281
282
    public function initializeTestApp()
283
    {
284
        if (!file_exists(__DIR__ . '/FacebookTestCredentials.php')) {
285
            throw new FacebookSDKException(
286
                'You must create a FacebookTestCredentials.php file from FacebookTestCredentials.php.dist'
287
            );
288
        }
289
290
        if (!strlen(FacebookTestCredentials::$appId) ||
291
            !strlen(FacebookTestCredentials::$appSecret)
292
        ) {
293
            throw new FacebookSDKException(
294
                'You must fill out FacebookTestCredentials.php'
295
            );
296
        }
297
        static::$testFacebookApp = new FacebookApp(
298
            FacebookTestCredentials::$appId,
299
            FacebookTestCredentials::$appSecret
300
        );
301
302
        // Use default client
303
        $client = null;
304
305
        // Uncomment to enable curl implementation.
306
        //$client = new FacebookCurlHttpClient();
307
308
        // Uncomment to enable stream wrapper implementation.
309
        //$client = new FacebookStreamHttpClient();
310
311
        // Uncomment to enable Guzzle implementation.
312
        //$client = new FacebookGuzzleHttpClient();
313
314
        static::$testFacebookClient = new FacebookClient($client);
315
    }
316
}
317