首页 > 解决方案 > 如何让 pytest 忽略名为 TestSomething 的类?

问题描述

我正在研究一种测试框架,TestSomething当然它恰好有类命名。而且我意识到我的测试失败了,因为 pytest 将这些类视为“我需要实例化和运行的东西!”,一旦导入。而这绝对行不通。

import pytest
from package import TestSomethingClass

是否可以直接从 pytest 测试文件中导入此类?或者我应该通过固定装置间接使用它们吗?

同样的问题也适用于异常,因为我需要做类似的事情

with pytest.raises(TestsSomethingError):

标签: pythonpytest

解决方案


显式禁用

你可以允许 pytest 忽略这个特定的类,因为它以 word 开头Test,通过将 __test__标志设置False在你的冲突类中

class TestSomethingClass(object):
    __test__ = False

    def test_class_something(self, object):
        pass

功能:https ://github.com/pytest-dev/pytest/pull/1561


配置文件

我们还可以在您的文件中完全更改约定pytest.ini并忽略所有以单词开头的类名Example。但我不建议这样做,因为我们可能会在未来遇到意想不到的后果。

#pytest.ini file
[pytest]
python_classes = !Example

Pytest 约定

  • 在类外测试前缀测试函数或方法

  • 测试前缀测试类中的测试前缀测试函数或方法(没有init方法)

来源:https ://docs.pytest.org/en/stable/customize.html


推荐阅读