Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exercise: parametrize the tests of the math functions

In this example we have several test cases in each test function. That means if one of the assertions fail the whole function fails and we don’t know what would be the result of the other test assertions.

import math

def test_gcd():
    assert math.gcd(6, 9) == 3
    assert math.gcd(17, 9) == 1

def test_ceil():
    assert math.ceil(0) == 0
    assert math.ceil(0.1) == 1
    assert math.ceil(-0.1) == 0

def test_factorial():
    assert math.factorial(0) == 1
    assert math.factorial(1) == 1
    assert math.factorial(2) == 2
    assert math.factorial(3) == 6

We could split up the test cases to several test functions along this example:

import math

def test_gcd_6_9():
    assert math.gcd(6, 9) == 3

def test_gcd_17_9():
    assert math.gcd(17, 9) == 1

def test_ceil_0():
    assert math.ceil(0) == 0

def test_ceil_0_1():
    assert math.ceil(0.1) == 1

def test_ceil__0_1():
    assert math.ceil(-0.1) == 0

def test_factorial_0():
    assert math.factorial(0) == 1

def test_factorial_1():
    assert math.factorial(1) == 1

def test_factorial_2():
    assert math.factorial(2) == 2

def test_factorial_3():
    assert math.factorial(3) == 6