Skip to content

Commit 47fdfb7

Browse files
authored
add note about using finally (#7314)
* 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 * Add example of finally
1 parent 1d298bf commit 47fdfb7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

AUTHORING_GUIDE.md

+32
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,38 @@ All temporary resources should be explicitly deleted when testing is
451451
complete. Use pytest's fixture for cleaning up these resouces instead
452452
of doing it in test itself.
453453
454+
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.
455+
456+
```python
457+
@pytest.fixture(scope="function")
458+
def setup_and_teardown_cluster():
459+
try:
460+
# Create cluster using cluster client
461+
cluster_client = dataproc.ClusterControllerClient(
462+
client_options={
463+
"api_endpoint": f"{CLUSTER_REGION}-dataproc.googleapis.com:443"
464+
}
465+
)
466+
467+
operation = cluster_client.create_cluster(
468+
project_id=PROJECT_ID, region=CLUSTER_REGION, cluster=CLUSTER_CONFIG
469+
)
470+
471+
# Wait for cluster to provision
472+
operation.result()
473+
474+
yield
475+
finally:
476+
try:
477+
# Delete cluster
478+
operation = cluster_client.delete_cluster(
479+
project_id=PROJECT_ID, region=CLUSTER_REGION, cluster_name=DATAPROC_CLUSTER
480+
)
481+
operation.result()
482+
except NotFound:
483+
print("Cluster already deleted")
484+
```
485+
454486
### Console Output
455487
456488
If the sample prints output to the console, the test should capture stdout to

0 commit comments

Comments
 (0)