import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from fastapi import HTTPException from web.backend.database import Base from web.backend.models import Account, User from web.backend.routers.accounts import list_accounts, set_account_tag from web.backend.schemas import AccountTag class TestAccountSensitiveFields: def setup_method(self): self.engine = create_engine("sqlite://") Base.metadata.create_all(self.engine) self.session = sessionmaker(bind=self.engine)() self.admin = User(username="admin", password_hash="hash", role="super_admin") self.session.add(self.admin) self.session.add( Account( username="account", password="account-password", email="account@example.com", email_password="email-password", ) ) self.session.commit() def teardown_method(self): self.session.close() Base.metadata.drop_all(self.engine) self.engine.dispose() def test_sensitive_fields_are_hidden_by_default_even_for_admin(self): result = list_accounts( assigned_only=False, tag=None, has_cookie=False, search="", page=1, page_size=20, include_sensitive=False, db=self.session, current=self.admin, ) item = result["items"][0] assert item.password is None assert item.email is None assert item.email_password is None def test_admin_can_explicitly_request_sensitive_fields(self): result = list_accounts( assigned_only=False, tag=None, has_cookie=False, search="", page=1, page_size=20, include_sensitive=True, db=self.session, current=self.admin, ) item = result["items"][0] assert item.password == "account-password" assert item.email == "account@example.com" assert item.email_password == "email-password" def test_support_can_only_change_tags_on_assigned_accounts(self): support = User(username="support", password_hash="hash", role="support") other_support = User( username="other-support", password_hash="hash", role="support" ) self.session.add_all([support, other_support]) self.session.commit() assigned = Account( username="assigned", password="password", email="assigned@example.com", email_password="mail-password", assigned_to=support.id, ) other = Account( username="other", password="password", email="other@example.com", email_password="mail-password", assigned_to=other_support.id, ) self.session.add_all([assigned, other]) self.session.commit() set_account_tag( assigned.id, AccountTag(tag="客服组"), db=self.session, current=support ) self.session.refresh(assigned) assert assigned.tag == "客服组" with pytest.raises(HTTPException) as context: set_account_tag( other.id, AccountTag(tag="越权"), db=self.session, current=support ) assert context.value.status_code == 404