示例工程 10-type-annotations-mypy
10-type-annotations-mypy/03-typeddict-json/test_typeddict_json.py
"""test_typeddict_json.py"""
from __future__ import annotations
import json
import pytest
from typeddict_json import User, load_user, main, validate
def test_cast_trusts_json() -> None:
user = load_user('{"name": "Ada", "age": 36}')
assert user == {"name": "Ada", "age": 36}
def test_cast_does_not_validate() -> None:
broken = load_user('{"name": "Ada", "age": "36"}')
assert isinstance(broken["age"], str)
def test_validate_rejects_bad_shape() -> None:
with pytest.raises(TypeError, match="invalid user shape"):
validate(json.loads('{"name": "Ada", "age": "36"}'))
with pytest.raises(TypeError, match="must be an object"):
validate(["not", "a", "dict"])
def test_validate_returns_typed_dict() -> None:
user: User = validate({"name": "Grace", "age": 85})
assert user["name"] == "Grace"
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
main()
out = capsys.readouterr().out
assert "rejected: invalid user shape" in out