@@ -288,6 +288,7 @@ example](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/
288
288
* Use pytest's fixture for resource setup and teardown, instead of
289
289
having them in the test itself.
290
290
* Avoid infinite loops.
291
+ * Retry RPCs
291
292
292
293
### Arrange, Act, Assert
293
294
@@ -332,10 +333,15 @@ glossary_id = 'test-glossary-{}'.format(uuid.uuid4())
332
333
or:
333
334
334
335
``` python
335
- # If full uuid4 is too long, use hex representation.
336
+ # If full uuid4 is too long, use its hex representation.
336
337
encrypted_disk_name = ' test-disk-{} ' .format(uuid.uuid4().hex)
337
338
```
338
339
340
+ ``` python
341
+ # If the hex representation is also too long, slice it.
342
+ encrypted_disk_name = ' test-disk-{} ' .format(uuid.uuid4().hex[:5 ]
343
+ ```
344
+
339
345
All temporary resources should be explicitly deleted when testing is
340
346
complete. Use pytest' s fixture for cleaning up these resouces instead
341
347
of doing it in test itself.
@@ -384,6 +390,44 @@ This combination will give you very high success rate with fixed test
384
390
execution time (0.999 success rate and 180 seconds operation wait time
385
391
in the worst case in this example).
386
392
393
+ # ## Retry RPCs
394
+
395
+ All the RPCs are inevitably flaky. It can fail for many reasons. The
396
+ `google- cloud` Python client retries requests automatically for most
397
+ cases.
398
+
399
+ The old api- client doesn' t retry automatically, so consider using
400
+ [`backoff` ](https:// pypi.org/ project/ backoff/ ) for retrying. Here is a
401
+ simple example:
402
+
403
+ ```python
404
+
405
+ import backoff
406
+ from googleapiclient.errors import HttpError
407
+
408
+ @ pytest.fixture(scope = ' module' )
409
+ def test_resource():
410
+ @ backoff.on_exception(backoff.expo, HttpError, max_time = 60 )
411
+ def create_resource():
412
+ try :
413
+ return client.projects().imaginaryResource().create(
414
+ name = resource_id, body = body).execute()
415
+ except HttpError as e:
416
+ if ' 409' in str (e):
417
+ # Ignore this case and get the existing one.
418
+ return client.projects().imaginaryResource().get(
419
+ name = resource_id).execute()
420
+ else :
421
+ raise
422
+
423
+ resource = create_resource()
424
+
425
+ yield resource
426
+
427
+ # cleanup
428
+ ...
429
+ ```
430
+
387
431
# ## Running tests
388
432
389
433
Automated testing for samples in `python- docs- samples` is managed by
0 commit comments