【问题标题】:Using sub-classes with py.test's parametrization使用带有 py.test 参数化的子类
【发布时间】:2015-06-24 02:24:56
【问题描述】:

我有一个场景,能够在 py.test 中对基础测试类进行子类化将使我们的测试环境非常可扩展。我遇到的问题是我无法覆盖基类的属性并在参数化装饰器中使用它们。

import pytest

class TestBase():
    l = [2,3]

    @pytest.mark.parametrize('p', l)
    def testOne(self, p):
        assert p == p

class TestSubClass(TestBase):
    l = [1, 2, 3, 4]

class TestSubClass2(TestBase):
    l = [3, 5]

在这种情况下,TestSubClassTestSubClass2 始终使用来自TestBase 的列表l 运行,因为装饰器查找l 的范围是直接本地范围。

我不能使用self.l,因为在评估装饰器时self 不存在(没有实例)。

我可以解决这个问题并在测试用例中手动执行参数化,但是我会丢失来自 py.test 的单个报告。例如。

import pytest
class TestBase()
    def testOne(self):
        for p in self.l:
            assert p == p

class TestSubClass(TestBase):
    l = [1, 2, 3, 4]

class TestSubClass2(TestBase):
    l = [3, 5]

如何对基类进行子类化并为每个子类自定义参数化?

【问题讨论】:

  • 除了你的问题:避免使用名为 l 的变量 - 在很多字体上它无法与 1I 区分开来 - 即使它是不同的仍然难以阅读。

标签: python decorator pytest


【解决方案1】:

我有一个稍微糟糕的解决方案:

  1. 更改基类以将列表作为所有可能选项的超集。
  2. 在收集时 py.test 构建所有可能测试的列表
  3. 在运行时检查参数值是否对该基类有效。如果不是,请跳过测试

代码:

import pytest

class TestBase():
    l = [1, 2, 3, 4, 5]

    @pytest.mark.parametrize('p', l)
    def testOne(self, p):
        if p not in self.l:
            pytest.skip("%d not supported on %s" % (p, self.__class__.__name__))
        assert p == p

class TestSubClass(TestBase):
    l = [1, 2]

class TestSubClass2(TestBase):
    l = [3, 5]

以及对应的输出:

py.test -v -rsf test_sample.py::TestSubClass
===================================== test session starts ======================================
platform darwin -- Python 2.7.9 -- py-1.4.26 -- pytest-2.6.4 -- 
collected 5 items 

test_sample.py::TestSubClass::testOne[1] PASSED
test_sample.py::TestSubClass::testOne[2] PASSED
test_sample.py::TestSubClass::testOne[3] SKIPPED
test_sample.py::TestSubClass::testOne[4] SKIPPED
test_sample.py::TestSubClass::testOne[5] SKIPPED
=================================== short test summary info ====================================
SKIP [1] test_sample.py:10: 4 not supported on TestSubClass
SKIP [1] test_sample.py:10: 3 not supported on TestSubClass
SKIP [1] test_sample.py:10: 5 not supported on TestSubClass

============================= 2 passed, 3 skipped in 0.01 seconds ==============================

这种方法有一些可怕的后果:

  • 为新子类添加单个特定案例需要您将其添加到子类和基类中
  • 如果您不将特定案例添加到基类中,它将不运行它。
  • 测试用例在开始时需要大量额外的“跳前检查”代码来确定它是否是有效的测试用例

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2015-09-23
    相关资源
    最近更新 更多