Another Solution: test more exceptions
def fib(n):
var_type = type(n).__name__
if var_type != 'int':
raise ValueError(f'Invalid value type of "{n}" is "{var_type}"')
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 value type of "3.5" is "float"'
def test_fib_small_floating_point():
with pytest.raises(ValueError) as err:
fib(0.5)
assert str(err.value) == 'Invalid value type of "0.5" is "float"'
def test_fib_big_floating_point():
with pytest.raises(ValueError) as err:
fib(3.0)
assert str(err.value) == 'Invalid value type of "3.0" is "float"'
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 6 items
test_fibonacci.py ...... [100%]
============================== 6 passed in 0.04s ===============================