替换pytest中的测试用例继承? [英] Replacement for test case inheritance in pytest?

查看:104
本文介绍了替换pytest中的测试用例继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 的 unittest 框架中,它是一个相当常见的习惯用法,它在一组基本测试上使用继承来将一整套测试应用于新问题,偶尔会添加额外的测试.一个简单的例子是:

In Python's unittest framework, it is a fairly common idiom to use inheritance on a base set of tests to apply an entire set of tests to a new problem, and occasionally to add additional tests. A trivial example would be:

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)

运行时,运行 3 个测试:

Which, when run, runs 3 tests:

$ 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

这在您测试类层次结构时特别有用,其中每个子类是一个 父类的子类型,因此除了它自己的测试套件之外,还应该能够通过父类的测试套件.

This is particularly useful if you are testing a class hierarchy, where each subclass is a subtype of the parent classes, and should thus be able to pass the parent class's test suite in addition to its own.

我想改用pytest,但我有很多测试都是以这种方式构建的.据我所知,pytest 打算用fixtures 替换TestCase 类的大部分功能,但是是否有允许测试继承的pytest 惯用语,如果那是什么?

I would like to switch over to using pytest, but I have a lot of tests that are structured this way. From what I can tell, pytest intends to replace most of the functionality of TestCase classes with fixtures, but is there a pytest idiom that allows test inheritance, and if so what is it?

我知道 pytest 可用于运行 unittest 样式的测试,但是 支持有限,我想使用一些永远不会被支持"的pytest 在我的测试中的特性.

I am aware that pytest can be used to run unittest-style tests, but the support is limited, and I would like to use some of the "will never be supported" features of pytest in my tests.

推荐答案

Pytest 允许你将测试用例分组到类中,所以它自然支持测试用例继承.

Pytest allows you to group test cases in classes, so it naturally has support for test case inheritance.

将您的 unittest 测试重写为 pytest 测试时,请记住遵循 pytest 的命名指南:

When rewriting your unittest tests to pytest tests, remember to follow pytest's naming guidelines:

  • 类名必须以Test
  • 开头
  • 函数/方法名称必须以 test_
  • 开头

不遵守此命名方案将阻止您的测试被收集和执行.

Failing to comply with this naming scheme will prevent your tests from being collected and executed.

您为 pytest 重写的测试如下所示:

Your tests rewritten for pytest would look like this:

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

这篇关于替换pytest中的测试用例继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆