Passed
Pull Request — master (#888)
by Tobias
01:52
created

testAFacebookBatchRequestWillProperlyBatchFiles()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 18
nc 1
nop 0
dl 0
loc 25
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright 2017 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
namespace Facebook\Tests;
24
25
use Facebook\Exception\SDKException;
26
use Facebook\Application;
27
use Facebook\Request;
28
use Facebook\BatchRequest;
29
use Facebook\Client;
30
use Facebook\FileUpload\File;
31
use Facebook\FileUpload\Video;
32
// These are needed when you uncomment the HTTP clients below.
33
use Facebook\HttpClients\FacebookCurlHttpClient;
0 ignored issues
show
Bug introduced by
The type Facebook\HttpClients\FacebookCurlHttpClient was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
use Facebook\HttpClients\FacebookGuzzleHttpClient;
0 ignored issues
show
Bug introduced by
The type Facebook\HttpClients\FacebookGuzzleHttpClient was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
35
use Facebook\HttpClients\FacebookStreamHttpClient;
0 ignored issues
show
Bug introduced by
The type Facebook\HttpClients\FacebookStreamHttpClient was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
36
use Facebook\Tests\Fixtures\MyFooBatchHttpClient;
37
use Facebook\Tests\Fixtures\MyFooHttpClient;
38
use Facebook\Response;
39
use Facebook\BatchResponse;
40
use Facebook\GraphNode\GraphNode;
41
use Http\Client\HttpClient;
42
use PHPUnit\Framework\TestCase;
43
44
class ClientTest extends TestCase
45
{
46
    /**
47
     * @var Application
48
     */
49
    public $fbApp;
50
51
    /**
52
     * @var Client
53
     */
54
    public $fbClient;
55
56
    /**
57
     * @var Application
58
     */
59
    public static $testFacebookApp;
60
61
    /**
62
     * @var Client
63
     */
64
    public static $testFacebookClient;
65
66
    protected function setUp()
67
    {
68
        $this->fbApp = new Application('id', 'shhhh!');
69
        $this->fbClient = new Client(new MyFooHttpClient());
70
    }
71
72
    public function testACustomHttpClientCanBeInjected()
73
    {
74
        $handler = new MyFooHttpClient();
75
        $client = new Client($handler);
76
        $httpClient = $client->getHttpClient();
77
78
        $this->assertInstanceOf(MyFooHttpClient::class, $httpClient);
79
    }
80
81
    public function testTheHttpClientWillFallbackToDefault()
82
    {
83
        $client = new Client();
84
        $httpClient = $client->getHttpClient();
85
86
        $this->assertInstanceOf(HttpClient::class, $httpClient);
87
    }
88
89
    public function testBetaModeCanBeDisabledOrEnabledViaConstructor()
90
    {
91
        $client = new Client(null, false);
92
        $url = $client->getBaseGraphUrl();
93
        $this->assertEquals(Client::BASE_GRAPH_URL, $url);
94
95
        $client = new Client(null, true);
96
        $url = $client->getBaseGraphUrl();
97
        $this->assertEquals(Client::BASE_GRAPH_URL_BETA, $url);
98
    }
99
100
    public function testBetaModeCanBeDisabledOrEnabledViaMethod()
101
    {
102
        $client = new Client();
103
        $client->enableBetaMode(false);
104
        $url = $client->getBaseGraphUrl();
105
        $this->assertEquals(Client::BASE_GRAPH_URL, $url);
106
107
        $client->enableBetaMode(true);
108
        $url = $client->getBaseGraphUrl();
109
        $this->assertEquals(Client::BASE_GRAPH_URL_BETA, $url);
110
    }
111
112
    public function testGraphVideoUrlCanBeSet()
113
    {
114
        $client = new Client();
115
        $client->enableBetaMode(false);
116
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
117
        $this->assertEquals(Client::BASE_GRAPH_VIDEO_URL, $url);
118
119
        $client->enableBetaMode(true);
120
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
121
        $this->assertEquals(Client::BASE_GRAPH_VIDEO_URL_BETA, $url);
122
    }
123
124
    public function testAFacebookRequestEntityCanBeUsedToSendARequestToGraph()
125
    {
126
        $fbRequest = new Request($this->fbApp, 'token', 'GET', '/foo');
127
        $response = $this->fbClient->sendRequest($fbRequest);
128
129
        $this->assertInstanceOf(Response::class, $response);
130
        $this->assertEquals(200, $response->getHttpStatusCode());
131
        $this->assertEquals('{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', $response->getBody());
132
    }
133
134
    public function testAFacebookBatchRequestEntityCanBeUsedToSendABatchRequestToGraph()
135
    {
136
        $fbRequests = [
137
            new Request($this->fbApp, 'token', 'GET', '/foo'),
138
            new Request($this->fbApp, 'token', 'POST', '/bar'),
139
        ];
140
        $fbBatchRequest = new BatchRequest($this->fbApp, $fbRequests);
141
142
        $fbBatchClient = new Client(new MyFooBatchHttpClient());
143
        $response = $fbBatchClient->sendBatchRequest($fbBatchRequest);
144
145
        $this->assertInstanceOf(BatchResponse::class, $response);
146
        $this->assertEquals('GET', $response[0]->getRequest()->getMethod());
0 ignored issues
show
Bug introduced by
The method getRequest() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

146
        $this->assertEquals('GET', $response[0]->/** @scrutinizer ignore-call */ getRequest()->getMethod());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
147
        $this->assertEquals('POST', $response[1]->getRequest()->getMethod());
0 ignored issues
show
Bug introduced by
The method getRequest() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

147
        $this->assertEquals('POST', $response[1]->/** @scrutinizer ignore-call */ getRequest()->getMethod());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
148
    }
149
150
    public function testAFacebookBatchRequestWillProperlyBatchFiles()
151
    {
152
        $fbRequests = [
153
            new Request($this->fbApp, 'token', 'POST', '/photo', [
154
                'message' => 'foobar',
155
                'source' => new File(__DIR__ . '/foo.txt'),
156
            ]),
157
            new Request($this->fbApp, 'token', 'POST', '/video', [
158
                'message' => 'foobar',
159
                'source' => new Video(__DIR__ . '/foo.txt'),
160
            ]),
161
        ];
162
        $fbBatchRequest = new BatchRequest($this->fbApp, $fbRequests);
163
        $fbBatchRequest->prepareRequestsForBatch();
164
165
        list($url, $method, $headers, $body) = $this->fbClient->prepareRequestMessage($fbBatchRequest);
166
167
        $this->assertEquals(Client::BASE_GRAPH_VIDEO_URL, $url);
168
        $this->assertEquals('POST', $method);
169
        $this->assertContains('multipart/form-data; boundary=', $headers['Content-Type']);
170
        $this->assertContains('Content-Disposition: form-data; name="batch"', $body);
171
        $this->assertContains('Content-Disposition: form-data; name="include_headers"', $body);
172
        $this->assertContains('"name":0,"attached_files":', $body);
173
        $this->assertContains('"name":1,"attached_files":', $body);
174
        $this->assertContains('"; filename="foo.txt"', $body);
175
    }
176
177
    public function testARequestOfParamsWillBeUrlEncoded()
178
    {
179
        $fbRequest = new Request($this->fbApp, 'token', 'POST', '/foo', ['foo' => 'bar']);
180
        $response = $this->fbClient->sendRequest($fbRequest);
181
182
        $headersSent = $response->getRequest()->getHeaders();
183
184
        $this->assertEquals('application/x-www-form-urlencoded', $headersSent['Content-Type']);
185
    }
186
187
    public function testARequestWithFilesWillBeMultipart()
188
    {
189
        $myFile = new File(__DIR__ . '/foo.txt');
190
        $fbRequest = new Request($this->fbApp, 'token', 'POST', '/foo', ['file' => $myFile]);
191
        $response = $this->fbClient->sendRequest($fbRequest);
192
193
        $headersSent = $response->getRequest()->getHeaders();
194
195
        $this->assertContains('multipart/form-data; boundary=', $headersSent['Content-Type']);
196
    }
197
198
    /**
199
     * @expectedException \Facebook\Exception\SDKException
200
     */
201
    public function testAFacebookRequestValidatesTheAccessTokenWhenOneIsNotProvided()
202
    {
203
        $fbRequest = new Request($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';
0 ignored issues
show
Bug introduced by
The type Facebook\Tests\FacebookTestCredentials was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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 Request(
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 Request(
237
            static::$testFacebookApp,
238
            $testUserAccessToken,
239
            'GET',
240
            '/me'
241
        );
242
        $graphNode = static::$testFacebookClient->sendRequest($request)->getGraphNode();
243
244
        $this->assertInstanceOf(GraphNode::class, $graphNode);
245
        $this->assertNotNull($graphNode->getField('id'));
246
        $this->assertEquals('Foo Phpunit User', $graphNode->getField('name'));
247
248
        // Delete test user
249
        $request = new Request(
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 SDKException(
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 SDKException(
272
                'You must fill out FacebookTestCredentials.php'
273
            );
274
        }
275
        static::$testFacebookApp = new Application(
276
            FacebookTestCredentials::$appId,
277
            FacebookTestCredentials::$appSecret
278
        );
279
280
        static::$testFacebookClient = new Client();
281
    }
282
}
283