Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting environment variable when running Python unit tests inside VSCode

I'd like to execute code inside my unit tests conditioned on whether they're running from within VSCode or the command line. Is there a way to do so?

The reasoning is to add additional visual feedback through cv2.imwrite statements, but to omit these when running a full regression from the command line or when running my CI.

I known that I can set a debugging profile inside launch.json and define environment variables there, but this applies only when debugging a unit test:

       {
            "name": "Debug Tests",
            "type": "python",
            "request": "test",
            "console": "integratedTerminal",
            "python": "${command:python.interpreterPath}",
            "justMyCode": false,
            "env": {
                "MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS": "1"
            }
        },

Is there a way to achieve something similar when not running through the debugger?

like image 763
Shahar Avatar asked Apr 13 '26 19:04

Shahar


2 Answers

Try defining environment variables by using .env files

enter image description here

.env:

MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS = 1

test1.py:

import os
from pathlib import Path
from dotenv import find_dotenv, load_dotenv

env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path, verbose=True)
print(os.getenv("MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS"))
like image 50
MingJie-MSFT Avatar answered Apr 15 '26 10:04

MingJie-MSFT


Add the following to your launch.json settings:

"purpose": [
    "debug-test"
 ]

The rest can remain the same, here is the full snippet:

       {
        "name": "Debug Tests",
        "type": "python",
        "request": "test",
        "console": "integratedTerminal",
        "python": "${command:python.interpreterPath}",
        "justMyCode": false,
        "purpose": [
            "debug-test"
        ],
        "env": {
            "MY_ENVIRONMENT_SWITCH_FOR_WRITING_JPEGS": "1"
        }
    },
like image 26
ranni rabadi Avatar answered Apr 15 '26 09:04

ranni rabadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!