"""config.py 单元测试: Pydantic 模型校验""" from __future__ import annotations from typing import Any import pytest from pydantic import HttpUrl, SecretStr, ValidationError from tjhlp.config import GiteaConfig, LabelDef class TestLabelDef: def test_valid_6_digit_hex(self): lbl = LabelDef(name="test", color="#aabbcc") assert lbl.color == "#aabbcc" def test_valid_3_digit_hex(self): lbl = LabelDef(name="test", color="#abc") assert lbl.color == "#abc" def test_strips_and_normalizes_hash(self): lbl = LabelDef(name="test", color="aabbcc") assert lbl.color == "#aabbcc" def test_uppercase_hex(self): lbl = LabelDef(name="test", color="#AABBCC") assert lbl.color == "#AABBCC" def test_invalid_hex_chars(self): with pytest.raises(ValidationError): LabelDef(name="test", color="#xyz123") def test_invalid_length_4(self): with pytest.raises(ValidationError): LabelDef(name="test", color="#abcd") def test_invalid_length_1(self): with pytest.raises(ValidationError): LabelDef(name="test", color="#a") def test_empty_color(self): with pytest.raises(ValidationError): LabelDef(name="test", color="") def test_hash_only(self): with pytest.raises(ValidationError): LabelDef(name="test", color="#") def test_default_description(self): lbl = LabelDef(name="test", color="#abc") assert lbl.description == "" def test_with_description(self): lbl = LabelDef(name="test", color="#abc", description="A label") assert lbl.description == "A label" class TestGiteaConfig: def test_valid(self): cfg = GiteaConfig( url=HttpUrl("http://localhost:3000"), token=SecretStr("token123"), ) assert cfg.email_domain == "tongji.edu.cn" assert cfg.labels == [] def test_missing_url_raises(self): with pytest.raises(ValidationError): kwargs: dict[str, Any] = {"token": SecretStr("token123")} GiteaConfig(**kwargs) def test_missing_token_raises(self): with pytest.raises(ValidationError): kwargs: dict[str, Any] = {"url": HttpUrl("http://localhost:3000")} GiteaConfig(**kwargs) def test_token_is_secret(self): cfg = GiteaConfig( url=HttpUrl("http://localhost:3000"), token=SecretStr("secret-token"), ) # SecretStr hides value in repr assert "secret-token" not in repr(cfg.token) assert cfg.token.get_secret_value() == "secret-token" def test_with_labels(self): cfg = GiteaConfig( url=HttpUrl("http://localhost:3000"), token=SecretStr("token"), labels=[LabelDef(name="bug", color="#ff0000")], ) assert len(cfg.labels) == 1