From 2b07038a86041bf7ba99983e1690bc69c23ff1e6 Mon Sep 17 00:00:00 2001 From: "Leah E. Cole" <6719667+leahecole@users.noreply.github.com> Date: Wed, 5 Jan 2022 13:26:00 -0800 Subject: [PATCH 1/2] add note about using finally @tswast reminded me about `finally` the other day and I thought I'd add a note about it in the authoring guide --- AUTHORING_GUIDE.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AUTHORING_GUIDE.md b/AUTHORING_GUIDE.md index 9e7f5771e7a..a0911cb18dc 100644 --- a/AUTHORING_GUIDE.md +++ b/AUTHORING_GUIDE.md @@ -451,6 +451,8 @@ All temporary resources should be explicitly deleted when testing is complete. Use pytest's fixture for cleaning up these resouces instead of doing it in test itself. +We recommend using `finally` to ensure that resource deletion occurs even if there is an error on creation, like in [this example](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/0169e1c7f0ab387832bd32d2f5ca8e2ddfe419b1/data-science-onramp/data-ingestion/ingestion_test.py#L75-L100) + ### Console Output If the sample prints output to the console, the test should capture stdout to From ccc9bc783ff768022f306e2633c1be33f1836bd3 Mon Sep 17 00:00:00 2001 From: Leah Cole Date: Thu, 6 Jan 2022 13:47:22 -0800 Subject: [PATCH 2/2] Add example of finally --- AUTHORING_GUIDE.md | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/AUTHORING_GUIDE.md b/AUTHORING_GUIDE.md index a0911cb18dc..8e34d5d993a 100644 --- a/AUTHORING_GUIDE.md +++ b/AUTHORING_GUIDE.md @@ -451,7 +451,37 @@ All temporary resources should be explicitly deleted when testing is complete. Use pytest's fixture for cleaning up these resouces instead of doing it in test itself. -We recommend using `finally` to ensure that resource deletion occurs even if there is an error on creation, like in [this example](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/0169e1c7f0ab387832bd32d2f5ca8e2ddfe419b1/data-science-onramp/data-ingestion/ingestion_test.py#L75-L100) +We recommend using `finally` to ensure that resource deletion occurs even if there is an error on creation. For example, this fixture creates a Dataproc cluster and tears it down regardless of errors during creation. + +```python +@pytest.fixture(scope="function") +def setup_and_teardown_cluster(): + try: + # Create cluster using cluster client + cluster_client = dataproc.ClusterControllerClient( + client_options={ + "api_endpoint": f"{CLUSTER_REGION}-dataproc.googleapis.com:443" + } + ) + + operation = cluster_client.create_cluster( + project_id=PROJECT_ID, region=CLUSTER_REGION, cluster=CLUSTER_CONFIG + ) + + # Wait for cluster to provision + operation.result() + + yield + finally: + try: + # Delete cluster + operation = cluster_client.delete_cluster( + project_id=PROJECT_ID, region=CLUSTER_REGION, cluster_name=DATAPROC_CLUSTER + ) + operation.result() + except NotFound: + print("Cluster already deleted") +``` ### Console Output