Skip to content

Instantly share code, notes, and snippets.

@bennylope
Created August 26, 2016 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennylope/fb4ddc66bbe1af75bfab53c0055d9371 to your computer and use it in GitHub Desktop.
Save bennylope/fb4ddc66bbe1af75bfab53c0055d9371 to your computer and use it in GitHub Desktop.
Assertion for ensuring that two values are close enough within a certain threshold, comparing on the percentage difference
class SomeTestMixin:
def assertCloseEnough(self, first, second, diff=0.0001):
"""
Asserts that the percentage difference between the two values
is smaller than given diff value.
Results may depend on the order of the values. A more robust
version might test the difference against both values.
Args:
first: original numerical argument
second: comparison numerical argument
diff: percentage difference allowed
Returns:
None
Raises:
AssertionError if the absolute % diff exceeds the diff threshold
"""
if abs((first - second) / first) > diff:
raise AssertionError("Difference between {f} and {s} is greater than {p}%".format(
f=first,
s=second,
p=diff * 100,
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment