Python Table Driven Unit Test in Python
Now days, table driven tests are pretty much industry standard. In my workplace, we use table driven tests when we write unit tests (in golang though). Here I shall share a simple code example using pytest that shows how to write table driven tests in Python.
In table driven test, what you need to do is, to gather all the tests cases together in a single table. We can use dictionary for each test case and a list to store all the test cases. Instead of discussing it further, let me show you an example :
1 | def average(L):<br /> if not L:<br /> return None<br /> return sum(L)/len(L)<br /><br />def test_average():<br /> test_cases = [<br /> {<br /> "name": "simple case 1",<br /> "input": [1, 2, 3],<br /> "expected": 2.0<br /> },<br /> {<br /> "name": "simple case 2",<br /> "input": [1, 2, 3, 4],<br /> "expected": 2.5<br /> },<br /> {<br /> "name": "list with one item",<br /> "input": [100],<br /> "expected": 100.0<br /> },<br /> {<br /> "name": "empty list",<br /> "input": [],<br /> "expected": None<br /> }<br /> ]<br /><br /> for test_case in test_cases:<br /> assert test_case["expected"] == average(test_case["input"]), test_case["name"]<br /><br /><br /> |
Now if you run the test, you will get the following output :
$ pytest average.py
==================== test session starts =====================
platform darwin — Python 3.5.1, pytest-3.0.3, py-1.4.31, pluggy-0.4.0
rootdir: /Users/tamimshahriar/…, inifile:
collected 1 items
average.py .
================== 1 passed in 0.01 seconds ==================
Hope you will find this post useful and use table driven tests. :)