Created
August 26, 2016 19:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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