"""Tests for the alias-aware email → IdentityPerson lookup. Cross-system sync jobs (Zoom, future Slack/Feishu) use this to resolve an external-system email that may be the person's primary ``work_email`` or any of their Google Workspace aliases stored in ``identity_persons.email_aliases``. """ from __future__ import annotations import uuid import pytest from sqlalchemy.ext.asyncio import AsyncSession from app.identity.email_lookup import build_person_by_email_index from app.identity.person_models import IdentityPerson async def _mk( db: AsyncSession, email: str, *, aliases: list[str] | None = None, deleted: bool = False, ) -> IdentityPerson: from datetime import UTC, datetime p = IdentityPerson( id=uuid.uuid4(), work_email=email, display_name=email.split("@")[0], employment_status="active", source_system="successfactors", hris_person_id=f"sf-{email}", email_aliases=aliases, deleted_at=datetime.now(UTC) if deleted else None, ) db.add(p) await db.flush() return p @pytest.mark.asyncio async def test_lookup_matches_primary_work_email(db_session) -> None: p = await _mk(db_session, "alice@x.io") await db_session.commit() idx = await build_person_by_email_index(db_session, ["alice@x.io"]) assert "alice@x.io" in idx assert idx["alice@x.io"].id == p.id @pytest.mark.asyncio async def test_lookup_matches_alias(db_session) -> None: p = await _mk( db_session, "reece.reynolds@x.io", aliases=["reece.r@x.io", "reece@x.io"], ) await db_session.commit() idx = await build_person_by_email_index(db_session, ["reece.r@x.io"]) assert idx["reece.r@x.io"].id == p.id @pytest.mark.asyncio async def test_lookup_is_case_insensitive(db_session) -> None: p = await _mk( db_session, "alice@x.io", aliases=["Alice.L@x.io"], ) await db_session.commit() idx = await build_person_by_email_index( db_session, ["ALICE@x.io", "alice.l@x.io"], ) assert idx["alice@x.io"].id == p.id assert idx["alice.l@x.io"].id == p.id @pytest.mark.asyncio async def test_lookup_skips_deleted_persons(db_session) -> None: await _mk(db_session, "ghost@x.io", aliases=["g@x.io"], deleted=True) await db_session.commit() idx = await build_person_by_email_index(db_session, ["g@x.io", "ghost@x.io"]) assert idx == {} @pytest.mark.asyncio async def test_lookup_returns_empty_for_unknown_emails(db_session) -> None: await _mk(db_session, "alice@x.io") await db_session.commit() idx = await build_person_by_email_index(db_session, ["nobody@x.io"]) assert idx == {} @pytest.mark.asyncio async def test_lookup_handles_empty_input(db_session) -> None: idx = await build_person_by_email_index(db_session, []) assert idx == {}