patchwise-agent-studio / web /src /components /components.test.tsx
EnergyVenom's picture
Tidy the web app: pages by area, CSS in load order, web/README.md (b2a039d)
fb43301 verified
Raw History Blame Contribute Delete
12.8 kB
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { statusTransitions } from '../domain/desktop';
import { nodeStates, type RunEvent } from '../hooks/useRunStream';
import { LoginPage } from '../pages/auth/LoginPage';
import { RunCases } from '../pages/run/RunCases';
import { StartRunForm } from '../pages/runs/StartRunWizard';
import { jsonResponse, renderUi } from '../test/utils';
import type { ProcessStep } from '../api/types';
import { reviewAnswer } from '../domain/glossary';
import { ScenarioReview } from '../pages/run/ScenarioReview';
import { runTitle } from '../domain/runName';
import { DecisionBadge, MockBanner, RuleResult } from './common';
import { ProcessFlow } from './ProcessFlow';
import { GraphView } from './GraphView';
afterEach(() => vi.restoreAllMocks());
const urlOf = (input: RequestInfo | URL) => (typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
describe('components', () => {
it('shows the mock banner', () => {
renderUi(<MockBanner />);
expect(screen.getByTestId('mock-banner')).toHaveTextContent(/mock app, not Oracle Fusion/i);
});
it('decision badge speaks consultant words and keeps the exact rule result', () => {
renderUi(<><DecisionBadge decision="NO-GO" /><RuleResult decision="NO-GO" /></>);
expect(screen.getByTestId('decision-badge')).toHaveTextContent('Not ready');
expect(screen.getByTestId('decision-badge')).toHaveAttribute('data-rule', 'NO-GO');
expect(screen.getByTestId('rule-result')).toHaveTextContent('Rule result: NO-GO');
});
it('failure review choices map onto the unchanged human_review answer format', () => {
expect(reviewAnswer('real_defect', {})).toEqual({ confirmed: 'real_defect' });
expect(reviewAnswer('expected_change', { note: 'label renamed' }))
.toEqual({ confirmed: 'not_defect', note: 'Expected change from the patch: update the scenario. label renamed' });
expect(reviewAnswer(undefined, { owner: 'automation' })).toEqual({ owner: 'automation' });
});
it('process flow colours each step by its state', () => {
const step = (name: string, state: ProcessStep['state'], cross = false): ProcessStep => ({ key: name, name, codes: [], cross_cutting: cross, group: null, order: 1,
scenarios: 2, library: 3, passed: 1, failed: state === 'failing' ? 1 : 0, flaky: 0, not_run: 0, touched: true, state });
renderUi(<ProcessFlow steps={[step('Requisition', 'failing'), step('Purchase order', 'passed'), step('Sourcing', 'gap'), step('Approvals', 'not_affected', true)]} />);
expect(screen.getByTestId('step-Requisition')).toHaveAttribute('data-state', 'failing');
expect(screen.getByTestId('step-Sourcing')).toHaveAttribute('data-state', 'gap');
expect(screen.getByText('Across the whole process')).toBeInTheDocument();
});
it('scenario review groups by process step, approves per step, and posts to the unchanged gate API', async () => {
const posts: unknown[] = [];
const scen = (id: string, title: string, step = 'Requisition') => ({ id, title, module: 'P2P', process: step, step, priority: 'P1', priority_words: 'Critical',
roles: ['requester'], preconditions: [], steps: [{ n: 1, text: 'Sign in as requester', expected: '' }], expected_result: 'Approved', test_data: [],
why: ['Changed by patch 26C: Approvals'], verification: 'UNVERIFIED', map_ids: ['REQ-02'], approval_status: 'draft', origin: 'library', pending: true, outcome: null });
const pend = (id: string, changed: boolean) => ({ id, title: id, module: 'P2P', priority: 'P1', origin: 'library', changed_by_patch: changed, new_or_changed: changed, yaml_path: 'x', diff: null });
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const req = input instanceof Request ? input : new Request(new URL(urlOf(input), 'http://localhost'), init);
if (req.method === 'POST') { posts.push(await req.json()); return jsonResponse({ status: 'queued' }); }
if (req.url.includes('/gate')) return jsonResponse({ gate: 'approve_cases', policy: 'L0', auto_approved: [],
pending: [pend('P2P-APR-001', true), pend('P2P-APR-002', true), pend('P2P-INV-001', true), pend('P2P-PAY-001', false)] });
if (req.url.includes('/scenarios')) return jsonResponse({ scenarios: [scen('P2P-APR-001', 'Below threshold'), scen('P2P-APR-002', 'Rejected requisition'),
scen('P2P-INV-001', 'Three-way match', 'Invoice'), scen('P2P-PAY-001', 'Payment run', 'Payment')], deferred: [] });
if (req.url.endsWith('/api/auth/me')) return jsonResponse({ id: 1, username: 'c', role: 'consultant', permissions: ['read', 'gate.approve_cases'] });
return jsonResponse({});
});
renderUi(<ScenarioReview id="r1" waiting />, { auth: true });
// grouped by step, with the unchanged library scenario behind its own toggle
expect(await screen.findByTestId('step-group-changed-Requisition')).toHaveTextContent('2 scenarios');
expect(screen.getByTestId('step-group-changed-Invoice')).toBeInTheDocument();
expect(screen.queryByTestId('step-group-unchanged-Payment')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Unchanged (1)' })).toBeInTheDocument();
// nothing is pre-approved: submit stays disabled until every scenario is decided
expect(screen.getByTestId('review-count')).toHaveTextContent('0 of 4 approved');
expect(screen.getByRole('button', { name: 'Submit review' })).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'Approve all 2 Requisition scenarios' }));
expect(screen.getByTestId('review-count')).toHaveTextContent('2 of 4 approved');
fireEvent.click(screen.getByRole('button', { name: /^Requisition/ }));
fireEvent.click(screen.getByRole('button', { name: 'Skip Rejected requisition for this patch', hidden: true }));
fireEvent.click(screen.getByRole('button', { name: 'Approve all 1 Invoice scenarios' }));
fireEvent.click(screen.getByRole('button', { name: 'Approve all 1 unchanged' }));
expect(screen.getByTestId('review-count')).toHaveTextContent('3 of 4 approved, 1 skipped');
fireEvent.click(screen.getByRole('button', { name: 'Submit review' }));
await waitFor(() => expect(posts).toHaveLength(1));
expect(posts[0]).toEqual({ approved: ['P2P-APR-001', 'P2P-INV-001', 'P2P-PAY-001'], rejected: ['P2P-APR-002'], comments: {} });
});
it('names a test run for people and keeps the machine id out of the title', () => {
const t = runTitle({ run_id: '20261011-094712-e2cd7c', modules: ['P2P'], patch_id: '26C', created_at: '2026-10-11T09:47:12' });
expect(t).toBe('Procure-to-Pay · 26C · 11 Oct 09:47');
expect(runTitle({ run_id: 'x', modules: ['P2P', 'O2C', 'R2R'], patch_id: null, created_at: null })).toBe('Procure-to-Pay + 2 more');
});
it('folds events into node states and renders the graph', () => {
const ev = (seq: number, node: string, kind: string, summary = {}): RunEvent => ({ seq, ts: '2026-10-10T00:00:00Z', node, kind, summary });
const events = [ev(1, 'scout', 'started'), ev(2, 'scout', 'finished'), ev(3, 'research_module', 'started', { module: 'P2P' }),
ev(4, 'research_module', 'started', { module: 'O2C' }), ev(5, 'approval_gate', 'started'), ev(6, 'approval_gate', 'interrupted')];
const st = nodeStates(events, ['scout', 'research_module', 'approval_gate', 'executor'], false);
expect(st.scout.state).toBe('done');
expect(st.research_module).toMatchObject({ state: 'running', count: 2, modules: ['P2P', 'O2C'] });
expect(st.approval_gate.state).toBe('waiting');
expect(nodeStates(events, ['executor'], true).executor.state).toBe('skipped');
renderUi(<GraphView states={st} />);
expect(screen.getByTestId('node-approval_gate')).toHaveAttribute('data-state', 'waiting');
expect(screen.getByLabelText('scout done')).toBeInTheDocument();
});
it('desktop notifications fire only on attention transitions', () => {
expect(statusTransitions({ a: 'running', b: 'queued' }, { a: 'waiting_approval', b: 'running', c: 'completed' }))
.toEqual([{ title: 'Astra (mock app)', body: 'Run a is waiting for case approval' }]);
expect(statusTransitions({ a: 'waiting_approval' }, { a: 'waiting_approval|reminder: run a is still waiting at approve_cases' }))
.toEqual([{ title: 'Astra (mock app)', body: 'reminder: run a is still waiting at approve_cases' }]);
});
it('login form has labelled inputs and shows API errors', async () => {
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
if (urlOf(input).endsWith('/api/auth/me')) return jsonResponse({ detail: 'not signed in', code: 'UNAUTHENTICATED' }, 401);
return jsonResponse({ detail: 'invalid username or password', code: 'BAD_CREDENTIALS' }, 401);
});
renderUi(<LoginPage />, { auth: true, route: '/login' });
fireEvent.change(await screen.findByLabelText(/Username/), { target: { value: 'alice' } });
fireEvent.change(screen.getByLabelText(/Password/), { target: { value: 'wrong-password' } });
fireEvent.click(screen.getByRole('button', { name: 'Sign in' }));
expect(await screen.findByRole('alert')).toHaveTextContent(/username or password is not right/i);
});
it('approval gate posts approved and rejected ids', async () => {
const posts: unknown[] = [];
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const req = input instanceof Request ? input : new Request(new URL(urlOf(input), 'http://localhost'), init);
const url = req.url;
if (req.method === 'POST') {
posts.push(await req.json());
return jsonResponse({ status: 'queued' });
}
if (url.includes('/gate')) {
return jsonResponse({ gate: 'approve_cases', policy: 'L0', auto_approved: [], pending: [
{ id: 'P2P-APR-001', title: 'a', module: 'P2P', priority: 'P1', origin: 'library', changed_by_patch: true, new_or_changed: true, yaml_path: 'x', diff: null },
{ id: 'P2P-GEN-AP01-001', title: 'g', module: 'P2P', priority: 'P1', origin: 'generated', changed_by_patch: true, new_or_changed: true, yaml_path: null, diff: 'id: x' }] });
}
if (url.includes('/cases')) return jsonResponse({ test_cases: [], deferred: [], proposed_cases: [], approvals: {}, approval_log: [] });
if (url.endsWith('/api/auth/me')) return jsonResponse({ id: 1, username: 'c', role: 'consultant', permissions: ['read', 'gate.approve_cases'] });
return jsonResponse({});
});
renderUi(<RunCases id="r1" waiting />, { auth: true });
const box = await screen.findByLabelText('approve P2P-GEN-AP01-001');
await waitFor(() => expect(box).toBeChecked());
fireEvent.click(box);
fireEvent.click(await screen.findByRole('button', { name: /Approve selected/ }));
await waitFor(() => expect(posts).toHaveLength(1));
expect(posts[0]).toEqual({ approved: ['P2P-APR-001'], rejected: ['P2P-GEN-AP01-001'], comments: {} });
});
it('a double click on Start run starts exactly one run', async () => {
let posts = 0;
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
const req = input instanceof Request ? input : new Request(new URL(urlOf(input), 'http://localhost'), init);
if (req.method === 'POST') {
posts += 1;
await new Promise((r) => setTimeout(r, 50));
return jsonResponse({ run_id: 'r1', status: 'queued' }, 202);
}
if (req.url.includes('/kill-switch')) return jsonResponse({ engaged: false, reason: null, actor: null, since: null });
if (req.url.includes('/api/pods')) return jsonResponse([{ id: 1, name: 'Local mock pod', kind: 'mock', base_url: 'http://127.0.0.1:3100', environment: 'test',
modules: [], notes: null, enabled: true, is_default: true, credentials: [], runnable: true, not_runnable_reason: null }]);
return jsonResponse({});
});
renderUi(<StartRunForm />);
await screen.findByText('Local mock pod');
for (let i = 0; i < 3; i += 1) {
const next = screen.getByRole('button', { name: 'Next' });
await waitFor(() => expect(next).toBeEnabled());
fireEvent.click(next);
}
const btn = await screen.findByRole('button', { name: 'Start run' });
await waitFor(() => expect(btn).toBeEnabled());
fireEvent.click(btn);
fireEvent.click(btn);
await waitFor(() => expect(posts).toBe(1));
await new Promise((r) => setTimeout(r, 120));
expect(posts).toBe(1);
});
});