I'm looking for a way to parameterise unit tests for those cases that an input and its results change, but writing another test feels too tedious.
Suppose the str.isalnum
function is under test. One could write a case for every character.
class TestIsalnum(unittest.TestCase):
def test_a(self):
self.assertTrue('a'.isalnum())
def test_dot(self):
self.assertFalse('.'.isalnum())
def test_comma(self):
self.assertFalse(','.isalnum())
There should be an easier way. Lo and behold: there is, with this well-named function below designed to not get recognised by the automatic execution of tests when using unittest.main()
.
class TestIsalnum(unittest.TestCase):
def tessst_with_params(self, char: str, value: bool):
self.assertEqual(char.isalnum(), value)
def test_not_alphanumerics(self):
chars = '.,_;*!'
for char in chars:
self.tessst_with_params(char, False)
All is well and the test is passed. But it's considered to be one test. Intuitively each call should be its own test case. Additionally, if one case fails, ones after are not executed and the traceback contains very little information.
Is there an established way of writing such tests? If not, how should these kinds of tests be implemented?
Having the functions on one line is a bit more concise, but I'm not sure about the style and elegance.
def test_dot(self): self.tessst_with_params('.', False)
def test_comma(self): self.tessst_with_params(',', False)