Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use py.test fixtures without importing them

Tags:

python

pytest

Say I have a file fixtures.py that defines a simple py.test fixture called foobar.

Normally I would have to import that fixture to use it (including all of the sub-fixtures), like this:

from fixtures import foobar

def test_bazinga(foobar):

Note that I also don't want to use a star import.

How do I import this fixture so that I can just write:

import fixtures

def test_bazinga(foobar):

Is this even possible? It seems like it, because py.test itself defines exactly such fixtures (e.g. monkeypatch).

like image 899
Dave Halter Avatar asked Apr 06 '16 13:04

Dave Halter


People also ask

How do you use pytest fixtures?

To access the fixture function, the tests have to mention the fixture name as input parameter. Pytest while the test is getting executed, will see the fixture name as input parameter. It then executes the fixture function and the returned value is stored to the input parameter, which can be used by the test.

Are pytest fixtures cached?

Pytest only caches one instance of a fixture at a time, which means that when using a parametrized fixture, pytest may invoke a fixture more than once in the given scope.

Can a pytest fixture be a test?

Those are the things that need to test a certain action. In pytest the fixtures are functions that we define to serve these purpose, we can pass these fixtures to our test functions (test cases) so that they can run and set up the desired state for you to perform the test.

Can you import pytest fixtures?

Fixtures and their visibility are a bit odd in pytest. They don't require importing, but if you defined them in a test_*. py file, they'll only be available in that file. You can however put them in a (project- or subfolder-wide) conftest.py to use them in multiple files.


Video Answer


1 Answers

Fixtures and their visibility are a bit odd in pytest. They don't require importing, but if you defined them in a test_*.py file, they'll only be available in that file.

You can however put them in a (project- or subfolder-wide) conftest.py to use them in multiple files.

pytest-internal fixtures are simply defined in a core plugin, and thus available everywhere. In fact, a conftest.py is basically nothing else than a per-directory plugin.

You can also run py.test --fixtures to see where fixtures are coming from.

like image 99
The Compiler Avatar answered Sep 21 '22 06:09

The Compiler