示例工程 16-stdlib-tour

16-stdlib-tour/06-argparse-subcommands/test_argparse_subcommands.py

python · 1.2 KB

"""test_argparse_subcommands.py"""
 
from __future__ import annotations
 
import io
from contextlib import redirect_stderr
 
import pytest
from argparse_subcommands import build_parser, main
 
 
def test_subcommands_and_type() -> None:
    parser = build_parser()
    args = parser.parse_args(["add", "apple", "--count", "3"])
    assert args.command == "add"
    assert args.name == "apple"
    assert args.count == 3
    args = parser.parse_args(["remove", "apple"])
    assert args.command == "remove"
    assert args.name == "apple"
 
 
def test_missing_required_argument() -> None:
    parser = build_parser()
    buffer = io.StringIO()
    with pytest.raises(SystemExit) as info, redirect_stderr(buffer):
        parser.parse_args(["add"])
    assert info.value.code == 2
    assert "name" in buffer.getvalue()
 
 
def test_invalid_int() -> None:
    parser = build_parser()
    with pytest.raises(SystemExit) as info, redirect_stderr(io.StringIO()):
        parser.parse_args(["add", "apple", "--count", "many"])
    assert info.value.code == 2
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "add: add apple 3" in out
    assert "missing: code=2 mentions_name=True" in out