Created
September 18, 2020 15:11
-
-
Save bmritz/28970a54e59efcfa74da7e8146a57498 to your computer and use it in GitHub Desktop.
Make several assertions and surface meaningful AssertionError messages for every one that fails
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
import inspect | |
import re | |
regex = 'assert_true[(]((.|\s)*)[)]' | |
class MultiAssert: | |
def __init__(self): | |
self.checks = [] | |
@staticmethod | |
def _get_string_for_boolean(boolean): | |
previous_frame = inspect.currentframe().f_back.f_back | |
(_, _, _, lines, _) = inspect.getframeinfo(previous_frame) | |
s = ''.join(lines) | |
arg_text = re.search(regex, s).groups()[0] | |
return arg_text | |
def assert_true(self, boolean): | |
s = self._get_string_for_boolean(boolean) | |
d = {"text": s, "result": boolean} | |
self.checks.append(d) | |
def raise_if_any_failed(self): | |
failures = [d['text'] for d in self.checks if not d['result']] | |
if failures: | |
txt = "The following checks failed:\n" + "\n".join(failures) | |
raise AssertionError(txt) | |
def test(): | |
a = MultiAssert() | |
xx = 3 | |
a.assert_true(True) | |
a.assert_true(False) | |
a.assert_true(False and True) | |
a.assert_true(1 == 1) | |
a.assert_true(1 == 5) | |
a.assert_true(xx == 9) | |
a.raise_if_any_failed() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment