bpo-38870: Correctly handle empty docstrings in ast.unparse (GH-18768)

Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
This commit is contained in:
Batuhan Taskaya 2020-05-17 01:49:07 +03:00 committed by GitHub
parent d5a980a607
commit e966af7cff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 7 deletions

View File

@ -1075,11 +1075,14 @@ class _Unparser(NodeVisitor):
if node.kind == "u": if node.kind == "u":
self.write("u") self.write("u")
# Preserve quotes in the docstring by escaping them value = node.value
value = node.value.replace("\\", "\\\\") if value:
value = value.replace('"""', '""\"') # Preserve quotes in the docstring by escaping them
if value[-1] == '"': value = value.replace("\\", "\\\\")
value = value.replace('"', '\\"', -1) value = value.replace('"""', '""\"')
value = value.replace("\r", "\\r")
if value[-1] == '"':
value = value.replace('"', '\\"', -1)
self.write(f'"""{value}"""') self.write(f'"""{value}"""')

View File

@ -313,11 +313,18 @@ class UnparseTestCase(ASTTestCase):
def test_docstrings(self): def test_docstrings(self):
docstrings = ( docstrings = (
'this ends with double quote"', 'this ends with double quote"',
'this includes a """triple quote"""' 'this includes a """triple quote"""',
'\r',
'\\r',
'\t',
'\\t',
'\n',
'\\n',
'\r\\r\t\\t\n\\n'
) )
for docstring in docstrings: for docstring in docstrings:
# check as Module docstrings for easy testing # check as Module docstrings for easy testing
self.check_ast_roundtrip(f"'{docstring}'") self.check_ast_roundtrip(f"'''{docstring}'''")
def test_constant_tuples(self): def test_constant_tuples(self):
self.check_src_roundtrip(ast.Constant(value=(1,), kind=None), "(1,)") self.check_src_roundtrip(ast.Constant(value=(1,), kind=None), "(1,)")
@ -390,6 +397,10 @@ class CosmeticTestCase(ASTTestCase):
empty newline"""''', empty newline"""''',
'"""With some \t"""', '"""With some \t"""',
'"""Foo "bar" baz """', '"""Foo "bar" baz """',
'"""\\r"""',
'""""""',
'"""\'\'\'"""',
'"""\'\'\'\'\'\'"""',
) )
for prefix in docstring_prefixes: for prefix in docstring_prefixes: