示例工程 15-dataclasses-slots-immutability
15-dataclasses-slots-immutability/02-frozen-hashable/test_frozen_hashable.py
"""test_frozen_hashable.py"""
from __future__ import annotations
import pytest
from frozen_hashable import Box, FrozenInstanceError, MutablePoint, Point, main
def test_frozen_is_hashable() -> None:
table = {Point(1, 2): "here"}
assert table[Point(1, 2)] == "here"
assert hash(Point(1, 2)) == hash(Point(1, 2))
def test_frozen_blocks_assignment() -> None:
point = Point(1, 2)
with pytest.raises(FrozenInstanceError, match="x"):
point.x = 3 # type: ignore[misc] # 演示 frozen 运行时拦截
def test_mutable_dataclass_is_unhashable() -> None:
assert MutablePoint.__hash__ is None
with pytest.raises(TypeError, match="unhashable"):
hash(MutablePoint(1))
def test_frozen_is_shallow() -> None:
box = Box([1])
box.items.append(2)
assert box.items == [1, 2]
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
main()
out = capsys.readouterr().out
assert "lookup: here" in out
assert "inner mutated: [1, 2]" in out