Home > Blockchain >  Inheritance with python unittest
Inheritance with python unittest

Time:10-28

I have two unittest classes in the same file which look like this:

class A(unittest.TestCase):
    def some_fun(param):
        # Set class parameters
        self.foo = param   100
        ...
    def some_fun2():
        do_something with self.foo
        self.assertEqual(self.foo,<check>)
    def some_fun3():
        do_something 

    def setUp(self):
        some_fun(some_foo1)

    def test1(self):
        some_fun2(some_foo1)

    def tearDown(self):
        some_fun3(some_foo1)

class B(unittest.TestCase):
    def some_fun(param):
        # Set class parameters
        self.foo = param   100
        ...
    def some_fun2():
        do_something with self.foo
        self.assertEqual(self.foo,<check>)
    def some_fun3():
        do_something 

    def setUp(self):
        some_fun(some_foo1)

    def test1(self):
        some_fun2(some_foo1)

    def tearDown(self):
        some_fun3(some_foo1)



I want to move some_fun, some_fun2, some_fun3 outside to reduce code repetition keeping in mind that these functions can have assert checks

What is the best way to do this? Im not sure how to do inheritance in this scenario

Edit: I am facing this weird issue

class X(unittest.TestCase):
    def __init__(self, foo):
        print(foo) # why is foo=somefun
    def test():
        <something>

class A(X):
    FOO = "SOMESTRING"

    def setUp(self):
        super().__init__(A.FOO)

    def somefun(self):
        self.test()

CodePudding user response:

Inheritance rules apply normally here. Create a base class with the methods you want that inherits from TestCase:

class BaseTest(unittest.TestCase):
    def some_fun(self):
        ...

    def some_fun2(self):
        ...

Create A and B inheriting from BaseTest:

class A(BaseTest):
    def test1(self):
        ...

class B(BaseTest):
    def test2(self):
        ...

CodePudding user response:

It can be like this:

class X(unittest.TestCase):

    def some_fun(self, param):
        # Set class parameters
        self.foo = param   100
        ...
    def some_fun2(self):
        do_something with self.foo
        self.assertEqual(self.foo,<check>)
    def some_fun3():
        do_something

class A(X):
    
    def setUp(self):
        self.some_fun(some_foo1)

    def test1(self):
        self.some_fun2(some_foo1)

    def tearDown(self):
        self.some_fun3(some_foo1)

class B(X):
    
    def setUp(self):
        self.some_fun(some_foo1)

    def test1(self):
        self.some_fun2(some_foo1)

    def tearDown(self):
        self.some_fun3(some_foo1)

  • Related