File size: 7,849 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""QA result parsing: extract structured results from Playwright JSON reports."""

import base64
import json
import shutil
import urllib.parse
from pathlib import Path

from config.qa import QA_FRONTEND_DIR
from enums import QaResult
from qa.store import qa_int, qa_run_root


def qa_status_from_playwright(result_status: str | None, test_status: str | None) -> str:
    status = result_status or ""
    if status == "passed":
        return QaResult.PASSED
    if status == "skipped":
        return QaResult.SKIPPED
    if status:
        return QaResult.FAILED
    if test_status == "expected":
        return QaResult.PASSED
    if test_status == "skipped":
        return QaResult.SKIPPED
    return QaResult.FAILED


def qa_find_attachment(result: dict, name: str):
    for attachment in result.get("attachments", []) or []:
        if attachment.get("name") == name:
            return attachment
    return None


def qa_attachment_path(attachment: dict | None, report_path: Path):
    if not attachment or not attachment.get("path"):
        return None
    raw_path = Path(str(attachment["path"]))
    candidates = [
        raw_path if raw_path.is_absolute() else (QA_FRONTEND_DIR / raw_path),
        raw_path if raw_path.is_absolute() else (report_path.parent / raw_path),
    ]
    for candidate in candidates:
        if candidate.exists():
            return candidate.resolve()
    return None


def qa_asset_url(run_id: str, source_path: Path | None):
    if source_path is None:
        return None
    root = qa_run_root(run_id).resolve()
    try:
        relative = source_path.resolve().relative_to(root)
    except ValueError:
        assets_dir = root / "assets"
        assets_dir.mkdir(parents=True, exist_ok=True)
        destination = assets_dir / source_path.name
        if not destination.exists():
            shutil.copy2(source_path, destination)
        relative = destination.relative_to(root)
    return f"/qa/runs/{run_id}/assets/{urllib.parse.quote(relative.as_posix())}"


def qa_read_attachment_text(attachment: dict | None, report_path: Path):
    if not attachment:
        return ""
    source_path = qa_attachment_path(attachment, report_path)
    if source_path is not None:
        return source_path.read_text()
    body = attachment.get("body")
    if not isinstance(body, str):
        return ""
    stripped = body.strip()
    if stripped.startswith("{") or stripped.startswith("["):
        return body
    try:
        return base64.b64decode(body).decode("utf-8")
    except Exception:
        return ""


def qa_parse_json_text(text: str):
    if not text.strip():
        return None
    try:
        return json.loads(text)
    except Exception:
        start = text.find("{")
        end = text.rfind("}")
        if start >= 0 and end > start:
            try:
                return json.loads(text[start:end + 1])
            except Exception:
                return None
    return None


def qa_title_parts(title: str):
    if ": apply " not in title:
        return title, "Unknown tile"
    image_name, rest = title.split(": apply ", 1)
    tile_name = rest.rsplit(" to ", 1)[0] if " to " in rest else rest
    return image_name, tile_name


def qa_grouped_case_metas(result: dict, report_path: Path):
    metas = []
    for attachment in result.get("attachments", []) or []:
        name = str(attachment.get("name") or "")
        if not name.startswith("qa-case-") or not name.endswith("-meta"):
            continue
        meta = qa_parse_json_text(qa_read_attachment_text(attachment, report_path))
        if not isinstance(meta, dict):
            continue
        prefix = str(meta.get("attachmentPrefix") or name.removesuffix("-meta"))
        metas.append((prefix, meta))

    def sort_key(item):
        _, meta = item
        return qa_int(meta.get("caseIndex"), 0)

    return sorted(metas, key=sort_key)


def qa_case_status(meta: dict, fallback_status: str) -> str:
    status = str(meta.get("status") or "").lower()
    if status in {QaResult.PASSED, QaResult.FAILED, QaResult.SKIPPED}:
        return status
    return fallback_status


def collect_playwright_specs(suite: dict, entries: list[tuple[str, dict]]):
    for spec in suite.get("specs", []) or []:
        title = spec.get("title") or "Untitled QA case"
        for test in spec.get("tests", []) or []:
            entries.append((title, test))
    for child in suite.get("suites", []) or []:
        collect_playwright_specs(child, entries)


def parse_qa_results(run_id: str, report_path: Path):
    if not report_path.exists():
        return []
    report = json.loads(report_path.read_text())
    entries: list[tuple[str, dict]] = []
    for suite in report.get("suites", []) or []:
        collect_playwright_specs(suite, entries)

    results = []
    for index, (title, test) in enumerate(entries):
        playwright_results = test.get("results", []) or [{}]
        final_result = playwright_results[-1]
        fallback_status = qa_status_from_playwright(final_result.get("status"), test.get("status"))
        grouped_cases = qa_grouped_case_metas(final_result, report_path)
        if grouped_cases:
            has_case_failure = any(qa_case_status(meta, fallback_status) == "failed" for _, meta in grouped_cases)
            global_error = final_result.get("error", {}).get("message") if isinstance(final_result.get("error"), dict) else None
            for case_index, (prefix, meta) in enumerate(grouped_cases, start=1):
                before_attachment = qa_find_attachment(final_result, f"{prefix}-before-canvas")
                after_attachment = qa_find_attachment(final_result, f"{prefix}-after-texture-canvas")
                gemini_attachment = qa_find_attachment(final_result, f"{prefix}-gemini-judge")
                status = qa_case_status(meta, fallback_status)
                if fallback_status == "failed" and not has_case_failure:
                    status = "failed"
                case_id = qa_int(meta.get("caseIndex"), case_index)
                results.append({
                    "id": f"{run_id}-{case_id}",
                    "imageKey": meta.get("imageName") or meta.get("roomName") or title,
                    "imageName": meta.get("imageName") or meta.get("roomName") or title,
                    "tileName": meta.get("tileName") or "Unknown tile",
                    "status": status,
                    "beforeImageUrl": qa_asset_url(run_id, qa_attachment_path(before_attachment, report_path)),
                    "afterImageUrl": qa_asset_url(run_id, qa_attachment_path(after_attachment, report_path)),
                    "gemini": qa_parse_json_text(qa_read_attachment_text(gemini_attachment, report_path)),
                    "error": meta.get("error") if isinstance(meta.get("error"), str) else global_error,
                })
            continue

        image_name, tile_name = qa_title_parts(title)
        before_attachment = qa_find_attachment(final_result, "before-canvas")
        after_attachment = qa_find_attachment(final_result, "after-texture-canvas")
        gemini_attachment = qa_find_attachment(final_result, "gemini-judge")
        error = final_result.get("error", {}).get("message") if isinstance(final_result.get("error"), dict) else None

        results.append({
            "id": f"{run_id}-{index + 1}",
            "imageKey": image_name,
            "imageName": image_name,
            "tileName": tile_name,
            "status": fallback_status,
            "beforeImageUrl": qa_asset_url(run_id, qa_attachment_path(before_attachment, report_path)),
            "afterImageUrl": qa_asset_url(run_id, qa_attachment_path(after_attachment, report_path)),
            "gemini": qa_parse_json_text(qa_read_attachment_text(gemini_attachment, report_path)),
            "error": error,
        })
    return results