如果定义了构造函数,py.test 会跳过测试类

问题描述 投票:0回答:4

我有以下通过 py.test 运行的单元测试代码。 构造函数的存在会使整个类在运行时跳过 py.test -v -s

已收集 0 件 / 已跳过 1 件

任何人都可以向我解释 py.test 的这种行为吗?

我有兴趣了解 py.test 行为,我知道不需要构造函数。

谢谢, 兹德内克

class TestClassName(object):
    def __init__(self):
       pass

    def setup_method(self, method):
       print "setup_method called"

    def teardown_method(self, method):
       print "teardown_method called"

    def test_a(self):
       print "test_a called"
       assert 1 == 1

    def test_b(self):
       print "test_b called"
       assert 1 == 1
python pytest
4个回答
76
投票

py.test 的文档 py.test 实现了以下标准测试发现:

  • 收集从初始命令行参数开始,这些参数可能是目录、文件名或测试 ID。 递归到目录,除非它们与 norecursedirs 匹配
  • test_*.py 或 *_test.py 文件,按包名导入。
  • Test
    前缀测试类(没有
    __init__
    方法)[<-- notice this one here]
  • test_
    前缀的测试函数或方法是测试项

所以并不是不需要构造函数,py.test只是忽略了构造函数的类。还有一个用于更改标准测试发现的指南


58
投票

正如 Matti Lyra 的答案中已经提到的,py.test 故意跳过具有构造函数的类。这样做的原因是,类仅在 py.test 中出于结构原因而使用,并且没有任何固有行为,而在实际编写代码时,情况恰恰相反,并且类没有

.__init__()
方法的情况要少得多。因此,在实践中,跳过带有构造函数的类可能是所期望的,通常它只是一个碰巧具有冲突名称的类。

最后 py.test 需要实例化该类才能执行测试。如果构造函数接受任何参数,它无法实例化它,所以再次跳过是正确的做法。


1
投票

以上所有答案都清楚地解释了根本原因,我只是想分享我的经验并解决警告。

通过为导入的类添加别名,我的测试可以在没有警告的情况下工作

from app.core.utils import model_from_meta
from app.core.models import Panel, TestType as _TestType
from app.core.serializers import PanelSerializer, TestType as _TestTypeSerializer


def test_model_from_meta():
    assert isinstance(Panel, model_from_meta(PanelSerializer)
    assert isinstance(_TestType, model_from_meta(_TestTypeSerializer)

使用别名导入类后,不再打印警告

我希望这对某人有帮助。


-1
投票

就我而言,我碰巧有一个参数的类名

TestParams
,这与
pytest
查找以名称
test...
开头的类相冲突。

解决方案:重命名自己的类

来源

© www.soinside.com 2019 - 2024. All rights reserved.