[pytest-dev] Running finalizer in case test setup has failed

holger krekel holger at merlinux.eu
Tue Nov 12 10:16:12 CET 2013


Hi Andrii,

On Mon, Nov 11, 2013 at 19:56 +0200, Andrii Smirnov wrote:
> Hello All,
> 
> We have complex enough (several stages of putting the test environment into
> some condition) code which should be executed in all cases regardless of
> test setup result (fixture setup).
> 
> Since finalizer for fixture will not be called in case its (fixture) setup
> failed we've put some calls to pytest_sessionfinish as a temporary
> workaround but we need to find a way how to call finalizer code explicitly.

Calling fixture finalizers from such a hook is hard if even possible.

But i don't understand yet why your finalizers are not run.  Take
this example::

    import pytest

    @pytest.fixture
    def fix(request):
        def fin():
            print "finalizing!"
        
        request.addfinalizer(fin)
        0/0

    def test_hello(fix):
        pass

If you run this with ``py.test -s`` you will see the ``finalizing!``
message although the fixture function fails.

If you are running xUnit-style ``setup*`` functions then indeed,
pytest is compatible to the way unittest or nose do xUnit setup:
teardownX functions are not run if a setupX function fails.
However, you can transform any such setup function into
a pytest style one by puttig a fixture-autouse decorator in front::

    @pytest.fixture(autouse=True)
    def setup_function(request):
        # as above you can register finalizers etc.

If you use the decorator you can also use other pytest fixtures
such as ``tmpdir`` or ``monkeypatch`` or your own fixtures, of course.

If both examples don't answer your question, please try to give a
code example on how things fail for you.

cheers,
holger


More information about the Pytest-dev mailing list