简体   繁体   中英

Base test case class for python unittest

I have a pile of objects "implementing" the same "interface". There are a few common behaviors that they all should exhibit, and that I thus want to test for in all those classes.

I was thinking of having an abstract base test case with the common stuff that is then derived from by specific test cases. There is at least one abstract method in this base test class that is called from the base class itself and needs to be defined in derivatives. I'm not sure how to call the method defined in the derivative from the base class though. If I do self.abstract_method, it'll say the method is not defined. How can I call this method?

If there is a better way of achieving my test goals here that does not involve inheritance, I'd be happy to hear about it.

Using inheritance

import cPickle
import pickle
import unittest

class TestPickleBase:
    def test_dumps_loads(self):
        self.assertEqual(self.pickle_impl.loads(self.pickle_impl.dumps('a')), 'a')

class TestCPickle(unittest.TestCase, TestPickleBase):
    pickle_impl = cPickle

class TestPickle(unittest.TestCase, TestPickleBase):
    pickle_impl = pickle

if __name__ == '__main__':
    unittest.main()

Using pytest

import cPickle
import pickle

import pytest

@pytest.mark.parametrize('pickle_impl', [pickle, cPickle])
def test_dumps_loads(pickle_impl):
    assert pickle_impl.loads(pickle_impl.dumps('a')) == 'a'

import cPickle
import pickle

import pytest

@pytest.fixture(params=[pickle, cPickle])
def pickle_impl(request):
    return request.param

def test_dumps_loads(pickle_impl):
    assert pickle_impl.loads(pickle_impl.dumps('a')) == 'a'

You can define a blank version of the method in your abstract classes to avoid being told the method is not defined as so:

class AbstractClass(object):

    def abstract_method(self):
        pass

class ConcreteClass(AbstractClass):

    def abstract_method(self):
        # Insert logic here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM