py.test : How do I access a test_function's parameter from within an @pytest.fixture
<p>My objective is to gain access to a test_function's "args" from within a pytest.fixture that lives in conftest.py, in order to pytest.skip() if a certain condition is met.</p>

<p>Here is the conftest.py code:</p>

<pre class="lang-py prettyprint-override"><code># conftest.py
import pytest

def pytest_generate_tests(metafunc):
    if 'param1' in metafunc.fixturenames:
        metafunc.parametrize("param1", [0, 1, 'a', 3, 4])

@pytest.fixture(autouse=True, scope="function")
def skip_if(request):
    # I want to do something like this
    # (but obviously request.node.param1 is not a real attribute):
    if request.node.param1 == 'a':
        xfail()
</code></pre>

<p>And the test.py code:</p>

<pre class="lang-py prettyprint-override"><code># test.py

def test_isdig(param1):
    assert isinstance(param1, int)
</code></pre>

<p>Does anyone happen to know if the request object can smoehow have access to the the current param1 value, so that my autouse skip_if() fixture can skip it on a certain conditions? I know that I can put the pytest.skip() call inside test_isdig() but I am trying to do it from within the fixture somehow. Any advice/guidance is very much appreciated!</p>

<p>Adding the parameter to the fixture as well as the test function seems to work.</p>

<p>Test code:</p>

<pre><code>import pytest

def pytest_generate_tests(metafunc):
    if 'param1' in metafunc.fixturenames:
        metafunc.parametrize("param1", [0, 1, 'a', 3, 4])

@pytest.fixture(autouse=True, scope="function")
def skip_if(param1):
    if param1 == 'a':
        pytest.xfail()

def test_isint(param1):
    assert isinstance(param1, int)
</code></pre>

<p>Results:</p>

<pre><code>============================= test session starts =============================
platform win32 -- Python 3.5.2, pytest-3.0.0, py-1.4.31, pluggy-0.3.1
rootdir: D:\Development\Hacks\StackOverflow\39482428 - Accessing test function p
arameters from pytest fixture, inifile:
collected 5 items

test_print_request_contents.py ..x..

===================== 4 passed, 1 xfailed in 0.10 seconds =====================
</code></pre>

<p>Note however that this <code>skip_if</code> fixture would be run for all tests, regardless of whether they had the <code>param1</code> parameter, so that could be problematic. It may be better, in that instance, to explicitly include the fixture in the relevant tests, or to even wrap the parameter in the fixture, so that only the fixture has <code>param1</code> as a parameter, which it then returns, and the test instead has the fixture as its parameter.</p>

python automated-tests py.test