Daniel
Daniel

Reputation: 389

Imports break VSCode testing with pytest

I have a project where I want to VS Code's discover tests and other testing features to make testing easier. I have a problem that imports in test files break when I try to discover tests.

I have a file structure like so:

project\
  __init__.py
  package1\
    module1.py
    __init__.py
  tests\
    test.py
    __init__.py

In test.py I have a line:

import project.package1.module1 as module1

I run my project by calling python -m project in the root folder, and I am able to run tests successfully by calling python -m pytest project from the root folder.

When I run VS Code's "discover tests" feature or try to step through a file with the debugger, I receive an error 'ModuleNotFoundError: No module named project'.

Does anyone know how to solve this problem?

Upvotes: 15

Views: 8564

Answers (3)

Francisco Mendoza
Francisco Mendoza

Reputation: 59

Next solution works for Linux and Windows,

import sys
from pathlib import Path
sys.path.insert(0, str(Path('package1/').resolve()))

It's based on @Chufolon answer. My StackOverflow reputation doesn't allow me to just comment on his answer. I prefer his solution because in the .env there could be sensitive information (passwords, ...) that shouldn't be shared (omit it in .gitignore file) for security reasons; and also because __init__.py is shared by default through Git.

Upvotes: 1

Kornel K
Kornel K

Reputation: 111

I had the same issue. The solution that worked for me was to introduce a .envfile that holds my PYTHONPATH entries, relative to my workspace folder.

PYTHONPATH="path1:path2:pathN"

Then I added a line to my workspace settings that specifies the location of my .env file.

// ...
"python.envFile": "${workspaceFolder}/.env",
// ...

Upvotes: 11

Chufolon
Chufolon

Reputation: 67

I had the same issue where I was able to run pytest and python -m pytest successfully in the terminal within VSCode but the discovery was failing. My solution was to implement the failing import in the following way

import sys
sys.path.insert(0, '/full/path/to/package1/')
from package1.module1 import module1

Note that VSCode was opened with the project folder being the root.

Upvotes: 4

Related Questions