| """§43 系統初始化 init_system 測試(透過 import script 模組)。""" |
| from __future__ import annotations |
|
|
| import sys |
| from pathlib import Path |
|
|
| import pytest |
|
|
| from app.auth.passwords import hash_password |
| from app.db import _utcnow, get_conn |
|
|
| |
| sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts")) |
|
|
|
|
| @pytest.fixture() |
| def initsys(monkeypatch): |
| monkeypatch.setenv("KBV5_INIT_NONINTERACTIVE", "1") |
| import init_system |
| init_system.NON_INTERACTIVE = True |
| return init_system |
|
|
|
|
| def _mkadmin(): |
| c = get_conn() |
| c.execute( |
| "INSERT INTO users (username, email, password_hash, role, department, " |
| "created_at, is_active) VALUES (?,?,?,?,?,?,1)", |
| ("adm", "adm@x.tw", hash_password("x"), "admin", "管理部", _utcnow()), |
| ) |
| return c.execute("SELECT id FROM users WHERE username='adm'").fetchone()["id"] |
|
|
|
|
| def test_sample_docs_created(initsys): |
| aid = _mkadmin() |
| n = initsys.step_sample_docs(get_conn(), aid) |
| assert n == 3 |
| rows = get_conn().execute( |
| "SELECT title FROM documents WHERE author_id=?", (aid,)).fetchall() |
| titles = {r["title"] for r in rows} |
| assert "歡迎使用知識庫系統" in titles |
| assert "如何提交筆記" in titles |
| assert "系統使用指南" in titles |
|
|
|
|
| def test_sample_docs_idempotent(initsys): |
| aid = _mkadmin() |
| initsys.step_sample_docs(get_conn(), aid) |
| n2 = initsys.step_sample_docs(get_conn(), aid) |
| assert n2 == 0 |
|
|
|
|
| def test_sample_docs_are_public(initsys): |
| aid = _mkadmin() |
| initsys.step_sample_docs(get_conn(), aid) |
| rows = get_conn().execute( |
| "SELECT visibility FROM documents WHERE author_id=?", (aid,)).fetchall() |
| assert all(r["visibility"] == "public" for r in rows) |
|
|
|
|
| def test_health_check_no_admin(initsys): |
| |
| issues = initsys.health_check(get_conn()) |
| assert any("admin" in i for i in issues) |
|
|
|
|
| def test_health_check_with_admin(initsys): |
| _mkadmin() |
| |
| get_conn().execute( |
| "INSERT OR IGNORE INTO departments (name, sort_order, is_active, created_at) " |
| "VALUES ('管理部', 0, 1, ?)", (_utcnow(),)) |
| issues = initsys.health_check(get_conn()) |
| |
| assert not any("無 active admin" in i for i in issues) |
| assert not any("無部門" in i for i in issues) |
|
|
|
|
| def test_step_admin_skips_when_exists(initsys): |
| aid = _mkadmin() |
| result = initsys.step_admin(get_conn()) |
| assert result == aid |
|
|