示例工程 40-type-checker-in-python

40-type-checker-in-python/01-expr-typechecker/test_expr_typechecker.py

python · 0.9 KB

"""test_expr_typechecker.py"""
 
from __future__ import annotations
 
import pytest
from expr_typechecker import Checker, main
 
 
def test_expression_types() -> None:
    env, errors = Checker().check('x = 1 + 2 * 3\ny = "a" + "b"\nz = x > 0\n')
    assert env == {"x": "int", "y": "str", "z": "bool"}
    assert errors == []
 
 
def test_binary_operator_error() -> None:
    _, errors = Checker().check('x = 1 + "a"\n')
    assert [error.code for error in errors] == ["E001"]
    assert errors[0].line == 1
 
 
def test_undefined_and_reassignment() -> None:
    _, errors = Checker().check("x = 1\nx = 's'\ny = missing\n")
    assert [error.code for error in errors] == ["E003", "E002"]
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    main()
    out = capsys.readouterr().out
    assert "codes: ['E001', 'E002', 'E003']" in out
    assert "undefined variable" in out