Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get pytest to understand command-line arguments on setups

So I have been trying to get pytest to run selenium tests on different environments based on some command-line argument. But it keeps throwing this error:

TypeError: setup_class() takes exactly 2 arguments (1 given)

It seems that it is understanding that setup_class takes 2 arguments, but host is not being passed. Here's the code for setup_class:

def setup_class(cls, host):
        cls.host = host

And here is the conftest.py file:

def pytest_addoption(parser):
    parser.addoption("--host", action="store", default='local',
        help="specify the host to run tests with. local|stage")

@pytest.fixture(scope='class')
def host(request):
    return request.config.option.host

What is strange is that host is being seen by the functions (so if I make a test_function and pass host as a parameter, it gets it just fine), it is just the setup fixtures that are not working.

I looked around and found this, pytest - use funcargs inside setup_module but that doesn't seem to be working (and it is outdated since 2.3.

Does anyone know what I'm doing wrong? Using py.test 2.3.2.

Thanks

like image 358
Nacht Avatar asked Nov 07 '12 18:11

Nacht


People also ask

Can pytest fixtures have arguments?

You can pass arguments to fixtures with the params keyword argument in the fixture decorator, and you can also pass arguments to tests with the @pytest.

How do you pass a command line argument?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative.

How does pytest know what to run?

Pytest automatically identifies those files as test files. We can make pytest run other filenames by explicitly mentioning them. Pytest requires the test function names to start with test. Function names which are not of format test* are not considered as test functions by pytest.


1 Answers

To access the command line options from inside the setup functions, you can use the pytest.config object. Here is an example... adapt as needed.

import pytest

def setup_module(mod):
    print "Host is %s" % pytest.config.getoption('host')
like image 96
Ben Bongalon Avatar answered Sep 20 '22 10:09

Ben Bongalon