示例工程 15-dataclasses-slots-immutability

15-dataclasses-slots-immutability/05-namedtuple-vs-dataclass/test_namedtuple_vs_dataclass.py

python · 0.8 KB

"""test_namedtuple_vs_dataclass.py"""
 
from __future__ import annotations
 
from dataclasses import replace
 
import pytest
from namedtuple_vs_dataclass import PointDC, PointNT, main
 
 
def test_namedtuple_behaves_like_tuple() -> None:
    point = PointNT(1, 2)
    assert isinstance(point, tuple)
    assert point[0] == 1
    assert tuple(point) == (1, 2)
    assert point == (1, 2)
    assert point._asdict() == {"x": 1, "y": 2}
    assert point._replace(x=3) == PointNT(3, 2)
 
 
def test_dataclass_is_not_indexable() -> None:
    point = PointDC(1, 2)
    assert not hasattr(point, "__getitem__")
    assert point != (1, 2)
    assert replace(point, x=3) == PointDC(3, 2)
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "nt is tuple: True" in out
    assert "dc indexable: False" in out