neverendingqs
neverendingqs

Reputation: 4286

Does Python provide ways to run the same unit test with multiple test inputs?

With C# and NUnit, there exists the TestCase attribute and the TestCaseSource attribute, both of which allows unit tests to be parameterized, so that the same "test" can be used multiple times with different input. This reduces code duplication while maintaining readability.

Does something similar exist for Python?

EDIT: @Dunes mentioned subtests, which I should have included as part of this question. Unfortunately, it is a 3.4 only functionality, and I'm looking to support 2.7 and 3.4.

Upvotes: 2

Views: 913

Answers (2)

M. K. Hunter
M. K. Hunter

Reputation: 1828

Several libraries will allow you to do this. For example, the py.test example is as follows:

import pytest
@pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8),
    ("2+4", 6),
    ("6*9", 42),
])

def test_eval(test_input, expected):
    assert eval(test_input) == expected

This is from the py.test documentation.

Upvotes: 0

Dunes
Dunes

Reputation: 40853

The answer is subTest. However, this is only available as of Python 3.4.

There is unittest2, though. It provides a backport of the latest features of unittest in Python 3.4 (including subTest). unittest2 is tested to run on Python 2.6, 2.7, 3.2, 3.3, 3.4 and pypy.

Upvotes: 2

Related Questions