pytest不运行任何测试

18
pytest不运行任何测试,原因不明。我尝试使用--debug,但没有得到任何有价值的信息。对于如何调试pytest的这种问题完全不清楚。(看起来像是pytest配置/环境变量/测试名称模式的问题?)
测试文件示例:
import pytest

@pytest.mark.sanity
def test_me():
    """I'm a test."""

    assert True

但是pytest为什么不运行任何测试呢?
$ pytest
================================================== test session starts ===================================================
platform linux2 -- Python 2.7.12, pytest-3.1.3, py-1.4.34, pluggy-0.4.0
rootdir: /home/qawizard/pytest-hell, inifile:
plugins: xdist-1.15.0, timeout-1.2.0
collected 1 item s

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Exit: Done! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================== no tests ran in 0.13 seconds ==============================================

2
你在 pytest.ini 中注册了那个标记吗? 你在 pytest.ini 中有其他的配置吗? 你可以重新运行 pytest -lsvvv 命令来查看额外的详细输出吗? 你是否有一个带有一些自定义配置的 conftest.py 文件? - Dmitry Tokarev
4个回答

47
为了确定为什么测试不运行,以下步骤很有用:
  1. 确认所有测试用例文件都有以'test_'为前缀。
  2. 确认所有测试用例名称也有以'test_'为前缀。
  3. 确认你在根目录下创建了pytest.ini文件。
  4. 确认你在项目的所有目录/子目录中都有__init__.py文件。

3
你需要确保所有测试的名称以 test_ 开头,同时你还需要告诉 Pytest 要查找哪些文件:
# pytest.ini

[pytest]

DJANGO_SETTIONS_MODULE = myproject.settings
python_files = tests.py test_*.py


1
什么是DJANGO_SETTINGS_MODULE,为什么我们要使用它? - Morticia A. Addams

1

对我来说,我的类名并没有以“test”开头。

我的代码是

class MainTest:
    ...

    def test_properties(self):
        ...

这样做不起作用,因为pytest会认为这个类不应该被包含。 对我来说,改成这样就可以了。

class TestMain:
    ...

    def test_properties(self):
        ...

0
例如,下面显示了一个名为apples/apple.py的示例:
project
 |-pytest.ini
 └-apples
    |-__init__.py
    └-apple.py # Here

然后,在下面所示的apples/apple.py中的Apple类中,有apple(self)
# "apples/apple.py"

import pytest

class Apple:
    def apple(self):
        assert True

现在,通过下面的pytest.iniapple(self)无法运行,因为默认情况下,Pytest可以运行test_*.py*_test.py文件,以及以Test为前缀的类和以test为前缀的函数,而不是apple.py文件、Apple类和apple(self)函数,根据python_filespython_classespython_functions,并且默认情况下,Pytest可以运行任何类似apples的文件夹。
# "pytest.ini"

[pytest]

所以,使用下面的pytest.ini,可以运行apple(self)
# "pytest.ini"

[pytest]
python_files = apple.py
python_classes = Apple
python_functions = apple

此外,默认情况下,您可以运行以下所有测试:apples/test_1.pyapples/oranges/test_2.pybananas/test_1.pybanana/kiwis/test_2.py,如上所述,因为默认情况下,Pytest可以运行任何类似applesorangesbananaskiwis的文件夹。*我的回答对此进行了解释。
project
 |-pytest.ini
 |-apples
 |  |-__init__.py
 |  |-test_1.py # Here
 |  └-oranges
 |     |-__init__.py
 |     └-test_2.py # Here
 └-bananas
    |-__init__.py
    |-test_1.py # Here
    └-kiwis
       |-__init__.py
       └-test_2.py Here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接