| 1 |
# -*- coding: UTF-8 -*- |
| 2 |
""" |
| 3 |
Explore contextmanager/generator behaviour when: |
| 4 |
* setup step raises error (generator step) |
| 5 |
* with-block raises error |
| 6 |
""" |
| 7 |
|
| 8 |
import pytest |
| 9 |
from contextlib import contextmanager |
| 10 |
|
| 11 |
|
| 12 |
class TestContextManager(object): |
| 13 |
def test_when_setup_raises_error_then_cleanup_isnot_called(self): |
| 14 |
@contextmanager |
| 15 |
def foo(checkpoints): |
| 16 |
checkpoints.append("foo.setup.begin") |
| 17 |
raise RuntimeError("OOPS") |
| 18 |
checkpoints.append("foo.setup.done") |
| 19 |
yield |
| 20 |
checkpoints.append("foo.cleanup") |
| 21 |
|
| 22 |
checkpoints = [] |
| 23 |
with pytest.raises(RuntimeError): |
| 24 |
with foo(checkpoints): |
| 25 |
checkpoints.append("foo.with-block") |
| 26 |
|
| 27 |
assert checkpoints == ["foo.setup.begin"] |
| 28 |
|
| 29 |
def test_with_try_finally_when_setup_raises_error_then_cleanup_is_called(self): |
| 30 |
@contextmanager |
| 31 |
def foo(checkpoints): |
| 32 |
try: |
| 33 |
checkpoints.append("foo.setup.begin") |
| 34 |
raise RuntimeError("OOPS") |
| 35 |
checkpoints.append("foo.setup.done") |
| 36 |
yield |
| 37 |
finally: |
| 38 |
checkpoints.append("foo.cleanup") |
| 39 |
|
| 40 |
checkpoints = [] |
| 41 |
with pytest.raises(RuntimeError): |
| 42 |
with foo(checkpoints): |
| 43 |
checkpoints.append("foo.with-block") |
| 44 |
|
| 45 |
assert checkpoints == ["foo.setup.begin", "foo.cleanup"] |
| 46 |
|
| 47 |
|
| 48 |
class TestGenerator(object): |
| 49 |
def test_when_setup_raises_error_then_cleanup_isnot_called(self): |
| 50 |
def foo(checkpoints): |
| 51 |
checkpoints.append("foo.setup.begin") |
| 52 |
raise RuntimeError("OOPS") |
| 53 |
checkpoints.append("foo.setup.done") |
| 54 |
yield |
| 55 |
checkpoints.append("foo.cleanup") |
| 56 |
|
| 57 |
checkpoints = [] |
| 58 |
with pytest.raises(RuntimeError): |
| 59 |
for iter in foo(checkpoints): |
| 60 |
checkpoints.append("foo.with-block") |
| 61 |
|
| 62 |
assert checkpoints == ["foo.setup.begin"] |
| 63 |
|
| 64 |
def test_with_try_finally_when_setup_raises_error_then_cleanup_is_called(self): |
| 65 |
def foo(checkpoints): |
| 66 |
try: |
| 67 |
checkpoints.append("foo.setup.begin") |
| 68 |
raise RuntimeError("OOPS") |
| 69 |
checkpoints.append("foo.setup.done") |
| 70 |
yield |
| 71 |
finally: |
| 72 |
checkpoints.append("foo.cleanup") |
| 73 |
|
| 74 |
checkpoints = [] |
| 75 |
with pytest.raises(RuntimeError): |
| 76 |
for iter in foo(checkpoints): |
| 77 |
checkpoints.append("foo.with-block") |
| 78 |
|
| 79 |
assert checkpoints == ["foo.setup.begin", "foo.cleanup"] |