I am developing multiple functions that answer a same problem but using different algorithm.
So the same input for all functions should generate the same output, that's why I wnted to use the same unit tests instead of having to create multiple tests with the same logic.
I was using the Python unittest framework, and I wanted to use an abstract test class to have the generic tests defined with a function variable so that I could just instantiate that generic function with the one I want to test in another normal test class. But it seems I can't instantiate the function variable in the child class.
So here is an example abstract class with generic tests for multiple functions.
class AbstractTestCase():
def test_generic_input_one(self):
result = self.function("input 1")
self.assertFalse(result)
def test_generic_input_two(self):
result = self.function("input 2")
self.assertTrue(result)
And here you would have a specific test class for the function_a
that inherits the generic tests from the AbstractTestCase
class and that implements its own.
class TestsFunctionA(AbstractTestCase, unittest.TestCase):
def setUp(self):
self.function = function_a
def test_specific_input(self):
result = self.assertTrue(self.function("specific input"))
self.assertTrue(result)
I am pretty sure it can be done, but I can't seem to find an example to see how to implement it. I would like to avoid code duplication.
What should be the simplest and best way to do it ?
Every behavior should be covered by a unit test, but every method doesn't need its own unit test. Many developers don't test get and set methods, because a method that does nothing but get or set an attribute value is so simple that it is considered immune to failure.
If you're using PyCharm IDE, you can simply press ctrl+shift+F10 to run unittest module. Otherwise you can use command prompt to run this module. For example, we named the file for unit-testing as Basic_Test.py . So the command to run python unittest will be: $python3.
By default, unittest-parallel runs unit tests on all CPU cores available.
I have been looking for it and got a couple of example like:
But what helped me the most was vegard's answer about making a class factory which would take parameters and create the TestCase accordingly
The function takes the parameters of the parameterised test case and the actual TestCase class can refer to them without any problems.
Here is an example, take a foo.py
file with:
import unittest
def make_test_case(x):
class MyTestCase(unittest.TestCase):
def test_foo(self):
self.assertEquals(x, 1)
return MyTestCase
class ConcreteTestCase(make_test_case(1)):
pass
Then run the test(s):
python -m unittest -v foo
Basically this is very flexible and adapted really well to my usecase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With