File size: 6,449 Bytes
240bbb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verifier for the screenshot2 sparse-spec variant of /add-expense/:groupId.

The agent gets a deliberately under-specified text instruction; the visual
quirks are only in /app/reference.png. These tests assert the visual
quirks present in the reference, beyond just functional correctness.
"""
from pathlib import Path

import pytest
from playwright.sync_api import sync_playwright


URL = "http://127.0.0.1:5173/add-expense/1"
ARTIFACTS = Path("/logs/artifacts")


@pytest.fixture(scope="module")
def page():
    ARTIFACTS.mkdir(parents=True, exist_ok=True)
    page_errors: list[str] = []
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        ctx = browser.new_context(viewport={"width": 1280, "height": 800})
        page = ctx.new_page()
        page.on("pageerror", lambda e: page_errors.append(str(e)))
        page.goto(URL, wait_until="networkidle", timeout=30_000)
        try:
            page.wait_for_selector("h1", timeout=10_000)
        except Exception:
            pass
        page.screenshot(path=str(ARTIFACTS / "agent-app.png"), full_page=True)
        (ARTIFACTS / "pageerrors.log").write_text("\n".join(page_errors))
        yield page
        browser.close()


# ---------- functional baseline (same as screenshot1) ----------

def test_no_page_errors():
    errs = (ARTIFACTS / "pageerrors.log").read_text() if (ARTIFACTS / "pageerrors.log").exists() else ""
    assert not errs.strip(), f"Page errors:\n{errs}"


def test_h1_add_expense(page):
    h1 = page.locator("h1").first
    assert h1.is_visible()
    assert "Add Expense" in h1.inner_text()


def test_back_link_to_group(page):
    assert page.locator('a[href$="/groups/1"]').count() > 0


def test_form_inputs_present(page):
    assert page.locator('input[type="text"]').count() >= 1, "Description text input missing"
    assert page.locator('input[type="number"]').count() >= 1, "Amount number input missing"
    assert page.locator('select').count() >= 1, "Paid-by select missing"
    assert page.locator('input[type="checkbox"]').count() == 3, "Expected 3 split-among checkboxes"


def test_submit_button(page):
    assert page.get_by_role("button", name="Add Expense").count() >= 1


# ---------- VARIANT-SPECIFIC quirks (only derivable from the screenshot) ----------

def test_quirk_summary_panel_above_form(page):
    """A summary line showing the group name + member count appears between h1 and the form."""
    body = page.locator("body").inner_text()
    # Summary mentions "Tahoe Trip" AND "3 members" (in some form, e.g. "3 members" or "members: 3")
    assert "Tahoe Trip" in body, "Summary should mention group name 'Tahoe Trip'"
    # Count "3" appearance — at minimum the summary should show the member count.
    # Be lenient: accept "3 member" anywhere in body OR a li/div mentioning member count.
    assert "3 member" in body.lower() or "members · 3" in body.lower() or "· 3" in body, (
        f"Summary should mention 3 members. Body excerpt: {body[:600]!r}"
    )


def test_quirk_amount_before_description(page):
    """In DOM order, the Amount input appears before the Description input."""
    inputs = page.locator('input[type="number"], input[type="text"]')
    n = inputs.count()
    assert n >= 2, f"Expected at least 2 inputs, got {n}"
    # Iterate in DOM order — first matching input should be the Amount (number).
    first_type = inputs.nth(0).get_attribute("type")
    assert first_type == "number", (
        f"In the reference layout, the Amount field (type=number) precedes Description (type=text). "
        f"Got first input type={first_type!r}."
    )


def test_quirk_submit_before_cancel(page):
    """In DOM order within form-actions, the primary submit button appears before the Cancel link."""
    # Find the primary submit button and the cancel link, compare their bounding boxes by Y then X.
    submit = page.get_by_role("button", name="Add Expense").first
    cancel = page.locator('a:has-text("Cancel")').first
    assert submit.count() > 0, "Missing 'Add Expense' submit button"
    assert cancel.count() > 0, "Missing 'Cancel' link"
    sb = submit.bounding_box()
    cb = cancel.bounding_box()
    assert sb is not None and cb is not None, "Could not measure submit/cancel positions"
    # Variant: submit on the LEFT, cancel on the RIGHT (same row, submit.x < cancel.x).
    # If they're on different rows, fall back to DOM order via JS evaluate.
    same_row = abs(sb["y"] - cb["y"]) < 30
    if same_row:
        assert sb["x"] < cb["x"], (
            f"Variant has 'Add Expense' on the LEFT and 'Cancel' on the RIGHT; "
            f"got submit.x={sb['x']} cancel.x={cb['x']}"
        )
    else:
        # DOM-order fallback
        order = page.evaluate(
            """() => {
                const sub = [...document.querySelectorAll('button')].find(b => b.textContent.trim().startsWith('Add Expense') || b.textContent.trim().startsWith('Adding'));
                const can = [...document.querySelectorAll('a')].find(a => a.textContent.trim() === 'Cancel');
                if (!sub || !can) return null;
                const cmp = sub.compareDocumentPosition(can);
                // 0x04 means can FOLLOWS sub
                return (cmp & 4) ? 'submit-first' : 'cancel-first';
            }"""
        )
        assert order == "submit-first", f"Variant requires submit-before-cancel in DOM, got {order!r}"


def test_quirk_split_among_two_columns(page):
    """The three Split-among checkboxes are arranged in 2 columns (one row of 2, second row of 1, or similar)."""
    boxes = page.locator('input[type="checkbox"]').evaluate_all(
        """nodes => nodes.map(n => {
            const r = n.closest('label, div')?.getBoundingClientRect() || n.getBoundingClientRect();
            return { x: r.x, y: r.y, w: r.width };
        })"""
    )
    assert len(boxes) == 3, f"Expected 3 checkboxes, got {len(boxes)}"
    # In a 2-col grid the first 2 share roughly the same Y; in a 1-col list, each Y is distinct.
    ys = sorted(b["y"] for b in boxes)
    rows = []
    cur = [ys[0]]
    for y in ys[1:]:
        if abs(y - cur[-1]) < 20:
            cur.append(y)
        else:
            rows.append(cur); cur = [y]
    rows.append(cur)
    max_per_row = max(len(r) for r in rows)
    assert max_per_row >= 2, (
        f"Variant uses a 2-column grid for split-among; "
        f"got {max_per_row} checkbox(es) per row across rows {rows!r}"
    )