Skip to content
Open
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
20 changes: 20 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -884,3 +884,23 @@ def test_parse_dotted_key_with_subsequent_key_at_nesting_limit() -> None:
# Inside table
doc_table = tomlkit.parse(f"[t]\n{key} = 1\na.b = 2\n")
assert doc_table["t"]["a"]["b"] == 2


def test_parse_bytes_invalid_utf8_raises() -> None:
data = b'a = "\xff"\n'
with pytest.raises(UnicodeDecodeError):
parse(data)

with pytest.raises(UnicodeDecodeError):
loads(data)

with pytest.raises(UnicodeDecodeError):
load(io.BytesIO(data))


def test_parse_bytes_valid_utf8() -> None:
data = b'a = "\xc3\xa9"\n'
doc = parse(data)
assert doc["a"] == "\xe9"
assert loads(data)["a"] == "\xe9"
assert load(io.BytesIO(data))["a"] == "\xe9"
9 changes: 9 additions & 0 deletions tests/test_toml_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,12 @@ def test_invalid_encode(toml11_invalid_encode_case: str) -> None:
with open(toml11_invalid_encode_case, encoding="utf-8") as f:
with pytest.raises((TOMLKitError, UnicodeDecodeError)):
load(f)


@pytest.mark.parametrize(
"toml11_invalid_encode_case", INVALID_ENCODE_CASES, ids=INVALID_ENCODE_IDS
)
def test_invalid_encode_bytes(toml11_invalid_encode_case: str) -> None:
with open(toml11_invalid_encode_case, "rb") as f:
with pytest.raises((TOMLKitError, UnicodeDecodeError)):
load(f)
6 changes: 4 additions & 2 deletions tomlkit/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from typing import Any
from typing import Callable

from tomlkit._compat import decode
from tomlkit._utils import RFC_3339_LOOSE
from tomlkit._utils import _escaped
from tomlkit._utils import parse_rfc3339
Expand Down Expand Up @@ -102,7 +101,10 @@ class Parser:

def __init__(self, string: str | bytes) -> None:
# Input to parse
self._src = Source(decode(string))
if isinstance(string, bytes):
string = string.decode("utf-8")

self._src = Source(string)

self._aot_stack: list[Key] = []
self._nesting_depth = 0
Expand Down
Loading