Encountered a ModuleNotFoundError: No module named 'pytest' after installing the pytest module in a virtual environment. How to fix it?

I encountered a ModuleNotFoundError: No module named ‘pytest’ after installing the pytest module in a virtual environment.

Although I installed pytest outside the virtual environment and can use it normally with Python, I am getting this error when running the following code inside the virtual environment:

import pytest

def test_main():
    assert 5 != 5

if __name__ == "__main__":
    pytest.main()

The error message is:

[Running] python -u "d:\MyPytest\test_sample.py" Traceback (most recent call last): File "d:\MyPytest\test_sample.py", line 1, in <module> import pytest ModuleNotFoundError: No module named 'pytest' [Done] exited with code=1 in 0.185 seconds

How can I resolve this issue?

Verify that pytest is installed in the active virtual environment.

If not, install it using:

pip install pytest

Ensure that your IDE or editor is configured to use the Python interpreter from the virtual environment. In many editors like VS Code, you can select the interpreter from the command palette or settings. Verify that it points to the Python executable inside the virtual environment, not the global Python installation.