Skip to content

Commit 4ec7c54

Browse files
committed
Add factorial example for hypothesis
1 parent 69090cf commit 4ec7c54

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Hypothesis
2+
3+
Examples of using `hypothesis`, a testing library that
4+
uses fuzzing to find issues in your code.
5+
6+
7+
## What is it?
8+
9+
1. `factorial.py`: implementatino of the factorial
10+
function.
11+
1. `test_factorial.py`: hypothesis tests of the factorial
12+
function
13+
14+
15+
## How to use it?
16+
17+
Run with pytest:
18+
```bash
19+
$ pytest --hypothesis-show-statistics
20+
```
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'''Module to compute the factorial of a number'''
2+
3+
4+
def fac(n: int) -> int:
5+
'''Return the factorial of n
6+
7+
Parameters
8+
----------
9+
n : int
10+
The number to compute the factorial of
11+
12+
Returns
13+
-------
14+
int
15+
The factorial of n
16+
17+
Raises
18+
------
19+
ValueError
20+
If n is negative
21+
'''
22+
if n < 0:
23+
raise ValueError("fac_iter() not defined for negative values")
24+
result = 1
25+
for i in range(n, 1, -1):
26+
result *= i
27+
return result
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from math import factorial as fac_math
2+
from hypothesis import assume, given, strategies as st
3+
from factorial import fac
4+
5+
6+
@given(st.integers(min_value=0, max_value=100))
7+
def test_fac_same(n):
8+
assert fac(n) == fac_math(n)
9+
10+
11+
@given(st.integers(max_value=-1))
12+
def test_fac_neg(n):
13+
try:
14+
assert fac(n) == fac_math(n)
15+
except ValueError:
16+
assert n < 0

0 commit comments

Comments
 (0)