From 7c2bd34ee1f4c76d3cb96f9401cdabd49c3cda58 Mon Sep 17 00:00:00 2001 From: Nigel Gaskin Date: Wed, 25 Nov 2026 17:08:29 +1030 Subject: [PATCH 1/2] ci: throwaway commit to run pr-checks on Node 22 (closed unmerged) From 2e4826db118e8224f01257030ebf648e10ad934f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:07:18 +0000 Subject: [PATCH 2/2] test(web-ui): add Vitest smoke tests for the Gateway Web UI The pr-checks "Comment Test Coverage" job runs `npm run test:coverage`, which failed because web-ui had no test files at all. Adds 36 tests across 10 files, driven by a routed fetch mock whose payloads are taken from the gateway handlers (MonitoringHandlers, ExecutionHandlers, ScriptAndPackageHandlers, Python3LogsHandler, Python3MetricsCollector): - App: renders the dashboard, shows the login prompt on 401, and navigates to every sidebar view. - Dashboard, Scripts, Python Versions, Packages, Diagnostics and IDE: heading and content with mocked data, empty and 500/unreachable states, and key interactions (create script, install version/package, pool resize validation, log level filter, run code via /exec). - api.ts, authCheck.ts and useGatewayFetch: session creation, Bearer and X-CSRF-Token headers, {data} unwrapping, HTTP and login-redirect errors. The existing setup file now imports '@testing-library/jest-dom/vitest' (the camera-driver pattern) so the matchers are typed for tsc. No product code, versions or build files changed. Co-Authored-By: Claude Opus 5.5 --- web-ui/src/App.test.tsx | 58 ++++ web-ui/src/components/DashboardView.test.tsx | 43 +++ .../src/components/DiagnosticsView.test.tsx | 76 ++++++ web-ui/src/components/IDEView.test.tsx | 50 ++++ web-ui/src/components/PackagesView.test.tsx | 70 +++++ web-ui/src/components/ScriptsView.test.tsx | 72 +++++ web-ui/src/components/VersionsView.test.tsx | 54 ++++ web-ui/src/hooks/useGatewayFetch.test.ts | 37 +++ web-ui/src/test/gatewayMock.ts | 248 ++++++++++++++++++ web-ui/src/test/setup.ts | 2 +- web-ui/src/utils/api.test.ts | 69 +++++ web-ui/src/utils/authCheck.test.ts | 17 ++ 12 files changed, 795 insertions(+), 1 deletion(-) create mode 100644 web-ui/src/App.test.tsx create mode 100644 web-ui/src/components/DashboardView.test.tsx create mode 100644 web-ui/src/components/DiagnosticsView.test.tsx create mode 100644 web-ui/src/components/IDEView.test.tsx create mode 100644 web-ui/src/components/PackagesView.test.tsx create mode 100644 web-ui/src/components/ScriptsView.test.tsx create mode 100644 web-ui/src/components/VersionsView.test.tsx create mode 100644 web-ui/src/hooks/useGatewayFetch.test.ts create mode 100644 web-ui/src/test/gatewayMock.ts create mode 100644 web-ui/src/utils/api.test.ts create mode 100644 web-ui/src/utils/authCheck.test.ts diff --git a/web-ui/src/App.test.tsx b/web-ui/src/App.test.tsx new file mode 100644 index 0000000..7f73c77 --- /dev/null +++ b/web-ui/src/App.test.tsx @@ -0,0 +1,58 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { render, screen, fireEvent, within } from '@testing-library/react' +import App from './App' +import { mockGateway, defaultRoutes, jsonResponse } from './test/gatewayMock' + +describe('App', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + localStorage.clear() + }) + + it('renders the dashboard with live gateway status on load', async () => { + mockGateway(defaultRoutes()) + render() + + expect(screen.getByRole('heading', { name: 'Dashboard' })).toBeInTheDocument() + expect(await screen.findByText('Healthy')).toBeInTheDocument() + expect(screen.getByText('3.11')).toBeInTheDocument() + expect(screen.getByText('3.12')).toBeInTheDocument() + // Sidebar shows the module version reported by /version, not its fallback. + expect(await screen.findByText('v9.8.7')).toBeInTheDocument() + }) + + it('shows the login prompt when the gateway rejects the health check', async () => { + mockGateway({ ...defaultRoutes(), '/api/v1/health': () => jsonResponse({ error: 'Unauthorized' }, 401) }) + render() + + expect(await screen.findByRole('heading', { name: 'Authentication Required' })).toBeInTheDocument() + expect(screen.getByRole('link', { name: 'Log In to Gateway' })).toHaveAttribute('href', '/web/login') + }) + + it.each([ + ['Scripts', 'Scripts', 'TankLevels'], + ['Python Versions', 'Python Versions', 'Python 3.13'], + ['Packages', 'Packages', 'numpy'], + ['Diagnostics', 'Diagnostics', 'Python3ProcessPool started with 3 executors'], + ])('navigates to %s from the sidebar', async (navLabel, heading, content) => { + mockGateway(defaultRoutes()) + render() + + const nav = screen.getByRole('navigation') + fireEvent.click(within(nav).getByRole('button', { name: navLabel })) + + expect(await screen.findByRole('heading', { name: heading })).toBeInTheDocument() + expect(await screen.findByText(content)).toBeInTheDocument() + expect(within(nav).getByRole('button', { name: navLabel })).toHaveAttribute('aria-current', 'page') + }) + + it('navigates to the IDE from the dashboard quick action', async () => { + mockGateway(defaultRoutes()) + render() + + fireEvent.click(screen.getByRole('button', { name: /New Script/ })) + expect(await screen.findByRole('button', { name: 'Run script' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Load Script' })).toBeInTheDocument() + }) +}) diff --git a/web-ui/src/components/DashboardView.test.tsx b/web-ui/src/components/DashboardView.test.tsx new file mode 100644 index 0000000..4f9e814 --- /dev/null +++ b/web-ui/src/components/DashboardView.test.tsx @@ -0,0 +1,43 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import DashboardView from './DashboardView' +import { mockGateway, defaultRoutes, callsTo, GATEWAY_PREFIX } from '../test/gatewayMock' + +const GATEWAY_URL = window.location.origin + GATEWAY_PREFIX + +describe('DashboardView', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('shows health, pool and version cards from the gateway', async () => { + mockGateway(defaultRoutes()) + render( {}} />) + + expect(await screen.findByText('Healthy')).toBeInTheDocument() + expect(screen.getByText('Process Pool')).toBeInTheDocument() + expect(screen.getByTitle('33% utilization')).toBeInTheDocument() // 1 in use of 3 + expect(screen.getByText('3.11')).toBeInTheDocument() + expect(screen.getByText(/^Last updated /)).toBeInTheDocument() + }) + + it('shows Down and the empty versions message when the gateway is unreachable', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))) + render( {}} />) + + expect(await screen.findByText('Down')).toBeInTheDocument() + expect(screen.getByText('No versions detected')).toBeInTheDocument() + }) + + it('refetches every card when Refresh is pressed', async () => { + const fetchMock = mockGateway(defaultRoutes()) + render( {}} />) + await screen.findByText('Healthy') + expect(callsTo(fetchMock, '/api/v1/health')).toHaveLength(1) + + fireEvent.click(screen.getByRole('button', { name: 'Refresh dashboard' })) + await waitFor(() => expect(callsTo(fetchMock, '/api/v1/health')).toHaveLength(2)) + expect(callsTo(fetchMock, '/api/v1/pool-stats')).toHaveLength(2) + }) +}) diff --git a/web-ui/src/components/DiagnosticsView.test.tsx b/web-ui/src/components/DiagnosticsView.test.tsx new file mode 100644 index 0000000..723b741 --- /dev/null +++ b/web-ui/src/components/DiagnosticsView.test.tsx @@ -0,0 +1,76 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import DiagnosticsView from './DiagnosticsView' +import { + mockGateway, defaultRoutes, callsTo, jsonResponse, GATEWAY_PREFIX, +} from '../test/gatewayMock' + +const GATEWAY_URL = window.location.origin + GATEWAY_PREFIX + +describe('DiagnosticsView', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('shows pool stats, health and module log entries', async () => { + mockGateway(defaultRoutes()) + render() + + expect(screen.getByRole('heading', { name: 'Diagnostics' })).toBeInTheDocument() + expect(await screen.findByRole('button', { name: 'Pool size 3, click to change' })).toBeInTheDocument() + expect(await screen.findByText('Executor 2 slow to respond')).toBeInTheDocument() + expect(screen.getByText('2 entries (module only)')).toBeInTheDocument() + }) + + it('shows each panel’s empty message when the gateway answers 500', async () => { + mockGateway({ '/api/v1/': () => jsonResponse({ success: false, error: 'Internal error' }, 500) }) + render() + + expect(await screen.findByText('No pool data available.')).toBeInTheDocument() + expect(screen.getByText('No metrics data available.')).toBeInTheDocument() + expect(screen.getByText('No log entries found')).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: /Raw Diagnostics/ })) + expect(screen.getByText('(no diagnostics data)')).toBeInTheDocument() + }) + + it('requests only ERROR logs when the ERROR filter is chosen', async () => { + const fetchMock = mockGateway(defaultRoutes()) + render() + await screen.findByText('Executor 2 slow to respond') + + fireEvent.click(screen.getByRole('button', { name: 'ERROR' })) + + await waitFor(() => { + const levels = callsTo(fetchMock, '/api/v1/logs').map(([u]) => new URL(String(u)).searchParams.get('level')) + expect(levels).toContain('ERROR') + }) + const logCalls = callsTo(fetchMock, '/api/v1/logs') + const last = logCalls[logCalls.length - 1] + const params = new URL(String(last[0])).searchParams + expect(params.get('filter')).toBe('Python3') + expect(params.get('lines')).toBe('100') + }) + + it('validates the pool size and POSTs a valid resize to /pool-size', async () => { + const fetchMock = mockGateway({ + ...defaultRoutes(), + '/api/v1/pool-size': { success: true, poolSize: 5, message: 'Pool size changed to 5' }, + }) + render() + + fireEvent.click(await screen.findByRole('button', { name: 'Pool size 3, click to change' })) + const input = screen.getByRole('spinbutton') + fireEvent.change(input, { target: { value: '25' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + expect(await screen.findByText('Must be 1–20')).toBeInTheDocument() + expect(callsTo(fetchMock, '/api/v1/pool-size')).toHaveLength(0) + + fireEvent.change(input, { target: { value: '5' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => expect(callsTo(fetchMock, '/api/v1/pool-size')).toHaveLength(1)) + const [call] = callsTo(fetchMock, '/api/v1/pool-size') + expect(call[1]?.method).toBe('POST') + expect(JSON.parse(String(call[1]?.body))).toEqual({ size: 5 }) + }) +}) diff --git a/web-ui/src/components/IDEView.test.tsx b/web-ui/src/components/IDEView.test.tsx new file mode 100644 index 0000000..ccd2fbe --- /dev/null +++ b/web-ui/src/components/IDEView.test.tsx @@ -0,0 +1,50 @@ +import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import IDEView from './IDEView' +import { mockGateway, defaultRoutes, callsTo, GATEWAY_PREFIX } from '../test/gatewayMock' + +const GATEWAY_URL = window.location.origin + GATEWAY_PREFIX + +// jsdom has no layout engine; CodeMirror measures text ranges after each update. +beforeAll(() => { + const emptyRects = () => Object.assign([], { item: () => null }) as unknown as DOMRectList + Range.prototype.getClientRects = emptyRects + Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0) +}) + +describe('IDEView', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + localStorage.clear() + }) + + it('runs the editor contents via POST /exec and shows the result', async () => { + const fetchMock = mockGateway({ + ...defaultRoutes(), + '/api/v1/exec': { success: true, result: 'hello from python' }, + }) + render() + expect(screen.getByText('Run a script to see output here. (Ctrl+Enter)')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: 'Run script' })) + + expect(await screen.findByText('hello from python')).toBeInTheDocument() + const [call] = callsTo(fetchMock, '/api/v1/exec') + expect(call[1]?.method).toBe('POST') + expect(JSON.parse(String(call[1]?.body))).toMatchObject({ + code: '# Create or load a script to get started\n', + variables: {}, + }) + }) + + it('lists saved scripts in the Load Script menu', async () => { + const fetchMock = mockGateway(defaultRoutes()) + render() + + fireEvent.click(screen.getByRole('button', { name: 'Load Script' })) + await waitFor(() => expect(callsTo(fetchMock, '/api/v1/scripts/list')).toHaveLength(1)) + expect(await screen.findByText('TankLevels')).toBeInTheDocument() + expect(screen.getByText('Housekeeping')).toBeInTheDocument() + }) +}) diff --git a/web-ui/src/components/PackagesView.test.tsx b/web-ui/src/components/PackagesView.test.tsx new file mode 100644 index 0000000..deef69a --- /dev/null +++ b/web-ui/src/components/PackagesView.test.tsx @@ -0,0 +1,70 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import PackagesView from './PackagesView' +import { + mockGateway, defaultRoutes, callsTo, headersOf, textResponse, GATEWAY_PREFIX, +} from '../test/gatewayMock' + +const GATEWAY_URL = window.location.origin + GATEWAY_PREFIX + +describe('PackagesView', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('renders the catalogue map with installed status', async () => { + mockGateway(defaultRoutes()) + render( {}} />) + + expect(await screen.findByText('numpy')).toBeInTheDocument() + expect(screen.getByText('pandas')).toBeInTheDocument() + expect(screen.getByText('1 installed · 2 total')).toBeInTheDocument() + expect(screen.getByTitle('Uninstall numpy')).toBeInTheDocument() + expect(screen.getByTitle('Install pandas')).toBeInTheDocument() + }) + + it('shows the gateway error text and empty state when the catalogue fails', async () => { + mockGateway({ + ...defaultRoutes(), + '/api/v1/packages/catalog': () => textResponse('Package manager not initialised', 500), + }) + render( {}} />) + + expect(await screen.findByText('Package manager not initialised')).toBeInTheDocument() + expect(screen.getByText('No packages found.')).toBeInTheDocument() + }) + + it('filters installed packages and reports no match', async () => { + mockGateway(defaultRoutes()) + render( {}} />) + await screen.findByText('numpy') + + const search = screen.getByPlaceholderText('Search installed packages…') + fireEvent.change(search, { target: { value: 'array' } }) + expect(screen.getByText('numpy')).toBeInTheDocument() + expect(screen.queryByText('pandas')).not.toBeInTheDocument() + + fireEvent.change(search, { target: { value: 'scipy' } }) + expect(screen.getByText('No packages match "scipy"')).toBeInTheDocument() + }) + + it('Install POSTs to /packages/install/ with auth headers', async () => { + const fetchMock = mockGateway({ + ...defaultRoutes(), + '/api/v1/packages/install/': { success: true, message: 'Installed pandas' }, + }) + const showToast = vi.fn() + render() + + fireEvent.click(await screen.findByTitle('Install pandas')) + + await waitFor(() => expect(showToast).toHaveBeenCalledWith('Package installed successfully', 'success')) + const [call] = callsTo(fetchMock, '/api/v1/packages/install/pandas') + expect(call[1]?.method).toBe('POST') + expect(headersOf(call[1])).toMatchObject({ + Authorization: 'Bearer api-token-456', + 'X-CSRF-Token': 'csrf-token-123', + }) + }) +}) diff --git a/web-ui/src/components/ScriptsView.test.tsx b/web-ui/src/components/ScriptsView.test.tsx new file mode 100644 index 0000000..3402b47 --- /dev/null +++ b/web-ui/src/components/ScriptsView.test.tsx @@ -0,0 +1,72 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import ScriptsView from './ScriptsView' +import { + mockGateway, defaultRoutes, callsTo, jsonResponse, GATEWAY_PREFIX, +} from '../test/gatewayMock' + +const GATEWAY_URL = window.location.origin + GATEWAY_PREFIX + +describe('ScriptsView', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('lists saved scripts and their folders', async () => { + mockGateway(defaultRoutes()) + render( {}} />) + + expect(screen.getByRole('heading', { name: 'Scripts' })).toBeInTheDocument() + expect(await screen.findByText('TankLevels')).toBeInTheDocument() + expect(screen.getByText('Housekeeping')).toBeInTheDocument() + expect(screen.getByText('Reports')).toBeInTheDocument() + }) + + it('shows the empty message when no scripts are saved', async () => { + mockGateway({ ...defaultRoutes(), '/api/v1/scripts/list': { success: true, scripts: [] } }) + render( {}} />) + + expect(await screen.findByText('No scripts saved yet.')).toBeInTheDocument() + }) + + it('shows the load error when the list endpoint answers 500', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + mockGateway({ + ...defaultRoutes(), + '/api/v1/scripts/list': () => jsonResponse({ success: false, error: 'Script repository not initialized' }, 500), + }) + render( {}} />) + + expect(await screen.findByText('Failed to load scripts: Error: HTTP 500')).toBeInTheDocument() + }) + + it('New Script saves an empty script with the prompted name', async () => { + vi.spyOn(window, 'prompt').mockReturnValue(' PumpReport ') + const fetchMock = mockGateway({ + ...defaultRoutes(), + '/api/v1/scripts/save': { success: true, message: 'Script saved' }, + }) + const showToast = vi.fn() + render() + await screen.findByText('TankLevels') + + fireEvent.click(screen.getByTitle('New Script')) + + await waitFor(() => expect(showToast).toHaveBeenCalledWith('Script created successfully', 'success')) + const [call] = callsTo(fetchMock, '/api/v1/scripts/save') + expect(call[1]?.method).toBe('POST') + expect(JSON.parse(String(call[1]?.body))).toEqual({ name: 'PumpReport', code: '', description: '' }) + }) + + it('New Folder rejects a folder name that already exists', async () => { + vi.spyOn(window, 'prompt').mockReturnValue('Reports') + mockGateway(defaultRoutes()) + const showToast = vi.fn() + render() + await screen.findByText('TankLevels') + + fireEvent.click(screen.getByTitle('New Folder')) + expect(showToast).toHaveBeenCalledWith('Folder "Reports" already exists.', 'error') + }) +}) diff --git a/web-ui/src/components/VersionsView.test.tsx b/web-ui/src/components/VersionsView.test.tsx new file mode 100644 index 0000000..72d35e7 --- /dev/null +++ b/web-ui/src/components/VersionsView.test.tsx @@ -0,0 +1,54 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import VersionsView from './VersionsView' +import { + mockGateway, defaultRoutes, callsTo, headersOf, jsonResponse, GATEWAY_PREFIX, +} from '../test/gatewayMock' + +const GATEWAY_URL = window.location.origin + GATEWAY_PREFIX + +describe('VersionsView', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('lists installed and available distributions', async () => { + mockGateway(defaultRoutes()) + render( {}} />) + + expect(await screen.findByText('Python 3.11')).toBeInTheDocument() + expect(screen.getByText('Python 3.13')).toBeInTheDocument() + expect(screen.getByTitle('Uninstall Python 3.11')).toBeInTheDocument() + expect(screen.getByTitle('Install Python 3.13')).toBeInTheDocument() + }) + + it('shows the empty state when every endpoint answers 500', async () => { + mockGateway({ + '/api/v1/': () => jsonResponse({ success: false, error: 'Internal error' }, 500), + }) + render( {}} />) + + expect(await screen.findByText('No Python versions found.')).toBeInTheDocument() + expect(screen.getByText('Click Refresh to reload or check gateway connectivity.')).toBeInTheDocument() + }) + + it('Install POSTs the version to /distributions/install with the CSRF token', async () => { + const fetchMock = mockGateway({ + ...defaultRoutes(), + '/api/v1/distributions/install': { success: true, message: 'Installed Python 3.13' }, + }) + const showToast = vi.fn() + render() + + fireEvent.click(await screen.findByTitle('Install Python 3.13')) + + await waitFor(() => + expect(showToast).toHaveBeenCalledWith('Python version installed successfully', 'success') + ) + const [call] = callsTo(fetchMock, '/api/v1/distributions/install') + expect(call[1]?.method).toBe('POST') + expect(JSON.parse(String(call[1]?.body))).toEqual({ version: '3.13' }) + expect(headersOf(call[1])['X-CSRF-Token']).toBe('csrf-token-123') + }) +}) diff --git a/web-ui/src/hooks/useGatewayFetch.test.ts b/web-ui/src/hooks/useGatewayFetch.test.ts new file mode 100644 index 0000000..1983a13 --- /dev/null +++ b/web-ui/src/hooks/useGatewayFetch.test.ts @@ -0,0 +1,37 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { renderHook, act } from '@testing-library/react' +import { useGatewayFetch } from './useGatewayFetch' +import { mockGateway, jsonResponse, GATEWAY_PREFIX, healthPayload } from '../test/gatewayMock' + +const BASE = window.location.origin + GATEWAY_PREFIX + +describe('useGatewayFetch', () => { + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('returns the unwrapped payload and clears loading', async () => { + mockGateway({ '/api/v1/health': { data: healthPayload } }) + const { result } = renderHook(() => useGatewayFetch(BASE)) + let data: unknown + await act(async () => { + data = await result.current.fetchData('api/v1/health') + }) + expect(data).toEqual(healthPayload) + expect(result.current.loading).toBe(false) + expect(result.current.error).toBeNull() + }) + + it('reports HTTP failures as an error and returns null', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + mockGateway({ '/api/v1/health': () => jsonResponse({ success: false, error: 'boom' }, 500) }) + const { result } = renderHook(() => useGatewayFetch(BASE)) + let data: unknown = 'unset' + await act(async () => { + data = await result.current.fetchData('api/v1/health') + }) + expect(data).toBeNull() + expect(result.current.error).toBe('HTTP 500') + }) +}) diff --git a/web-ui/src/test/gatewayMock.ts b/web-ui/src/test/gatewayMock.ts new file mode 100644 index 0000000..4f12c3f --- /dev/null +++ b/web-ui/src/test/gatewayMock.ts @@ -0,0 +1,248 @@ +/** + * Test helpers: a routed `fetch` stand-in for the Python 3 Integration gateway. + * + * Fixture payloads mirror what the gateway route handlers actually return + * (MonitoringHandlers, ExecutionHandlers, ScriptAndPackageHandlers, + * Python3LogsHandler, Python3MetricsCollector) so the UI is exercised + * against real response shapes rather than invented ones. + */ +import { vi } from 'vitest' + +export const GATEWAY_PREFIX = '/data/python3integration' + +export function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }) +} + +export function textResponse(body: string, status: number, contentType = 'text/plain'): Response { + return new Response(body, { status, headers: { 'Content-Type': contentType } }) +} + +type RouteValue = unknown | ((url: URL, init?: RequestInit) => Response | Promise) + +/** + * Installs a mocked global fetch. Keys are gateway paths without the module + * prefix (e.g. `/api/v1/health`); the longest matching prefix wins. + * Unmatched paths answer 404 so a missing mock is obvious rather than silent. + */ +export function mockGateway(routes: Record) { + const keys = Object.keys(routes).sort((a, b) => b.length - a.length) + const fn = vi.fn(async (input: RequestInfo | URL, init?: RequestInit): Promise => { + const url = new URL(String(input), window.location.origin) + const path = url.pathname.startsWith(GATEWAY_PREFIX) + ? url.pathname.slice(GATEWAY_PREFIX.length) + : url.pathname + const key = keys.find(k => path === k || path.startsWith(k)) + if (key === undefined) { + return jsonResponse({ success: false, error: `Not mocked: ${path}` }, 404) + } + const value = routes[key] + if (typeof value === 'function') { + return (value as (u: URL, i?: RequestInit) => Response | Promise)(url, init) + } + return jsonResponse(value) + }) + vi.stubGlobal('fetch', fn) + return fn +} + +/** Finds the recorded fetch calls whose URL path ends with `pathSuffix`. */ +export function callsTo(fn: ReturnType, pathSuffix: string) { + return fn.mock.calls.filter(([input]) => + new URL(String(input), window.location.origin).pathname.endsWith(pathSuffix) + ) +} + +export function headersOf(init: RequestInit | undefined): Record { + return (init?.headers ?? {}) as Record +} + +// ---- Fixtures (shapes from the gateway Java handlers) ---- + +/** ExecutionHandlers.handleCreateSession */ +export const sessionPayload = { + success: true, + token: 'csrf-token-123', + api_token: 'api-token-456', + expires_in: 28800, +} + +/** MonitoringHandlers.handleHealthCheck */ +export const healthPayload = { + healthy: true, + available: true, + status: 'HEALTHY', + timestamp: 1764028800000, +} + +/** MonitoringHandlers.handleGetPoolStats (Python3ScriptModule.getPoolStats + healthCheckStatus) */ +export const poolStatsPayload = { + poolSize: 3, + available: 2, + inUse: 1, + healthy: true, + healthCheckStatus: 'Healthy', +} + +/** MonitoringHandlers.handleGetVersions (PoolManager mode) */ +export const versionsPayload = { + versions: ['3.11', '3.12'], + default: '3.11', + count: 2, + details: { + '3.11': { path: '/usr/bin/python3.11', isDefault: true, poolSize: 3, available: 2, healthy: true }, + '3.12': { path: '/usr/bin/python3.12', isDefault: false, poolSize: 3, available: 3, healthy: true }, + }, + success: true, + timestamp: 1764028800000, +} + +/** MonitoringHandlers.handleGetVersion */ +export const versionPayload = { + version: '3.11.9', + available: true, + pythonVersion: '3.11.9', + moduleVersion: '9.8.7', +} + +/** MonitoringHandlers.handleGetMetrics (Python3MetricsCollector.getMetrics) */ +export const metricsPayload = { + total_executions: 42, + successful_executions: 40, + failed_executions: 2, + success_rate: 95.2, + total_execution_time_ms: 840, + average_execution_time_ms: 20, + min_execution_time_ms: 3, + max_execution_time_ms: 110, + pool_size: 3, + active_executions: 1, + pool_utilization: 33.3, + pool_wait_count: 0, + average_pool_wait_ms: 0, + error_counts: {}, + uptime_ms: 3600000, + uptime_hours: 1.0, +} + +/** MonitoringHandlers.handleDiagnostics */ +export const diagnosticsPayload = { + available: true, + poolStats: { poolSize: 3, available: 2, inUse: 1, healthy: true }, + versionInfo: { version: '3.11.9', available: true }, + distributionInfo: { os: 'linux' }, + timestamp: 1764028800000, +} + +/** MonitoringHandlers.handleGetDistributions */ +export const distributionsPayload = { + distributions: [ + { + version: '3.11', + fullVersion: '3.11.9', + installed: true, + available: true, + pythonPath: '/opt/ignition/data/python3-integration/python/3.11/bin/python3', + installSizeBytes: 104857600, + installSizeMB: 100, + poolActive: true, + }, + { + version: '3.13', + fullVersion: '3.13.1', + installed: false, + available: true, + poolActive: false, + }, + ], + os: 'linux', + installedCount: 1, + success: true, + timestamp: 1764028800000, +} + +/** ScriptAndPackageHandlers.handleListScripts */ +export const scriptsListPayload = { + success: true, + scripts: [ + { + id: 'a1', + name: 'TankLevels', + description: 'Reads tank levels', + author: 'admin', + createdDate: '2026-11-01T09:00:00Z', + lastModified: '2026-11-20T10:30:00Z', + folderPath: 'Reports', + version: 1, + }, + { + id: 'b2', + name: 'Housekeeping', + description: 'Nightly clean-up', + author: 'admin', + createdDate: '2026-11-02T09:00:00Z', + lastModified: '2026-11-21T10:30:00Z', + folderPath: '', + version: 3, + }, + ], +} + +/** ScriptAndPackageHandlers.handleGetPackageCatalog (object map keyed by package name) */ +export const catalogPayload = { + packages: { + numpy: { + version: '2.1.3', + description: 'Fundamental package for array computing', + sizeMb: 18.5, + importName: 'numpy', + installed: true, + wheels: ['numpy-2.1.3-cp311-cp311-manylinux_2_17_x86_64.whl'], + pipPackages: ['numpy'], + requiredFor: ['pandas'], + }, + pandas: { + version: '2.2.3', + description: 'Powerful data structures for data analysis', + sizeMb: 42.0, + importName: 'pandas', + installed: false, + wheels: [], + pipPackages: ['pandas'], + requiredFor: [], + }, + }, + count: 2, +} + +/** Python3LogsHandler.readLogs */ +export const logsPayload = { + success: true, + entries: [ + { id: 101, timestamp: '2026-11-25 08:00:01', level: 'INFO', message: 'Python3ProcessPool started with 3 executors' }, + { id: 102, timestamp: '2026-11-25 08:00:05', level: 'WARN', message: 'Executor 2 slow to respond' }, + ], + count: 2, + total: 2, + hasMore: false, +} + +/** The standard set of read-only routes the app hits on load. */ +export function defaultRoutes(): Record { + return { + '/auth/session': sessionPayload, + '/api/v1/health': healthPayload, + '/api/v1/pool-stats': poolStatsPayload, + '/api/v1/versions': versionsPayload, + '/api/v1/version': versionPayload, + '/api/v1/metrics': metricsPayload, + '/api/v1/diagnostics': diagnosticsPayload, + '/api/v1/distributions': distributionsPayload, + '/api/v1/scripts/list': scriptsListPayload, + '/api/v1/packages/catalog': catalogPayload, + '/api/v1/logs': logsPayload, + } +} diff --git a/web-ui/src/test/setup.ts b/web-ui/src/test/setup.ts index 7b0828b..bb02c60 100644 --- a/web-ui/src/test/setup.ts +++ b/web-ui/src/test/setup.ts @@ -1 +1 @@ -import '@testing-library/jest-dom'; +import '@testing-library/jest-dom/vitest'; diff --git a/web-ui/src/utils/api.test.ts b/web-ui/src/utils/api.test.ts new file mode 100644 index 0000000..33d1665 --- /dev/null +++ b/web-ui/src/utils/api.test.ts @@ -0,0 +1,69 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { mockGateway, callsTo, headersOf, sessionPayload, textResponse } from '../test/gatewayMock' + +// api.ts caches the session token at module level, so each test gets a fresh copy. +async function loadApi() { + vi.resetModules() + return import('./api') +} + +describe('api client', () => { + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + }) + afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('creates a session, then apiPost sends its Bearer and CSRF tokens with a JSON body', async () => { + const fetchMock = mockGateway({ + '/auth/session': sessionPayload, + '/api/v1/exec': { success: true, result: '2' }, + }) + const api = await loadApi() + const data = await api.apiPost<{ success: boolean; result: string }>('/api/v1/exec', { code: 'print(1+1)' }) + + expect(data).toEqual({ success: true, result: '2' }) + const [session] = callsTo(fetchMock, '/auth/session') + expect(session[1]?.method).toBe('POST') + expect(JSON.parse(String(session[1]?.body))).toEqual({ client_id: 'gateway-web-ui' }) + const [call] = callsTo(fetchMock, '/api/v1/exec') + expect(call[1]?.method).toBe('POST') + expect(headersOf(call[1])).toMatchObject({ + 'Content-Type': 'application/json', + Authorization: 'Bearer api-token-456', + 'X-CSRF-Token': 'csrf-token-123', + }) + expect(JSON.parse(String(call[1]?.body))).toEqual({ code: 'print(1+1)' }) + }) + + it('apiGet unwraps the Ignition {data: ...} envelope', async () => { + mockGateway({ + '/auth/session': { data: sessionPayload }, + '/api/v1/health': { data: { healthy: true, status: 'HEALTHY' } }, + }) + const api = await loadApi() + await expect(api.apiGet('/api/v1/health')).resolves.toEqual({ healthy: true, status: 'HEALTHY' }) + }) + + it('throws the server error body when the gateway answers 500', async () => { + mockGateway({ + '/auth/session': sessionPayload, + '/api/v1/packages/catalog': () => textResponse('Python 3 process pool is not initialized', 500), + }) + const api = await loadApi() + await expect(api.apiGet('/api/v1/packages/catalog')).rejects.toThrow( + 'Python 3 process pool is not initialized' + ) + }) + + it('throws AuthRequiredError when a request is redirected to the login page', async () => { + mockGateway({ + '/auth/session': sessionPayload, + '/api/v1/health': () => textResponse('', 200, 'text/html'), + }) + const api = await loadApi() + await expect(api.apiGet('/api/v1/health')).rejects.toMatchObject({ name: 'AuthRequiredError' }) + }) +}) diff --git a/web-ui/src/utils/authCheck.test.ts b/web-ui/src/utils/authCheck.test.ts new file mode 100644 index 0000000..732f341 --- /dev/null +++ b/web-ui/src/utils/authCheck.test.ts @@ -0,0 +1,17 @@ +import { describe, it, expect } from 'vitest' +import { AuthRequiredError, checkAuthResponse } from './authCheck' +import { jsonResponse, textResponse } from '../test/gatewayMock' + +describe('checkAuthResponse', () => { + it('throws AuthRequiredError when the gateway answers with its HTML login page', () => { + const res = textResponse('login', 200, 'text/html; charset=utf-8') + expect(() => checkAuthResponse(res)).toThrow(AuthRequiredError) + expect(() => checkAuthResponse(res)).toThrow( + 'Authentication required. Please log in to the Ignition Gateway first.' + ) + }) + + it('accepts a JSON response', () => { + expect(() => checkAuthResponse(jsonResponse({ success: true }))).not.toThrow() + }) +})