File size: 5,223 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""Tests for GET /health/preflight endpoint."""
from __future__ import annotations

import os
from pathlib import Path
from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient

from schemas.api import PreflightResponse


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture
def app(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
    root = tmp_path / "audits"
    root.mkdir(parents=True, exist_ok=True)
    monkeypatch.setenv("AUDIT_JOBS_ROOT", str(root))
    monkeypatch.setenv("OPENAI_API_KEY", "sk-test-key")

    import services.renderer as renderer_module
    monkeypatch.setattr(renderer_module, "warmup", lambda: None)

    from main import create_app
    return create_app()


@pytest.fixture
def client(app):
    return TestClient(app)


# ---------------------------------------------------------------------------
# Test 1: All checks pass → ready=True, warnings=[]
# ---------------------------------------------------------------------------


def test_preflight_all_pass(client: TestClient, monkeypatch: pytest.MonkeyPatch):
    """When env + binaries are present the endpoint reports ready=True."""
    monkeypatch.setenv("OPENAI_API_KEY", "sk-test")

    import shutil as _shutil
    original_which = _shutil.which

    def fake_which(name):
        if name in ("soffice", "pdftoppm"):
            return f"/usr/bin/{name}"
        return original_which(name)

    with patch("services.preflight.shutil.which", side_effect=fake_which):
        response = client.get("/health/preflight")

    assert response.status_code == 200
    body = response.json()
    parsed = PreflightResponse.model_validate(body)
    assert parsed.ready is True
    assert parsed.warnings == []
    assert parsed.checks.jobs_root_writable is True
    assert parsed.checks.openai_api_key is True
    assert parsed.checks.soffice is True
    assert parsed.checks.pdftoppm is True
    assert parsed.jobs_root != ""


# ---------------------------------------------------------------------------
# Test 2: Missing OPENAI_API_KEY → ready=False, appropriate warning
# ---------------------------------------------------------------------------


def test_preflight_missing_openai_key(client: TestClient, monkeypatch: pytest.MonkeyPatch):
    """Missing OPENAI_API_KEY causes ready=False with a meaningful warning."""
    monkeypatch.delenv("OPENAI_API_KEY", raising=False)

    import shutil as _shutil
    original_which = _shutil.which

    def fake_which(name):
        if name in ("soffice", "pdftoppm"):
            return f"/usr/bin/{name}"
        return original_which(name)

    with patch("services.preflight.shutil.which", side_effect=fake_which):
        response = client.get("/health/preflight")

    assert response.status_code == 200
    body = response.json()
    parsed = PreflightResponse.model_validate(body)
    assert parsed.ready is False
    assert parsed.checks.openai_api_key is False
    assert any("OPENAI_API_KEY" in w for w in parsed.warnings)


# ---------------------------------------------------------------------------
# Test 3: jobs_root not writable → ready=False, appropriate warning
# ---------------------------------------------------------------------------


def test_preflight_unwritable_jobs_root(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
    """An unwritable jobs_root causes ready=False with a meaningful warning."""
    monkeypatch.setenv("OPENAI_API_KEY", "sk-test")

    import services.renderer as renderer_module
    monkeypatch.setattr(renderer_module, "warmup", lambda: None)

    # Patch _writable_dir to simulate an unwritable directory.
    with patch("services.preflight._writable_dir", return_value=False):
        monkeypatch.setenv("AUDIT_JOBS_ROOT", str(tmp_path / "audits"))
        from main import create_app
        app = create_app()
        with TestClient(app) as fresh_client:
            response = fresh_client.get("/health/preflight")

    assert response.status_code == 200
    body = response.json()
    parsed = PreflightResponse.model_validate(body)
    assert parsed.ready is False
    assert parsed.checks.jobs_root_writable is False
    assert any("not writable" in w for w in parsed.warnings)


# ---------------------------------------------------------------------------
# Test 4: Endpoint always returns 200 even when all checks fail
# ---------------------------------------------------------------------------


def test_preflight_always_200(client: TestClient, monkeypatch: pytest.MonkeyPatch):
    """The preflight endpoint never raises — it always returns HTTP 200."""
    monkeypatch.delenv("OPENAI_API_KEY", raising=False)

    with patch("services.preflight._writable_dir", return_value=False):
        with patch("services.preflight.shutil.which", return_value=None):
            response = client.get("/health/preflight")

    assert response.status_code == 200
    body = response.json()
    parsed = PreflightResponse.model_validate(body)
    assert parsed.ready is False
    # All four warnings should be present
    assert len(parsed.warnings) == 4