[TIP] testing-in-python Digest, Vol 87, Issue 3

Pella,Chris Chris.Pella at safenet-inc.com
Thu Apr 10 13:27:06 PDT 2014

Thanks Carl,
Actually, in reference to point 1), we found that the only way we could guarantee resources being released was if we called the finalizing function from the exception clause. That was surprising to us. We started out with no exception handling at all in the fixtures and only added this to get around the issue. 
I didn't know about the yield_fixture.


> I would say the better way in modern pytest is to use yield_fixture rather
> than request.addfinalizer:
> @pytest.yield_fixture(scope='class')
> def test_fixture():
>     cleanup_parameter = "Cleaning up"
>     try:
>         raise
>     except Exception:
>         cleanup_parameter = "Problem in fixture!"
>     yield None
>     print cleanup_parameter
> This gives you flexibility to do whatever you like in cleanup, without the
> constraint of "pass a callable to addfinalizer." It also puts the code in
> execution order (once you understand that your test runs at the point of the
> "yield"), which is nice.
> (You'd actually yield whatever you'd have returned from the non-yield
> fixture; I used None here to make it equivalent to what you posted).
> A couple other notes about the version you posted:
> 1) Why does it call cleanup() in the except clause, but then still add a
> finalizer? That will result in cleanup() being run twice, once before the test
> and once after it.
> 2) There is no need for all those "global" declarations; closures can access
> variables in their parent scope with no such declaration. Remove both global
> statements and your version should still work the same.
> HTH,
> Carl
The information contained in this electronic mail transmission 
may be privileged and confidential, and therefore, protected 
from disclosure. If you have received this communication in 
error, please notify us immediately by replying to this 
message and deleting it from your computer without copying 
or disclosing it.

More information about the testing-in-python mailing list