1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
|
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response;
class Google_Task_RunnerTest extends BaseTest { private $client;
private $mockedCallsCount = 0; private $currentMockedCall = 0; private $mockedCalls = array(); private $retryMap; private $retryConfig;
protected function setUp() { $this->client = new Google_Client(); }
/** * @dataProvider defaultRestErrorProvider * @expectedException Google_Service_Exception */ public function testRestRetryOffByDefault($errorCode, $errorBody = '{}') { $this->setNextResponse($errorCode, $errorBody)->makeRequest(); }
/** * @dataProvider defaultRestErrorProvider * @expectedException Google_Service_Exception */ public function testOneRestRetryWithError($errorCode, $errorBody = '{}') { $this->setRetryConfig(array('retries' => 1)); $this->setNextResponses(2, $errorCode, $errorBody)->makeRequest(); }
/** * @dataProvider defaultRestErrorProvider * @expectedException Google_Service_Exception */ public function testMultipleRestRetriesWithErrors( $errorCode, $errorBody = '{}' ) { $this->setRetryConfig(array('retries' => 5)); $this->setNextResponses(6, $errorCode, $errorBody)->makeRequest(); }
/** * @dataProvider defaultRestErrorProvider */ public function testOneRestRetryWithSuccess($errorCode, $errorBody = '{}') { $this->setRetryConfig(array('retries' => 1)); $result = $this->setNextResponse($errorCode, $errorBody) ->setNextResponse(200, '{"success": true}') ->makeRequest();
$this->assertEquals('{"success": true}', (string) $result->getBody()); }
/** * @dataProvider defaultRestErrorProvider */ public function testMultipleRestRetriesWithSuccess( $errorCode, $errorBody = '{}' ) { $this->setRetryConfig(array('retries' => 5)); $result = $this->setNextResponses(2, $errorCode, $errorBody) ->setNextResponse(200, '{"success": true}') ->makeRequest();
$this->assertEquals('{"success": true}', (string) $result->getBody()); }
/** * @dataProvider defaultRestErrorProvider * @expectedException Google_Service_Exception */ public function testCustomRestRetryMapReplacesDefaults( $errorCode, $errorBody = '{}' ) { $this->setRetryMap(array());
$this->setRetryConfig(array('retries' => 5)); $this->setNextResponse($errorCode, $errorBody)->makeRequest(); }
public function testCustomRestRetryMapAddsNewHandlers() { $this->setRetryMap( array('403' => Google_Task_Runner::TASK_RETRY_ALWAYS) );
$this->setRetryConfig(array('retries' => 5)); $result = $this->setNextResponses(2, 403) ->setNextResponse(200, '{"success": true}') ->makeRequest();
$this->assertEquals('{"success": true}', (string) $result->getBody()); }
/** * @expectedException Google_Service_Exception * @dataProvider customLimitsProvider */ public function testCustomRestRetryMapWithCustomLimits($limit) { $this->setRetryMap( array('403' => $limit) );
$this->setRetryConfig(array('retries' => 5)); $this->setNextResponses($limit + 1, 403)->makeRequest(); }
/** * @dataProvider timeoutProvider */ public function testRestTimeouts($config, $minTime) { $this->setRetryConfig($config); $this->setNextResponses($config['retries'], 500) ->setNextResponse(200, '{"success": true}');
$this->assertTaskTimeGreaterThanOrEqual( $minTime, array($this, 'makeRequest'), $config['initial_delay'] / 10 ); }
/** * @requires extension curl * @dataProvider defaultCurlErrorProvider * @expectedException Google_Service_Exception */ public function testCurlRetryOffByDefault($errorCode, $errorMessage = '') { $this->setNextResponseThrows($errorMessage, $errorCode)->makeRequest(); }
/** * @requires extension curl * @dataProvider defaultCurlErrorProvider * @expectedException Google_Service_Exception */ public function testOneCurlRetryWithError($errorCode, $errorMessage = '') { $this->setRetryConfig(array('retries' => 1)); $this->setNextResponsesThrow(2, $errorMessage, $errorCode)->makeRequest(); }
/** * @requires extension curl * @dataProvider defaultCurlErrorProvider * @expectedException Google_Service_Exception */ public function testMultipleCurlRetriesWithErrors( $errorCode, $errorMessage = '' ) { $this->setRetryConfig(array('retries' => 5)); $this->setNextResponsesThrow(6, $errorMessage, $errorCode)->makeRequest(); }
/** * @requires extension curl * @dataProvider defaultCurlErrorProvider */ public function testOneCurlRetryWithSuccess($errorCode, $errorMessage = '') { $this->setRetryConfig(array('retries' => 1)); $result = $this->setNextResponseThrows($errorMessage, $errorCode) ->setNextResponse(200, '{"success": true}') ->makeRequest();
$this->assertEquals('{"success": true}', (string) $result->getBody()); }
/** * @requires extension curl * @dataProvider defaultCurlErrorProvider */ public function testMultipleCurlRetriesWithSuccess( $errorCode, $errorMessage = '' ) { $this->setRetryConfig(array('retries' => 5)); $result = $this->setNextResponsesThrow(2, $errorMessage, $errorCode) ->setNextResponse(200, '{"success": true}') ->makeRequest();
$this->assertEquals('{"success": true}', (string) $result->getBody()); }
/** * @requires extension curl * @dataProvider defaultCurlErrorProvider * @expectedException Google_Service_Exception */ public function testCustomCurlRetryMapReplacesDefaults( $errorCode, $errorMessage = '' ) { $this->setRetryMap(array());
$this->setRetryConfig(array('retries' => 5)); $this->setNextResponseThrows($errorMessage, $errorCode)->makeRequest(); }
/** * @requires extension curl */ public function testCustomCurlRetryMapAddsNewHandlers() { $this->setRetryMap( array(CURLE_COULDNT_RESOLVE_PROXY => Google_Task_Runner::TASK_RETRY_ALWAYS) );
$this->setRetryConfig(array('retries' => 5)); $result = $this->setNextResponsesThrow(2, '', CURLE_COULDNT_RESOLVE_PROXY) ->setNextResponse(200, '{"success": true}') ->makeRequest();
$this->assertEquals('{"success": true}', (string) $result->getBody()); }
/** * @requires extension curl * @expectedException Google_Service_Exception * @dataProvider customLimitsProvider */ public function testCustomCurlRetryMapWithCustomLimits($limit) { $this->setRetryMap( array(CURLE_COULDNT_RESOLVE_PROXY => $limit) );
$this->setRetryConfig(array('retries' => 5)); $this->setNextResponsesThrow($limit + 1, '', CURLE_COULDNT_RESOLVE_PROXY) ->makeRequest(); }
/** * @requires extension curl * @dataProvider timeoutProvider */ public function testCurlTimeouts($config, $minTime) { $this->setRetryConfig($config); $this->setNextResponsesThrow($config['retries'], '', CURLE_GOT_NOTHING) ->setNextResponse(200, '{"success": true}');
$this->assertTaskTimeGreaterThanOrEqual( $minTime, array($this, 'makeRequest'), $config['initial_delay'] / 10 ); }
/** * @dataProvider badTaskConfigProvider */ public function testBadTaskConfig($config, $message) { $this->setExpectedException('Google_Task_Exception', $message); $this->setRetryConfig($config);
new Google_Task_Runner( $this->retryConfig, '', array($this, 'testBadTaskConfig') ); }
/** * @expectedException Google_Task_Exception * @expectedExceptionMessage must be a valid callable */ public function testBadTaskCallback() { $config = []; new Google_Task_Runner($config, '', 5); }
/** * @expectedException Google_Service_Exception */ public function testTaskRetryOffByDefault() { $this->setNextTaskAllowedRetries(Google_Task_Runner::TASK_RETRY_ALWAYS) ->runTask(); }
/** * @expectedException Google_Service_Exception */ public function testOneTaskRetryWithError() { $this->setRetryConfig(array('retries' => 1)); $this->setNextTasksAllowedRetries(2, Google_Task_Runner::TASK_RETRY_ALWAYS) ->runTask(); }
/** * @expectedException Google_Service_Exception */ public function testMultipleTaskRetriesWithErrors() { $this->setRetryConfig(array('retries' => 5)); $this->setNextTasksAllowedRetries(6, Google_Task_Runner::TASK_RETRY_ALWAYS) ->runTask(); }
public function testOneTaskRetryWithSuccess() { $this->setRetryConfig(array('retries' => 1)); $result = $this->setNextTaskAllowedRetries(Google_Task_Runner::TASK_RETRY_ALWAYS) ->setNextTaskReturnValue('success') ->runTask();
$this->assertEquals('success', $result); }
public function testMultipleTaskRetriesWithSuccess() { $this->setRetryConfig(array('retries' => 5)); $result = $this->setNextTasksAllowedRetries(2, Google_Task_Runner::TASK_RETRY_ALWAYS) ->setNextTaskReturnValue('success') ->runTask();
$this->assertEquals('success', $result); }
/** * @expectedException Google_Service_Exception * @dataProvider customLimitsProvider */ public function testTaskRetryWithCustomLimits($limit) { $this->setRetryConfig(array('retries' => 5)); $this->setNextTasksAllowedRetries($limit + 1, $limit) ->runTask(); }
/** * @dataProvider timeoutProvider */ public function testTaskTimeouts($config, $minTime) { $this->setRetryConfig($config); $this->setNextTasksAllowedRetries($config['retries'], $config['retries'] + 1) ->setNextTaskReturnValue('success');
$this->assertTaskTimeGreaterThanOrEqual( $minTime, array($this, 'runTask'), $config['initial_delay'] / 10 ); }
public function testTaskWithManualRetries() { $this->setRetryConfig(array('retries' => 2)); $this->setNextTasksAllowedRetries(2, Google_Task_Runner::TASK_RETRY_ALWAYS);
$task = new Google_Task_Runner( $this->retryConfig, '', array($this, 'runNextTask') );
$this->assertTrue($task->canAttempt()); $this->assertTrue($task->attempt());
$this->assertTrue($task->canAttempt()); $this->assertTrue($task->attempt());
$this->assertTrue($task->canAttempt()); $this->assertTrue($task->attempt());
$this->assertFalse($task->canAttempt()); $this->assertFalse($task->attempt()); }
/** * Provider for backoff configurations and expected minimum runtimes. * * @return array */ public function timeoutProvider() { $config = array('initial_delay' => .001, 'max_delay' => .01);
return array( array(array_merge($config, array('retries' => 1)), .001), array(array_merge($config, array('retries' => 2)), .0015), array(array_merge($config, array('retries' => 3)), .00225), array(array_merge($config, array('retries' => 4)), .00375), array(array_merge($config, array('retries' => 5)), .005625) ); }
/** * Provider for custom retry limits. * * @return array */ public function customLimitsProvider() { return array( array(Google_Task_Runner::TASK_RETRY_NEVER), array(Google_Task_Runner::TASK_RETRY_ONCE), ); }
/** * Provider for invalid task configurations. * * @return array */ public function badTaskConfigProvider() { return array( array(array('initial_delay' => -1), 'must not be negative'), array(array('max_delay' => 0), 'must be greater than 0'), array(array('factor' => 0), 'must be greater than 0'), array(array('jitter' => 0), 'must be greater than 0'), array(array('retries' => -1), 'must not be negative') ); }
/** * Provider for the default REST errors. * * @return array */ public function defaultRestErrorProvider() { return array( array(500), array(503), array(403, '{"error":{"errors":[{"reason":"rateLimitExceeded"}]}}'), array(403, '{"error":{"errors":[{"reason":"userRateLimitExceeded"}]}}'), ); }
/** * Provider for the default cURL errors. * * @return array */ public function defaultCurlErrorProvider() { return array( array(6), // CURLE_COULDNT_RESOLVE_HOST array(7), // CURLE_COULDNT_CONNECT array(28), // CURLE_OPERATION_TIMEOUTED array(35), // CURLE_SSL_CONNECT_ERROR array(52), // CURLE_GOT_NOTHING ); }
/** * Assert the minimum amount of time required to run a task. * * NOTE: Intentionally crude for brevity. * * @param float $expected The expected minimum execution time * @param callable $callback The task to time * @param float $delta Allowable relative error * * @throws PHPUnit_Framework_ExpectationFailedException */ public static function assertTaskTimeGreaterThanOrEqual( $expected, $callback, $delta = 0.0 ) { $time = microtime(true);
call_user_func($callback);
self::assertThat( microtime(true) - $time, self::logicalOr( self::greaterThan($expected), self::equalTo($expected, $delta) ) ); }
/** * Sets the task runner configurations. * * @param array $config The task runner configurations */ private function setRetryConfig(array $config) { $config += array( 'initial_delay' => .0001, 'max_delay' => .001, 'factor' => 2, 'jitter' => .5, 'retries' => 1 ); $this->retryConfig = $config; }
private function setRetryMap(array $retryMap) { $this->retryMap = $retryMap; }
/** * Sets the next responses. * * @param integer $count The number of responses * @param string $code The response code * @param string $body The response body * @param array $headers The response headers * * @return TaskTest */ private function setNextResponses( $count, $code = '200', $body = '{}', array $headers = array() ) { while ($count-- > 0) { $this->setNextResponse($code, $body, $headers); }
return $this; }
/** * Sets the next response. * * @param string $code The response code * @param string $body The response body * @param array $headers The response headers * * @return TaskTest */ private function setNextResponse( $code = '200', $body = '{}', array $headers = array() ) { $this->mockedCalls[$this->mockedCallsCount++] = array( 'code' => (string) $code, 'headers' => $headers, 'body' => is_string($body) ? $body : json_encode($body) );
return $this; }
/** * Forces the next responses to throw an IO exception. * * @param integer $count The number of responses * @param string $message The exception messages * @param string $code The exception code * * @return TaskTest */ private function setNextResponsesThrow($count, $message, $code) { while ($count-- > 0) { $this->setNextResponseThrows($message, $code); }
return $this; }
/** * Forces the next response to throw an IO exception. * * @param string $message The exception messages * @param string $code The exception code * * @return TaskTest */ private function setNextResponseThrows($message, $code) { $this->mockedCalls[$this->mockedCallsCount++] = new Google_Service_Exception( $message, $code, null, array() );
return $this; }
/** * Runs the defined request. * * @return array */ private function makeRequest() { $request = new Request('GET', '/test'); $http = $this->getMock('GuzzleHttp\ClientInterface'); $http->expects($this->exactly($this->mockedCallsCount)) ->method('send') ->will($this->returnCallback(array($this, 'getNextMockedCall')));
if ($this->isGuzzle5()) { $http->expects($this->exactly($this->mockedCallsCount)) ->method('createRequest') ->will($this->returnValue(new GuzzleHttp\Message\Request('GET', '/test'))); }
return Google_Http_REST::execute($http, $request, '', $this->retryConfig, $this->retryMap); }
/** * Gets the next mocked response. * * @param Google_Http_Request $request The mocked request * * @return Google_Http_Request */ public function getNextMockedCall($request) { $current = $this->mockedCalls[$this->currentMockedCall++];
if ($current instanceof Exception) { throw $current; }
$stream = Psr7\stream_for($current['body']); $response = new Response($current['code'], $current['headers'], $stream);
return $response; }
/** * Sets the next task return value. * * @param mixed $value The next return value * * @return TaskTest */ private function setNextTaskReturnValue($value) { $this->mockedCalls[$this->mockedCallsCount++] = $value; return $this; }
/** * Sets the next exception `allowedRetries()` return value. * * @param boolean $allowedRetries The next `allowedRetries()` return value. * * @return TaskTest */ private function setNextTaskAllowedRetries($allowedRetries) { $this->mockedCalls[$this->mockedCallsCount++] = $allowedRetries; return $this; }
/** * Sets multiple exception `allowedRetries()` return value. * * @param integer $count The number of `allowedRetries()` return values. * @param boolean $allowedRetries The `allowedRetries()` return value. * * @return TaskTest */ private function setNextTasksAllowedRetries($count, $allowedRetries) { while ($count-- > 0) { $this->setNextTaskAllowedRetries($allowedRetries); }
return $this; }
/** * Runs the defined task. * * @return mixed */ private function runTask() { $task = new Google_Task_Runner( $this->retryConfig, '', array($this, 'runNextTask') );
if (null !== $this->retryMap) { $task->setRetryMap($this->retryMap); }
$exception = $this->getMockBuilder('Google_Service_Exception') // HHVM blows up unless this is set // @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/207 ->setMethods(array('setTraceOptions')) ->disableOriginalConstructor() ->getMock(); $exceptionCount = 0; $exceptionCalls = array();
for ($i = 0; $i < $this->mockedCallsCount; $i++) { if (is_int($this->mockedCalls[$i])) { $exceptionCalls[$exceptionCount++] = $this->mockedCalls[$i]; $this->mockedCalls[$i] = $exception; } }
$task->setRetryMap($exceptionCalls);
return $task->run(); }
/** * Gets the next task return value. * * @return mixed */ public function runNextTask() { $current = $this->mockedCalls[$this->currentMockedCall++];
if ($current instanceof Exception) { throw $current; }
return $current; } }
|