feat(backend): Phase 1-4 全新開發完成,37/37 TDD 通過

[Phase 0 Reset]
- 清除舊版 app/、alembic/versions/、雜亂測試腳本
- 新 requirements.txt (移除 caldav/redis/keycloak-lib,加入 apscheduler/croniter/docker/paramiko/ping3/dnspython)

[Phase 1 資料庫]
- 9 張資料表 SQLAlchemy Models:tenants / accounts / schedules / schedule_logs /
  tenant_schedule_results / account_schedule_results / servers / server_status_logs / system_status_logs
- Alembic migration 001_create_all_tables (已套用到 10.1.0.20:5433/virtual_mis)
- seed.py:schedules 初始 3 筆 / servers 初始 4 筆

[Phase 2 CRUD API]
- GET/POST/PUT/DELETE: /api/v1/tenants / accounts / servers / schedules
- /api/v1/system-status
- 帳號編碼自動產生 (prefix + seq_no 4碼左補0)
- 燈號 (lights) 從最新排程結果取得

[Phase 3 Watchdog]
- APScheduler interval 3分鐘,原子 UPDATE status=Going 防重複執行
- 手動觸發 API: POST /api/v1/schedules/{id}/run

[Phase 4 Service Clients]
- KeycloakClient:vmis-admin realm,REST API (不用 python-keycloak)
- MailClient:Docker Mailserver @ 10.1.0.254:8080,含 MX DNS 驗證
- DockerClient:docker-py 本機 + paramiko SSH 遠端 compose
- NextcloudClient:OCS API user/quota
- SystemChecker:功能驗證 (traefik routers>0 / keycloak token / SMTP EHLO / DB SELECT 1 / ping)

[TDD]
- 37 tests / 37 passed (2.11s)
- SQLite in-memory + StaticPool,無需外部 DB

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
VMIS Developer
2026-03-14 13:10:15 +08:00
parent 22611f7f73
commit 42d1420f9c
52 changed files with 2934 additions and 0 deletions

87
backend/tests/conftest.py Normal file
View File

@@ -0,0 +1,87 @@
"""
pytest fixtures for VMIS backend testing.
Uses SQLite in-memory DB (no external DB required for unit tests).
"""
import pytest
from unittest.mock import patch
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.core.database import Base, get_db
# ⚠️ Import all models BEFORE create_all so SQLAlchemy registers the tables
import app.models # noqa: F401
from app.main import app
TEST_DATABASE_URL = "sqlite:///:memory:"
# StaticPool ensures all connections share the same in-memory SQLite database
engine = create_engine(
TEST_DATABASE_URL,
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
@pytest.fixture(scope="function")
def db():
"""Create fresh DB tables for each test."""
Base.metadata.create_all(bind=engine)
session = TestingSessionLocal()
try:
yield session
finally:
session.close()
Base.metadata.drop_all(bind=engine)
@pytest.fixture(scope="function")
def client(db):
"""TestClient with DB override. Patches lifespan to skip real DB/scheduler."""
def override_get_db():
try:
yield db
finally:
pass
app.dependency_overrides[get_db] = override_get_db
# Patch lifespan startup/shutdown to avoid connecting to real DB or starting scheduler
with patch("app.main.seed_initial_data"), \
patch("app.main.start_watchdog"), \
patch("app.main.stop_watchdog"):
with TestClient(app, raise_server_exceptions=True) as c:
yield c
app.dependency_overrides.clear()
@pytest.fixture
def sample_tenant(client):
"""Create and return a sample tenant."""
payload = {
"code": "TEST01",
"prefix": "TC",
"name": "測試租戶一",
"domain": "test01.lab.taipei",
"status": "trial",
}
resp = client.post("/api/v1/tenants", json=payload)
assert resp.status_code == 201
return resp.json()
@pytest.fixture
def sample_account(client, sample_tenant):
"""Create and return a sample account."""
payload = {
"tenant_id": sample_tenant["id"],
"sso_account": "user01",
"notification_email": "user01@external.com",
"quota_limit": 20,
}
resp = client.post("/api/v1/accounts", json=payload)
assert resp.status_code == 201
return resp.json()