示例工程 13-descriptors-properties

13-descriptors-properties/01-validated-descriptor/test_validated_descriptor.py

python · 1.1 KB

"""test_validated_descriptor.py"""
 
from __future__ import annotations
 
import pytest
from validated_descriptor import Product, Validated, main
 
 
def test_set_name_records_attribute_name() -> None:
    assert Product.name.name == "name"
    assert Product.price.name == "price"
 
 
def test_valid_assignment() -> None:
    product = Product("Widget", 99)
    assert (product.name, product.price) == ("Widget", 99)
    product.price = 0
    assert product.price == 0
 
 
def test_type_and_range_validation() -> None:
    product = Product("Widget", 99)
    with pytest.raises(TypeError, match="must be int"):
        product.price = "99"  # 演示运行时类型校验
    with pytest.raises(ValueError, match="<= 10000"):
        product.price = 20000
    with pytest.raises(ValueError, match=">= 0"):
        product.price = -1
 
 
def test_class_access_returns_descriptor() -> None:
    assert isinstance(Product.price, Validated)
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "names: name, price" in out
    assert "type error:" in out