VS Code 编辑器中配置 Pytest 联调环境
最近在学习 MiniTorch
项目,里面的 Assignmenst 均使用 Pytest
来对自己实现的 module 进行 unit test。
以往在 Code 中调试代码时,都是使用网上通用的 .vscode/launch.json
配置文件,然后在 VS Code 中按需进行 Debug。
但在使用 Pytest
时,由于其运行方式不同,需要在 Pytest
的运行环境中进行 Debug,这就需要对 Pytest
进行配置。
现在的需求是:
- 可以使用
.vscode/launch.json
配置 VS Code 对 Debug 的支持
- 可以断点
- 可以添加 debug 的
arguments
参数
下面是配置步骤:
1. 增加 .vscode/launch.json
的启动配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
///////// 配置 [1]:这是我用来带参调试当前 .py 的配置
{
"name": "Python Debugger: Current File with Arguments",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"args": [
"${command:pickArgs}"
]
},
///////// 配置 [2]:这是我用 pytest 带参调试的配置
{
"name": "Python: pytest",
"type": "debugpy",
"request": "launch",
/// 由于我的 pytest 在虚拟环境中,所以这里指定了虚拟环境中的解释器和 pytest
"python": "/home/shikai/tools/anaconda3/envs/env-minitorch/bin/python",
"program": "/home/shikai/tools/anaconda3/envs/env-minitorch/bin/pytest",
"args": [
"--capture=no",
"-m", // 指定 pytest 的 marker
"${command:pickArgs}", // 这里是我在调试时输入的参数, 比如 pytest -m test_01, 这里用于接受 test_01
"--capture=no", // 不捕获输出
"--no-header", // 不显示 pytest 的 header
"--disable-warnings" // 禁用 pytest 的 warning
],
"console": "integratedTerminal"
}
]
}
|
2. 在待调试的 .py
文件中,手动添加 breakpoint
:
目前发现除了可以使用通过 code 的 GUI 添加 断点外,还可以在代码中手动添加 pytest 的 trace() 断点:
1
2
3
4
5
6
|
# 比如我要测试 named_parameters() 函数
def named_parameters(self) -> Sequence[Tuple[str, Parameter]]:
# ....
# ....
pytest.set_trace() # 这里添加断点,程序会在这里停下来
return [(k, v) for k, v in self._parameters.items()]
|
3. 在 VS Code 中按 F5
输入参数进行 Debug