When should I use pytest --import-mode importlib
05:06 23 Aug 2020

This is my project structure:

git_dir/
    root/
        __init__.py
        tests/
            __init__.piy
            test1.py
        foo_to_test/
            foo.py

I'm using pytest to test foo.py, and test1.py is as follows:

from foo_to_test.foo import func_to_test

def test1():
    assert something about func_to_test

From the terminal, i want to run

pytest tests

Now for the problem. When using --import-mode append or --import-mode prepend it adds 'git_dir' to PYTHONPATH. The problem is that 'git_dir' is not the project root.

  • I can add sys.path.append('git_dir/root') but the name 'git_dir' is different for other programmers working on other computers.

  • I've seen in the pytest documentation that using --import-mode importlib might solve my problem, but it doesn't seem to have any effect on my PYTHONPATH and i can't understand what it is doing.

So my questions are:

  • What --import-mode importlib is doing?
  • How can i automatically add my root to the path when testing so it will be the same for every programmer pulling this project?
python-3.x pytest python-import