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 :

def average(L):
    if not L:
        return None
    return sum(L)/len(L)

def test_average():
    test_cases = [
        {
            "name": "simple case 1",
            "input": [1, 2, 3],
            "expected": 2.0
        },
        {
            "name": "simple case 2",
            "input": [1, 2, 3, 4],
            "expected": 2.5
        },
        {
            "name": "list with one item",
            "input": [100],
            "expected": 100.0
        },
        {
            "name": "empty list",
            "input": [],
            "expected": None
        }
    ]

    for test_case in test_cases:
        assert test_case["expected"] == average(test_case["input"]), test_case["name"]


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. :)

Comments

Popular posts from this blog

Get next element from a list in Python

Convert text to ASCII and ASCII to text - Python code

Use Proxy in your Spider