首页 > 解决方案 > 无法让 PyTest 在 VSCode 或终端中运行。没有认可的测试

问题描述

我已经使用 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 才能运行。

标签: pythonvisual-studio-codepytest

解决方案


尝试将文件重命名为“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


推荐阅读