Replacement for test case inheritance in pytest?

假装没事ソ 提交于 2020-07-08 21:29:35

问题


Background

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)

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.

Problem

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?

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.


回答1:


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

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

  • class names must begin with Test
  • function/method names must begin with test_

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


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


来源:https://stackoverflow.com/questions/52044490/replacement-for-test-case-inheritance-in-pytest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!