Skip to content

Commit e8c8559

Browse files
authored
Remove usage of parser module (deprecated in Python 3.9) (#6407)
Remove usage of parser module (deprecated in Python 3.9)
2 parents 0fa3596 + 91a96ec commit e8c8559

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

changelog/6404.trivial.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Removed unused ``_pytest.code.Source.isparseable`` function.
1+
Remove usage of ``parser`` module, deprecated in Python 3.9.

src/_pytest/_code/source.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,21 @@ def deindent(self) -> "Source":
136136
newsource.lines[:] = deindent(self.lines)
137137
return newsource
138138

139+
def isparseable(self, deindent: bool = True) -> bool:
140+
""" return True if source is parseable, heuristically
141+
deindenting it by default.
142+
"""
143+
if deindent:
144+
source = str(self.deindent())
145+
else:
146+
source = str(self)
147+
try:
148+
ast.parse(source)
149+
except (SyntaxError, ValueError, TypeError):
150+
return False
151+
else:
152+
return True
153+
139154
def __str__(self) -> str:
140155
return "\n".join(self.lines)
141156

testing/code/test_source.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,15 @@ def test_syntaxerror_rerepresentation() -> None:
121121
assert ex.value.text == "xyz xyz\n"
122122

123123

124+
def test_isparseable() -> None:
125+
assert Source("hello").isparseable()
126+
assert Source("if 1:\n pass").isparseable()
127+
assert Source(" \nif 1:\n pass").isparseable()
128+
assert not Source("if 1:\n").isparseable()
129+
assert not Source(" \nif 1:\npass").isparseable()
130+
assert not Source(chr(0)).isparseable()
131+
132+
124133
class TestAccesses:
125134
def setup_class(self) -> None:
126135
self.source = Source(
@@ -134,6 +143,7 @@ def g(x):
134143

135144
def test_getrange(self) -> None:
136145
x = self.source[0:2]
146+
assert x.isparseable()
137147
assert len(x.lines) == 2
138148
assert str(x) == "def f(x):\n pass"
139149

0 commit comments

Comments
 (0)