Python Package parameterized

Stackoverflowing around I found this nice package

https://github.com/wolever/parameterized

Parameterized testing in Python sucks.

parameterized fixes that. For everything. Parameterized testing for nose, parameterized testing for py.test, parameterized testing for unittest.

Reading this description I had very high expectations 🙂

so let’s see if the package can hold up to it.

Installation

Nothing special here just:

pip install parameterized

Parameterized Tests

You can use the package in three situations, to parameterize

  • test functions
  • test methods
  • test classes

Parameterized test methods

The first thing you definitely need is parameterization of test methods in a unitttest class. parameterized can do that trick and it looks quite neat:

from parameterized import parameterized

class TestMean(unittest.TestCase):

    @parameterized.expand([
        # name               data             expected_mean
        ("positive_integer", [1, 2, 3, 4, 5], 3),
        ("negative_integer", [-1, -2, -3, -4, -5], -3),
    ])
    def test_calculate_mean(self, name, data, expected_mean):
        sum = 0
        for d in data:
            sum += int(d)
            mean = sum / len(data)
            self.assertEqual(expected_mean, mean)

It uses a decorator @parameterized.expand and the cool things is that you can give a name for every scenario so when you run the tests with pytest you get

test_parameterized.py::TestMean::test_calculate_mean_0_positive_integer PASSED
test_parameterized.py::TestMean::test_calculate_mean_1_negative_integer PASSED

pytest can do something similar but you have to provide a string containing the names of the corresponding function parameters, that is a bit akward and can break, if you e.g. rename the parameter

import pytest

@pytest.mark.parametrize(
    "data, expected_mean",
    [
     ([1, 2, 3, 4, 5], 3),
     ([-1, -2, -3, -4, -5], -3)
     ],
)
def test_calculate_mean(data, expected_mean):
    sum = 0
    for d in data:
        sum += int(d)
    mean = sum / len(data)
    assert expected_mean == mean