From e94fe8175136e190bb29b937856dab3146ae852d Mon Sep 17 00:00:00 2001 From: Christoph Zwerschke Date: Sun, 4 Jun 2023 21:15:29 +0200 Subject: [PATCH] Include name in representation of nodes (#198) --- src/graphql/language/ast.py | 13 +++++++++++-- tests/language/test_ast.py | 29 ++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/graphql/language/ast.py b/src/graphql/language/ast.py index e57adb82..bbae00d2 100644 --- a/src/graphql/language/ast.py +++ b/src/graphql/language/ast.py @@ -359,8 +359,17 @@ def __init__(self, **kwargs: Any) -> None: def __repr__(self) -> str: """Get a simple representation of the node.""" - name, loc = self.__class__.__name__, getattr(self, "loc", None) - return f"{name} at {loc}" if loc else name + rep = self.__class__.__name__ + if isinstance(self, NameNode): + rep += f"({self.value!r})" + else: + name = getattr(self, "name", None) + if name: + rep += f"(name={name.value!r})" + loc = getattr(self, "loc", None) + if loc: + rep += f" at {loc}" + return rep def __eq__(self, other: Any) -> bool: """Test whether two nodes are equal (recursively).""" diff --git a/tests/language/test_ast.py b/tests/language/test_ast.py index 46619e40..76e8a66c 100644 --- a/tests/language/test_ast.py +++ b/tests/language/test_ast.py @@ -1,7 +1,8 @@ import weakref from copy import copy, deepcopy +from typing import Optional -from graphql.language import Location, Node, Source, Token, TokenKind +from graphql.language import Location, NameNode, Node, Source, Token, TokenKind from graphql.pyutils import inspect @@ -12,6 +13,13 @@ class SampleTestNode(Node): beta: int +class SampleNamedNode(Node): + __slots__ = "foo", "name" + + foo: str + name: Optional[str] + + def describe_token_class(): def initializes(): token = Token( @@ -160,6 +168,25 @@ def has_representation_with_loc(): node = SampleTestNode(alpha=1, beta=2, loc=3) assert repr(node) == "SampleTestNode at 3" + def has_representation_when_named(): + name_node = NameNode(value="baz") + node = SampleNamedNode(foo="bar", name=name_node) + assert repr(node) == "SampleNamedNode(name='baz')" + node = SampleNamedNode(alpha=1, beta=2, name=name_node, loc=3) + assert repr(node) == "SampleNamedNode(name='baz') at 3" + + def has_representation_when_named_but_name_is_none(): + node = SampleNamedNode(alpha=1, beta=2, name=None) + assert repr(node) == "SampleNamedNode" + node = SampleNamedNode(alpha=1, beta=2, name=None, loc=3) + assert repr(node) == "SampleNamedNode at 3" + + def has_special_representation_when_it_is_a_name_node(): + node = NameNode(value="foo") + assert repr(node) == "NameNode('foo')" + node = NameNode(value="foo", loc=3) + assert repr(node) == "NameNode('foo') at 3" + def can_check_equality(): node = SampleTestNode(alpha=1, beta=2) node2 = SampleTestNode(alpha=1, beta=2)