Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions tests/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,34 @@ def test_string_add_preserve_escapes() -> None:
assert i.as_string() == '"foo\\"bar baz"'


def test_string_add_escapes_appended_content() -> None:
# Appending a character that must be escaped in a basic string used
# to be spliced into the raw value unescaped, producing a literal
# that no TOML parser (including this one) can read back.
i = item("foo")
i += '"'
assert i == 'foo"'
assert i.as_string() == '"foo\\""'
assert parse(f"k = {i.as_string()}")["k"] == 'foo"'

i = item("foo")
i += "\\"
assert i == "foo\\"
assert i.as_string() == '"foo\\\\"'
assert parse(f"k = {i.as_string()}")["k"] == "foo\\"

# Appending a String splices its raw (already escaped) form.
j = item("foo")
j += item('"')
assert j == 'foo"'
assert j.as_string() == '"foo\\""'

# Plain text without special characters is appended verbatim.
k = item("foo")
k += " bar"
assert k.as_string() == '"foo bar"'


def test_tables_behave_like_dicts() -> None:
t = item({"foo": "bar"})

Expand Down
8 changes: 7 additions & 1 deletion tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -2223,7 +2223,13 @@ def type(self) -> StringType:

def __add__(self, other: str) -> String:
result = super().__add__(other)
original = self._original + getattr(other, "_original", other)
if isinstance(other, String):
original = self._original + other._original
else:
escaped = self._t.escaped_sequences
original = self._original + (
escape_string(other, escaped) if escaped else other
)

return self._new(result, original)

Expand Down
Loading