替换pytest中的测试用例继承?
Replacement for test case inheritance in pytest?
背景
在 Python 的 unittest
框架中,在一组基本测试上使用继承以将整组测试应用于新问题是一种相当常见的习惯用法,偶尔添加额外的测试。一个简单的例子是:
from unittest import TestCase
class BaseTestCase(TestCase):
VAR = 3
def test_var_positive(self):
self.assertGreaterEqual(self.VAR, 0)
class SubTestCase(BaseTestCase):
VAR = 8
def test_var_even(self):
self.assertTrue(self.VAR % 2 == 0)
其中,当 运行、运行s 3 次测试时:
$ python -m unittest -v
test_var_positive (test_unittest.BaseTestCase) ... ok
test_var_even (test_unittest.SubTestCase) ... ok
test_var_positive (test_unittest.SubTestCase) ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
如果您正在测试 class 层次结构,这将特别有用,其中父 classes 的每个子class is a 子类型,因此应该能够除了自己的测试套件之外,还要通过父级 class 的测试套件。
问题
我想改用 pytest
,但我有很多测试都是这样构建的。据我所知,pytest
打算用 fixtures 替换 TestCase
classes 的大部分功能,但是 是否有允许测试继承的 pytest idiom,并且如果是的话是什么?
我知道 pytest
可以用于 运行 unittest
式测试,但是 the support is limited,我想使用一些“will在我的测试中永远不会支持 pytest
的功能。
Pytest 允许您将测试用例分组在 classes 中,因此它自然支持测试用例继承。
将 unittest
测试重写为 pytest
测试时,请记住遵循 pytest's naming guidelines:
- class 名称必须以
Test
开头
- function/method 名称必须以
test_
开头
不遵守此命名方案将阻止您的测试被收集和执行。
为 pytest 重写的测试将如下所示:
class TestBase:
VAR = 3
def test_var_positive(self):
assert self.VAR >= 0
class TestSub(TestBase):
VAR = 8
def test_var_even(self):
assert self.VAR % 2 == 0
背景
在 Python 的 unittest
框架中,在一组基本测试上使用继承以将整组测试应用于新问题是一种相当常见的习惯用法,偶尔添加额外的测试。一个简单的例子是:
from unittest import TestCase
class BaseTestCase(TestCase):
VAR = 3
def test_var_positive(self):
self.assertGreaterEqual(self.VAR, 0)
class SubTestCase(BaseTestCase):
VAR = 8
def test_var_even(self):
self.assertTrue(self.VAR % 2 == 0)
其中,当 运行、运行s 3 次测试时:
$ python -m unittest -v
test_var_positive (test_unittest.BaseTestCase) ... ok
test_var_even (test_unittest.SubTestCase) ... ok
test_var_positive (test_unittest.SubTestCase) ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.000s
如果您正在测试 class 层次结构,这将特别有用,其中父 classes 的每个子class is a 子类型,因此应该能够除了自己的测试套件之外,还要通过父级 class 的测试套件。
问题
我想改用 pytest
,但我有很多测试都是这样构建的。据我所知,pytest
打算用 fixtures 替换 TestCase
classes 的大部分功能,但是 是否有允许测试继承的 pytest idiom,并且如果是的话是什么?
我知道 pytest
可以用于 运行 unittest
式测试,但是 the support is limited,我想使用一些“will在我的测试中永远不会支持 pytest
的功能。
Pytest 允许您将测试用例分组在 classes 中,因此它自然支持测试用例继承。
将 unittest
测试重写为 pytest
测试时,请记住遵循 pytest's naming guidelines:
- class 名称必须以
Test
开头
- function/method 名称必须以
test_
开头
不遵守此命名方案将阻止您的测试被收集和执行。
为 pytest 重写的测试将如下所示:
class TestBase:
VAR = 3
def test_var_positive(self):
assert self.VAR >= 0
class TestSub(TestBase):
VAR = 8
def test_var_even(self):
assert self.VAR % 2 == 0