示例工程 22-object-model-refcount-gc

22-object-model-refcount-gc/03-weakref-cache/test_weakref_cache.py

python · 0.7 KB

"""test_weakref_cache.py"""
 
from __future__ import annotations
 
import pytest
from weakref_cache import Record, demo, main
 
 
def test_weak_cache_evicts_without_strong_ref() -> None:
    before, after, with_strong = demo()
    assert before == ["a"]
    assert after == []
    assert with_strong == ["b"]
 
 
def test_value_stays_while_held() -> None:
    import weakref
 
    cache: weakref.WeakValueDictionary[str, Record] = weakref.WeakValueDictionary()
    record = Record("x")
    cache["x"] = record
    assert sorted(cache) == ["x"]
    assert cache["x"] is record
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "before: ['a']" in out
    assert "after del: []" in out