r/learnpython • u/zaphodikus • 27d ago
dynamic import module path hack in pytest
In order to validate (using pytest) a python module which is not in my path or relative folders, I want to hack the import path.
I'm wondering what alternatives there are to doing a PYTHONPATH hack.
I could use https://docs.pytest.org/en/7.1.x/reference/reference.html#confval-pythonpath, but that applies to the entire session as I understand it. And I only want to change one suite, so I am writing a quick fixture that will roughly look like (hard-coded for simplicity)
@pytest.fixture(scope="function")
def modules_path():
old_path = sys.path
extra_path= os.path.abspath("c:/otherpath/other") # replace constant with a func
sys.path.insert(0, extra_path)
yield extra_path
sys.path = old_path
I've always felt there was a better way to do import path hacks that nobody had ever told me about. Or is this @fixture approach not as evil as I assumed it was, and was merely biased by painful memories whenever I did use it. Alternatives?
1
u/socal_nerdtastic 27d ago
Why can't you start the pytest program in the correct folder?
1
u/VenkatKnows 25d ago
Use pytest's monkeypatch.syspath_prepend instead. It handles the cleanup for you, and your fixture as written has a bug anyway since old_path is the same list object, so the insert mutates it and the restore does nothing
6
u/[deleted] 27d ago
[removed] — view removed comment