How to get pytest fixture data dynamically
<p>I'm trying to define init data for several tests scenarios that test a single api endpoint.  I want to do this so that I don't have to produce boiler plate code for multiple iterations of a test where just the data differs. I can't seem to wrap my head around how to do this using the built-in pytest fixtures.  Here's essentially what I'm trying to do:</p>

<p>In tests/conftext.py:</p>

<pre><code>import pytest

@pytest.fixture(scope="module")
def data_for_a():
    return "a_data"

@pytest.fixture(scope="module")
def data_for_b():
    return "b_data"
</code></pre>

<p>In tests/tests.py</p>

<pre><code>import pytest

# this works
def test_a(data_for_a):
    assert "a_data" == data_for_a

# but I want to do this and it fails:
scenarios = [
    { "name": "a", "data": data_for_a },
    { "name": "b", "data": data_for_b },
]

for scenario in scenarios:
    print(scenario.name, scenario.data)

# desired output:
# "a a_data"
# "b b_data"
</code></pre>

<p>I get a <code>NameError: name 'data_for_a' is not defined</code> exception.  I've tried various approaches to get this to work, but there seems to be no way around having to pass the fixture as a parameter to the test method - so either define a bunch of boilerplate tests or have a bunch of if/else statements in a single test and pass each fixture explicitly.  I don't like either of these options.  At the moment it seems like I have to just build my own helper module to pull in this test data, but I'd rather use the built-in mechanism for this.  Is there any way to do this?</p>

<p>You can import from your conftest.py like so:</p>

<pre><code>from conftest import data_for_a, data_for_b
</code></pre>

<p>or</p>

<pre><code>from conftest import *
</code></pre>

<p>which will allow you to reference that function without passing it as an parameter to a test function.</p>

<p><strong>Edit:</strong>
Note that this is generally not recommended practice according to <a href="http://pytest.org/2.2.4/plugins.html" rel="nofollow">the official pytest documentation</a></p>

<blockquote>
  <p>If you have conftest.py files which do not reside in a python package directory (i.e. one containing an <strong>__init__.py</strong>) then âimport conftestâ can be ambiguous because there might be other conftest.py files as well on your PYTHONPATH or sys.path. It is thus good practise for projects to either put conftest.py under a package scope or to never import anything from a conftest.py file.</p>
</blockquote>

python py.test python-3.5 fixtures