Skip to content

Commit e716ebb

Browse files
committed
Add example of parameterized test
1 parent c126c0d commit e716ebb

File tree

5 files changed

+59
-0
lines changed

5 files changed

+59
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Parameterize
2+
3+
pytest tests can be parameterized so that it can be run on a list of input
4+
arguments and expected output.
5+
6+
7+
## What is it?
8+
9+
1. `fibonacci.py`: Python script that implements the Fibonacci function.
10+
1. `test_fib.py`: parameterized tests for the Fibonacci function.
11+
1. `pytest.ini`: pytest configuration file that defines a `slow` marker.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#!/usr/bin/env python
2+
3+
def fib(n):
4+
if n < 0:
5+
raise ValueError('fac argument must be positive')
6+
elif n < 2:
7+
return 1
8+
else:
9+
return fib(n - 1) + fib(n - 2)
10+
11+
12+
if __name__ == '__main__':
13+
from argparse import ArgumentParser
14+
arg_parser = ArgumentParser(description='compute fibonacci numbers')
15+
arg_parser.add_argument('n', type=int, default=5,
16+
help='maximum argument')
17+
options = arg_parser.parse_args()
18+
for i in range(options.n + 1):
19+
print(f'fib({i}) = {fib(i)}')
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[pytest]
2+
markers =
3+
slow: marks tests as slow (deselect with '-m "not slow"')
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from fibonacci import fib
2+
3+
import pytest
4+
5+
@pytest.mark.parametrize("n, expected", [
6+
(0, 1),
7+
(1, 1),
8+
(2, 2),
9+
(5, 8),
10+
])
11+
def test_fib(n, expected):
12+
assert fib(n) == expected
13+
14+
@pytest.mark.slow
15+
@pytest.mark.parametrize("n, expected", [
16+
(40, 165580141),
17+
(41, 267914296),
18+
(42, 433494437),
19+
])
20+
def test_fib_40(n, expected):
21+
assert fib(n) == expected
22+
23+
def test_fib_negative():
24+
with pytest.raises(ValueError):
25+
_ = fib(-1)

source-code/testing/PyTest/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ module provided by the Python standard library.
88
1. `Fixtures`: illustrates using fixtures with pytest.
99
1. `CustomMarkers`: illustrates using custom markers with pytest to
1010
selectively run tests.
11+
1. `Parametrize`: illustrates using parameterized tests.

0 commit comments

Comments
 (0)