pytest可以在测试类中运行测试吗?

2024-06-09 05:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一堆测试,我决定把它们放在一个类中,示例代码如下:

class IntegrationTests:

    @pytest.mark.integrationtest
    @pytest.mark.asyncio
    async def test_job(self):
        assert await do_stuff()

但是,当我尝试运行测试时: pipenv run pytest -v -m integrationtest,它们根本没有被检测到,在将它们移到类之前,我得到了以下信息:

^{pr2}$

我现在明白了:

2 passed, 4 deselected in 0.51 seconds

为什么pytest没有检测到这些测试?不支持测试类吗?在


Tags: 代码testselfasyncio示例asyncpytestdef
3条回答

创建pytest.ini文件在

来自the docs

In case you need to change the naming convention for test files, classes and tests, you can create a file pytest.ini, and set the options python_files, python_classes, and python_functions:

示例:

# content of pytest.ini
# Example 1: have pytest look for "check" instead of "test"
# can also be defined in tox.ini or setup.cfg file, although the section
# name in setup.cfg files should be "tool:pytest"
[pytest]
python_files = check_*.py
python_classes = *Tests
python_functions = *_check

在您的例子中,如果您不想更改类名IntegrationTests,请将python_classes设置为*Tests。在

在类内运行测试

^{pr2}$

EHA内部测试
pytest /path/to/test_file_name.py::ClassName::test_name

类的名称需要以Test开头,pytest发现才能找到它。在

class TestIntegration:

    @pytest.mark.integrationtest
    @pytest.mark.asyncio
    async def test_job(self):
        assert await do_stuff()

Conventions for Python test discovery

要运行类“TestIntegration”下的所有测试,可以使用:

pytest -k TestIntegration

相关问题 更多 >