【发布时间】:2021-11-13 09:29:02
【问题描述】:
问题
我无法让 VSCode/unittest 识别我为其编写单元测试的子模块(即背景示例中的 common.nested_module)。
VSCode 发现测试用例并执行test_my_module.py 中的测试用例,但抱怨import 的import 语句行中没有模块common.nested_module test_nested_module.py(在输出中:ModuleNotFoundError: No module named 'common.nested_module')。
我将print(sys.path) 添加到已执行的测试用例中,并且在Python 测试日志中我什至在添加.env 文件时得到以下输出,如下所述我尝试了什么2。:
test_get_version (test_my_module.TestCase1) ... ['/workspaces/test_project/project/tests', '/workspaces/test_project/project/src', '/workspaces/test_project/project/common', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/home/vscode/.local/lib/python3.9/site-packages', '/usr/local/lib/python3.9/site-packages']
背景
在PyPA tutorial for packaging and distribution之后我创建了一个项目结构,省略了其他细节(例如README.md),如下:
project
|--src
|--common
|-- __init__.py
|-- nested_module.py
|-- __init__.py
|-- my_module.py
|--tests
|--__init__.py
|--test_my_module.py
|--test_nested_module.py
settings.json中与测试相关的设置:
{
"python.testing.unittestArgs": [
"-v",
"-s",
"${workspaceFolder}/project/tests",
"-p",
"test_*.py"
],
"python.testing.cwd": "project/src",
"python.testing.pytestEnabled": false,
"python.testing.unittestEnabled": true,
}
我尝试了什么
- 按照建议的here 将以下内容添加到我的
__init__.py中的project/tests和test_nested_module.py。
import os
import sys
PROJECT_PATH = os.getcwd()
SOURCE_PATH = os.path.join(
PROJECT_PATH,"project/src/common"
)
sys.path.append(SOURCE_PATH)
- 将
.env添加到包含以下内容的project,同时将"python.envFile": "${workspaceFolder}/afinad/.env"添加到settings.json,类似于建议的here。
PYTHONPATH = ./common
- 将
-t选项与${workspaceFolder}/project/src和.添加到settings.jsonforpython.testing.unittestArgs建议here:
"python.testing.unittestArgs": [
"-v",
"-s",
"${workspaceFolder}/project/tests",
"-p",
"test_*.py",
"-t",
"${workspaceFolder}/project/src"
],
- 在终端更改为
./tests后运行python3 -m unittest discover给了我:
ModuleNotFoundError: No module named 'my_module'
感谢您花时间阅读。非常感谢任何帮助!
【问题讨论】:
-
{WorkspaceFolder}是否指向workspaces/test_project? -
@zerocukor287 是的,按预期解决了。
标签: python visual-studio-code python-unittest