[英]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.