Home > Software design >  How to run seperate folder of pytests in VScode
How to run seperate folder of pytests in VScode

Time:11-17

I'm trying to run a pytests for my code in VSCode from a separate folder, but I keep getting the following error:

ModuleNotFoundError: No module named 'src'

My basic file structure is:

Root
|
|- src
| |- file1.py
|
|- tests
| |- test_file.py

My code in test_file.py is:

from src import file1

I saw How to run tests without installing package? and all of the millions of other import questions but I still can't figure it out. I've also tried

from ..src import file1

but then I get an ImportError: attempted relative import beyond top-level package

How do I use imports in this way to run tests on my code?

CodePudding user response:

You can modify the PYTHONPATH to avoid this problem. You can refer to the official docs.

An example of when to use PYTHONPATH would be if you have source code in a src folder and tests in a tests folder. When running tests, however, those tests can't normally access modules in src unless you hard-code relative paths.

To solve this problem, you could add the path to src to PYTHONPATH by creating an .env file within your VS Code workspace.

PYTHONPATH=src Then set python.envFile in your settings.json file to point to the .env file you just created. For example, if the .env file was in your workspace root, your settings.json would be set as shown:

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

And the Test is not routed through the terminal, so setting the terminal.integrated.env.* will not work.

  • Related