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