如何使用环境变量为pytest配置VS代码

How to configure VS code for pytest with environment variable

我正在尝试调试 pytest。我想注入一个环境变量。这是我设置 launch.json

的方式
{
    "type": "python",
    "request": "test",
    "name": "pytest",
    "console": "integratedTerminal",
    "env": {
        "ENV_VAR":"RandomStuff"
    }
},

但是我开始调试的时候好像。我没有看到注入的 env 变量,因此我的测试期望 env 变量失败。

我也注意到错误

Could not load unit test config from launch.json

无法真正弄清楚如何使用 Vscode 修复“单元”测试调试。但是使用 Pytest 可以调用像 python -m pytest <test file>(https://docs.pytest.org/en/stable/usage.html#cmdline) 这样的测试 这意味着 Vscode 可以像模块一样配置

"configurations": [
        {
            "name": "Python: Module",
            "type": "python",
            "request": "launch",
            "module": "pytest",
            "args": ["--headful","--capture=no", "--html=report.html"],
        }

这足以调试 python 测试。然后你也可以插入环境变量

   "env": {
        "ENV_VAR":"RandomStuff"
    }

pytest-env

安装

根据 :

conda install -c conda-forge pytest-env

或者:

pip install pytest-env

pytest.ini

在项目目录中创建pytest.ini文件:

[pytest]
env = 
    ENV_VAR=RandomStuff

Python

在您的代码中,像往常一样加载环境变量:

import os
env_var = os.environ["ENV_VAR"]

pytest / VS 代码

或者运行:

pytest

(注意它是怎么说的 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 ...

或者:

这似乎只适用于手动设置的断点,我猜需要进行一些其他更改才能在出现错误时暂停。

Python 用于 VS 代码扩展

显然 the Python for VS Code extension recognizes a .env file automatically。例如。 .env 文件:

ENV_VAR=RandomStuff

尚未验证,但我认为这与将 pytest-envpytest.ini 文件一起使用具有相同的行为。

当一切都失败时

当我不想处理让 VS Code、Anaconda 环境和 pytest 很好地协同工作所必需的奇怪的 hackery 时(and/or 忘记我之前是如何修复它的),我手动调用我的测试运行 它就像一个普通的脚本(见下文)。例如,这可能不适用于使用固定装置的更高级的 pytest 技巧。在 Python 脚本的末尾,您可以添加如下内容:

if __name__ == "__main__":
    my_first_test()
    my_second_test()

和 运行 它在调试模式下 (F5) 正常。