| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222 |
- # -*- coding: utf-8 -*-
- import pytest
- import pytest_asyncio
- from unittest.mock import AsyncMock, patch, MagicMock
- from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
- from fastapi.testclient import TestClient
- from app.core.database import Base, get_db
- from app.core.auth import get_current_user, require_min_role, RoleLevel
- from app.models.plugin import Plugin, PluginVersion
- from app.services.plugin_service import PluginService
- from app.schemas.plugin import PluginUpdate, PluginSwitchVersion, PluginUpgradeDispatch
- from app.core.biz_exception import BizLogicError
- from app.main import app
- # 使用 SQLite 内存数据库进行测试
- TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
- test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
- TestSessionLocal = async_sessionmaker(
- bind=test_engine,
- class_=AsyncSession,
- autoflush=False,
- expire_on_commit=False,
- )
- @pytest_asyncio.fixture(scope="function")
- async def async_db():
- async with test_engine.begin() as conn:
- await conn.run_sync(Base.metadata.create_all)
- async with TestSessionLocal() as session:
- yield session
- async with test_engine.begin() as conn:
- await conn.run_sync(Base.metadata.drop_all)
- @pytest.mark.asyncio
- async def test_plugin_publish_and_versions(async_db: AsyncSession):
- # 1. 发布 1.0.0 版本
- res1 = await PluginService.publish_plugin(
- db=async_db,
- name="tls_plugin",
- version="1.0.0",
- display_name="TLSContact 插件",
- description="TLS 签证自动预约",
- download_url="https://oss.example.com/plugins/tls_plugin-1.0.0.py",
- sha256="hash100",
- changelog="初始版本",
- set_as_latest=True,
- )
- assert res1["name"] == "tls_plugin"
- assert res1["version"] == "1.0.0"
- assert res1["download_url"] == "https://oss.example.com/plugins/tls_plugin-1.0.0.py"
- # 2. 发布 1.0.1 版本
- res2 = await PluginService.publish_plugin(
- db=async_db,
- name="tls_plugin",
- version="1.0.1",
- display_name="TLSContact 插件更新版",
- description="TLS 签证更新",
- download_url="https://oss.example.com/plugins/tls_plugin-1.0.1.py",
- sha256="hash101",
- changelog="修复问题",
- set_as_latest=True,
- )
- assert res2["version"] == "1.0.1"
- # 3. 获取详情并验证版本列表
- detail = await PluginService.get_plugin_detail(db=async_db, plugin_id=res1["plugin_id"])
- assert detail["name"] == "tls_plugin"
- assert detail["latest_version"] == "1.0.1"
- assert len(detail["versions"]) == 2
- # 4. 获取列表
- list_res = await PluginService.get_plugin_list(db=async_db, page=1, page_size=10)
- assert list_res["total"] == 1
- assert list_res["list"][0].latest_version == "1.0.1"
- @pytest.mark.asyncio
- async def test_plugin_switch_version_and_delete_protection(async_db: AsyncSession):
- # 发布 1.0.0 和 1.0.1
- p = await PluginService.publish_plugin(
- db=async_db,
- name="bls_plugin",
- version="1.0.0",
- download_url="https://oss.example.com/bls-1.0.0.py",
- sha256="h1",
- )
- plugin_id = p["plugin_id"]
- await PluginService.publish_plugin(
- db=async_db,
- name="bls_plugin",
- version="1.0.1",
- download_url="https://oss.example.com/bls-1.0.1.py",
- sha256="h2",
- set_as_latest=True,
- )
- # 尝试删除当前生效版本 1.0.1 -> 应该报错被阻止
- with pytest.raises(BizLogicError) as exc_info:
- await PluginService.delete_version(db=async_db, plugin_id=plugin_id, version="1.0.1")
- assert "Cannot delete active latest version" in str(exc_info.value)
- # 切换生效版本回退到 1.0.0
- switched = await PluginService.switch_version(db=async_db, plugin_id=plugin_id, version="1.0.0")
- assert switched.latest_version == "1.0.0"
- # 此时允许删除 1.0.1
- deleted = await PluginService.delete_version(db=async_db, plugin_id=plugin_id, version="1.0.1")
- assert deleted is True
- # 验证版本仅剩 1.0.0
- detail = await PluginService.get_plugin_detail(db=async_db, plugin_id=plugin_id)
- assert len(detail["versions"]) == 1
- assert detail["versions"][0].version == "1.0.0"
- @pytest.mark.asyncio
- async def test_plugin_upgrade_dispatch_and_latest(async_db: AsyncSession):
- await PluginService.publish_plugin(
- db=async_db,
- name="vfs_plugin",
- version="2.0.0",
- display_name="VFS 插件",
- download_url="https://oss.example.com/vfs-2.0.0.py",
- sha256="sha_vfs",
- )
- # 模拟 Redis Client
- mock_redis = AsyncMock()
- with patch("app.services.plugin_service.get_redis_client", return_value=mock_redis):
- # 广播给全部节点
- payload = await PluginService.dispatch_upgrade(db=async_db, target_node="all", plugins=["vfs_plugin"])
- assert len(payload) == 1
- assert payload[0]["name"] == "vfs_plugin"
- assert payload[0]["version"] == "2.0.0"
- mock_redis.publish.assert_called_once()
- args, _ = mock_redis.publish.call_args
- assert args[0] == "vs:channel:upgrade"
- # 节点主动拉取最新插件
- latest_list = await PluginService.get_latest_plugins(db=async_db)
- assert len(latest_list) == 1
- assert latest_list[0]["name"] == "vfs_plugin"
- assert latest_list[0]["version"] == "2.0.0"
- class DummyAdminUser:
- id = 1
- role = "admin"
- @pytest.fixture
- def test_client():
- async def override_get_db():
- async with TestSessionLocal() as session:
- yield session
- app.dependency_overrides[get_db] = override_get_db
- app.dependency_overrides[get_current_user] = lambda: DummyAdminUser()
- app.dependency_overrides[require_min_role(RoleLevel.admin)] = lambda: DummyAdminUser()
- with TestClient(app) as client:
- yield client
- app.dependency_overrides.clear()
- def test_plugin_api_http_endpoints(test_client):
- import asyncio
- async def setup_db():
- async with test_engine.begin() as conn:
- await conn.run_sync(Base.metadata.create_all)
- asyncio.run(setup_db())
- # 1. POST /api/plugins/publish (JSON 格式)
- resp = test_client.post("/api/plugins/publish", json={
- "name": "tls_plugin",
- "version": "1.0.0",
- "display_name": "TLS 签证插件",
- "download_url": "https://oss.example.com/tls.py",
- "sha256": "abc123sha",
- "changelog": "init",
- "set_as_latest": True
- })
- assert resp.status_code == 200
- data = resp.json()
- assert data["code"] == 0
- plugin_id = data["data"]["plugin_id"]
- # 2. GET /api/plugins/list_all
- resp = test_client.get("/api/plugins/list_all")
- assert resp.status_code == 200
- assert resp.json()["data"]["total"] == 1
- # 3. GET /api/plugins/detail
- resp = test_client.get(f"/api/plugins/detail?plugin_id={plugin_id}")
- assert resp.status_code == 200
- assert resp.json()["data"]["name"] == "tls_plugin"
- # 4. PUT /api/plugins/update
- resp = test_client.put(f"/api/plugins/update?plugin_id={plugin_id}", json={
- "display_name": "TLS 签证插件 (修改版)"
- })
- assert resp.status_code == 200
- assert resp.json()["data"]["display_name"] == "TLS 签证插件 (修改版)"
- # 5. GET /api/plugins/latest
- resp = test_client.get("/api/plugins/latest")
- assert resp.status_code == 200
- assert len(resp.json()["data"]) == 1
- # 6. DELETE /api/plugins/delete
- resp = test_client.delete(f"/api/plugins/delete?plugin_id={plugin_id}")
- assert resp.status_code == 200
- assert resp.json()["data"] is True
|