Skip to content

Commit

Permalink
Add hypothesis testing
Browse files Browse the repository at this point in the history
  • Loading branch information
abhidg committed Aug 25, 2024
1 parent 242529d commit 4f5fd02
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pandas==2.*
requests==2.*
pytest
pytest
hypothesis==6.*
40 changes: 40 additions & 0 deletions tests/test_hypothesis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
Property based testing
Testing module using hypothesis
"""
from hypothesis import given, reject, settings
from hypothesis.strategies import floats, integers

from sunblock import fahrenheit_to_celsius

# In property based testing, we encode assumptions or properties of the
# system that should always be true, regardless of parameter values a
# function takes. Often this reveals edge cases that are not handled in
# the code, which might not have been caught by example-based testing if
# our list of examples was not exhaustive enough.

# Here we check that no matter what temperature in degrees fahrenheit we
# are given, we never return a value less than absolute zero (0 K) which
# is equivalent to -273.15 degrees celsius.

@given(floats())
def test_fahrenheit_to_celsius(temp):
try:
assert fahrenheit_to_celsius(temp) > -273.15 # absolute zero
except ValueError:
reject()

# hypothesis can also be used to intentionally find counter-examples
# here we are trying to find an example where the numerical values of a
# temperature in celsius and fahrenheit are the same.

# This should fail as there is a counterexample (-40 F = -40 C) but
# hypothesis may not find it. Try increasing the max_examples setting to
# make hypothesis stumble upon the correct answer!
@given(integers(min_value=-450))
@settings(max_examples=100)
def test_fahrenheit_differs_from_celsius(temp):
try:
assert fahrenheit_to_celsius(temp) != temp
except ValueError:
reject()

0 comments on commit 4f5fd02

Please sign in to comment.