pytest-env
Install
Per https://stackoverflow.com/a/39162893/13697228:
conda install -c conda-forge pytest-env
Or:
pip install pytest-env
pytest.ini
Create pytest.ini file in project directory:
[pytest]
env =
ENV_VAR=RandomStuff
Python
In your code, load environment variables as you normally would:
import os
env_var = os.environ["ENV_VAR"]
pytest / VS Code
Either run:
pytest
(Notice how it says configfile: pytest.ini)
C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split> pytest ==================================== test session starts ===================================== platform win32 -- Python 3.9.12, pytest-7.1.1, pluggy-1.0.0 rootdir: C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split, configfile: pytest.ini plugins: anyio-3.6.1, cov-3.0.0, env-0.6.2 collecting ...
Or:

This only seems to work with breakpoints that have manually been set, I'm guessing some other change is needed to pause on errors.
Python for VS Code Extension
Apparently the Python for VS Code extension recognizes a .env file automatically. E.g.
.env file:
ENV_VAR=RandomStuff
Haven't verified, but I'd assume this has the same behavior as using pytest-env with a pytest.ini file.
When all else fails
When I don't feel like dealing with the strange hackery necessary to get VS Code, Anaconda environments, and pytest playing nicely together (and/or forget how I fixed it before), I call my tests manually and run it like a normal script (see below). This may not work with more advanced pytest trickery using fixtures for example. At the end of your Python script, you can add something like:
if __name__ == "__main__":
my_first_test()
my_second_test()
and run it in debug mode (F5) as normal.
vscode debugger - How to configure VS code for pytest with environment variable - Stack Overflow
Issues setting up python testing in VSCODE using pytest - Stack Overflow
On Visual Studio Code, how do I specify my pytest.ini file for test discovery - Stack Overflow
Visual Studio Code triggers use of pytest when configured for unittest - Stack Overflow
Videos
pytest-env
Install
Per https://stackoverflow.com/a/39162893/13697228:
conda install -c conda-forge pytest-env
Or:
pip install pytest-env
pytest.ini
Create pytest.ini file in project directory:
[pytest]
env =
ENV_VAR=RandomStuff
Python
In your code, load environment variables as you normally would:
import os
env_var = os.environ["ENV_VAR"]
pytest / VS Code
Either run:
pytest
(Notice how it says configfile: pytest.ini)
C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split> pytest ==================================== test session starts ===================================== platform win32 -- Python 3.9.12, pytest-7.1.1, pluggy-1.0.0 rootdir: C:\Users\sterg\Documents\GitHub\sparks-baird\mp-time-split, configfile: pytest.ini plugins: anyio-3.6.1, cov-3.0.0, env-0.6.2 collecting ...
Or:

This only seems to work with breakpoints that have manually been set, I'm guessing some other change is needed to pause on errors.
Python for VS Code Extension
Apparently the Python for VS Code extension recognizes a .env file automatically. E.g.
.env file:
ENV_VAR=RandomStuff
Haven't verified, but I'd assume this has the same behavior as using pytest-env with a pytest.ini file.
When all else fails
When I don't feel like dealing with the strange hackery necessary to get VS Code, Anaconda environments, and pytest playing nicely together (and/or forget how I fixed it before), I call my tests manually and run it like a normal script (see below). This may not work with more advanced pytest trickery using fixtures for example. At the end of your Python script, you can add something like:
if __name__ == "__main__":
my_first_test()
my_second_test()
and run it in debug mode (F5) as normal.
Could not really figure out how to fix "unit" test debugging with Vscode. But with Pytest one can call tests from the command line like this:
python -m pytest <test file>
That means the VSCode launch.json debug configuration file can be setup using the "module" property for Python:
"configurations": [
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "pytest",
"args": ["--headful","--capture=no", "--html=report.html"],
}
This is good enough to do debugging of python tests. Also you can then insert environment variables
"env": {
"ENV_VAR":"RandomStuff"
}
To set up VS Code to use a specific pytest.ini file, you need to do the following:
- Open a directory in VS Code (
ctrl+k > ctrl+o) - Select a Python interpreter (
ctrl+shift+p > Python: Select Interpreter > Python interpreter) - Configure the testing framework you want to use, in this case PyTest (
ctrl+shift+p > Python: Configure Tests > Pytest > {pytest rootdir} - Open the
settings.jsonfile generated inside the.vscode/directory that was created in your working directory (the one you chose in step 1) - Add the following setting to the file (it may already exist if you specified a
rootdirwhen configuring pytest):
"python.testing.pytestArgs": [
"-c",
"/path/to/your/pytest.ini"
],
That's it! VS Code should be using the pytest.ini file you specify in the last argument. You can specify any CLI options you want there.
Source
Pytest requires the test function names to start with test or ends with test.
The ini file instructs py.test to treat all *_test.py files as unit tests.
This may end up being a short term issue. Two workarounds fix it for me, as per comments in GitHub issue VS Code python unittest fails to import modules outside tests folder.
A. Revert the version of Python extension in VSCode from v2023.12.0 to v2023.8.0.
B. Insert setting "python.experiments.optOutFrom": ["pythonTestAdapter"] into the User Settings (not the Workspace Settings). Be mindful of trailing commas.
I can now debug python unittest tests.
Update
The bug that led to this issue was fixed in Python extension v2023.19.
I experienced the same issue with Python extension v2024.2.1. Editing settings.json fixed the problem:
- remove:
"python.testing.pytestEnabled": false, - keep:
"python.testing.unittestEnabled": true
The fixed settings.json:
{
"python.testing.unittestArgs": [
"-v",
"-s",
"./tests",
"-p",
"test_*.py"
],
"python.testing.unittestEnabled": true
}
I am working on a data science project and my project tree looks like this:
data/ notebooks/ scripts/ utils/ - __init__.py - utils1.py - utils2.py - utils3.py - utils4.py - tests/ -- test_utils1.py -- test_utils2.py -- test_utils3.py -- test_utils4.py
I import functions I wrote in utils1.py, utils2.py, etc. to reuse throughout my notebooks and scripts. To run the tests for these, I cd into utils/ and then run python -m pytest from the terminal, which works fine.
I saw that there is a beaker icon for testing in VSCode, but my tests are not being discovered:
screenshotContents of __init__.py look a little like this:
from utils.utils4 import foo, barfrom .utils1 import foo2, bar2from .utils2 import function1, function2from .utils3 import *
See the comment below for Output.
It breaks my flow to switch to the terminal each time I modify a utility function to verify tests are passing. How should I configure VSCode to make better use of the Test Explorer?
Update: see my comment for the solution
Hello, I am hoping someone here has an idea on how to do this.
I have a pytest.ini that looks like this
[pytest]
addopts = -n auto --dist worksteal --cov-report xml:coverage.xml
This works great when running the tests so they run quickly and I get test coverage. However, when I try to debug a single by right clicking on the green arrow for the test and selecting debug it won't hit any breakpoints in the test. If I remove the pytest.ini config then it will hit the breakpoints.
Does anyone know of a way to have a separate config when running a single test.
Thanks
UPDATE: I figured out a way to make this work. It turns out using type debugpy will not work and doesn't even read the environment variable. However, if I set the type to python it works just fine. It looks like this is a feature that debugpy needs to support.
{
"name": "Python: Debug Tests",
"type": "python",
"request": "launch",
"program": "${file}",
"purpose": ["debug-test"],
"console": "integratedTerminal",
"justMyCode": false,
"env": {
"PYTEST_ADDOPTS": "-c pytest_alt.ini",
}
}