Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pytest fixtures be combined?

Tags:

python

pytest

Can one fixture build on another in pytest? I have a very simple fixture called "cleaner" defined as:

import pytest
from mypackage import db

@pytest.fixture()
def cleaner(request):
  def finalizer():
    db.clear()
  request.addfinalizer(finalizer)

then in my setup.cfg I have:

[pytest]
norecursedirs = .git venv
usefixtures = cleaner

This results in the database being truncated after each test, which is great. But now I want other fixtures I make to also call the finalizer from cleaner. Is there a way to define another fixture that somehow expands on or calls cleaner?

like image 994
Trey Stout Avatar asked Aug 07 '14 17:08

Trey Stout


People also ask

Can pytest fixtures have arguments?

You can pass arguments to fixtures with the params keyword argument in the fixture decorator, and you can also pass arguments to tests with the @pytest.

How do pytest fixtures work?

What Are Pytest Fixtures? Pytest fixtures are functions that can be used to manage our apps states and dependencies. Most importantly, they can provide data for testing and a wide range of value types when explicitly called by our testing software. You can use the mock data that fixtures create across multiple tests.

Is pytest fixture a decorator?

pytest. fixture decorator makes it possible to inject the return value in the test functions whose have in their signature the decorated function name. Easy, isn't it? You can potentially generate and create everything you need in these fixture-functions and then use it in all the tests you need.

Are pytest fixtures cached?

the fixture will be evaluated once per test session and the result will be cached and reused in all dependent tests.


1 Answers

You have to declare that your other fixture depends on cleaner explicitly:

import pytest

@pytest.fixture
def cleaner(request):
  def finalizer():
    print '\n"cleaner" finalized'
  print '\n"cleaner" fixture'
  request.addfinalizer(finalizer)


@pytest.fixture
def other(cleaner):
    print '\n"other" fixture'


def test_foo(other):
    pass

Running this with py.test -s -v produces:

test_foo.py@16::test_foo
"cleaner" fixture

"other" fixture
PASSED
"cleaner" finalized
like image 180
Bruno Oliveira Avatar answered Oct 11 '22 07:10

Bruno Oliveira