Python Unittest:在 Visual Studio Code 中未发现任何测试

新手上路,请多包涵

我正在尝试使 Visual Studio Code 单元测试的自运行 功能 发挥作用。我最近对我的 Python 项目的目录结构进行了更改,该目录结构以前是这样的:

 myproje\
    domain\
        __init__.py
    repositories\
    tests\
        __init__.py
        guardstest.py
    utils\
        __init__.py
        guards.py
    web\

我的单元测试设置是这样的:

     "python.unitTest.unittestArgs": [
    "-v",
    "-s",
    "tests",
    "-p",
    "*test*.py"
]

改动后,项目结构如下:

 myprojet\
    app\
        controllers\
            __init__.py
        models\
            __init__.py
            entities.py
            enums.py
        tests\
            res\
                image1.png
                image2.png
            __init__.py
            guardstest.py
        utils\
            __init__.py
            guards.py
        views\
            static\
            templnates\
        __init__.py
    uml\

之后,扩展程序不再发现我的测试。 I’ve tried to change the ‘-s’ parameter to "./app/tests" , ".tests" , "./tests" , "app/tests" , "/app/tests" , "app.tests" ,未成功。

在此处输入图像描述

原文由 Matheus Saraiva 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.6k
2 个回答

问题是我在测试模块中使用了相对导入( from ..utils import guards )。我只是将其更改为绝对导入( from app.utils import guards )并且它再次起作用。

原文由 Matheus Saraiva 发布,翻译遵循 CC BY-SA 4.0 许可协议

这可能不起作用的原因有两个:

测试有错误

如果测试脚本中有错误,python Testing 插件将找不到你的测试。

要检查是否存在潜在错误,请单击 Show Test Output ,然后使用 Run All Tests 运行测试(这两个按钮都位于左上角,就在测试应出现的位置上方)。

如果有错误,会出现在 OUTPUT 选项卡中。

测试配置不正确

检查您的 .vscode/settings.json ,并获取 python.testing.unittestArgs 列表。

您可以通过将 args 添加到命令行中的 python3 -m unittest discover 命令来调试命令行中测试的发现。

所以有了这个配置:

 {
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        ".",
        "-p",
        "*test*.py"
    ]
}

您将启动命令:

 python3 -m unittest discover -v -s . -p "*test*.py"

您可以在发现测试之前使用 args,并相应地修改 .vscode/settings.json 中的 args。

这是 unittest 的文档

笔记

一个常见的原因是您正在尝试使用依赖项运行测试。 If this is the case, you can select your interpreter by running ctrl + shift + p and searching Python: Select Interpreter , then selecting the correct口译员。

原文由 Preston 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题