test_plugin_api.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. import pytest_asyncio
  4. from unittest.mock import AsyncMock, patch, MagicMock
  5. from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
  6. from fastapi.testclient import TestClient
  7. from app.core.database import Base, get_db
  8. from app.core.auth import get_current_user, require_min_role, RoleLevel
  9. from app.models.plugin import Plugin, PluginVersion
  10. from app.services.plugin_service import PluginService
  11. from app.schemas.plugin import PluginUpdate, PluginSwitchVersion, PluginUpgradeDispatch
  12. from app.core.biz_exception import BizLogicError
  13. from app.main import app
  14. # 使用 SQLite 内存数据库进行测试
  15. TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
  16. test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
  17. TestSessionLocal = async_sessionmaker(
  18. bind=test_engine,
  19. class_=AsyncSession,
  20. autoflush=False,
  21. expire_on_commit=False,
  22. )
  23. @pytest_asyncio.fixture(scope="function")
  24. async def async_db():
  25. async with test_engine.begin() as conn:
  26. await conn.run_sync(Base.metadata.create_all)
  27. async with TestSessionLocal() as session:
  28. yield session
  29. async with test_engine.begin() as conn:
  30. await conn.run_sync(Base.metadata.drop_all)
  31. @pytest.mark.asyncio
  32. async def test_plugin_publish_and_versions(async_db: AsyncSession):
  33. # 1. 发布 1.0.0 版本
  34. res1 = await PluginService.publish_plugin(
  35. db=async_db,
  36. name="tls_plugin",
  37. version="1.0.0",
  38. display_name="TLSContact 插件",
  39. description="TLS 签证自动预约",
  40. download_url="https://oss.example.com/plugins/tls_plugin-1.0.0.py",
  41. sha256="hash100",
  42. changelog="初始版本",
  43. set_as_latest=True,
  44. )
  45. assert res1["name"] == "tls_plugin"
  46. assert res1["version"] == "1.0.0"
  47. assert res1["download_url"] == "https://oss.example.com/plugins/tls_plugin-1.0.0.py"
  48. # 2. 发布 1.0.1 版本
  49. res2 = await PluginService.publish_plugin(
  50. db=async_db,
  51. name="tls_plugin",
  52. version="1.0.1",
  53. display_name="TLSContact 插件更新版",
  54. description="TLS 签证更新",
  55. download_url="https://oss.example.com/plugins/tls_plugin-1.0.1.py",
  56. sha256="hash101",
  57. changelog="修复问题",
  58. set_as_latest=True,
  59. )
  60. assert res2["version"] == "1.0.1"
  61. # 3. 获取详情并验证版本列表
  62. detail = await PluginService.get_plugin_detail(db=async_db, plugin_id=res1["plugin_id"])
  63. assert detail["name"] == "tls_plugin"
  64. assert detail["latest_version"] == "1.0.1"
  65. assert len(detail["versions"]) == 2
  66. # 4. 获取列表
  67. list_res = await PluginService.get_plugin_list(db=async_db, page=1, page_size=10)
  68. assert list_res["total"] == 1
  69. assert list_res["list"][0].latest_version == "1.0.1"
  70. @pytest.mark.asyncio
  71. async def test_plugin_switch_version_and_delete_protection(async_db: AsyncSession):
  72. # 发布 1.0.0 和 1.0.1
  73. p = await PluginService.publish_plugin(
  74. db=async_db,
  75. name="bls_plugin",
  76. version="1.0.0",
  77. download_url="https://oss.example.com/bls-1.0.0.py",
  78. sha256="h1",
  79. )
  80. plugin_id = p["plugin_id"]
  81. await PluginService.publish_plugin(
  82. db=async_db,
  83. name="bls_plugin",
  84. version="1.0.1",
  85. download_url="https://oss.example.com/bls-1.0.1.py",
  86. sha256="h2",
  87. set_as_latest=True,
  88. )
  89. # 尝试删除当前生效版本 1.0.1 -> 应该报错被阻止
  90. with pytest.raises(BizLogicError) as exc_info:
  91. await PluginService.delete_version(db=async_db, plugin_id=plugin_id, version="1.0.1")
  92. assert "Cannot delete active latest version" in str(exc_info.value)
  93. # 切换生效版本回退到 1.0.0
  94. switched = await PluginService.switch_version(db=async_db, plugin_id=plugin_id, version="1.0.0")
  95. assert switched.latest_version == "1.0.0"
  96. # 此时允许删除 1.0.1
  97. deleted = await PluginService.delete_version(db=async_db, plugin_id=plugin_id, version="1.0.1")
  98. assert deleted is True
  99. # 验证版本仅剩 1.0.0
  100. detail = await PluginService.get_plugin_detail(db=async_db, plugin_id=plugin_id)
  101. assert len(detail["versions"]) == 1
  102. assert detail["versions"][0].version == "1.0.0"
  103. @pytest.mark.asyncio
  104. async def test_plugin_upgrade_dispatch_and_latest(async_db: AsyncSession):
  105. await PluginService.publish_plugin(
  106. db=async_db,
  107. name="vfs_plugin",
  108. version="2.0.0",
  109. display_name="VFS 插件",
  110. download_url="https://oss.example.com/vfs-2.0.0.py",
  111. sha256="sha_vfs",
  112. )
  113. # 模拟 Redis Client
  114. mock_redis = AsyncMock()
  115. with patch("app.services.plugin_service.get_redis_client", return_value=mock_redis):
  116. # 广播给全部节点
  117. payload = await PluginService.dispatch_upgrade(db=async_db, target_node="all", plugins=["vfs_plugin"])
  118. assert len(payload) == 1
  119. assert payload[0]["name"] == "vfs_plugin"
  120. assert payload[0]["version"] == "2.0.0"
  121. mock_redis.publish.assert_called_once()
  122. args, _ = mock_redis.publish.call_args
  123. assert args[0] == "vs:channel:upgrade"
  124. # 节点主动拉取最新插件
  125. latest_list = await PluginService.get_latest_plugins(db=async_db)
  126. assert len(latest_list) == 1
  127. assert latest_list[0]["name"] == "vfs_plugin"
  128. assert latest_list[0]["version"] == "2.0.0"
  129. class DummyAdminUser:
  130. id = 1
  131. role = "admin"
  132. @pytest.fixture
  133. def test_client():
  134. async def override_get_db():
  135. async with TestSessionLocal() as session:
  136. yield session
  137. app.dependency_overrides[get_db] = override_get_db
  138. app.dependency_overrides[get_current_user] = lambda: DummyAdminUser()
  139. app.dependency_overrides[require_min_role(RoleLevel.admin)] = lambda: DummyAdminUser()
  140. with TestClient(app) as client:
  141. yield client
  142. app.dependency_overrides.clear()
  143. def test_plugin_api_http_endpoints(test_client):
  144. import asyncio
  145. async def setup_db():
  146. async with test_engine.begin() as conn:
  147. await conn.run_sync(Base.metadata.create_all)
  148. asyncio.run(setup_db())
  149. # 1. POST /api/plugins/publish (JSON 格式)
  150. resp = test_client.post("/api/plugins/publish", json={
  151. "name": "tls_plugin",
  152. "version": "1.0.0",
  153. "display_name": "TLS 签证插件",
  154. "download_url": "https://oss.example.com/tls.py",
  155. "sha256": "abc123sha",
  156. "changelog": "init",
  157. "set_as_latest": True
  158. })
  159. assert resp.status_code == 200
  160. data = resp.json()
  161. assert data["code"] == 0
  162. plugin_id = data["data"]["plugin_id"]
  163. # 2. GET /api/plugins/list_all
  164. resp = test_client.get("/api/plugins/list_all")
  165. assert resp.status_code == 200
  166. assert resp.json()["data"]["total"] == 1
  167. # 3. GET /api/plugins/detail
  168. resp = test_client.get(f"/api/plugins/detail?plugin_id={plugin_id}")
  169. assert resp.status_code == 200
  170. assert resp.json()["data"]["name"] == "tls_plugin"
  171. # 4. PUT /api/plugins/update
  172. resp = test_client.put(f"/api/plugins/update?plugin_id={plugin_id}", json={
  173. "display_name": "TLS 签证插件 (修改版)"
  174. })
  175. assert resp.status_code == 200
  176. assert resp.json()["data"]["display_name"] == "TLS 签证插件 (修改版)"
  177. # 5. GET /api/plugins/latest
  178. resp = test_client.get("/api/plugins/latest")
  179. assert resp.status_code == 200
  180. assert len(resp.json()["data"]) == 1
  181. # 6. DELETE /api/plugins/delete
  182. resp = test_client.delete(f"/api/plugins/delete?plugin_id={plugin_id}")
  183. assert resp.status_code == 200
  184. assert resp.json()["data"] is True