2

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'.

user1179317
  • 2,693
  • 3
  • 34
  • 62

2 Answers2

4

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")
Tomasz Swider
  • 2,314
  • 18
  • 22
0

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)
  • Yea I guess first example could work, but if I have to base on multiple parameter, get messy. With second example, how come if i run that i get USE_FAKE_MODULE not recognized as a command. I am running in windows, does that only work on linux environment? I know you are just setting an environment variable – user1179317 Aug 07 '20 at 15:17
  • Yeah, the syntax for setting the env var would be different on windows (though the python code should be the same, I think). You could see https://superuser.com/questions/223104/setting-and-using-variable-within-same-command-line-in-windows-cmd-exe or https://stackoverflow.com/questions/1420719/powershell-setting-an-environment-variable-for-a-single-command-only – brokensandals Aug 07 '20 at 15:23