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

testRequestsCanBeInjectedIntoConstructor()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 12
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\Application;
26
use Facebook\Facebook;
27
use Facebook\Request;
28
use Facebook\BatchRequest;
29
use Facebook\FileUpload\File;
30
use PHPUnit\Framework\TestCase;
31
32
class BatchRequestTest extends TestCase
33
{
34
    /**
35
     * @var Application
36
     */
37
    private $app;
38
39
    protected function setUp()
40
    {
41
        $this->app = new Application('123', 'foo_secret');
42
    }
43
44
    public function testABatchRequestWillInstantiateWithTheProperProperties()
45
    {
46
        $batchRequest = new BatchRequest($this->app, [], 'foo_token', 'v0.1337');
47
48
        $this->assertSame($this->app, $batchRequest->getApp());
49
        $this->assertEquals('foo_token', $batchRequest->getAccessToken());
50
        $this->assertEquals('POST', $batchRequest->getMethod());
51
        $this->assertEquals('', $batchRequest->getEndpoint());
52
        $this->assertEquals('v0.1337', $batchRequest->getGraphVersion());
53
    }
54
55
    public function testEmptyRequestWillFallbackToBatchDefaults()
56
    {
57
        $request = new Request();
58
59
        $this->createBatchRequest()->addFallbackDefaults($request);
60
61
        $this->assertRequestContainsAppAndToken($request, $this->app, 'foo_token');
62
    }
63
64
    public function testRequestWithTokenOnlyWillFallbackToBatchDefaults()
65
    {
66
        $request = new Request(null, 'bar_token');
67
68
        $this->createBatchRequest()->addFallbackDefaults($request);
69
70
        $this->assertRequestContainsAppAndToken($request, $this->app, 'bar_token');
71
    }
72
73
    public function testRequestWithAppOnlyWillFallbackToBatchDefaults()
74
    {
75
        $customApp = new Application('1337', 'bar_secret');
76
        $request = new Request($customApp);
77
78
        $this->createBatchRequest()->addFallbackDefaults($request);
79
80
        $this->assertRequestContainsAppAndToken($request, $customApp, 'foo_token');
81
    }
82
83
    /**
84
     * @expectedException \Facebook\Exception\SDKException
85
     */
86
    public function testWillThrowWhenNoThereIsNoAppFallback()
87
    {
88
        $batchRequest = new BatchRequest();
89
90
        $batchRequest->addFallbackDefaults(new Request(null, 'foo_token'));
91
    }
92
93
    /**
94
     * @expectedException \Facebook\Exception\SDKException
95
     */
96
    public function testWillThrowWhenNoThereIsNoAccessTokenFallback()
97
    {
98
        $request = new BatchRequest();
99
100
        $request->addFallbackDefaults(new Request($this->app));
101
    }
102
103
    /**
104
     * @expectedException \InvalidArgumentException
105
     */
106
    public function testAnInvalidTypeGivenToAddWillThrow()
107
    {
108
        $request = new BatchRequest();
109
110
        $request->add('foo');
0 ignored issues
show
Bug introduced by
'foo' of type string is incompatible with the type array|Facebook\Request expected by parameter $request of Facebook\BatchRequest::add(). ( Ignorable by Annotation )

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

110
        $request->add(/** @scrutinizer ignore-type */ 'foo');
Loading history...
111
    }
112
113
    public function testAddingRequestsWillBeFormattedInAnArrayProperly()
114
    {
115
        $requests = [
116
            null => new Request(null, null, 'GET', '/foo'),
117
            'my-second-request' => new Request(null, null, 'POST', '/bar', ['foo' => 'bar']),
118
            'my-third-request' => new Request(null, null, 'DELETE', '/baz')
119
        ];
120
121
        $batchRequest = $this->createBatchRequest();
122
        $batchRequest->add($requests[null]);
123
        $batchRequest->add($requests['my-second-request'], 'my-second-request');
124
        $batchRequest->add($requests['my-third-request'], 'my-third-request');
125
126
        $formattedRequests = $batchRequest->getRequests();
127
128
        $this->assertRequestsMatch($requests, $formattedRequests);
129
    }
130
131 View Code Duplication
    public function testANumericArrayOfRequestsCanBeAdded()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133
        $requests = [
134
            new Request(null, null, 'GET', '/foo'),
135
            new Request(null, null, 'POST', '/bar', ['foo' => 'bar']),
136
            new Request(null, null, 'DELETE', '/baz'),
137
        ];
138
139
        $formattedRequests = $this->createBatchRequestWithRequests($requests)->getRequests();
140
141
        $this->assertRequestsMatch($requests, $formattedRequests);
142
    }
143
144 View Code Duplication
    public function testAnAssociativeArrayOfRequestsCanBeAdded()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
145
    {
146
        $requests = [
147
            'req-one' => new Request(null, null, 'GET', '/foo'),
148
            'req-two' => new Request(null, null, 'POST', '/bar', ['foo' => 'bar']),
149
            'req-three' => new Request(null, null, 'DELETE', '/baz'),
150
        ];
151
152
        $formattedRequests = $this->createBatchRequestWithRequests($requests)->getRequests();
153
154
        $this->assertRequestsMatch($requests, $formattedRequests);
155
    }
156
157
    public function testRequestsCanBeInjectedIntoConstructor()
158
    {
159
        $requests = [
160
            new Request(null, null, 'GET', '/foo'),
161
            new Request(null, null, 'POST', '/bar', ['foo' => 'bar']),
162
            new Request(null, null, 'DELETE', '/baz'),
163
        ];
164
165
        $batchRequest = new BatchRequest($this->app, $requests, 'foo_token');
166
        $formattedRequests = $batchRequest->getRequests();
167
168
        $this->assertRequestsMatch($requests, $formattedRequests);
169
    }
170
171
    /**
172
     * @expectedException \Facebook\Exception\SDKException
173
     */
174
    public function testAZeroRequestCountWithThrow()
175
    {
176
        $batchRequest = new BatchRequest($this->app, [], 'foo_token');
177
178
        $batchRequest->validateBatchRequestCount();
179
    }
180
181
    /**
182
     * @expectedException \Facebook\Exception\SDKException
183
     */
184
    public function testMoreThanFiftyRequestsWillThrow()
185
    {
186
        $batchRequest = $this->createBatchRequest();
187
188
        $this->createAndAppendRequestsTo($batchRequest, 51);
189
190
        $batchRequest->validateBatchRequestCount();
191
    }
192
193
    public function testLessOrEqualThanFiftyRequestsWillNotThrow()
194
    {
195
        $batchRequest = $this->createBatchRequest();
196
197
        $this->createAndAppendRequestsTo($batchRequest, 50);
198
199
        $batchRequest->validateBatchRequestCount();
200
201
        $this->assertTrue(true);
202
    }
203
204
    /**
205
     * @dataProvider requestsAndExpectedResponsesProvider
206
     *
207
     * @param mixed $request
208
     * @param mixed $expectedArray
209
     */
210
    public function testBatchRequestEntitiesProperlyGetConvertedToAnArray($request, $expectedArray)
211
    {
212
        $batchRequest = $this->createBatchRequest();
213
        $batchRequest->add($request, 'foo_name');
214
215
        $requests = $batchRequest->getRequests();
216
        $batchRequestArray = $batchRequest->requestEntityToBatchArray($requests[0]['request'], $requests[0]['name']);
217
218
        $this->assertEquals($expectedArray, $batchRequestArray);
219
    }
220
221
    public function requestsAndExpectedResponsesProvider()
222
    {
223
        $headers = $this->defaultHeaders();
224
225
        return [
226
            [
227
                new Request(null, null, 'GET', '/foo', ['foo' => 'bar']),
228
                [
229
                    'headers' => $headers,
230
                    'method' => 'GET',
231
                    'relative_url' => '/foo?foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
232
                    'name' => 'foo_name',
233
                ],
234
            ],
235
            [
236
                new Request(null, null, 'POST', '/bar', ['bar' => 'baz']),
237
                [
238
                    'headers' => $headers,
239
                    'method' => 'POST',
240
                    'relative_url' => '/bar',
241
                    'body' => 'bar=baz&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
242
                    'name' => 'foo_name',
243
                ],
244
            ],
245
            [
246
                new Request(null, null, 'DELETE', '/bar'),
247
                [
248
                    'headers' => $headers,
249
                    'method' => 'DELETE',
250
                    'relative_url' => '/bar?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
251
                    'name' => 'foo_name',
252
                ],
253
            ],
254
        ];
255
    }
256
257
    public function testBatchRequestsWithFilesGetConvertedToAnArray()
258
    {
259
        $request = new Request(null, null, 'POST', '/bar', [
260
            'message' => 'foobar',
261
            'source' => new File(__DIR__ . '/foo.txt'),
262
        ]);
263
264
        $batchRequest = $this->createBatchRequest();
265
        $batchRequest->add($request, 'foo_name');
266
267
        $requests = $batchRequest->getRequests();
268
269
        $attachedFiles = $requests[0]['attached_files'];
270
271
        $batchRequestArray = $batchRequest->requestEntityToBatchArray(
272
            $requests[0]['request'],
273
            $requests[0]['name'],
274
            $attachedFiles
275
        );
276
277
        $this->assertEquals([
278
            'headers' => $this->defaultHeaders(),
279
            'method' => 'POST',
280
            'relative_url' => '/bar',
281
            'body' => 'message=foobar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
282
            'name' => 'foo_name',
283
            'attached_files' => $attachedFiles,
284
        ], $batchRequestArray);
285
    }
286
287
    public function testBatchRequestsWithOptionsGetConvertedToAnArray()
288
    {
289
        $request = new Request(null, null, 'GET', '/bar');
290
        $batchRequest = $this->createBatchRequest();
291
        $batchRequest->add($request, [
292
            'name' => 'foo_name',
293
            'omit_response_on_success' => false,
294
        ]);
295
296
        $requests = $batchRequest->getRequests();
297
298
        $options = $requests[0]['options'];
299
        $options['name'] = $requests[0]['name'];
300
301
        $batchRequestArray = $batchRequest->requestEntityToBatchArray($requests[0]['request'], $options);
302
303
        $this->assertEquals([
304
            'headers' => $this->defaultHeaders(),
305
            'method' => 'GET',
306
            'relative_url' => '/' . Facebook::DEFAULT_GRAPH_VERSION . '/bar?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
0 ignored issues
show
Bug introduced by
The constant Facebook\Facebook::DEFAULT_GRAPH_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
307
            'name' => 'foo_name',
308
            'omit_response_on_success' => false,
309
        ], $batchRequestArray);
310
    }
311
312
    public function testPreppingABatchRequestProperlySetsThePostParams()
313
    {
314
        $batchRequest = $this->createBatchRequest();
315
        $batchRequest->add(new Request(null, 'bar_token', 'GET', '/foo'), 'foo_name');
316
        $batchRequest->add(new Request(null, null, 'POST', '/bar', ['foo' => 'bar']));
317
        $batchRequest->prepareRequestsForBatch();
318
319
        $params = $batchRequest->getParams();
320
321
        $expectedHeaders = json_encode($this->defaultHeaders());
322
        $expectedBatchParams = [
323
            'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/foo?access_token=bar_token&appsecret_proof=2ceec40b7b9fd7d38fff1767b766bcc6b1f9feb378febac4612c156e6a8354bd","name":"foo_name"},'
324
                . '{"headers":' . $expectedHeaders . ',"method":"POST","relative_url":"\\/bar","body":"foo=bar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9"}]',
325
            'include_headers' => true,
326
            'access_token' => 'foo_token',
327
            'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
328
        ];
329
        $this->assertEquals($expectedBatchParams, $params);
330
    }
331
332
    public function testPreppingABatchRequestProperlyMovesTheFiles()
333
    {
334
        $batchRequest = $this->createBatchRequest();
335
        $batchRequest->add(new Request(null, 'bar_token', 'GET', '/foo'), 'foo_name');
336
        $batchRequest->add(new Request(null, null, 'POST', '/me/photos', [
337
            'message' => 'foobar',
338
            'source' => new File(__DIR__ . '/foo.txt'),
339
        ]));
340
        $batchRequest->prepareRequestsForBatch();
341
342
        $params = $batchRequest->getParams();
343
        $files = $batchRequest->getFiles();
344
345
        $attachedFiles = implode(',', array_keys($files));
346
347
        $expectedHeaders = json_encode($this->defaultHeaders());
348
        $expectedBatchParams = [
349
            'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/foo?access_token=bar_token&appsecret_proof=2ceec40b7b9fd7d38fff1767b766bcc6b1f9feb378febac4612c156e6a8354bd","name":"foo_name"},'
350
                . '{"headers":' . $expectedHeaders . ',"method":"POST","relative_url":"\\/me\\/photos","body":"message=foobar&access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9","attached_files":"' . $attachedFiles . '"}]',
351
            'include_headers' => true,
352
            'access_token' => 'foo_token',
353
            'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
354
        ];
355
        $this->assertEquals($expectedBatchParams, $params);
356
    }
357
358
    public function testPreppingABatchRequestWithOptionsProperlySetsThePostParams()
359
    {
360
        $batchRequest = $this->createBatchRequest();
361
        $batchRequest->add(new Request(null, null, 'GET', '/foo'), [
362
            'name' => 'foo_name',
363
            'omit_response_on_success' => false,
364
        ]);
365
366
        $batchRequest->prepareRequestsForBatch();
367
        $params = $batchRequest->getParams();
368
369
        $expectedHeaders = json_encode($this->defaultHeaders());
370
        $version = Facebook::DEFAULT_GRAPH_VERSION;
0 ignored issues
show
Bug introduced by
The constant Facebook\Facebook::DEFAULT_GRAPH_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
371
372
        $expectedBatchParams = [
373
            'batch' => '[{"headers":' . $expectedHeaders . ',"method":"GET","relative_url":"\\/' . $version . '\\/foo?access_token=foo_token&appsecret_proof=df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9",'
374
                . '"name":"foo_name","omit_response_on_success":false}]',
375
            'include_headers' => true,
376
            'access_token' => 'foo_token',
377
            'appsecret_proof' => 'df4256903ba4e23636cc142117aa632133d75c642bd2a68955be1443bd14deb9',
378
        ];
379
        $this->assertEquals($expectedBatchParams, $params);
380
    }
381
382
    private function assertRequestContainsAppAndToken(Request $request, Application $expectedApp, $expectedToken)
383
    {
384
        $app = $request->getApp();
385
        $token = $request->getAccessToken();
386
387
        $this->assertSame($expectedApp, $app);
388
        $this->assertEquals($expectedToken, $token);
389
    }
390
391
    private function defaultHeaders()
392
    {
393
        $headers = [];
394
        foreach (Request::getDefaultHeaders() as $name => $value) {
395
            $headers[] = $name . ': ' . $value;
396
        }
397
398
        return $headers;
399
    }
400
401
    private function createAndAppendRequestsTo(BatchRequest $batchRequest, $number)
402
    {
403
        for ($i = 0; $i < $number; $i++) {
404
            $batchRequest->add(new Request());
405
        }
406
    }
407
408
    private function createBatchRequest()
409
    {
410
        return new BatchRequest($this->app, [], 'foo_token');
411
    }
412
413
    private function createBatchRequestWithRequests(array $requests)
414
    {
415
        $batchRequest = $this->createBatchRequest();
416
        $batchRequest->add($requests);
417
418
        return $batchRequest;
419
    }
420
421
    private function assertRequestsMatch($requests, $formattedRequests)
422
    {
423
        $expectedRequests = [];
424
        foreach ($requests as $name => $request) {
425
            $expectedRequests[] = [
426
                'name' => $name,
427
                'request' => $request,
428
                'attached_files' => null,
429
                'options' => [],
430
            ];
431
        }
432
        $this->assertEquals($expectedRequests, $formattedRequests);
433
    }
434
}
435