kroe761
kroe761

Reputation: 3534

adding parameters to pytest setup function

I am trying to learn pytest, and i'm running into a snag. I need to define a variable in the setup_method that is defined via a command line parameter. I am able to do this in individual tests with no problem, but trying to do the same thing in the setup method fails. I get this message -

TypeError: setup_method() takes exactly 3 arguments (2 given)

Am I doing something wrong? Any help would be appreciated.

Here is my conftest.py

# Conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption("--var_one", action="store", default=False)
    parser.addoption("--var_two", action="store", default=False)

@pytest.fixture
def var_one(request):
    var_one_param = request.config.getoption("--var_one")
    return var_one

@pytest.fixture
def var_two(request):
    var_two_param = request.config.getoption("--var_two")
    return var_two_param

Actualy running the test I do this -

py.test --var_one=True --var_two==True tests.py 

And here is the file, where i would hope the variables are defined and called when the file is executed -

import pytest

class Tests:

    def setup_method(self, method, var_one):
        if var_one == True:
            # do stuff
        else:
            # do other stuff

    def test_one(self, var_two):
        assert var_two == True

    def teardown_method(self):
        #Not needed here
        pass

Upvotes: 1

Views: 3400

Answers (1)

flub
flub

Reputation: 6357

The .setup_method() and .teardown_method() functions are the nose-compatibility options and they do not accept fixtures as parameters. Better would be to use an autouse fixture on the class:

class Tests:

    @pytest.fixture(autouse=True)
    def do_stuff_based_on_var_one(self, var_one):
        if var_one:
            # do stuff
        else:
            # do other stuff

    def test_one(self, var_two):
        assert var_two is True

As a sidenote, notice that comparing booleans with == is considered bad practice, in conditions simply use it's implied truth value. If you really need to compare it acknowledge it's singleton nature and use object identity with is.

Upvotes: 4

Related Questions