Skip to content

Commit 3e6f1fa

Browse files
committed
Simplify warning creation by using ast.parse
in py2 it's a ast.Name where in py3 it's a ast.NamedConstant Fixes namespace by using import from
1 parent aaf7f7f commit 3e6f1fa

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed

src/_pytest/assertion/rewrite.py

+17-23
Original file line numberDiff line numberDiff line change
@@ -891,30 +891,24 @@ def warn_about_none_ast(self, node, module_path, lineno):
891891
)
892892
"""
893893

894-
warning_msg = ast.Str(
895-
'Asserting the value None directly, Please use "assert is None" to eliminate ambiguity'
896-
)
897-
AST_NONE = ast.NameConstant(None)
894+
# using parse because it's different between py2 py3
895+
AST_NONE = ast.parse("None").body[0].value
898896
val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE])
899-
import_warnings = ast.ImportFrom(
900-
module="warnings", names=[ast.alias("warn_explicit", None)], level=0
901-
)
902-
import_pytest_warning = ast.ImportFrom(
903-
module="pytest", names=[ast.alias("PytestWarning", None)], level=0
904-
)
905-
pytest_warning = ast_Call_helper("PytestWarning", warning_msg)
906-
# This won't work because this isn't the same "self" as an AssertionRewriter!
907-
# ast_filename = improved_ast_Call('str',ast.Attribute('self','module_path',ast.Load).module_path)
908-
warn = ast_Call_helper(
909-
"warn_explicit",
910-
pytest_warning,
911-
category=AST_NONE,
912-
filename=ast.Str(str(module_path)),
913-
lineno=ast.Num(lineno),
914-
)
915-
return ast.If(
916-
val_is_none, [import_warnings, import_pytest_warning, ast.Expr(warn)], []
917-
)
897+
send_warning = ast.parse(
898+
"""
899+
from _pytest.warning_types import PytestWarning
900+
from warnings import warn_explicit
901+
warn_explicit(
902+
PytestWarning('assertion the value None, Please use "assert is None"'),
903+
category=None,
904+
filename='{filename}',
905+
lineno={lineno},
906+
)
907+
""".format(
908+
filename=str(module_path), lineno=lineno
909+
)
910+
).body
911+
return ast.If(val_is_none, send_warning, [])
918912

919913
def visit_Name(self, name):
920914
# Display the repr of the name if it's a local variable or

0 commit comments

Comments
 (0)