pythonunit-testingpython-unittestmultiple-input

Python unit testing multiple inputs


This is a generic question geared towards unit testing specifically in Python. Is it acceptable to place 20 or some number of inputs to test in a dictionary as keys, where the values are the expected result output from the function?

I can't find an answer after scouring the internet. Almost everything I read were toy examples like adding numbers to obtain a sum or concatenating a first and last name. The following is another toyish example to describe my question in a simple way.

import unittest
import some_module

class SomeModuleUnitTest(unittest.TestCase):

    def test_some_function(self):

        input_output_dict = {
            1: 1,
            2: 4,
            3: 9,
            4: 16,
            5: 25,
            6: 36,
            7: 49,
              .
              .
              .

            20: 400
        }

        for input_case, output_expected in input_output_dict.items():
            output_actual = some_module.some_function(input_case)
            self.assertEqual(output_expected, output_actual)

If this is considered archaic, what would be the Pythonic solution for testing multiple inputs?


Solution

  • Ok, I will have a go. Trying to answer the explicit and implicit questions that I see here.

    Is it pythonic? If that is the data you have, then putting it in a dictionary is certainly ok. If it gets very large, you could consider reading it from a file, but this is probably not needed in this case.

    Is this the best way to test multiple inputs?.
    No, there are possibilities to use test parametrization in test frameworks that provide output that is better organized than in your example. The most commonly used is probably the pytest.mark.parametrize decorator in pytest.

    Do you need that much different input in your test?
    That depends on your functionality. If each of the inputs represents a different scenario, certainly yes. If they represent the same scenario, you may think of typical and edge cases, but usually you won't need many different inputs.