Skip to content

Commit 998c657

Browse files
committed
Fixup error messages and tests
Finishing up applying error message improvements throughout, and updating the tests to cover the new patterns.
1 parent c8fd121 commit 998c657

4 files changed

Lines changed: 78 additions & 29 deletions

File tree

‎msgspec/core.c‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ TypeNodeFixTuple_Repr(TypeNode *type) {
319319
}
320320
delim = PyUnicode_FromString(", ");
321321
if (delim == NULL) goto done;
322-
out = PyUnicode_Join(delim, elements);
322+
element_str = PyUnicode_Join(delim, elements);
323323
out = PyUnicode_FromFormat(
324324
type->optional ? "Optional[Tuple[%S]]" : "Tuple[%S]",
325325
element_str
@@ -2225,17 +2225,17 @@ Decoder_dealloc(Decoder *self)
22252225
static PyObject *
22262226
Decoder_repr(Decoder *self) {
22272227
int recursive;
2228-
PyObject *out;
2228+
PyObject *typstr, *out = NULL;
22292229

22302230
recursive = Py_ReprEnter((PyObject *)self);
22312231
if (recursive != 0) {
22322232
return (recursive < 0) ? NULL : PyUnicode_FromString("...");
22332233
}
2234-
if (PyType_Check(self->orig_type)) {
2235-
out = PyUnicode_FromFormat("Decoder(%s)", ((PyTypeObject*)self->orig_type)->tp_name);
2236-
} else {
2237-
out = PyUnicode_FromFormat("Decoder(%R)", self->orig_type);
2234+
typstr = TypeNode_Repr(self->type);
2235+
if (typstr != NULL) {
2236+
out = PyUnicode_FromFormat("Decoder(%S)", typstr);
22382237
}
2238+
Py_XDECREF(typstr);
22392239
Py_ReprLeave((PyObject *)self);
22402240
return out;
22412241
}

‎msgspec/core.pyi‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,9 @@ from typing import Any, Type, TypeVar, Generic
33
T = TypeVar("T")
44

55
class Decoder(Generic[T]):
6-
def __init__(self, type: Type[T]):
7-
...
8-
9-
def decode(self, data: bytes) -> T:
10-
...
11-
6+
def __init__(self, type: Type[T]): ...
7+
def decode(self, data: bytes) -> T: ...
128

139
class Encoder:
14-
def __init__(self, *, write_buffer_size : int = ...):
15-
...
16-
17-
def encode(self, obj: Any) -> bytes:
18-
...
10+
def __init__(self, *, write_buffer_size: int = ...): ...
11+
def encode(self, obj: Any) -> bytes: ...

‎setup.cfg‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@ ignore =
55
E741, # Ambiguous variable names
66
W503, # line break before binary operator
77
W504, # line break after binary operator
8-
max-line-length = 95
8+
max-line-length = 100

‎tests/test_msgspec.py‎

Lines changed: 67 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -131,12 +131,44 @@ def test_decoder_type_attribute(self):
131131
dec = msgspec.Decoder(int)
132132
assert dec.type is int
133133

134-
def test_decoder_repr(self):
135-
dec = msgspec.Decoder()
136-
assert repr(dec) == "Decoder(%r)" % Any
134+
@pytest.mark.parametrize("typ, typstr", [(None, "None"), (Any, "Any")])
135+
def test_decoder_none_any_repr(self, typ, typstr):
136+
dec = msgspec.Decoder(typ)
137+
assert repr(dec) == f"Decoder({typstr})"
138+
# Optionality of None/Any doesn't change things
139+
dec = msgspec.Decoder(Optional[typ])
140+
assert repr(dec) == f"Decoder({typstr})"
137141

138-
dec = msgspec.Decoder(int)
139-
assert repr(dec) == "Decoder(int)"
142+
@pytest.mark.parametrize(
143+
"typ, typstr",
144+
[
145+
(bool, "bool"),
146+
(int, "int"),
147+
(float, "float"),
148+
(str, "str"),
149+
(bytes, "bytes"),
150+
(bytearray, "bytearray"),
151+
(Dict, "Dict[Any, Any]"),
152+
(Dict[int, str], "Dict[int, str]"),
153+
(List, "List[Any]"),
154+
(List[Optional[int]], "List[Optional[int]]"),
155+
(Set, "Set[Any]"),
156+
(Set[Optional[int]], "Set[Optional[int]]"),
157+
(Tuple, "Tuple[Any, ...]"),
158+
(Tuple[Optional[int], ...], "Tuple[Optional[int], ...]"),
159+
(Tuple[int, str], "Tuple[int, str]"),
160+
(Person, "Person"),
161+
(FruitInt, "FruitInt"),
162+
(FruitStr, "FruitStr"),
163+
(List[Optional[Dict[str, Person]]], "List[Optional[Dict[str, Person]]]"),
164+
],
165+
)
166+
def test_decoder_repr(self, typ, typstr):
167+
dec = msgspec.Decoder(typ)
168+
assert repr(dec) == f"Decoder({typstr})"
169+
170+
dec = msgspec.Decoder(Optional[typ])
171+
assert repr(dec) == f"Decoder(Optional[{typstr}])"
140172

141173
def test_decoder_unsupported_type(self):
142174
with pytest.raises(TypeError):
@@ -325,7 +357,10 @@ def test_fixtuple_any(self):
325357
assert res == x
326358
with pytest.raises(msgspec.DecodingError, match="expected `tuple`"):
327359
dec.decode(enc.encode(1))
328-
with pytest.raises(msgspec.DecodingError, match="expected tuple of length 3"):
360+
with pytest.raises(
361+
msgspec.DecodingError,
362+
match=r"Error decoding `Tuple\[Any, Any, Any\]`: expected tuple of length 3, got 2",
363+
):
329364
dec.decode(enc.encode((1, 2)))
330365

331366
def test_fixtuple_typed(self):
@@ -336,7 +371,10 @@ def test_fixtuple_typed(self):
336371
assert res == x
337372
with pytest.raises(msgspec.DecodingError, match="expected `bytes`"):
338373
dec.decode(enc.encode((1, "two", "three")))
339-
with pytest.raises(msgspec.DecodingError, match="expected tuple of length 3"):
374+
with pytest.raises(
375+
msgspec.DecodingError,
376+
match=r"Error decoding `Tuple\[int, str, bytes\]`: expected tuple of length 3, got 2",
377+
):
340378
dec.decode(enc.encode((1, 2)))
341379

342380
@pytest.mark.parametrize("size", SIZES)
@@ -396,7 +434,9 @@ def test_enum(self):
396434

397435
with pytest.raises(msgspec.DecodingError, match="truncated"):
398436
dec.decode(a[:-2])
399-
with pytest.raises(msgspec.DecodingError, match="Error decoding enum `FruitStr`"):
437+
with pytest.raises(
438+
msgspec.DecodingError, match="Error decoding enum `FruitStr`"
439+
):
400440
dec.decode(enc.encode("MISSING"))
401441
with pytest.raises(msgspec.DecodingError):
402442
dec.decode(enc.encode(1))
@@ -411,7 +451,9 @@ def test_int_enum(self):
411451

412452
with pytest.raises(msgspec.DecodingError, match="truncated"):
413453
dec.decode(a[:-2])
414-
with pytest.raises(msgspec.DecodingError, match="Error decoding enum `FruitInt`"):
454+
with pytest.raises(
455+
msgspec.DecodingError, match="Error decoding enum `FruitInt`"
456+
):
415457
dec.decode(enc.encode(1000))
416458
with pytest.raises(msgspec.DecodingError):
417459
dec.decode(enc.encode("INVALID"))
@@ -436,7 +478,10 @@ def test_struct(self):
436478
with pytest.raises(msgspec.DecodingError, match="expected `struct`"):
437479
dec.decode(enc.encode(1))
438480

439-
with pytest.raises(msgspec.DecodingError, match="expected `str`"):
481+
with pytest.raises(
482+
msgspec.DecodingError,
483+
match=r"Error decoding `Person` field `first` \(`str`\): expected `str`, got `int`",
484+
):
440485
dec.decode(enc.encode({1: "harry"}))
441486

442487
def test_struct_field_wrong_type(self):
@@ -456,7 +501,9 @@ def test_struct_missing_fields(self):
456501
dec.decode(bad)
457502

458503
bad = enc.encode({})
459-
with pytest.raises(msgspec.DecodingError, match="missing required field `first`"):
504+
with pytest.raises(
505+
msgspec.DecodingError, match="missing required field `first`"
506+
):
460507
dec.decode(bad)
461508

462509
@pytest.mark.parametrize(
@@ -570,6 +617,15 @@ def test_optional_nested(self, typ, value):
570617
s = enc.encode(value)
571618
assert dec.decode(s) == value
572619

620+
def test_decoding_error_no_struct_toplevel(self):
621+
b = msgspec.Encoder().encode([{"a": 1}])
622+
dec = msgspec.Decoder(List[Dict[str, str]])
623+
with pytest.raises(
624+
msgspec.DecodingError,
625+
match=r"Error decoding `List\[Dict\[str, str\]\]`: expected `str`, got `int`",
626+
):
627+
dec.decode(b)
628+
573629

574630
class CommonTypeTestBase:
575631
"""Test msgspec untyped encode/decode"""

0 commit comments

Comments
 (0)