【问题标题】:How to get VSCode Python extension recognize submodules when running unittest test cases?运行单元测试测试用例时如何让 VSCode Python 扩展识别子模块?
【发布时间】:2021-11-13 09:29:02
【问题描述】:

问题

我无法让 VSCode/unittest 识别我为其编写单元测试的子模块(即背景示例中的 common.nested_module)。

VSCode 发现测试用例并执行test_my_module.py 中的测试用例,但抱怨importimport 语句行中没有模块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,
}

我尝试了什么

  1. 按照建议的here 将以下内容添加到我的__init__.py 中的project/teststest_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)
  1. .env 添加到包含以下内容的project,同时将"python.envFile": "${workspaceFolder}/afinad/.env" 添加到settings.json,类似于建议的here
PYTHONPATH = ./common
  1. -t 选项与${workspaceFolder}/project/src. 添加到settings.json for python.testing.unittestArgs 建议here

"python.testing.unittestArgs": [
        "-v",
        "-s",
        "${workspaceFolder}/project/tests",
        "-p",
        "test_*.py",
        "-t",
        "${workspaceFolder}/project/src"
    ],
  1. 在终端更改为./tests 后运行python3 -m unittest discover 给了我:
ModuleNotFoundError: No module named 'my_module'

感谢您花时间阅读。非常感谢任何帮助!

【问题讨论】:

  • {WorkspaceFolder} 是否指向workspaces/test_project
  • @zerocukor287 是的,按预期解决了。

标签: python visual-studio-code python-unittest


【解决方案1】:

在尝试了各种建议解决方案的不同组合近两天后,我发现了我的错误。看来,像我这样的新手,我对name shadowing trap 有感觉。

最初,我打算在tests 中使用与src 中相同的文件夹结构。但是,当我发现test_my_module.py 有效时,我将test_nested_module.pytests/common 移动到tests,但我没有删除文件夹tests/common。这似乎导致了ModuleNotFoundError,因为在删除文件夹后,它按预期工作。

我希望这会为其他人节省一些时间。

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多