@@ -288,6 +288,7 @@ example](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/
288288* Use pytest's fixture for resource setup and teardown, instead of
289289 having them in the test itself.
290290* Avoid infinite loops.
291+ * Retry RPCs
291292
292293### Arrange, Act, Assert
293294
@@ -332,10 +333,15 @@ glossary_id = 'test-glossary-{}'.format(uuid.uuid4())
332333or:
333334
334335``` python
335- # If full uuid4 is too long, use hex representation.
336+ # If full uuid4 is too long, use its hex representation.
336337encrypted_disk_name = ' test-disk-{} ' .format(uuid.uuid4().hex)
337338```
338339
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+
339345All temporary resources should be explicitly deleted when testing is
340346complete. Use pytest' s fixture for cleaning up these resouces instead
341347of doing it in test itself.
@@ -384,6 +390,44 @@ This combination will give you very high success rate with fixed test
384390execution time (0.999 success rate and 180 seconds operation wait time
385391in the worst case in this example).
386392
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+
387431# ## Running tests
388432
389433Automated testing for samples in `python- docs- samples` is managed by
0 commit comments