skip to Main Content

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?

2

Answers


  1. 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"))
    
    Login or Signup to reply.
  2. 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"
            }
        },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search