Search code examples
python-3.xpytestconftest

How to pass arguments from 'conftest,py' to test file (pytest)?


How to pass arguments from conftest.py to test file ?

conftest.py

import sys,pytest


def tear_down():
    print("teardown")

def pytest_addoption(parser):
    parser.addoption("--a1", action="store", default="some_default_value", help="provide a1")
    parser.addoption("--b1", action="store", default=None, help="provide b1")
    parser.addoption("--c1", action="store", default=None, help="provide c1")


@pytest.fixture(autouse=True)
def set_up(request):
    print("set up")

    a1 = request.config.getoption("--a1")
    b1 = request.config.getoption("--b1")
    c1 = request.config.getoption("--c1")

    if not(b1) and not(c1):
        sys.exit("Both values can't be empty")

    if b1 and c1:
        sys.exit("provide either b1 or c1, not both")

In test.py, I need to access all those arguments a,b & c. How can I do that ?

test.py

import pytest

class Test1:
    def fun1(self,a,b="",c=""):
        print("task1")

    def fun2(self,a,b="",c=""):
        print("task2")

class Test2:
    def fun12(self,a,b="",c=""):
        print("task12")

    def fun34(self, a, b="", c=""):
        print("task34")

I'm new to pytest. Can you please help me ?


Solution

  • This has been answered many times already. And you can find it easily in the official documentation here. Learn how to search for solutions and read documentations, it's an invaluable skill.

    To answer your question, you'd do it like this:

    conftest.py

    import pytest
    
    @pytest.fixture(autouse=True)
    def set_up(request):    
        return {"a": 1, "b": 2, "c": 3}
    

    test.py

    import pytest
    
    class Test1:
        def test_fun1(self, set_up):
            print("{0} - {1} - {2}".format(set_up["a"], set_up["b"], set_up["c"]))    
    

    I left out the rest of our example in order to focus on what you missed. I also renamed the test function, because pytest will by default discover only functions that start with test as actuall test cases: https://docs.pytest.org/en/latest/reference.html#confval-python_functions So unless you change the behaviour in e.g. pytest.ini, this function would not be run as a test case.