Skip to content

Instantly share code, notes, and snippets.

@secemp9
Created August 7, 2024 09:12
Show Gist options
  • Save secemp9/a9fc1f38a3324d988850a17d6920573e to your computer and use it in GitHub Desktop.
Save secemp9/a9fc1f38a3324d988850a17d6920573e to your computer and use it in GitHub Desktop.
Verbose assertion
import ast
import astor
# Sample Python code with assert statements outside a function
code = """
x = 5
assert x == 5
assert x < 3
assert x > 0
"""
# Parse the code into an AST
parsed_code = ast.parse(code)
class AssertVisitor(ast.NodeVisitor):
def __init__(self, code):
# Extract the code without assert statements to initialize the namespace
self.code_without_asserts = self.remove_asserts(code)
self.namespace = {}
exec(compile(self.code_without_asserts, '<string>', 'exec'), self.namespace)
super().__init__()
def remove_asserts(self, code):
"""Remove assert statements from the given code."""
lines = code.split('\n')
non_assert_lines = [line for line in lines if not line.strip().startswith('assert')]
return '\n'.join(non_assert_lines)
def visit_Assert(self, node):
# Extract the condition
condition = astor.to_source(node.test).strip()
# Evaluate the condition and catch AssertionError
try:
condition_result = eval(condition, self.namespace)
if condition_result:
status = "PASS"
else:
raise AssertionError("Assertion failed")
except AssertionError:
status = "FAIL"
# Print the result
print(f"Assertion: {condition}", f"Status: {status}")
# Continue to the next node
self.generic_visit(node)
if __name__ == "__main__":
# Create a visitor and visit the parsed code
visitor = AssertVisitor(code)
visitor.visit(parsed_code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment