简体   繁体   中英

Pytest doesn't throw exceptions into fixture generators

In pytest, it's possible to add finalizers to fixtures by turning them into generators and supplying finalization code after the first (and only) yield .

I was surprised to see that the exceptions are not thrown back into the generator. I guess this makes sense, otherwise users would always have to wrap the yield with a try...except or something similar.

What I was hoping for was for something like this to work:

import pytest

@pytest.fixture
def some_val():
    return 42

@pytest.fixture
def a_val(some_val):
    try:
        yield some_val
    except Exception as e:
        print(f"An exception occurred: {e}")

def test_a_val(a_val):
    raise ValueError("Something bad happened..")

The context for this is that I would like to add a routine to provide some additional debugging information on a specific type of error and I really don't want to have to put this code into the tests themselves.

Ideally, I would wrap the yield with a context manager to catch the exception but that obviously suffers from the same problem here.

Is there an alternative pytest way of making this work I'm not aware of?

For anyone else wanting this behavior, it can be simulated using one of pytest's hooks, in this case pytest_pyfunc_call will work well.

conftest.py :

import pytest

@pytest.hookimpl(hookwrapper=True)
def pytest_pyfunc_call(pyfuncitem):
    print("Hook executing...")

    funcargs = pyfuncitem.funcargs
    testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
    print(f"funcargs: {funcargs}")
    print(f"testargs: {testargs}")
    try:
        outcome = yield
        outcome.get_result()
    except Exception as e:
        print(f"Got exception: {e}")
        raise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM