File size: 8,539 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
const { chromium } = require('playwright');

const TASK_ID = 7;
const KIND = "browser";
const TESTIDS = [];
const HAS_QUESTION_WORKFLOW = false;
const SKIP_DIRS = new Set([
  "tests",
  "logs",
  "node_modules",
  ".git"
]);

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

function walk(dir) {
  let out = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (SKIP_DIRS.has(entry.name)) continue;
    const p = path.join(dir, entry.name);
    if (entry.isDirectory()) out = out.concat(walk(p));
    else out.push(p);
  }
  return out;
}

function findEntry() {
  const files = walk(process.cwd());
  if (KIND === 'svg') return files.find(f => f.toLowerCase().endsWith('.svg'));
  return files.find(f => f.toLowerCase().endsWith('.html')) || files.find(f => f.toLowerCase().endsWith('.svg'));
}

async function snapshot(page) {
  return await page.evaluate(() => JSON.stringify({
    text: document.body?.innerText || '',
    htmlLength: document.body?.innerHTML?.length || 0,
    controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length,
    storage: window.localStorage ? window.localStorage.length : 0,
    canvas: Array.from(document.querySelectorAll('canvas')).map(c => {
      try { return c.toDataURL().slice(0, 80); } catch { return ''; }
    }),
  }));
}

async function runQuestionWorkflow(page) {
  const input = page.locator('[data-testid="question-input"]');
  const upload = page.locator('[data-testid="upload-question"]');
  const items = page.locator('[data-testid="question-item"]');
  const before = await items.count();
  const text = 'AAAV dynamic question ' + Date.now();
  await input.fill(text);
  await upload.click();
  await page.waitForTimeout(150);
  assert(await items.count() > before, 'upload-question should add a question item');
  const first = items.first();
  if (await first.locator('[data-testid="offline-question"]').count()) {
    const oldStatus = await first.getAttribute('data-status');
    await first.locator('[data-testid="offline-question"]').click();
    await page.waitForTimeout(100);
    assert(oldStatus !== await first.getAttribute('data-status'), 'offline-question should toggle data-status');
  }
  if (await first.locator('[data-testid="edit-question"]').count()) {
    await first.locator('[data-testid="edit-question"]').click();
    await page.waitForTimeout(100);
    assert(await first.getAttribute('data-edited') === 'true', 'edit-question should mark item as edited');
  }
  if (await page.locator('[data-testid="role-select"]').count()) {
    await page.locator('[data-testid="role-select"]').selectOption('normal user').catch(() => {});
    await page.waitForTimeout(100);
    assert(!(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false)), 'delete should hide for normal user');
    await page.locator('[data-testid="role-select"]').selectOption('admin').catch(() => {});
    await page.waitForTimeout(100);
    assert(await page.locator('[data-testid="delete-question"]').first().isVisible().catch(() => false), 'delete should show for admin');
  }
}

(async () => {
  const entry = findEntry();
  assert(entry, 'no browser-openable entrypoint found');
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage({ viewport: { width: 1100, height: 760 } });
  const errors = [];
  page.on('pageerror', err => errors.push(err.message));
  page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); });
  await page.goto(pathToFileURL(entry).href, { waitUntil: 'domcontentloaded' });
  await page.waitForTimeout(500);
  assert(errors.length === 0, 'browser errors on load: ' + errors.join(' | '));

  if (KIND === 'svg') {
    const stats = await page.evaluate(() => ({
      svg: document.querySelectorAll('svg').length,
      elems: document.querySelectorAll('svg *').length,
      text: (document.body?.innerText || '').trim().length,
    }));
    assert(stats.svg >= 1, 'svg task should render an svg root');
    assert(stats.elems >= 2 || stats.text >= 5, 'svg task should render visible structure');
  } else {
    const stats = await page.evaluate(() => ({
      visible: Array.from(document.querySelectorAll('body *')).filter(el => {
        const r = el.getBoundingClientRect();
        const s = getComputedStyle(el);
        return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none';
      }).length,
      text: (document.body?.innerText || '').trim().length,
      controls: document.querySelectorAll('button,[role="button"],input,select,textarea,canvas,svg,a[href]').length,
    }));
    assert(stats.visible >= 3 || stats.text >= 20, 'page should render meaningful visible content');

    for (const id of TESTIDS) {
      const count = await page.locator(`[data-testid="${id}"]`).count();
      assert(count > 0, `missing required data-testid: ${id}`);
    }
    if (HAS_QUESTION_WORKFLOW) await runQuestionWorkflow(page);

    // Expense-tracker behavior: adding a record must append a list row AND
    // update the total/balance summary text. Gated on the oracle's ids so it
    // is a no-op for pages that do not expose this form.
    const descInput = page.locator('#desc');
    const amountInput = page.locator('#amount');
    const addBtn = page.locator('#addBtn, #addForm button[type="submit"]');
    const list = page.locator('#list');
    if (await descInput.count() && await amountInput.count() && await addBtn.count() && await list.count()) {
      const rowsBefore = await page.locator('#list li').count();
      const summaryBefore = await page.evaluate(() => {
        const t = document.querySelector('#totalExpense');
        const b = document.querySelector('#balance');
        return { total: t ? t.innerText.trim() : null, balance: b ? b.innerText.trim() : null };
      });
      await descInput.fill('AAAV lunch');
      await amountInput.fill('12.50');
      await addBtn.first().click();
      await page.waitForTimeout(200);
      const rowsAfter = await page.locator('#list li').count();
      assert(rowsAfter > rowsBefore, 'adding an expense should append a new list row');
      const summaryAfter = await page.evaluate(() => {
        const t = document.querySelector('#totalExpense');
        const b = document.querySelector('#balance');
        return { total: t ? t.innerText.trim() : null, balance: b ? b.innerText.trim() : null };
      });
      if (summaryBefore.total != null) {
        assert(summaryAfter.total !== summaryBefore.total, 'total expense text should update after adding an expense');
      }
      if (summaryBefore.balance != null) {
        assert(summaryAfter.balance !== summaryBefore.balance, 'balance text should update after adding an expense');
      }
      // clean up persisted state so the generic interaction pass starts fresh
      await page.evaluate(() => { try { localStorage.clear(); } catch {} });
    }

    const controls = await page.$$('button,[role="button"],input,select,textarea,canvas,svg,a[href]');
    if (controls.length) {
      const before = await snapshot(page);
      for (const control of controls.slice(0, 6)) {
        const tag = await control.evaluate(el => el.tagName.toLowerCase()).catch(() => '');
        if (tag === 'input' || tag === 'textarea') await control.fill('aaav-dynamic-input').catch(() => {});
        else if (tag === 'select') {
          const value = await control.evaluate(el => Array.from(el.options || [])[1]?.value || Array.from(el.options || [])[0]?.value || '').catch(() => '');
          if (value) await control.selectOption(value).catch(() => {});
        } else {
          await control.click({ force: true }).catch(() => {});
        }
      }
      await page.keyboard.press('Enter').catch(() => {});
      await page.keyboard.press('Space').catch(() => {});
      await page.waitForTimeout(200);
      await snapshot(page);
      // State changes are informative but not mandatory: static dashboards and
      // diagrams may be valid even when generic clicks do not mutate state.
      void before;
    }
  }
  assert(errors.length === 0, 'browser errors after interaction: ' + errors.join(' | '));
  await browser.close();
  console.log(`AAAV targeted dynamic test passed for task ${TASK_ID}`);
})().catch(err => {
  console.error(err && err.stack || err);
  process.exit(1);
});