2
votes

My issue is, how can I execute a setup method, that is based on a pytest argument when I run pytest? Basically I want this 'setup method' to run first before running any tests.

For simplicity lets say I have a file 'text_something.py'

import somemodule

def test_some(usefakemodule):
   ...

the 'somemodule' is either installed in the environment or not. If its installed already, then it will work no problem. If not, I need to add the path of the fake module by running a method that basically does sys.path.append(XXX).

In short, I want to run 'pytest -v --usefakemodule' if I want to use the fake module dir, or just 'pytest -v' to just use that library installed locally (assuming its installed there).

I tried adding a fixture (scope=session) in conftest.py, but it doesnt seem to run/execute it first before it executes 'test_something.py', which will then state no module named 'somemodule'

I can run a regular method in conftest, but I dont know how it can depend on the pytest command line argument 'usefakemodule'.

2

2 Answers

3
votes

In your conftest.py you use pytest_addoption combined with pytest_cmdline_main, pleas refer to the documentation for details.

import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--usefakemodule", action="store_true", default=False, help="Use fake module "
    )

def pytest_cmdline_main(config):
    usefakemodule = config.getoption("--usefakemodule")
    print(usefakemodule)
    if usefakemodule:
        print("OK fake module ")
    else:
        print("no fakes")
0
votes

I don't know whether/how you can have pytest accept extra arguments, but here are a couple other ideas for accomplishing this:

  1. Just try to import the real module, and update the load path if you get an ImportError:
try:
  import somemodule
except ImportError:
  sys.path.append(XXX)
  import somemodule
  1. Or, use an environment var, and run with USE_FAKE_MODULE=true pytest -v:
import os
if os.environ.get('USE_FAKE_MODULE'):
  sys.path.append(XXX)