【问题标题】:Can't get PyTest to run in VSCode or terminal. No tests recognized无法让 PyTest 在 VSCode 或终端中运行。没有认可的测试
【发布时间】:2021-05-19 07:08:03
【问题描述】:

我已经使用 pip 安装了 pytest。下面的示例代码

import pytest


def example():
    assert 9 == 9

我的 settings.json 文件如下所示

{
    "python.testing.pytestArgs": [
        "."
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true
} 

使用 pytest filename.py 命令时,终端中一直没有运行任何测试。

Python 版本:3.9.1 pytest 版本:6.2.2.

有人有什么想法吗?

更新:下面杰森的回答是有效的。问题是文件和方法的命名。文件名需要以“_test.py”结尾,vscode 才能运行测试,函数需要以“test_”开头,终端和 vscode 才能运行。

【问题讨论】:

  • 如果设置正确,VSC 可以在保存测试文件或按下测试活动栏中的refresh 图标时自动检测测试。查看 VSC 文档中的 Python 测试页面
  • 是的,这是我的模块命名和测试方法的问题
  • 我应该做的另一件事是在 vscode 中配置 python 测试并选择 pytest

标签: python visual-studio-code pytest


【解决方案1】:

尝试将文件重命名为“test_filename.py”,将测试函数重命名为“test_example”,以便 pytest 检测到它们。

https://docs.pytest.org/en/reorganize-docs/new-docs/user/naming_conventions.html

此外,调试运行测试能力的一个有用的 pytest 选项是“--collect-only”。它将尝试仅查找测试而不运行它们。

pytest --collect-only

VSCode 能够自行运行测试,而无需您在终端中执行它们。

https://code.visualstudio.com/docs/python/testing

【讨论】:

  • 谢谢杰森!我最终让它在 vscode 和终端中运行。我不知道“仅收集命令”我一定会继续使用它。
猜你喜欢
  • 2021-10-20
  • 2020-04-08
  • 2023-03-06
  • 2018-06-01
  • 1970-01-01
  • 2021-11-08
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多