kat*_*tch 25 visual-studio-code vscode-debugger
我正在尝试调试 pytest。我想注入一个环境变量。这是我设置 launch.json 的方法
{
"type": "python",
"request": "test",
"name": "pytest",
"console": "integratedTerminal",
"env": {
"ENV_VAR":"RandomStuff"
}
},
Run Code Online (Sandbox Code Playgroud)
但当我开始调试时似乎。我没有看到注入的 env 变量,因此我的测试预计 env 变量失败。
我还注意到错误
Could not load unit test config from launch.json
Run Code Online (Sandbox Code Playgroud)
Ste*_*ing 15
pytest-envconda install -c conda-forge pytest-env
Run Code Online (Sandbox Code Playgroud)
或者:
pip install pytest-env
Run Code Online (Sandbox Code Playgroud)
pytest.inipytest.ini在项目目录中创建文件:
[pytest]
env =
ENV_VAR=RandomStuff
Run Code Online (Sandbox Code Playgroud)
在您的代码中,像平常一样加载环境变量:
import os
env_var = os.environ["ENV_VAR"]
Run Code Online (Sandbox Code Playgroud)
pytest/ VS 代码要么运行:
pytest
Run Code Online (Sandbox Code Playgroud)
(注意它是怎么说的configfile: pytest.ini)
Run Code Online (Sandbox Code Playgroud)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 for VS Code 扩展会.env自动识别文件。例如
.env文件:
ENV_VAR=RandomStuff
Run Code Online (Sandbox Code Playgroud)
尚未验证,但我认为这与使用文件具有相同的pytest-env行为pytest.ini。
当我不想处理让 VS Code、Anaconda 环境和 pytest 很好地协同工作所需的奇怪黑客行为(和/或忘记我之前如何修复它)时,我会手动调用我的测试并像普通脚本一样运行它(见下文)。例如,这可能不适用于使用固定装置的更高级的 pytest 技巧。在 Python 脚本的末尾,您可以添加如下内容:
ENV_VAR=RandomStuff
Run Code Online (Sandbox Code Playgroud)
F5并正常在调试模式 ( ) 下运行它。
无法真正弄清楚如何使用 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"],
}
Run Code Online (Sandbox Code Playgroud)
这足以进行 python 测试的调试。您也可以插入环境变量
"env": {
"ENV_VAR":"RandomStuff"
}
Run Code Online (Sandbox Code Playgroud)
当您在 python 测试中运行调试器时,VSCode 的 python 扩展现在有一种特殊的运行调试器的方式。
您可以按照本指南进行配置。简而言之:
Python: Configure Tests在命令面板中输入命令pytest或unittest当前).vscode/launch.json使用必要的环境在文件中创建配置:{
"name": "Python: Tests in current file",
"purpose": ["debug-test"],
"type": "python",
"request": "launch",
"program": "${file}",
"args": ["--color=yes"],
"env": {"ENV_VAR":"RandomStuff"},
"console": "integratedTerminal",
"justMyCode": false
}
Run Code Online (Sandbox Code Playgroud)
^ 这"purpose": ["debug-test"]很重要,这就是 VSCode 知道此配置用于调试测试的方式。
Test: Debug Tests in Current File(或)Test: Debug Test at Cursor相对于“模块”方法的优点:不确定是否真的存在。cmd ;那么,您将获得一个专用的 VS Code 快捷方式,用于调试当前文件 ( + )中的测试cmd f。
编辑:尝试后,我不会推荐该Test: Debug Test at Cursor命令,因为它似乎会搞乱拆卸(在我的情况下,它阻止了测试数据库的清空)
| 归档时间: |
|
| 查看次数: |
25812 次 |
| 最近记录: |