Skip to content

Verify nodes' str() and repr() don't raise errors/warnings #2198

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions astroid/nodes/node_ng.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def __str__(self) -> str:
alignment = len(cname) + 1
result = []
for field in self._other_fields + self._astroid_fields:
value = getattr(self, field)
value = getattr(self, field, "Unknown")
width = 80 - len(field) - alignment
lines = pprint.pformat(value, indent=2, width=width).splitlines(True)

Expand All @@ -227,14 +227,19 @@ def __str__(self) -> str:

def __repr__(self) -> str:
rname = self.repr_name()
# The dependencies used to calculate fromlineno (if not cached) may not exist at the time
try:
lineno = self.fromlineno
except AttributeError:
lineno = 0
if rname:
string = "<%(cname)s.%(rname)s l.%(lineno)s at 0x%(id)x>"
else:
string = "<%(cname)s l.%(lineno)s at 0x%(id)x>"
return string % {
"cname": type(self).__name__,
"rname": rname,
"lineno": self.fromlineno,
"lineno": lineno,
"id": id(self),
}

Expand Down
34 changes: 34 additions & 0 deletions tests/test_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
from __future__ import annotations

import copy
import inspect
import os
import random
import sys
import textwrap
import unittest
Expand Down Expand Up @@ -1880,3 +1882,35 @@ def return_from_match(x):
inferred = node.inferred()
assert len(inferred) == 2
assert [inf.value for inf in inferred] == [10, -1]


@pytest.mark.parametrize(
"node",
[
node
for node in astroid.nodes.ALL_NODE_CLASSES
if node.__name__
not in ["_BaseContainer", "BaseContainer", "NodeNG", "const_factory"]
],
)
@pytest.mark.filterwarnings("error")
def test_str_repr_no_warnings(node):
parameters = inspect.signature(node.__init__).parameters

args = {}
for name, param_type in parameters.items():
if name == "self":
continue

if "int" in param_type.annotation:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this trick, never thought of doing it like this!

args[name] = random.randint(0, 50)
elif "NodeNG" in param_type.annotation:
args[name] = nodes.Unknown()
elif "str" in param_type.annotation:
args[name] = ""
else:
args[name] = None

test_node = node(**args)
str(test_node)
repr(test_node)