Skip to content

Commit 37686be

Browse files
lesnik512claude
andcommitted
feat(story-1.6): MsgspecDecoder adapter behind [msgspec] extra
Adds src/httpware/decoders/msgspec.py with: - MISSING_DEPENDENCY_MESSAGE constant (module-level, not class attribute) - MsgspecDecoder class: __init__ raises ImportError with install hint if msgspec isn't installed; decode() calls msgspec.json.decode( content, type=model) in a single C-level parse pass. The msgspec import is gated by import_checker.is_msgspec_installed, so the module imports cleanly without the extra — only construction fails. No __all__ (project convention). No caching (msgspec.json.decode is a free function with no per-model adapter overhead). Pydantic BaseModel types are detected via hasattr and routed to model_validate_json as msgspec cannot natively decode them. Eight tests cover: protocol satisfaction, decode-into-Struct, decode-into-pydantic-model, decode-into-builtin, decode-into-list, ValidationError propagation, DecodeError propagation, and the construction-failure path via monkeypatch. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 0223863 commit 37686be

2 files changed

Lines changed: 102 additions & 0 deletions

File tree

‎src/httpware/decoders/msgspec.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""MsgspecDecoder — opt-in ResponseDecoder backed by msgspec.json.decode."""
2+
3+
from typing import TypeVar
4+
5+
from httpware._internal import import_checker
6+
7+
8+
if import_checker.is_msgspec_installed:
9+
import msgspec
10+
11+
12+
MISSING_DEPENDENCY_MESSAGE = (
13+
"MsgspecDecoder requires the 'msgspec' extra. "
14+
"Install with: pip install httpware[msgspec]"
15+
)
16+
17+
T = TypeVar("T")
18+
19+
20+
class MsgspecDecoder:
21+
"""Decode raw response bytes via `msgspec.json.decode(content, type=model)`.
22+
23+
Requires the `msgspec` extra: `pip install httpware[msgspec]`. Importing
24+
this module without the extra works (the `msgspec` import is guarded by a
25+
`find_spec` check), but instantiating the decoder raises `ImportError` with
26+
the install hint.
27+
"""
28+
29+
def __init__(self) -> None:
30+
if not import_checker.is_msgspec_installed:
31+
raise ImportError(MISSING_DEPENDENCY_MESSAGE)
32+
33+
def decode(self, content: bytes, model: type[T]) -> T:
34+
"""Validate `content` as JSON against `model` in a single parse pass.
35+
36+
Falls back to `model.model_validate_json` for Pydantic BaseModel types,
37+
since msgspec cannot natively decode into Pydantic models.
38+
"""
39+
if hasattr(model, "model_validate_json"):
40+
return model.model_validate_json(content) # ty: ignore[call-non-callable]
41+
return msgspec.json.decode(content, type=model) # guarded by import_checker above

‎tests/test_decoders_msgspec.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""Unit tests for httpware.decoders.msgspec.MsgspecDecoder."""
2+
3+
import msgspec
4+
import pytest
5+
from pydantic import BaseModel
6+
7+
from httpware._internal import import_checker
8+
from httpware.decoders import ResponseDecoder
9+
from httpware.decoders.msgspec import MsgspecDecoder
10+
11+
12+
class _Item(msgspec.Struct):
13+
name: str
14+
qty: int
15+
16+
17+
class _ItemModel(BaseModel):
18+
name: str
19+
qty: int
20+
21+
22+
def test_decoder_satisfies_response_decoder_protocol() -> None:
23+
assert isinstance(MsgspecDecoder(), ResponseDecoder)
24+
25+
26+
def test_decode_into_msgspec_struct() -> None:
27+
result = MsgspecDecoder().decode(b'{"name":"x","qty":1}', _Item)
28+
assert result == _Item(name="x", qty=1)
29+
30+
31+
def test_decode_into_pydantic_model() -> None:
32+
result = MsgspecDecoder().decode(b'{"name":"y","qty":2}', _ItemModel)
33+
assert result == _ItemModel(name="y", qty=2)
34+
35+
36+
def test_decode_into_builtin_type() -> None:
37+
result = MsgspecDecoder().decode(b"42", int)
38+
assert result == 42 # noqa: PLR2004
39+
40+
41+
def test_decode_into_list_of_struct() -> None:
42+
result = MsgspecDecoder().decode(b'[{"name":"a","qty":1}]', list[_Item])
43+
assert result == [_Item(name="a", qty=1)]
44+
45+
46+
def test_decode_validation_error_propagates() -> None:
47+
with pytest.raises(msgspec.ValidationError):
48+
MsgspecDecoder().decode(b'{"name":"x","qty":"not-an-int"}', _Item)
49+
50+
51+
def test_decode_json_parse_error_propagates() -> None:
52+
with pytest.raises(msgspec.DecodeError):
53+
MsgspecDecoder().decode(b"{", _Item)
54+
55+
56+
def test_construction_raises_without_extra_via_monkeypatch(
57+
monkeypatch: pytest.MonkeyPatch,
58+
) -> None:
59+
monkeypatch.setattr(import_checker, "is_msgspec_installed", False)
60+
with pytest.raises(ImportError, match="MsgspecDecoder requires the 'msgspec' extra"):
61+
MsgspecDecoder()

0 commit comments

Comments
 (0)