Skip to content

Commit

Permalink
Include name in representation of nodes (#198)
Browse files Browse the repository at this point in the history
  • Loading branch information
Cito committed Jun 4, 2023
1 parent 1a62f30 commit e94fe81
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
13 changes: 11 additions & 2 deletions src/graphql/language/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""
Expand Down
29 changes: 28 additions & 1 deletion tests/language/test_ast.py
Original file line number Diff line number Diff line change
@@ -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


Expand All @@ -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(
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit e94fe81

Please sign in to comment.