Skip to content

Commit

Permalink
Merge pull request #111 from 15r10nk/one_line_string
Browse files Browse the repository at this point in the history
feat: strings with one line-break at the end stay single-quoted strings
  • Loading branch information
15r10nk authored Sep 9, 2024
2 parents 1df0885 + 59e6c06 commit 9d67e5f
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 3 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ jobs:
with:
name: coverage
path: .coverage.*
include-hidden-files: true

combine_coverage:
name: combine coverage and check for 100%
Expand Down
4 changes: 3 additions & 1 deletion src/inline_snapshot/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ def map_string(tok):
"""Convert strings with newlines in triple quoted strings."""
if tok.type == token.STRING:
s = ast.literal_eval(tok.string)
if isinstance(s, str) and "\n" in s:
if isinstance(s, str) and (
("\n" in s and s[-1] != "\n") or s.count("\n") > 1
):
# unparse creates a triple quoted string here,
# because it thinks that the string should be a docstring
tripple_quoted_string = triple_quote(s)
Expand Down
50 changes: 48 additions & 2 deletions tests/test_inline_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,21 +686,24 @@ def test_string_newline(check_update):

def test_string_quote_choice(check_update):
assert check_update(
"s = snapshot(\" \\'\\'\\' \\'\\'\\' \\\"\\\"\\\"\\n\")", flags="update"
"s = snapshot(\" \\'\\'\\' \\'\\'\\' \\\"\\\"\\\"\\nother_line\")",
flags="update",
) == snapshot(
'''\
s = snapshot("""\\
\'\'\' \'\'\' \\"\\"\\"
other_line\\
""")\
'''
)

assert check_update(
's = snapshot(" \\\'\\\'\\\' \\"\\"\\" \\"\\"\\"\\n")', flags="update"
's = snapshot(" \\\'\\\'\\\' \\"\\"\\" \\"\\"\\"\\nother_line")', flags="update"
) == snapshot(
"""\
s = snapshot('''\\
\\'\\'\\' \"\"\" \"\"\"
other_line\\
''')\
"""
)
Expand All @@ -714,6 +717,49 @@ def test_string_quote_choice(check_update):
'''
)

assert check_update(
"s=snapshot('\\n')", flags="update", reported_flags=""
) == snapshot("s=snapshot('\\n')")
assert check_update(
"s=snapshot('abc\\n')", flags="update", reported_flags=""
) == snapshot("s=snapshot('abc\\n')")
assert check_update("s=snapshot('abc\\nabc')", flags="update") == snapshot(
'''\
s=snapshot("""\\
abc
abc\\
""")\
'''
)
assert check_update("s=snapshot('\\nabc')", flags="update") == snapshot(
'''\
s=snapshot("""\\
abc\\
""")\
'''
)
assert check_update("s=snapshot('a\\na\\n')", flags="update") == snapshot(
'''\
s=snapshot("""\\
a
a
""")\
'''
)

assert (
check_update(
'''\
s=snapshot("""\\
a
""")\
''',
flags="update",
)
== snapshot('s=snapshot("a\\n")')
)


@given(s=text())
def test_string_convert(s):
Expand Down

0 comments on commit 9d67e5f

Please sign in to comment.