aws-deadline / deadline-cloud-test-fixtures

This package contains pytest fixtures that are used to test AWS Deadline Cloud Python packages
Apache License 2.0
9 stars 13 forks source link

fix: properly handly exceptions in the `deletable` context manager #50

Closed ttblanchard closed 9 months ago

ttblanchard commented 9 months ago

What was the problem/requirement? (What/Why)

During the initialization of resources, if an exception occurred the previously created resources were not being cleaned up.

What was the solution? (How)

The deletable context manager needs a try/except block in order for those exceptions to be caught and for the __exit__ statements to be called on the previous contextmanagers. See the following code example below:

from contextlib import ExitStack,contextmanager

@contextmanager
def deletable1(r):
    yield r
    print(r + " is being deleted")

@contextmanager
def deletable2(r):
    try:
        yield r
    finally:
        print(r + " is being deleted")

try:
    with ExitStack() as context_stack:
        r1 = context_stack.enter_context(deletable1("test1_1"))
        r2 = context_stack.enter_context(deletable2("test1_2"))
        raise Exception("Trevor Test 1")
except: 
    pass

print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")

try:
    with ExitStack() as context_stack:
        r1 = context_stack.enter_context(deletable1("test2_1"))
        raise Exception("Trevor Test 2")
except: 
    pass

print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")

try:
    with ExitStack() as context_stack:
        r1 = context_stack.enter_context(deletable2("test3_1"))
        r1 = context_stack.enter_context(deletable2("test3_2"))
        raise Exception("Trevor Test 3")
except: 
    pass

print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")

with ExitStack() as context_stack:
    r1 = context_stack.enter_context(deletable2("test4_1"))
    r1 = context_stack.enter_context(deletable2("test4_2"))

Here is the output when run:

C:\deadlinecloud>python testexitstack.py
test1_2 is being deleted
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test3_2 is being deleted
test3_1 is being deleted
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test4_2 is being deleted
test4_1 is being deleted

What is the impact of this change?

When resources fail to create after other resources were already created during bootstrapping, everything is cleaned up nicely.

How was this change tested?

Was this change documented?

Is this a breaking change?