7

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

Community
  • 1
  • 1
Nacht
  • 10,488
  • 8
  • 31
  • 39

2 Answers2

19

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')
Ben Bongalon
  • 191
  • 1
  • 3
  • 1
    For the future visitors, Just skip the accepted answer and use this. This works and takes lesser steps than the accepted answer. – pr4bh4sh May 09 '16 at 10:31
  • 1
    From the future : pytest.config has been removed in version 5.0. https://docs.pytest.org/en/stable/deprecations.html#pytest-config-global – User Mar 12 '21 at 08:47
1

setup_module/class/method and friends cannot work with pytest fixtures directly. The pytest-2.3 way of doing the equivalent is to use autouse fixtures. If you can it's better to pass fixtures explicitely to test functions or to put a usefixtures marker on a class or module.

hpk42
  • 21,501
  • 4
  • 47
  • 53
  • [Here](http://pytest.org/latest/fixture.html#working-with-a-module-shared-fixture) it says "The name of the fixture again is smtp and you can access its result by listing the name smtp as an input parameter in any test or setup function". So I can use it on Setups and such, no? And `autouse` and `uses` makes all tests run that code, I just want the set up to do that. – Nacht Nov 08 '12 at 15:22
  • I'll give you the answer. Even though you didn't answer my specific answer, you gave me an idea as a work-around. This is strange, the docs say that you can do it, but it doesn't seem to be the case. Anyways, thanks. – Nacht Nov 08 '12 at 16:47
  • 1
    you are right, the docs are misleading. Or actually were, i just uploaded a fix which substitutes "setup function" with "fixture function". sorry! – hpk42 Nov 08 '12 at 18:06