Skip to content

Commit 6d6dda7

Browse files
committed
Add tests for is_close_to_zero()
We also add hypothesis as a test dependency. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 8585373 commit 6d6dda7

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ dev-pytest = [
8484
"pytest-mock == 3.14.0",
8585
"pytest-asyncio == 0.23.7",
8686
"async-solipsism == 0.6",
87+
"hypothesis == 6.103.2",
8788
]
8889
dev = [
8990
"frequenz-core[dev-mkdocs,dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]",

tests/test_math.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# License: MIT
2+
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3+
4+
"""Tests for the math module."""
5+
6+
from hypothesis import given
7+
from hypothesis import strategies as st
8+
9+
from frequenz.core.math import is_close_to_zero
10+
11+
# We first do some regular test cases to avoid mistakes using hypothesis and having
12+
# basic cases not working.
13+
14+
15+
def test_is_close_to_zero_default_tolerance() -> None:
16+
"""Test the is_close_to_zero function with the default tolerance."""
17+
assert is_close_to_zero(0.0)
18+
assert is_close_to_zero(1e-10)
19+
assert not is_close_to_zero(1e-8)
20+
21+
22+
def test_is_close_to_zero_custom_tolerance() -> None:
23+
"""Test the is_close_to_zero function with a custom tolerance."""
24+
assert is_close_to_zero(0.0, abs_tol=1e-8)
25+
assert is_close_to_zero(1e-8, abs_tol=1e-8)
26+
assert not is_close_to_zero(1e-7, abs_tol=1e-8)
27+
28+
29+
def test_is_close_to_zero_negative_values() -> None:
30+
"""Test the is_close_to_zero function with negative values."""
31+
assert is_close_to_zero(-1e-10)
32+
assert not is_close_to_zero(-1e-8)
33+
34+
35+
@given(st.floats(allow_nan=False, allow_infinity=False))
36+
def test_is_close_to_zero_default_tolerance_hypothesis(value: float) -> None:
37+
"""Test the is_close_to_zero function with the default tolerance for many values."""
38+
if -1e-9 <= value <= 1e-9:
39+
assert is_close_to_zero(value)
40+
else:
41+
assert not is_close_to_zero(value)
42+
43+
44+
@given(
45+
st.floats(allow_nan=False, allow_infinity=False),
46+
st.floats(allow_nan=False, allow_infinity=False, min_value=0.0, max_value=2.0),
47+
)
48+
def test_is_close_to_zero_custom_tolerance_hypothesis(
49+
value: float, abs_tol: float
50+
) -> None:
51+
"""Test the is_close_to_zero function with a custom tolerance with many values/tolerance."""
52+
if -abs_tol <= value <= abs_tol:
53+
assert is_close_to_zero(value, abs_tol=abs_tol)
54+
else:
55+
assert not is_close_to_zero(value, abs_tol=abs_tol)

0 commit comments

Comments
 (0)