Passed
Pull Request — master (#957)
by
unknown
02:52
created

ClientTest::testARequestWithJSONWillJSONEncoded()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 0
dl 0
loc 13
rs 9.4285
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\Tests\Fixtures\MyFooBatchHttpClient;
34
use Facebook\Tests\Fixtures\MyFooHttpClient;
35
use Facebook\Response;
36
use Facebook\BatchResponse;
37
use Facebook\GraphNode\GraphNode;
38
use Http\Client\HttpClient;
39
use PHPUnit\Framework\TestCase;
40
41
class ClientTest extends TestCase
42
{
43
    /**
44
     * @var Application
45
     */
46
    public $fbApp;
47
48
    /**
49
     * @var Client
50
     */
51
    public $fbClient;
52
53
    /**
54
     * @var Application
55
     */
56
    public static $testApp;
57
58
    /**
59
     * @var Client
60
     */
61
    public static $testClient;
62
63
    protected function setUp()
64
    {
65
        $this->fbApp = new Application('id', 'shhhh!');
66
        $this->fbClient = new Client(new MyFooHttpClient());
67
    }
68
69
    public function testACustomHttpClientCanBeInjected()
70
    {
71
        $handler = new MyFooHttpClient();
72
        $client = new Client($handler);
73
        $httpClient = $client->getHttpClient();
74
75
        $this->assertInstanceOf(MyFooHttpClient::class, $httpClient);
76
    }
77
78
    public function testTheHttpClientWillFallbackToDefault()
79
    {
80
        $client = new Client();
81
        $httpClient = $client->getHttpClient();
82
83
        $this->assertInstanceOf(HttpClient::class, $httpClient);
84
    }
85
86
    public function testBetaModeCanBeDisabledOrEnabledViaConstructor()
87
    {
88
        $client = new Client(null, false);
89
        $url = $client->getBaseGraphUrl();
90
        $this->assertEquals(Client::BASE_GRAPH_URL, $url);
91
92
        $client = new Client(null, true);
93
        $url = $client->getBaseGraphUrl();
94
        $this->assertEquals(Client::BASE_GRAPH_URL_BETA, $url);
95
    }
96
97
    public function testBetaModeCanBeDisabledOrEnabledViaMethod()
98
    {
99
        $client = new Client();
100
        $client->enableBetaMode(false);
101
        $url = $client->getBaseGraphUrl();
102
        $this->assertEquals(Client::BASE_GRAPH_URL, $url);
103
104
        $client->enableBetaMode(true);
105
        $url = $client->getBaseGraphUrl();
106
        $this->assertEquals(Client::BASE_GRAPH_URL_BETA, $url);
107
    }
108
109
    public function testGraphVideoUrlCanBeSet()
110
    {
111
        $client = new Client();
112
        $client->enableBetaMode(false);
113
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
114
        $this->assertEquals(Client::BASE_GRAPH_VIDEO_URL, $url);
115
116
        $client->enableBetaMode(true);
117
        $url = $client->getBaseGraphUrl($postToVideoUrl = true);
118
        $this->assertEquals(Client::BASE_GRAPH_VIDEO_URL_BETA, $url);
119
    }
120
121
    public function testARequestEntityCanBeUsedToSendARequestToGraph()
122
    {
123
        $fbRequest = new Request($this->fbApp, 'token', 'GET', '/foo');
124
        $response = $this->fbClient->sendRequest($fbRequest);
125
126
        $this->assertInstanceOf(Response::class, $response);
127
        $this->assertEquals(200, $response->getHttpStatusCode());
128
        $this->assertEquals('{"data":[{"id":"123","name":"Foo"},{"id":"1337","name":"Bar"}]}', $response->getBody());
129
    }
130
131
    public function testABatchRequestEntityCanBeUsedToSendABatchRequestToGraph()
132
    {
133
        $fbRequests = [
134
            new Request($this->fbApp, 'token', 'GET', '/foo'),
135
            new Request($this->fbApp, 'token', 'POST', '/bar'),
136
        ];
137
        $fbBatchRequest = new BatchRequest($this->fbApp, $fbRequests);
138
139
        $fbBatchClient = new Client(new MyFooBatchHttpClient());
140
        $response = $fbBatchClient->sendBatchRequest($fbBatchRequest);
141
142
        $this->assertInstanceOf(BatchResponse::class, $response);
143
        $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

143
        $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...
144
        $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

144
        $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...
145
    }
146
147
    public function testABatchRequestWillProperlyBatchFiles()
148
    {
149
        $fbRequests = [
150
            new Request($this->fbApp, 'token', 'POST', '/photo', [
151
                'message' => 'foobar',
152
                'source' => new File(__DIR__ . '/foo.txt'),
153
            ]),
154
            new Request($this->fbApp, 'token', 'POST', '/video', [
155
                'message' => 'foobar',
156
                'source' => new Video(__DIR__ . '/foo.txt'),
157
            ]),
158
        ];
159
        $fbBatchRequest = new BatchRequest($this->fbApp, $fbRequests);
160
        $fbBatchRequest->prepareRequestsForBatch();
161
162
        list($url, $method, $headers, $body) = $this->fbClient->prepareRequestMessage($fbBatchRequest);
163
164
        $this->assertEquals(Client::BASE_GRAPH_VIDEO_URL, $url);
165
        $this->assertEquals('POST', $method);
166
        $this->assertContains('multipart/form-data; boundary=', $headers['Content-Type']);
167
        $this->assertContains('Content-Disposition: form-data; name="batch"', $body);
168
        $this->assertContains('Content-Disposition: form-data; name="include_headers"', $body);
169
        $this->assertContains('"name":0,"attached_files":', $body);
170
        $this->assertContains('"name":1,"attached_files":', $body);
171
        $this->assertContains('"; filename="foo.txt"', $body);
172
    }
173
174
    public function testARequestOfParamsWillBeUrlEncoded()
175
    {
176
        $fbRequest = new Request($this->fbApp, 'token', 'POST', '/foo', ['foo' => 'bar']);
177
        $response = $this->fbClient->sendRequest($fbRequest);
178
179
        $request = $response->getRequest();
180
        $headersSent = $request->getHeaders();
181
        $body = $request->getUrlEncodedBody()->getBody();
182
183
        $this->assertEquals('application/x-www-form-urlencoded', $headersSent['Content-Type']);
184
        $this->assertContains('foo=bar', $body);
185
        $this->assertContains('access_token=token', $body);
186
    }
187
188
    public function testARequestWithJSONWillJSONEncoded()
189
    {
190
        $fbRequest = new Request($this->fbApp, 'token', 'POST', '/foo', ['foo' => 'bar']);
191
        $fbRequest->useJson(true);
192
        $response = $this->fbClient->sendRequest($fbRequest);        
193
194
        $request = $response->getRequest();
195
        $headersSent = $request->getHeaders();
196
        $body = $request->getJsonEncodedBody()->getBody();
197
        
198
        $this->assertEquals('application/json', $headersSent['Content-Type']);        
199
        $this->assertContains('"foo":"bar"', $body);
200
        $this->assertNotContains('"access_token": "token"', $body);
201
    }
202
203
    public function testARequestWithFilesWillBeMultipart()
204
    {
205
        $myFile = new File(__DIR__ . '/foo.txt');
206
        $fbRequest = new Request($this->fbApp, 'token', 'POST', '/foo', ['file' => $myFile]);
207
        $response = $this->fbClient->sendRequest($fbRequest);
208
209
        $headersSent = $response->getRequest()->getHeaders();
210
211
        $this->assertContains('multipart/form-data; boundary=', $headersSent['Content-Type']);
212
    }
213
214
    /**
215
     * @expectedException \Facebook\Exception\SDKException
216
     */
217
    public function testARequestValidatesTheAccessTokenWhenOneIsNotProvided()
218
    {
219
        $fbRequest = new Request($this->fbApp, null, 'GET', '/foo');
220
        $this->fbClient->sendRequest($fbRequest);
221
    }
222
223
    /**
224
     * @group integration
225
     */
226
    public function testCanCreateATestUserAndGetTheProfileAndThenDeleteTheTestUser()
227
    {
228
        $this->initializeTestApp();
229
230
        // Create a test user
231
        $testUserPath = '/' . TestCredentials::$appId . '/accounts/test-users';
0 ignored issues
show
Bug introduced by
The type Facebook\Tests\TestCredentials 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...
232
        $params = [
233
            'installed' => true,
234
            'name' => 'Foo Phpunit User',
235
            'locale' => 'en_US',
236
            'permissions' => implode(',', ['read_stream', 'user_photos']),
237
        ];
238
239
        $request = new Request(
240
            static::$testApp,
241
            static::$testApp->getAccessToken(),
242
            'POST',
243
            $testUserPath,
244
            $params
245
        );
246
        $response = static::$testClient->sendRequest($request)->getGraphNode();
247
248
        $testUserId = $response->getField('id');
249
        $testUserAccessToken = $response->getField('access_token');
250
251
        // Get the test user's profile
252
        $request = new Request(
253
            static::$testApp,
254
            $testUserAccessToken,
255
            'GET',
256
            '/me'
257
        );
258
        $graphNode = static::$testClient->sendRequest($request)->getGraphNode();
259
260
        $this->assertInstanceOf(GraphNode::class, $graphNode);
261
        $this->assertNotNull($graphNode->getField('id'));
262
        $this->assertEquals('Foo Phpunit User', $graphNode->getField('name'));
263
264
        // Delete test user
265
        $request = new Request(
266
            static::$testApp,
267
            static::$testApp->getAccessToken(),
268
            'DELETE',
269
            '/' . $testUserId
270
        );
271
        $graphNode = static::$testClient->sendRequest($request)->getGraphNode();
272
273
        $this->assertTrue($graphNode->getField('success'));
274
    }
275
276
    public function initializeTestApp()
277
    {
278
        if (!file_exists(__DIR__ . '/TestCredentials.php')) {
279
            throw new SDKException(
280
                'You must create a TestCredentials.php file from TestCredentials.php.dist'
281
            );
282
        }
283
284
        if (!strlen(TestCredentials::$appId) ||
285
            !strlen(TestCredentials::$appSecret)
286
        ) {
287
            throw new SDKException(
288
                'You must fill out TestCredentials.php'
289
            );
290
        }
291
        static::$testApp = new Application(
292
            TestCredentials::$appId,
293
            TestCredentials::$appSecret
294
        );
295
296
        static::$testClient = new Client();
297
    }
298
}
299