Angiin

test: 添加 account_manager 多账号端口测试

  1 +"""account_manager 单元测试。"""
  2 +from __future__ import annotations
  3 +
  4 +import sys
  5 +from pathlib import Path
  6 +
  7 +import pytest
  8 +
  9 +# 把 scripts/ 加入路径,使 account_manager 可导入
  10 +sys.path.insert(0, str(Path(__file__).parent.parent / "scripts"))
  11 +import account_manager
  12 +
  13 +
  14 +@pytest.fixture(autouse=True)
  15 +def tmp_config(tmp_path, monkeypatch):
  16 + """将配置目录重定向到临时目录。"""
  17 + monkeypatch.setattr(account_manager, "_CONFIG_DIR", tmp_path / ".xhs")
  18 + monkeypatch.setattr(
  19 + account_manager, "_ACCOUNTS_FILE", tmp_path / ".xhs" / "accounts.json"
  20 + )
  21 +
  22 +
  23 +def test_add_account_assigns_port():
  24 + """首个命名账号应分配端口 9223。"""
  25 + account_manager.add_account("work", "工作号")
  26 + port = account_manager.get_account_port("work")
  27 + assert port == 9223
  28 +
  29 +
  30 +def test_second_account_gets_next_port():
  31 + """第二个账号应分配端口 9224。"""
  32 + account_manager.add_account("work")
  33 + account_manager.add_account("personal")
  34 + assert account_manager.get_account_port("personal") == 9224
  35 +
  36 +
  37 +def test_get_profile_dir_public():
  38 + """get_profile_dir 应返回正确路径。"""
  39 + account_manager.add_account("work")
  40 + profile = account_manager.get_profile_dir("work")
  41 + assert "work" in profile
  42 + assert "chrome-profile" in profile
  43 +
  44 +
  45 +def test_get_account_port_unknown_raises():
  46 + """不存在的账号应抛出 ValueError。"""
  47 + with pytest.raises(ValueError, match="不存在"):
  48 + account_manager.get_account_port("ghost")
  49 +
  50 +
  51 +def test_list_accounts_includes_port():
  52 + """list_accounts 返回结果中应包含 port 字段。"""
  53 + account_manager.add_account("work", "工作")
  54 + accounts = account_manager.list_accounts()
  55 + assert len(accounts) == 1
  56 + assert accounts[0]["port"] == 9223