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

Solution: test more exceptions

def fib(n):
    if int(n) != n:
        raise ValueError(f'Invalid parameter {n} is not an integer')
    if n < 1:
        raise ValueError(f'Invalid parameter {n} is negative')
    a, b = 1, 1
    for _ in range(1, n):
        a, b = b, a+b
    return a

import pytest
from fibonacci import fib

def test_fib():
    assert fib(10) == 55

def test_fib_negative():
    with pytest.raises(Exception) as err:
        fib(-1)
    assert err.type == ValueError
    assert str(err.value) == 'Invalid parameter -1 is negative'

def test_fib_negative_again():
    with pytest.raises(ValueError) as err:
        fib(-1)
    assert str(err.value) == 'Invalid parameter -1 is negative'

def test_fib_floating_point():
    with pytest.raises(ValueError) as err:
        fib(3.5)
    assert str(err.value) == 'Invalid parameter 3.5 is not an integer'

def test_fib_small_floating_point():
    with pytest.raises(ValueError) as err:
        fib(0.5)
    assert str(err.value) == 'Invalid parameter 0.5 is not an integer'

Output:

============================= test session starts ==============================
platform linux -- Python 3.13.7, pytest-9.0.2, pluggy-1.6.0
rootdir: /home/gabor/github/code-maven.com/python.code-maven.com
configfile: pyproject.toml
plugins: anyio-4.12.0, cov-7.0.0
collected 5 items

test_fibonacci.py .....                                                  [100%]

============================== 5 passed in 0.07s ===============================