python - How to unittest multiple similar classes -


i have program multiple similar classes:

class blackbox1():     def calc(self, a, b):         return + b  class blackbox2():     def calc(self, a, b):         return * b ... 

now want write unittests classes. of course write separate tests each blackbox. anyway, since each blackbox has same method calc(a, b) tested, wonder, if there “best practise”, automatically give classes , expected results abstract test framework, like

import unittest class testabstractbox(unittest.testcase):     def setup(self):         self.box = blackbox()         self.param_a =         self.param_b = b         self.expected_result = result      def test_calc_method(self):         real_result = self.box.calc(self.param_a, self.param_b)         self.assertequal(real_result, self.expected_result,                          "{0} gives wrong result".format(self.box.__class__))  tabstracttest = unittest.defaulttestloader.loadtestsfromtestcase(testabstractbox) 

is there way pass {"blackbox": blackbox1, "a": 3, "b": 5, "result": 8} , {"blackbox": blackbox2, "a": 4, "b": 7, "result": 28} testabstractbox class not have multiple times same code, have easy way test new blackboxes?

you can add these classes setup:

class testabstractbox(unittest.testcase):   def setup(self):     self.boxes = [blackbox1(), blackbox2()]     self.param_a =     self.param_b = b     self.expected_result = result    def test_calc_method(self):     box in self.boxes:       real_result = self.box.calc(self.param_a, self.param_b)       self.assertequal(real_result, self.expected_result,            "{0} gives wrong result".format(self.box.__class__)) 

edit version 2:

class testabstractbox(unittest.testcase):   def setup(self):     self.boxes = [       { "blackbox":blackbox1(), "a":a1, "b":b1, "expected_result":result1 },       { "blackbox":blackbox2(), "a":a2, "b":b2, "expected_result":result2 },     ]    def test_calc_method(self):     box in self.boxes:       real_result = box["blackbox"].calc(box["a"], box["b"])       self.assertequal(real_result, box["expected_result"],            "{0} gives wrong result".format(box["blackbox"].__class__)) 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -