0

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)
Felix
  • 2,548
  • 19
  • 48
  • You can trying using ```Hypothesis```, a unit testing library that integrates with ```unittest``` and allows you specify parameters. – Michael Bianconi Jul 01 '19 at 12:37
  • @MichaelBianconi Thank you! It looks good, and the `unittest.TestCase.subTest` solution provided in the duplicate question seems quite usable too. – Felix Jul 01 '19 at 13:13

1 Answers1

0

possible duplicate of How do you generate dynamic (parameterized) unit tests in python?

or at least that question may have some answers, I believe the parametrize module is what you're after for verbosity in test results

bain2236
  • 111
  • 1
  • 9
  • I see, and agree. Thanks for the link! Let's vote this down as a duplicate then instead, shall we? – Felix Jul 01 '19 at 12:50