示例工程 10-type-annotations-mypy

10-type-annotations-mypy/06-runtime-validation/test_runtime_validation.py

python · 1.2 KB

"""test_runtime_validation.py"""
 
from __future__ import annotations
 
import pytest
from runtime_validation import first_upper, is_str_list, main, parse_config
 
 
def test_parse_config_accepts_valid() -> None:
    config = parse_config({"host": "localhost", "port": 8080})
    assert config == {"host": "localhost", "port": 8080}
 
 
def test_parse_config_rejects_bad_shapes() -> None:
    with pytest.raises(TypeError, match="config must be a mapping"):
        parse_config(["not", "mapping"])
    with pytest.raises(TypeError, match="host must be a str"):
        parse_config({"host": 1, "port": 1})
    with pytest.raises(TypeError, match="port must be an int"):
        parse_config({"host": "x", "port": "1"})
    with pytest.raises(TypeError, match="port must be an int"):
        parse_config({"host": "x", "port": True})
 
 
def test_type_guard_narrows_list() -> None:
    assert is_str_list(["a", "b"]) is True
    assert is_str_list(["a", 1]) is False
    assert first_upper(["ok", "no"]) == "OK"
    assert first_upper([]) == ""
    with pytest.raises(TypeError, match="list"):
        first_upper(["a", 1])
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "rejected: port must be an int" in out