VSCode pytest 测试发现失败

VSCode pytest test discovery fails

Pytest 测试发现失败。 UI 状态:

Test discovery error, please check the configuration settings for the tests

输出 window 状态:

Test Discovery failed: 
Error: Traceback (most recent call last):
  File "C:\Users\mikep\.vscode\extensions\ms-python.python-2019.4.11987\pythonFiles\testing_tools\run_adapter.py", line 16, in <module>
    main(tool, cmd, subargs, toolargs)
  File "C:\Users\mikep\.vscode\extensions\ms-python.python-2019.4.11987\pythonFiles\testing_tools\adapter\__main__.py", line 90, in main
    parents, result = run(toolargs, **subargs)
  File "C:\Users\mikep\.vscode\extensions\ms-python.python-2019.4.11987\pythonFiles\testing_tools\adapter\pytest.py", line 43, in discover
    raise Exception('pytest discovery failed (exit code {})'.format(ec))
Exception: pytest discovery failed (exit code 3)

这是我的设置:

{
    "python.pythonPath": ".venv\Scripts\python.exe",
    "python.testing.pyTestArgs": [
        "tests"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pyTestEnabled": true
}

我可以 运行 从命令行成功 FWIW pytest。

查看 https://docs.pytest.org/en/latest/usage.html#possible-exit-codes 似乎 pytest 本身因某些内部错误而崩溃。

这不是一个完整的答案,因为我不知道为什么会这样,并且可能与您的问题无关,具体取决于您的测试结构。

我通过将 __init__.py 文件放入我的测试文件夹解决了这个问题

例如:


├───.vscode
│       settings.json
│
├───app
│       myapp.py
│
└───tests
        test_myapp.py
        __init__.py

这几天前没有这个就可以工作,但是最近更新了 python 扩展。我不确定这是预期的行为还是现在发现的副作用

https://github.com/Microsoft/vscode-python/blob/master/CHANGELOG.md
Use Python code for discovery of tests when using pytest. (#4795)

我通过将 pytest 升级到最新版本解决了这个问题:4.4.1 "pip install --upgrade pytest"。我显然是 运行 旧版本 3.4.2

似乎是最新版本的 VS Code Python 扩展中的错误。我有同样的问题,然后我将 Python 扩展降级为 2019.3.6558 然后它再次工作。因此,我们应该转到我们的 VS Code 扩展列表,select Python 扩展和 "Install another version..." 来自该扩展的设置。

我希望这对你也有用。

在创建了一个有导入错误的测试后,我花了很长时间试图破译这个无用的错误。在进行任何更深入的故障排除之前,请验证您的测试套件是否确实可以执行。

pytest --collect-only是你的朋友。

我遇到了同样的问题并将其追溯到我的 pytest.ini 文件。从该文件中删除大部分 addopts 解决了这个问题。

在开始测试发现之前,检查 python.testing.cwd 是否正确指向您的测试目录,并且您的 python.testing.pytestEnabled 设置为 true

一旦正确设置了这些要求,运行 就会测试发现及其输出(参见 OUTPUT window)。你应该看到这样的东西:

python $HOME/.vscode/extensions/ms-python.python-$VERSION/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir $ROOT_DIR_OF_YOUR_PROJECT -s --cache-clear
Test Discovery failed: 
Error: ============================= test session starts ==============================
<SETTINGS RELATED TO YOUR MACHINE, PYTHON VERSION, PYTEST VERSION,...>
collected N items / M errors
...

在这里突出显示最后一行很重要:collected N items / M errors。以下行将包含有关 pytest 发现的测试的信息。因此,您的测试 是可发现的 但存在与其正确执行相关的错误。

以下行将包含错误,在大多数情况下,这些错误与不正确的导入有关

检查之前是否已下载所有依赖项。如果您正在使用特定版本的依赖项(在 requirements.txt 文件中,您有类似 your_package == X.Y.Z 的内容),请确保它是您需要的正确版本。

我只是想在这里添加我的答案,因为这很可能会影响使用 .env 文件作为项目环境设置的人,因为它是 12 因素应用程序的常见配置。

我的示例假设您使用 pipenv 进行虚拟环境管理,并且在项目的根目录中有一个 .env 文件。

我的 vscode 工作区设置 json 文件如下所示。这里对我来说至关重要的是 "python.envFile": "${workspaceFolder}/.env",

{
    "python.pythonPath": ".venv/bin/python",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pycodestyleEnabled": false,
    "python.linting.flake8Enabled": false,
    "python.linting.pylintPath": ".venv/bin/pylint",
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
    ],
    "python.formatting.provider": "black",
    "python.formatting.blackArgs": [
        "--line-length",
        "100"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.pytestPath": ".venv/bin/pytest",
    "python.envFile": "${workspaceFolder}/.env",
    "python.testing.pytestArgs": [
        "--no-cov"
    ],
}

我希望这可以节省我花在解决这个问题上的时间。

在我的例子中,vscode 无法发现测试的问题是在 setup.cfg 中启用了 coverage 模块(或者这可能是 pytest.ini) , 即

addopts= --cov <path> -ra

由于覆盖率低导致测试发现失败。解决方案是从配置文件中删除该行。

此外,如 documentation 中所建议:

You can also configure testing manually by setting one and only one of the following settings to true: python.testing.unittestEnabled, python.testing.pytestEnabled, and python.testing.nosetestsEnabled.

settings.json 中,您还可以使用 --no-cov 标志禁用覆盖:

"python.testing.pytestArgs": ["--no-cov"],

编辑:

稍微相关 - 如果是更复杂的项目,当 运行 使用 pytest 进行测试时,可能还需要更改 rootdir 参数(在您的 settings.json 内) (在 ModuleNotFoundError 的情况下):

    "python.testing.pytestArgs": [
        "--rootdir","${workspaceFolder}/<path-to-directory-with-tests>"
    ],

如果您在使用 pytest 时遇到问题,我正在为发现测试部分苦苦挣扎。

阅读 vscode 中的一些 open issue (other) 我找到了使用 the test-adapter 扩展

的解决方法

market_place_link

这个扩展很有魅力。 (并解决我的发现问题)

我在设置中搜索了“python”并找到了这个:

切换到 pytest 自动检测我的测试:

我遇到了这个问题,并为此苦苦挣扎了几个小时。我认为每个其他平台配置都有一个特殊的解决方案。我的平台是:

  • VSCode: 1.55.0 (Ubuntu)
  • Pytest:6.2.3
  • MS Python 分机 (ms-python.python 2021.3.680753044)
  • Python Visual Studio 代码的测试资源管理器(littlefoxteam.vscode-python-test-adapter - 0.6.7)

最糟糕的是该工具本身没有标准输出(至少我知道或可以在 Internet 上轻松找到)。

最后,问题是

--no-cov

VSCode 测试浏览器工具无法识别的参数(我从互联网上的某个页面复制的)并且扩展名 littlefoxteam.vscode- 显示了错误python-test-adapter 它可能会帮助您找到损坏的地方。

这个错误太令人沮丧了.. 在我的例子中,通过将 settings.json 中的 python.pythonPath 参数(在项目根目录下的 .vscode 文件夹中找到)修改为我在终端中使用 which python 获得的路径来修复错误(例如 /usr/local/var/pyenv/shims/python

我将 pyenv 与 python3.9 一起使用,我之前的错误是:

Error: Process returned an error: /Users/"user-name"/.pyenv/shims/python: line 21: /usr/local/Cellar/pyenv/1.2.23/libexec/pyenv: No such file or directory

at ChildProcess. (/Users/"user-name"/.vscode/extensions/littlefoxteam.vscode-python-test-adapter-0.6.8/out/src/processRunner.js:35:36) at Object.onceWrapper (events.js:422:26) at ChildProcess.emit (events.js:315:20) at maybeClose (internal/child_process.js:1021:16) at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)

在我的例子中,每次 flake8 linter 报告错误时都会出现同样的问题。即使是一个错误也足以导致 VS Code 测试发现失败。 因此,解决方法是禁用 linter 或修复 linter 错误。 我使用 here.

中描述的设置

就我而言,这是 vscode python 扩展问题。 我将测试平台从 pytest 切换回来,然后又切换回来,然后发现了测试。 似乎当所有 python 项目普遍启用测试并且在开始时未能发现测试时,它永远失败!

2021-12-22

请在下面找到我用来让 pytest 在 VsCode 中工作的设置。我在这里和 Internet 上的其他地方找到了许多有用的建议,但是 none 已经足够完整,让我不用再骂人了。我希望以下内容可以帮助某人。此设置允许我 运行 从测试资源管理器扩展和集成终端进行可视化测试。我在我的工作区和 Conda 中使用 src 格式进行环境管理。与终端设置相关的设置使我不必手动启用我的 Conda 环境或设置 python 路径。可能已经使用 VSCODE 超过两天的人可以添加一些好的东西来使这个更好 and/or 更完整。

##### Vscode 信息:

版本:1.63.2(通用) 提交:899d46d82c4c95423fb7e10e68eba52050e30ba3 日期:2021-12-15T09:37:28.172Z(1 周前) 电子:13.5.2 铬:91.0.4472.164 Node.js:14.16.0 V8:9.1.269.39-电子.0 OS:达尔文 x64 20.6.0

##### 测试扩展:

Python Visual Studio 代码的测试资源管理器 已安装扩展,v. 0.7.0

##### Pytest 版本

pytest 6.2.5

#####目录结构:

     workspace
       .env
       ./src
            __init__.py
            code1.py
            code2.py
       ./tests
            __init__.py
            test_code1.py
            test_code2.py

##### .env 文件(在 root 中,但请参阅 settings.json 中的“python.envFile”设置)

PYTHONPATH=src

#####。 settings.json

    {
        "workbench.colorTheme": "Visual Studio Dark",
        "editor.fontFamily": " monospace, Menlo, Monaco, Courier New",
        "python.testing.unittestEnabled": false,
        "python.testing.cwd": ".",
        "terminal.integrated.inheritEnv": true,
        "python.envFile": "${workspaceFolder}/.env",
        "python.defaultInterpreterPath": 
        "~/anaconda3/envs/mycurrentenv/bin/python",
        "pythonTestExplorer.testFramework": "pytest",
        "python.testing.pytestEnabled": true,
        "python.testing.pytestArgs": [
           "tests"
        ],
        "python.terminal.activateEnvironment": true,
        "python.terminal.activateEnvInCurrentTerminal": true,
        "terminal.integrated.env.osx": {
            "PYTHONPATH": "${workspaceFolder}/src:${env:PYTHONPATH}"
          }
    }

这是使 Django 测试达到 运行 的通用方法 full vscode 支持

  1. 配置 python 测试
    1. 选择单元测试
    2. 根目录
    3. test*.py
  2. 然后每个测试用例需要如下所示:
from django.test import TestCase

class views(TestCase):

    @classmethod
    def setUpClass(cls):
        import django
        django.setup()

    def test_something(self,):
        from user.model import something
        ...

您要导入的任何函数 都有 导入到测试用例中(如图所示)。设置测试 class 之前的 setUpClass 运行s 并将设置您的 django 项目。设置完成后,您可以在测试方法中导入函数。如果您尝试在脚本顶部导入 models/views ,它将引发异常,因为未设置 django。如果你有任何其他预初始化需要 运行 让你的 django 项目工作,运行 它在 setUpClass 里面。 Pytest 可能会以同样的方式工作,我还没有测试过。

在我的例子中,我必须确保在安装库的地方使用正确的解释器(我使用虚拟环境),但解释器指向全局安装的 python。将解释器改成虚拟环境的解释器后,就可以了。

测试文件需要命名为 test_*.py*_test.py 才能使 pytest 集合正常工作。

然后在命令行中 运行 pytest --collect-only 以确保找到所有测试。然后神奇地,VSCode 中的烧瓶图标突然显示测试文件及其测试。

作为菜鸟,我将我的单元测试 放在 模块文件中,因为我遵循 unittest 的模式,然后是 运行宁pytest *.py。这不适用于 pytest,我没有发现命令行参数覆盖命名约定。

这有几个原因。

答案很简单,它并不完美。此外,Python 不是 VS Code 原生的; Python 扩展可能也玩得不好。

不过,我观察到了一些缓解措施。

注意 VS Code 没有“设计”测试发现;那是测试框架的工作。确保您对它的工作原理有基本的了解。

疑难解答

对于每一个“电池”测试,VS Code 都会很乐意告诉您出了什么问题,就在“测试”视图面板中。要查看此内容,请展开带有项目名称的栏,并将鼠标悬停在显示的行上。 查看回溯

在上图中,错误是“No module named src”。这比听起来更有趣。如果我从另一个文件导入一个文件,则该导入路径可能对测试发现机制不可见。它可能是 运行 来自不同的“cwd”。您能做的最好的事情就是尝试找出项目的最顶层路径,然后添加或删除路径限定符。直到成功为止。

主要原因

  1. 有时,VS Code 会丢失有关项目测试配置的信息。使用 command window (Ctrl + Shift + P) 至:

    1. (重新)扫描测试
    2. (重新)配置项目的测试规范 <-- 重要!
    3. 重启Python语言服务器
  2. Python 应该消除对空 __init__.py 的需要; VS Code 似乎很喜欢这些。它们应该在 each 文件夹中, 通向 test 文件夹。不是每个文件夹,而是 top-down 路径。

  1. 根据您 select 作为测试配置中的“根测试文件夹”,根据 VS Code 认为是 root 的内容,它可能具有不同的含义 您的项目。这可能也适用于任何特定文件夹。

  2. import。 VS Code 不喜欢语法错误。 有可能一些语法错误不会在代码中突出显示。 这(不幸的是)适用于 您文件中的所有导入 。但是无论如何你都不应该测试无效代码,对吧?

轻微的错误行为

  1. 运行 一些其他可见的测试可能有助于刷新发现过程。
  2. VS Code 应该 自动(通过设置)刷新每个 Save 操作的测试。不过手动刷新也无妨

TLDR

  1. 查看测试面板中的错误项
  2. Re-configure项目测试不时发现参数
  3. 确保您没有语法错误(可见或不可见)
  4. 在项目的每个通向测试文件夹的文件夹中创建空 __init__.pys
  5. 清理导入逻辑

P.S。在 1 年的时间里,测试视图得到了广泛的改进和改进。期待行为发生变化。