示例工程 17-generators-coroutines
17-generators-coroutines/03-pep479-stopiteration/test_pep479_stopiteration.py
"""test_pep479_stopiteration.py"""
from __future__ import annotations
import pytest
from pep479_stopiteration import bad, bad_next, good, main, with_return
def test_stopiteration_becomes_runtime_error() -> None:
gen = bad()
assert next(gen) == 1
with pytest.raises(RuntimeError, match="generator raised StopIteration"):
next(gen)
def test_next_inside_generator_also_wrapped() -> None:
gen = bad_next()
with pytest.raises(RuntimeError, match="generator raised StopIteration"):
next(gen)
def test_fixed_generator_and_return_value() -> None:
assert list(good()) == []
gen = with_return()
assert next(gen) == 1
with pytest.raises(StopIteration) as info:
next(gen)
assert info.value.value == "done"
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
main()
out = capsys.readouterr().out
assert "raise: RuntimeError: generator raised StopIteration" in out
assert "return value: done" in out