pytest fixture finalization in the presence of errors

坚强是说给别人听的谎言 提交于 2021-01-28 18:25:45

问题


I have a test bench setup where I make heavy use of fixtures to provide resources and "items to test" to the tests I have defined. This is great, it allows my test functions to contain as little code as possible.

However I find myself fighting with pytest quite a lot in the area of finalization.

In pytest, fixture finalizers are conveniently described by making a generator of the form:

@pytest.fixture
def a_fixture():
    #some setup code
    resource = setup_resource()

    yield resource

    #finalizer code here
    close_resource(resource)

Frequently, I find myself wishing that I could do this:

@pytest.fixture
def a_fixture():
    #some setup code
    resource = setup_resource()

    try:
        yield resource
    except ValueError as e:
        #handle errors in finalization code
        handle_error(resource)

    #finalizer code here
    close_resource()

Some example usecases for this:

  1. Many of my tests are testing functionality on a piece of hardware connected to a host PC. When an error occurs, I'd like the finalization code to collect more information from the device and log it.
  2. In the event of a specific kind of error, I'd like to alter the finalization code that executes. For example, the tests have resulted in the device under test crashing and attempting to run the finalization code will just result in wasted time.

I raised a ticket with the pytest project about this, they informed me that this decision is by design and the best option for me would be to create a custom report hook.

I find the concept of fixtures to be extremely useful and powerful. I also find the inability of finalizer code to be informed of errors to be very limiting. A custom report hook doesn't work for me because the finalizer code is too closely linked with its source fixture.

So now to the question: If not propagating exceptions into fixtures is by design, how do you provide conditional resource finalization?

来源:https://stackoverflow.com/questions/62424582/pytest-fixture-finalization-in-the-presence-of-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!