4

I need to setup tests depending on where or how I want to run py.test tests. I want to be able to do something like this

py.test --do_this

py.test --do_that

and retrieve the values in the setup method of a test class

class TestSuite(object):
    def setup(self):
        if (do_this): 
            ...

Something like that. Can this be done? And if so, how?

Alex
  • 41,580
  • 88
  • 260
  • 469
  • Not quite. That uses an ini file. But I want to use some command line arguments, so I can easily run the tests differently ... – Alex Jan 30 '18 at 09:10
  • 1
    Look into it https://stackoverflow.com/questions/40880259/how-to-pass-arguments-in-pytest-by-command-line and pytest doc https://docs.pytest.org/en/latest/example/simple.html – Anup Jan 30 '18 at 09:12
  • @Anup: Yes, with that I can 'access' extra parameters in the test methods. But I need them in the `setup` methods already... – Alex Jan 30 '18 at 09:15
  • Possible duplicate of [How to pass arguments in pytest by command line](https://stackoverflow.com/questions/40880259/how-to-pass-arguments-in-pytest-by-command-line) – phd Jan 30 '18 at 16:46

1 Answers1

2

From the documentation, you can add arguments to the pytest caller

# content of test_sample.py
def test_answer(do):
    if do == "this":
        print ("do this option")
    elif do == "that":
        print ("do that option")
    assert 0 # to see what was printed

# content of conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption("--do", action="store", default="that",
        help="my option: this or that")

@pytest.fixture
def do(request):
    return request.config.getoption("--do")

Then, you can call pytest as pytest -q test_sample.py to get the default case with that and pytest -q --do=this for the other case

Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
  • Can I call the fixture in the `setup` method? Like `setup(do)` or `setup_class(do)`? – Alex Jan 30 '18 at 09:16
  • You should be able to use that fixture in the setup, but with pytest you should do setup via fixtures. – Ignacio Vergara Kausel Jan 30 '18 at 09:18
  • I cannot do `setup_class(do)`: `TypeError: setup_class() takes exactly 2 arguments (1 given)` – Alex Jan 30 '18 at 09:29
  • That's because you forgot to give and extra argument to the method. – Ignacio Vergara Kausel Jan 30 '18 at 09:38
  • I define the method like that: `def setup_class(cls, do):` – Alex Jan 30 '18 at 09:40
  • (For a single test method it works just fine, but not for the `setup_class` method) – Alex Jan 30 '18 at 09:40
  • 1
    One of the reasons I would like to do this: Depending on where I run the tests (local/jenkins), I need to specify different folders and paths. I have those path/folders definitions in different config files, and so I would be able to just say something like `py.test --config=jenkins.conf` or something like `py.test --config=local.conf`. – Alex Jan 30 '18 at 09:47