[英]how to debug python unittests in Visual Studio Code?
我有以下目录结构(一位朋友在检查时非常友好地将其放在github上)
- code
- elements
__init__.py
type_of_car.py
__init__.py
car.py
- tests
__init__.py
test_car.py
这些是我的 launch.json 设置:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Debug Tests",
"type": "python",
"request": "launch",
"program": "${file}",
"purpose": ["debug-test"],
"console": "integratedTerminal",
"justMyCode": false
},
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "main",
"justMyCode": false,
"cwd": "${workspaceFolder}"
}
]
}
VS Python 测试设置为:
{
"python.testing.unittestArgs": [
"-v",
"-s",
"./tests",
"-p",
"test_*.py"
],
"python.testing.pytestEnabled": false,
"python.testing.unittestEnabled": true,
"python.testing.cwd": "${workspaceFolder}"
}
test_car.py 导入模块——当然——code.car。 而且还有 code.car.type_of_car
当我从项目根目录运行测试时,可以调用并通过测试。 py -m unittest tests.test_car.py
但是,我无法通过按 F5(请参阅 launch.json)配置来运行我的主代码。 这失败了,因为No module named 'code.car'; 'code' is not a package
No module named 'code.car'; 'code' is not a package
。
此外,我还必须使用 Visual Studio Code 调试我的测试:
Python: Debug Tests
配置 这失败了,因为No module named 'code.car'; 'code' is not a package
No module named 'code.car'; 'code' is not a package
。
如何解决模块地狱,以便我也可以从 VSCode/调试器运行测试? (这件事确实花了我几个小时。任何提示都表示赞赏。)
有人在调用模块时了解 VS Code 启动器认为它的根目录吗?
您可以按如下方式修改car.py
和test_car.py
文件:
我只粘贴了修改后的代码。
car.py
:
# your code
from code.elements.type_of_car import TypeOfCar
# my code
from elements.type_of_car import TypeOfCar
test_car.py
:
# your code
import unittest
from code.car import Car
from random import randint
from code.elements.type_of_car import TypeOfCar
# my code
import unittest
import sys
sys.path.append("./code")
from car import Car
from random import randint
from elements.type_of_car import TypeOfCar
调试Python: Debug Tests
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.