[TIP] fixture ordering and dynamically adding fixtures to Testcases

Bruno Oliveira nicoddemus at gmail.com
Mon Jan 15 06:19:29 PST 2018


Hi Arun,

On Sat, Jan 13, 2018 at 3:11 PM arun kali raja arunsep886 at gmail.com
<http://mailto:arunsep886@gmail.com> wrote:

1. I have a .py file where i have defined two Autouse fixtures..
> fixtureMod_1 is module scoped and fixtureFunc_1 is function scoped.. Now in
> conftest.py i have imported these two fixtures.. in my test_x.py i have a
> another module scoped fixture say fixtureMod_2..The order of execution of
> fixture seems to be fixtureMod_1,fixtureFunc_1 and then fixtureMod_2.. isnt
> module level fixtures supposed to be executed before function level
> fixtures?? isnt that how scopes are ordered.. i am able to solve the issues
> by giving fixtureMod_2  as a dependency to fixtureFunc_1.. but still i am
> trying to understand why pytest respects the scope ordering in this case..
> does the order of sourcing the fixture override the scope based ordering??
>
Your reasoning makes sense, but pytest works differently: fixtures are
created on-demand, the scope only guarantees when a fixture will be
deleted. For example:

def test_foo(function_fixture, module_fixture):
    ...

When test_foo executes, pytest will create function_fixture and then create
module_fixture because that’s the order they appear in test_foo‘s
signature.

module_fixture will be destroyed when the last test in the module executes,
but without any guarantees that all function fixtures will have been
destroyed by then, it depends on their internal dependencies and when each
fixture was created.


> 2. I have one usecase where i want to dynamically create a fixture chain..
> say i mark by testcase with useCaseA and that translates to an ordering of
> fixture.. can i add a fixture to a testcase at run time.. at
> pytest_generate_test phase or pytest_configure phase?? i found a method
> called add_marker to add a marker at runt time.. since fixtures can also be
> added via markers i was trying to explore if can use that method but it
> doesnt accept any parameters.. any way i can achieve this??
>
I think you can inject fixture functions during collection. One way to do
that is to override one of the collection hooks, or depending on your use
case even a class decorator might be doable.

Cheers,
Bruno.
​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20180115/af58097f/attachment.html>


More information about the testing-in-python mailing list