Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 629
Daniel Avatar asked Jul 30 '19 14:07

Daniel


2 Answers

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",
// ...
like image 197
Kornel K Avatar answered Oct 01 '22 21:10

Kornel K


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.

like image 33
Francisco Mendoza Avatar answered Oct 01 '22 19:10

Francisco Mendoza