Skip to content

Commit 114a0f3

Browse files
committed
Add example of finding a bug using fuzz testing
1 parent 636345e commit 114a0f3

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

source-code/testing/Hypothesis/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ uses fuzzing to find issues in your code.
1010
function.
1111
1. `test_factorial.py`: hypothesis tests of the factorial
1212
function
13+
1. `points.py`: example of finding a bug with fuzz testing.
1314

1415

1516
## How to use it?
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import math
2+
from hypothesis import given, strategies as st
3+
4+
5+
class Point:
6+
7+
_x: float
8+
_y: float
9+
10+
def __init__(self, x: float, y: float):
11+
self._x = float(x)
12+
self._y = float(y)
13+
14+
@property
15+
def x(self):
16+
return self._x
17+
18+
@x.setter
19+
def x(self, x):
20+
self._x = float(x)
21+
22+
@property
23+
def y(self):
24+
return self._y
25+
26+
@y.setter
27+
def y(self, y):
28+
self._y = float(y)
29+
30+
def __repr__(self):
31+
return f'Point({self._x}, {self._y})'
32+
33+
def __str__(self):
34+
return f'({self._x}, {self._y})'
35+
36+
def distance(self, other):
37+
return math.sqrt((self._x - other._x)**2 + (self._y - other._y)**2)
38+
39+
def is_on_line(self, p1, p2):
40+
return math.isclose(self.y - ((p2.y - p1.y)*self.x - p1.x*p2.y + p2.x*p1.y)/(p2.x - p1.x), 0.0)
41+
42+
43+
def test_distance():
44+
p1 = Point(0, 0)
45+
p2 = Point(3, 4)
46+
assert math.isclose(p1.distance(p2), 5.0)
47+
48+
49+
@given(x1=st.floats(), y1=st.floats(), x2=st.floats(), y2=st.floats(), x=st.floats(), y=st.floats())
50+
def test_is_on_line(x1: float, y1: float, x2: float, y2: float, x: float, y: float):
51+
p1 = Point(x1, y1)
52+
p2 = Point(x2, y2)
53+
p = Point(x, y)
54+
assert p.is_on_line(p1, p2)

0 commit comments

Comments
 (0)