Skip to content

Commit c645af8

Browse files
fix: conditional string equivalence (#139)
* fix: conditional string equivalence * fix: typoes
1 parent b4651a2 commit c645af8

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

python/py_helpers.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,16 @@ def is_equivalent(self, target_str):
130130
# equivalent to any string.
131131
if self.tree == None:
132132
return False
133-
return ast.unparse(self.tree) == ast.unparse(ast.parse(target_str))
133+
code_str = ast.unparse(self.tree)
134+
135+
# Why parse and unparse again? Because of an edge case when comparing
136+
# the `target_str` "'True'" with the test in "if 'True':". These should
137+
# be equivalent, but the condition unparses to "'True'", while the
138+
# `target_str` becomes '"""True"""' when parsed and unparsed again.
139+
140+
# By parsing and unparsing `code_str` we get '"""True"""' and the
141+
# comparison returns True as expected.
142+
return ast.unparse(ast.parse(code_str)) == ast.unparse(ast.parse(target_str))
134143

135144
# Finds the class definition with the given name
136145

python/py_helpers.test.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,17 @@ def test_whitespace_equivalence(self):
329329
Node(str_with_whitespace).is_equivalent(str_with_different_whitespace)
330330
)
331331

332+
def test_string_equivalence(self):
333+
self.assertTrue(Node("'True'").is_equivalent('"""True"""'))
334+
335+
def test_string_cond_equivalence(self):
336+
self.assertTrue(
337+
Node("if 'True':\n pass")
338+
.find_ifs()[0]
339+
.find_conditions()[0]
340+
.is_equivalent("'True'")
341+
)
342+
332343

333344
class TestConditionalHelpers(unittest.TestCase):
334345
def test_find_if_statements(self):

0 commit comments

Comments
 (0)