Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

8.4 KB
Raw Blame
"""Tests for the Word MCP connector seed migration."""

import importlib.util
import json
from pathlib import Path
from unittest.mock import patch

import pytest
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy import create_engine, text


def _load_migration_module():
    migration_file = (
        Path(__file__).parent.parent.parent
        / "src/xagent/migrations/versions/20260917_seed_word_mcp_app.py"
    )
    spec = importlib.util.spec_from_file_location("seed_word_migration", migration_file)
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module


def _operations(connection):
    return Operations(MigrationContext.configure(connection))


def _create_table(connection):
    connection.execute(
        text(
            """
            CREATE TABLE public_mcp_apps (
                id INTEGER PRIMARY KEY,
                app_id VARCHAR(100) NOT NULL UNIQUE,
                name VARCHAR(200) NOT NULL,
                description TEXT,
                icon VARCHAR(1000),
                transport VARCHAR(50) NOT NULL DEFAULT 'oauth',
                provider_name VARCHAR(50),
                category VARCHAR(100),
                oauth_scopes JSON,
                is_visible_in_connector BOOLEAN NOT NULL DEFAULT 1,
                launch_config JSON
            )
            """
        )
    )


def _app_ids(connection):
    return set(connection.execute(text("SELECT app_id FROM public_mcp_apps")).scalars())


def test_upgrade_inserts_word(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        _create_table(connection)
        with patch.object(migration, "op", _operations(connection)):
            migration.upgrade()
        assert "word" in _app_ids(connection)
        row = connection.execute(
            text(
                "SELECT transport, provider_name, launch_config FROM public_mcp_apps"
                " WHERE app_id='word'"
            )
        ).first()
        assert row[0] == "oauth"
        assert row[1] == "microsoft"
        assert "xagent.web.tools.mcp.word" in str(row[2])
        assert '"builtin_provenance"' in str(row[2])


def test_upgrade_is_idempotent(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        _create_table(connection)
        with patch.object(migration, "op", _operations(connection)):
            migration.upgrade()
            migration.upgrade()  # second run must not raise or duplicate
        rows = connection.execute(
            text("SELECT COUNT(*) FROM public_mcp_apps WHERE app_id='word'")
        ).scalar()
        assert rows == 1


def test_upgrade_accepts_provenance_owned_row(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        _create_table(connection)
        launch_config = dict(migration.ROW["launch_config"])
        marker = dict(migration.BUILTIN_PROVENANCE)
        marker["version"] = 0
        launch_config["builtin_provenance"] = marker
        connection.execute(
            text(
                "INSERT INTO public_mcp_apps "
                "(app_id, name, transport, launch_config) "
                "VALUES ('word', 'Word', 'oauth', :launch_config)"
            ),
            {"launch_config": json.dumps(launch_config)},
        )
        with patch.object(migration, "op", _operations(connection)):
            migration.upgrade()
        assert "word" in _app_ids(connection)


def test_upgrade_preserves_unowned_custom_word_row(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        _create_table(connection)
        connection.execute(
            text(
                "INSERT INTO public_mcp_apps "
                "(app_id, name, description, transport, launch_config) "
                "VALUES ('word', 'Operator Word', 'custom', 'stdio', NULL)"
            )
        )
        with patch.object(migration, "op", _operations(connection)):
            migration.upgrade()
        row = connection.execute(
            text("SELECT name FROM public_mcp_apps WHERE app_id='word'")
        ).scalar_one()
        assert row == "Operator Word"


def test_seed_row_keeps_stable_registry_identity(tmp_path):
    """The frozen seed keeps identity fields aligned with the registry.

    Description and launch configuration intentionally evolve in the next
    migration, so comparing the entire row would make a correct migration
    chain impossible to downgrade faithfully.
    """
    from xagent.web.builtin_mcp_registry import get_builtin_public_mcp_app_rows

    migration = _load_migration_module()
    registry_row = next(
        r for r in get_builtin_public_mcp_app_rows() if r["app_id"] == "word"
    )
    # offline_access was added after this seed by 20261008_microsoft_offline_access.
    registry_row = {
        **registry_row,
        "oauth_scopes": [
            s for s in registry_row["oauth_scopes"] if s != "offline_access"
        ],
    }
    assert {
        key: migration.ROW[key]
        for key in (
            "app_id",
            "name",
            "icon",
            "transport",
            "provider_name",
            "category",
            "oauth_scopes",
            "is_visible_in_connector",
        )
    } == {
        key: registry_row[key]
        for key in (
            "app_id",
            "name",
            "icon",
            "transport",
            "provider_name",
            "category",
            "oauth_scopes",
            "is_visible_in_connector",
        )
    }
    assert (
        migration.ROW["launch_config"]["builtin_provenance"]
        == registry_row["launch_config"]["builtin_provenance"]
    )


def test_downgrade_removes_word(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        _create_table(connection)
        with patch.object(migration, "op", _operations(connection)):
            migration.upgrade()
            migration.downgrade()
        assert "word" not in _app_ids(connection)


def test_downgrade_preserves_unowned_custom_word_row(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        _create_table(connection)
        connection.execute(
            text(
                "INSERT INTO public_mcp_apps "
                "(app_id, name, description, transport, launch_config) "
                "VALUES ('word', 'Operator Word', 'custom', 'stdio', '{}')"
            )
        )
        with patch.object(migration, "op", _operations(connection)):
            migration.downgrade()
        row = connection.execute(
            text("SELECT name FROM public_mcp_apps WHERE app_id='word'")
        ).scalar_one()
        assert row == "Operator Word"


def test_upgrade_requires_launch_config_for_provenance(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        connection.execute(
            text(
                """
                CREATE TABLE public_mcp_apps (
                    id INTEGER PRIMARY KEY,
                    app_id VARCHAR(100) NOT NULL UNIQUE,
                    name VARCHAR(200) NOT NULL,
                    transport VARCHAR(50) NOT NULL DEFAULT 'oauth'
                )
                """
            )
        )
        with patch.object(migration, "op", _operations(connection)):
            with pytest.raises(RuntimeError, match="launch_config"):
                migration.upgrade()


def test_upgrade_and_downgrade_no_op_without_table(tmp_path):
    engine = create_engine(f"sqlite:///{tmp_path / 'test.db'}")
    migration = _load_migration_module()
    with engine.begin() as connection:
        with patch.object(migration, "op", _operations(connection)):
            migration.upgrade()
            migration.downgrade()
        table_names = set(
            connection.execute(
                text("SELECT name FROM sqlite_master WHERE type='table'")
            ).scalars()
        )
        assert "public_mcp_apps" not in table_names