James Lin
James Lin

Reputation: 26528

pytest fixture of fixture, not found

Based on this stackoverflow: pytest fixture of fixtures

I have the following code in the same file:

@pytest.fixture
def form_data():
    return { ... }

@pytest.fixture
def example_event(form_data):
    return {... 'data': form_data, ... }

But when I run pytest, it complains that fixture 'form_data' not found

I am new to pytest so I am not even sure if this is possible?

Upvotes: 48

Views: 80172

Answers (1)

m. bron
m. bron

Reputation: 666

Yes, it is possible.

If you have the test and all the fixtures in 1 file: test.py

import pytest

@pytest.fixture
def foo():
    return "foo"

@pytest.fixture
def bar(foo):
    return foo, "bar"

def test_foo_bar(bar):
    expected = ("foo", "bar")
    assert bar == expected

and run pytest test.py then Success!!!

======================================= test session starts ========================================
platform darwin -- Python 3.6.8, pytest-4.3.0
collected 1 item                                                                                   

test.py .                                                                                    [100%]

===================================== 1 passed in 0.02 seconds =====================================

But if you put the fixtures in a different file: test_foo_bar.py

from test import bar

def test_foo_bar(bar):
    expected = ("foo", "bar")
    assert bar == expected

and run pytest test_foo_bar.py expecting (like I did) that importing only the bar fixture is enough since on importing it would already have executed the foo fixture then you get the error you are getting.

======================================= test session starts ========================================
platform darwin -- Python 3.6.8, pytest-4.3.0
collected 1 item                                                                                   

test2.py E                                                                                   [100%]

============================================== ERRORS ==============================================
__________________________________ ERROR at setup of test_foo_bar __________________________________
file .../test_foo_bar.py, line 3
  def test_foo_bar(bar):
.../test.py, line 7
  @pytest.fixture
  def bar(foo):
E       fixture 'foo' not found
>       available fixtures: TIMEOUT, bar, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, cov, doctest_namespace, monkeypatch, no_cover, once_without_docker, pytestconfig, record_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

.../test.py:7
===================================== 1 error in 0.03 seconds ======================================

To fix this also import the foo fixture in the test_foo_bar.py module.

Upvotes: 58

Related Questions