Skip to content Skip to sidebar Skip to footer

Filenotfounderror When Using Python -m Pytest Vs. Pytest

I recently changed the IDE I am using to VSCode. For the most part I like it, but there is one particular problem that I can't seem to resolve. I didn't realize it was a problem ei

Solution 1:

Probably not enough information to answer this for you straight out, but lets try some things:

  • In your test code, above the line where you are getting the error insert some lines like these and see if they print out what you're expecting
print(os.getcwd())
print(EXPECTED_RESULTS_BASE.absolute())
  • Since you're using a venv and the error is a result of calling pytest with a different command, try using which to see if you're actually calling different things. Both before and after activating your venv:
which pytest
which python

python -m pytest will call the pytest module installed with the version of python you've just called. If python calls a different version than you're getting from pytest inside your venv, then that could be the problem.

You should be able to check which python version pytest is calling by looking at the hashbang at the top of the file

head -1 $(which pytest)

On my system, macOS with anaconda Python installed, I get the following from those commands

$ which pytest
/Users/Shannon/anaconda/bin/pytest

$ which python
/Users/Shannon/anaconda/bin/python

$ head -1 $(which pytest)#!/Users/Shannon/anaconda/bin/python

This tells me that pytest is calling the same version of python I get when I call python. As such, pytest and python -m pytest should result in the same thing for me, inside my default environment.

Are you sure VSCode is loading your venv correctly before running the test?

Solution 2:

Assuming you have a virtual environment selected for your Python interpreter in VS Code:

  1. Open the terminal in VS Code
  2. Let the virtual environment activate
  3. Run python -m pip install pytest

That will install pytest into the virtual environment which is why python -m fails (pytest globally on your PATH is installed in some global Python install which a virtual environment won't have access to).

Post a Comment for "Filenotfounderror When Using Python -m Pytest Vs. Pytest"