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:
0
backend/tests/__init__.py
Normal file
0
backend/tests/__init__.py
Normal file
87
backend/tests/conftest.py
Normal file
87
backend/tests/conftest.py
Normal 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()
|
||||
101
backend/tests/test_accounts.py
Normal file
101
backend/tests/test_accounts.py
Normal file
@@ -0,0 +1,101 @@
|
||||
"""TDD: Account CRUD API tests - 含帳號編碼自動產生驗證"""
|
||||
|
||||
|
||||
def test_create_account(client, sample_tenant):
|
||||
payload = {
|
||||
"tenant_id": sample_tenant["id"],
|
||||
"sso_account": "alice",
|
||||
"notification_email": "alice@gmail.com",
|
||||
"quota_limit": 30,
|
||||
}
|
||||
resp = client.post("/api/v1/accounts", json=payload)
|
||||
assert resp.status_code == 201
|
||||
data = resp.json()
|
||||
assert data["sso_account"] == "alice"
|
||||
assert data["tenant_id"] == sample_tenant["id"]
|
||||
assert data["quota_limit"] == 30
|
||||
assert data["is_active"] is True
|
||||
assert data["seq_no"] == 1
|
||||
# account_code = prefix(TC) + seq_no 4碼左補0
|
||||
assert data["account_code"] == "TC0001"
|
||||
# email = sso_account@domain
|
||||
assert data["email"] == f"alice@{sample_tenant['domain']}"
|
||||
|
||||
|
||||
def test_account_code_auto_increment(client, sample_tenant):
|
||||
"""驗證同租戶內帳號編碼流水號遞增"""
|
||||
for sso in ["alice", "bob", "carol"]:
|
||||
client.post("/api/v1/accounts", json={
|
||||
"tenant_id": sample_tenant["id"],
|
||||
"sso_account": sso,
|
||||
"notification_email": f"{sso}@external.com",
|
||||
})
|
||||
resp = client.get("/api/v1/accounts", params={"tenant_id": sample_tenant["id"]})
|
||||
accounts = resp.json()
|
||||
codes = [a["account_code"] for a in accounts]
|
||||
assert "TC0001" in codes
|
||||
assert "TC0002" in codes
|
||||
assert "TC0003" in codes
|
||||
|
||||
|
||||
def test_create_account_tenant_not_found(client):
|
||||
payload = {
|
||||
"tenant_id": 99999,
|
||||
"sso_account": "ghost",
|
||||
"notification_email": "ghost@gmail.com",
|
||||
}
|
||||
resp = client.post("/api/v1/accounts", json=payload)
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_list_accounts(client, sample_account):
|
||||
resp = client.get("/api/v1/accounts")
|
||||
assert resp.status_code == 200
|
||||
accounts = resp.json()
|
||||
assert len(accounts) == 1
|
||||
assert accounts[0]["sso_account"] == sample_account["sso_account"]
|
||||
assert accounts[0]["tenant_name"] is not None
|
||||
|
||||
|
||||
def test_list_accounts_by_tenant(client, sample_tenant, sample_account):
|
||||
resp = client.get("/api/v1/accounts", params={"tenant_id": sample_tenant["id"]})
|
||||
assert resp.status_code == 200
|
||||
assert len(resp.json()) == 1
|
||||
|
||||
|
||||
def test_get_account(client, sample_account):
|
||||
resp = client.get(f"/api/v1/accounts/{sample_account['id']}")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["id"] == sample_account["id"]
|
||||
assert data["lights"] is None
|
||||
|
||||
|
||||
def test_get_account_not_found(client):
|
||||
resp = client.get("/api/v1/accounts/99999")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_update_account(client, sample_account):
|
||||
resp = client.put(
|
||||
f"/api/v1/accounts/{sample_account['id']}",
|
||||
json={"legal_name": "Alice Chen", "quota_limit": 50},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["legal_name"] == "Alice Chen"
|
||||
assert data["quota_limit"] == 50
|
||||
|
||||
|
||||
def test_delete_account(client, sample_account):
|
||||
resp = client.delete(f"/api/v1/accounts/{sample_account['id']}")
|
||||
assert resp.status_code == 204
|
||||
resp = client.get(f"/api/v1/accounts/{sample_account['id']}")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_delete_tenant_cascades_accounts(client, sample_tenant, sample_account):
|
||||
"""刪除租戶後,帳號應該被 CASCADE 刪除"""
|
||||
client.delete(f"/api/v1/tenants/{sample_tenant['id']}")
|
||||
resp = client.get(f"/api/v1/accounts/{sample_account['id']}")
|
||||
assert resp.status_code == 404
|
||||
88
backend/tests/test_schedules.py
Normal file
88
backend/tests/test_schedules.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""TDD: Schedule API tests"""
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def _seed_schedules(db):
|
||||
"""Insert initial schedule records for tests"""
|
||||
from app.models.schedule import Schedule
|
||||
from croniter import croniter
|
||||
schedules = [
|
||||
Schedule(id=1, name="租戶檢查", cron_timer="0 */3 * * * *",
|
||||
status="Waiting", next_run_at=croniter("0 */3 * * * *", datetime.utcnow()).get_next(datetime)),
|
||||
Schedule(id=2, name="帳號檢查", cron_timer="0 */3 * * * *",
|
||||
status="Waiting", next_run_at=croniter("0 */3 * * * *", datetime.utcnow()).get_next(datetime)),
|
||||
Schedule(id=3, name="系統狀態", cron_timer="0 0 8 * * *",
|
||||
status="Waiting", next_run_at=croniter("0 0 8 * * *", datetime.utcnow()).get_next(datetime)),
|
||||
]
|
||||
for s in schedules:
|
||||
db.add(s)
|
||||
db.commit()
|
||||
|
||||
|
||||
def test_list_schedules(client, db):
|
||||
_seed_schedules(db)
|
||||
resp = client.get("/api/v1/schedules")
|
||||
assert resp.status_code == 200
|
||||
schedules = resp.json()
|
||||
assert len(schedules) == 3
|
||||
names = [s["name"] for s in schedules]
|
||||
assert "租戶檢查" in names
|
||||
assert "帳號檢查" in names
|
||||
assert "系統狀態" in names
|
||||
|
||||
|
||||
def test_get_schedule(client, db):
|
||||
_seed_schedules(db)
|
||||
resp = client.get("/api/v1/schedules/1")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["id"] == 1
|
||||
assert data["name"] == "租戶檢查"
|
||||
assert data["status"] == "Waiting"
|
||||
assert data["cron_timer"] == "0 */3 * * * *"
|
||||
assert data["next_run_at"] is not None
|
||||
|
||||
|
||||
def test_get_schedule_not_found(client, db):
|
||||
resp = client.get("/api/v1/schedules/99")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_update_schedule_cron(client, db):
|
||||
_seed_schedules(db)
|
||||
resp = client.put("/api/v1/schedules/1", json={"cron_timer": "0 */5 * * * *"})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["cron_timer"] == "0 */5 * * * *"
|
||||
assert data["next_run_at"] is not None
|
||||
|
||||
|
||||
def test_update_schedule_invalid_cron(client, db):
|
||||
_seed_schedules(db)
|
||||
resp = client.put("/api/v1/schedules/1", json={"cron_timer": "invalid cron"})
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_manual_run_schedule(client, db):
|
||||
_seed_schedules(db)
|
||||
resp = client.post("/api/v1/schedules/1/run")
|
||||
assert resp.status_code == 202
|
||||
data = resp.json()
|
||||
assert data["schedule_id"] == 1
|
||||
|
||||
|
||||
def test_manual_run_already_going(client, db):
|
||||
_seed_schedules(db)
|
||||
from app.models.schedule import Schedule
|
||||
s = db.get(Schedule, 1)
|
||||
s.status = "Going"
|
||||
db.commit()
|
||||
resp = client.post("/api/v1/schedules/1/run")
|
||||
assert resp.status_code == 409
|
||||
|
||||
|
||||
def test_schedule_logs_empty(client, db):
|
||||
_seed_schedules(db)
|
||||
resp = client.get("/api/v1/schedules/1/logs")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == []
|
||||
110
backend/tests/test_servers.py
Normal file
110
backend/tests/test_servers.py
Normal file
@@ -0,0 +1,110 @@
|
||||
"""TDD: Server CRUD + availability API tests"""
|
||||
|
||||
|
||||
def test_create_server(client):
|
||||
payload = {
|
||||
"name": "home",
|
||||
"ip_address": "10.1.0.254",
|
||||
"description": "核心服務主機",
|
||||
"sort_order": 1,
|
||||
}
|
||||
resp = client.post("/api/v1/servers", json=payload)
|
||||
assert resp.status_code == 201
|
||||
data = resp.json()
|
||||
assert data["name"] == "home"
|
||||
assert data["ip_address"] == "10.1.0.254"
|
||||
assert data["sort_order"] == 1
|
||||
assert data["is_active"] is True
|
||||
assert data["last_result"] is None
|
||||
# New server has no status logs: availability is None (not yet computed)
|
||||
assert data["availability"] is None
|
||||
|
||||
|
||||
def test_create_server_duplicate_ip(client):
|
||||
client.post("/api/v1/servers", json={"name": "A", "ip_address": "10.1.0.10"})
|
||||
resp = client.post("/api/v1/servers", json={"name": "B", "ip_address": "10.1.0.10"})
|
||||
assert resp.status_code == 409
|
||||
|
||||
|
||||
def test_list_servers_ordered_by_sort_order(client):
|
||||
client.post("/api/v1/servers", json={"name": "C", "ip_address": "10.1.0.30", "sort_order": 3})
|
||||
client.post("/api/v1/servers", json={"name": "A", "ip_address": "10.1.0.10", "sort_order": 1})
|
||||
client.post("/api/v1/servers", json={"name": "B", "ip_address": "10.1.0.20", "sort_order": 2})
|
||||
resp = client.get("/api/v1/servers")
|
||||
assert resp.status_code == 200
|
||||
servers = resp.json()
|
||||
assert [s["name"] for s in servers] == ["A", "B", "C"]
|
||||
|
||||
|
||||
def test_get_server(client):
|
||||
r = client.post("/api/v1/servers", json={"name": "nas", "ip_address": "10.1.0.20", "sort_order": 2})
|
||||
sid = r.json()["id"]
|
||||
resp = client.get(f"/api/v1/servers/{sid}")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["ip_address"] == "10.1.0.20"
|
||||
|
||||
|
||||
def test_get_server_not_found(client):
|
||||
resp = client.get("/api/v1/servers/99999")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_update_server(client):
|
||||
r = client.post("/api/v1/servers", json={"name": "old", "ip_address": "10.1.0.50"})
|
||||
sid = r.json()["id"]
|
||||
resp = client.put(f"/api/v1/servers/{sid}", json={"name": "new", "sort_order": 5})
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["name"] == "new"
|
||||
assert data["sort_order"] == 5
|
||||
|
||||
|
||||
def test_delete_server(client):
|
||||
r = client.post("/api/v1/servers", json={"name": "temp", "ip_address": "10.1.0.99"})
|
||||
sid = r.json()["id"]
|
||||
resp = client.delete(f"/api/v1/servers/{sid}")
|
||||
assert resp.status_code == 204
|
||||
resp = client.get(f"/api/v1/servers/{sid}")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_server_availability_with_logs(client, db):
|
||||
"""驗證可用率計算(有歷史紀錄)"""
|
||||
from datetime import datetime
|
||||
from app.models.schedule import Schedule, ScheduleLog
|
||||
from app.models.server import Server, ServerStatusLog
|
||||
|
||||
# Create schedule and log
|
||||
s = Schedule(id=10, name="test", cron_timer="0 * * * * *", status="Waiting", recorded_at=datetime.utcnow())
|
||||
db.add(s)
|
||||
slog = ScheduleLog(schedule_id=10, schedule_name="test", started_at=datetime.utcnow(), status="ok")
|
||||
db.add(slog)
|
||||
db.commit()
|
||||
db.refresh(slog)
|
||||
|
||||
# Create server
|
||||
r = client.post("/api/v1/servers", json={"name": "pingable", "ip_address": "10.1.0.100"})
|
||||
server_id = r.json()["id"]
|
||||
|
||||
# Insert 3 ok + 1 fail status logs with distinct timestamps to ensure ordering
|
||||
from datetime import timedelta
|
||||
base_time = datetime.utcnow()
|
||||
for i, ok in enumerate([True, True, True, False]):
|
||||
db.add(ServerStatusLog(
|
||||
schedule_log_id=slog.id, server_id=server_id,
|
||||
result=ok, response_time=12.5 if ok else None,
|
||||
recorded_at=base_time + timedelta(seconds=i), # ascending timestamps
|
||||
))
|
||||
db.commit()
|
||||
|
||||
resp = client.get(f"/api/v1/servers/{server_id}")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["last_result"] is False # last inserted (highest id, latest time) was False
|
||||
assert data["availability"]["availability_30d"] == 75.0
|
||||
|
||||
|
||||
def test_system_status_empty(client):
|
||||
resp = client.get("/api/v1/system-status")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == []
|
||||
100
backend/tests/test_tenants.py
Normal file
100
backend/tests/test_tenants.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""TDD: Tenant CRUD API tests"""
|
||||
|
||||
|
||||
def test_create_tenant(client):
|
||||
payload = {
|
||||
"code": "PORS01",
|
||||
"prefix": "PC",
|
||||
"name": "Porsche測試公司",
|
||||
"domain": "porsche.lab.taipei",
|
||||
"status": "trial",
|
||||
}
|
||||
resp = client.post("/api/v1/tenants", json=payload)
|
||||
assert resp.status_code == 201
|
||||
data = resp.json()
|
||||
assert data["code"] == "PORS01"
|
||||
assert data["prefix"] == "PC"
|
||||
assert data["domain"] == "porsche.lab.taipei"
|
||||
assert data["status"] == "trial"
|
||||
assert data["is_active"] is True
|
||||
assert data["quota_per_user"] == 20
|
||||
assert data["total_quota"] == 200
|
||||
assert data["id"] is not None
|
||||
|
||||
|
||||
def test_create_tenant_duplicate_code(client, sample_tenant):
|
||||
payload = {
|
||||
"code": sample_tenant["code"],
|
||||
"prefix": "XX",
|
||||
"name": "重複代碼",
|
||||
"domain": "another.lab.taipei",
|
||||
"status": "trial",
|
||||
}
|
||||
resp = client.post("/api/v1/tenants", json=payload)
|
||||
assert resp.status_code == 409
|
||||
|
||||
|
||||
def test_create_tenant_duplicate_domain(client, sample_tenant):
|
||||
payload = {
|
||||
"code": "NEWCODE",
|
||||
"prefix": "XX",
|
||||
"name": "重複網域",
|
||||
"domain": sample_tenant["domain"],
|
||||
"status": "trial",
|
||||
}
|
||||
resp = client.post("/api/v1/tenants", json=payload)
|
||||
assert resp.status_code == 409
|
||||
|
||||
|
||||
def test_list_tenants(client, sample_tenant):
|
||||
resp = client.get("/api/v1/tenants")
|
||||
assert resp.status_code == 200
|
||||
tenants = resp.json()
|
||||
assert len(tenants) == 1
|
||||
assert tenants[0]["code"] == sample_tenant["code"]
|
||||
|
||||
|
||||
def test_list_tenants_filter_active(client, sample_tenant):
|
||||
# Deactivate
|
||||
client.put(f"/api/v1/tenants/{sample_tenant['id']}", json={"is_active": False})
|
||||
resp = client.get("/api/v1/tenants", params={"is_active": True})
|
||||
assert resp.status_code == 200
|
||||
assert len(resp.json()) == 0
|
||||
|
||||
|
||||
def test_get_tenant(client, sample_tenant):
|
||||
resp = client.get(f"/api/v1/tenants/{sample_tenant['id']}")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["id"] == sample_tenant["id"]
|
||||
assert data["code"] == sample_tenant["code"]
|
||||
assert data["lights"] is None # No schedule runs yet
|
||||
|
||||
|
||||
def test_get_tenant_not_found(client):
|
||||
resp = client.get("/api/v1/tenants/99999")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_update_tenant(client, sample_tenant):
|
||||
resp = client.put(
|
||||
f"/api/v1/tenants/{sample_tenant['id']}",
|
||||
json={"name": "更新後的名稱", "status": "active"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["name"] == "更新後的名稱"
|
||||
assert data["status"] == "active"
|
||||
|
||||
|
||||
def test_delete_tenant(client, sample_tenant):
|
||||
resp = client.delete(f"/api/v1/tenants/{sample_tenant['id']}")
|
||||
assert resp.status_code == 204
|
||||
resp = client.get(f"/api/v1/tenants/{sample_tenant['id']}")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_health_endpoint(client):
|
||||
resp = client.get("/health")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["status"] == "ok"
|
||||
Reference in New Issue
Block a user