| 1 |
import ast |
| 2 |
|
| 3 |
class ASTTestMixin: |
| 4 |
"""Test mixing to have basic assertions for AST nodes.""" |
| 5 |
|
| 6 |
def assertASTEqual(self, ast1, ast2): |
| 7 |
# Ensure the comparisons start at an AST node |
| 8 |
self.assertIsInstance(ast1, ast.AST) |
| 9 |
self.assertIsInstance(ast2, ast.AST) |
| 10 |
|
| 11 |
# An AST comparison routine modeled after ast.dump(), but |
| 12 |
# instead of string building, it traverses the two trees |
| 13 |
# in lock-step. |
| 14 |
def traverse_compare(a, b, missing=object()): |
| 15 |
if type(a) is not type(b): |
| 16 |
self.fail(f"{type(a)!r} is not {type(b)!r}") |
| 17 |
if isinstance(a, ast.AST): |
| 18 |
for field in a._fields: |
| 19 |
if isinstance(a, ast.Constant) and field == "kind": |
| 20 |
# Skip the 'kind' field for ast.Constant |
| 21 |
continue |
| 22 |
value1 = getattr(a, field, missing) |
| 23 |
value2 = getattr(b, field, missing) |
| 24 |
# Singletons are equal by definition, so further |
| 25 |
# testing can be skipped. |
| 26 |
if value1 is not value2: |
| 27 |
traverse_compare(value1, value2) |
| 28 |
elif isinstance(a, list): |
| 29 |
try: |
| 30 |
for node1, node2 in zip(a, b, strict=True): |
| 31 |
traverse_compare(node1, node2) |
| 32 |
except ValueError: |
| 33 |
# Attempt a "pretty" error ala assertSequenceEqual() |
| 34 |
len1 = len(a) |
| 35 |
len2 = len(b) |
| 36 |
if len1 > len2: |
| 37 |
what = "First" |
| 38 |
diff = len1 - len2 |
| 39 |
else: |
| 40 |
what = "Second" |
| 41 |
diff = len2 - len1 |
| 42 |
msg = f"{what} list contains {diff} additional elements." |
| 43 |
raise self.failureException(msg) from None |
| 44 |
elif a != b: |
| 45 |
self.fail(f"{a!r} != {b!r}") |
| 46 |
traverse_compare(ast1, ast2) |