Image Pipeline Playground
test(frontend): add unit tests for CustomCodeTrust components and related functionality
Mohammad Rajaei928cfdc30bed
diff --git a/frontend/src/features/execution/CustomCodeTrustBanner.test.tsx b/frontend/src/features/execution/CustomCodeTrustBanner.test.tsxnew file mode 100644index 0000000..f5d7dee--- /dev/null+++ b/frontend/src/features/execution/CustomCodeTrustBanner.test.tsx@@ -0,0 +1,44 @@+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it } from 'vitest'+import { useGraphStore } from '../../store/graphStore'+import { computeCustomCodeHash } from '../../workflow/customCodeTrust'+import {+ pipelineCustomNode,+ resetCustomCodeStore,+} from '../../test/customPythonFixtures'+import { CustomCodeTrustBanner } from './CustomCodeTrustBanner'++describe('CustomCodeTrustBanner', () => {+ beforeEach(() => resetCustomCodeStore())++ it('is hidden without custom code or when already trusted', () => {+ const empty = render(<CustomCodeTrustBanner />)+ expect(empty.container).toBeEmptyDOMElement()+ empty.unmount()++ const nodes = [pipelineCustomNode('return image')]+ resetCustomCodeStore({+ nodes,+ trustedCustomCodeHash: computeCustomCodeHash(nodes),+ })+ const trusted = render(<CustomCodeTrustBanner />)+ expect(trusted.container).toBeEmptyDOMElement()+ })++ it('warns when untrusted and opens review dialog without auto-run', async () => {+ const user = userEvent.setup()+ resetCustomCodeStore({+ nodes: [pipelineCustomNode('return image')],+ trustedCustomCodeHash: null,+ })+ render(<CustomCodeTrustBanner />)++ expect(screen.getByText(/includes custom Python/i)).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: /Review & trust/i }))+ expect(useGraphStore.getState()).toMatchObject({+ customCodeTrustDialogOpen: true,+ pendingRunAfterTrust: false,+ })+ })+})diff --git a/frontend/src/features/execution/CustomCodeTrustDialog.test.tsx b/frontend/src/features/execution/CustomCodeTrustDialog.test.tsxnew file mode 100644index 0000000..d2b4865--- /dev/null+++ b/frontend/src/features/execution/CustomCodeTrustDialog.test.tsx@@ -0,0 +1,65 @@+import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { useGraphStore } from '../../store/graphStore'+import {+ IDENTITY_CODE,+ pipelineCustomNode,+ resetCustomCodeStore,+} from '../../test/customPythonFixtures'+import { CustomCodeTrustDialog } from './CustomCodeTrustDialog'++const runPipeline = vi.fn()++vi.mock('../../hooks/useExecutionSocket', () => ({+ runPipeline: (...args: unknown[]) => runPipeline(...args),+}))++const store = () => useGraphStore.getState()++function openDialog(runAfterTrust: boolean) {+ resetCustomCodeStore({+ nodes: [pipelineCustomNode(IDENTITY_CODE)],+ trustedCustomCodeHash: null,+ customCodeTrustDialogOpen: true,+ pendingRunOptions: {},+ pendingRunAfterTrust: runAfterTrust,+ })+ render(<CustomCodeTrustDialog />)+}++describe('CustomCodeTrustDialog', () => {+ beforeEach(() => {+ runPipeline.mockReset()+ resetCustomCodeStore()+ })++ it('lists nodes and labels the confirm action by pending-run mode', () => {+ openDialog(true)+ expect(screen.getByText(/Trust custom Python\?/i)).toBeInTheDocument()+ expect(screen.getByText(/\(custom-1\)/)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Trust and run/i })).toBeInTheDocument()+ })++ it('trusts and optionally runs on confirm; Cancel leaves untrusted', async () => {+ const user = userEvent.setup()++ openDialog(true)+ await user.click(screen.getByRole('button', { name: /Trust and run/i }))+ await waitFor(() => expect(store().isCustomCodeTrusted()).toBe(true))+ expect(store().customCodeTrustDialogOpen).toBe(false)+ expect(runPipeline).toHaveBeenCalled()++ runPipeline.mockClear()+ openDialog(false)+ await user.click(screen.getByRole('button', { name: /^Trust$/i }))+ await waitFor(() => expect(store().isCustomCodeTrusted()).toBe(true))+ expect(runPipeline).not.toHaveBeenCalled()++ openDialog(true)+ await user.click(screen.getByRole('button', { name: /Cancel/i }))+ expect(store().customCodeTrustDialogOpen).toBe(false)+ expect(store().isCustomCodeTrusted()).toBe(false)+ expect(runPipeline).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/features/inspector/CustomPythonParams.test.tsx b/frontend/src/features/inspector/CustomPythonParams.test.tsxnew file mode 100644index 0000000..6c5c4c3--- /dev/null+++ b/frontend/src/features/inspector/CustomPythonParams.test.tsx@@ -0,0 +1,65 @@+import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { describe, expect, it, vi } from 'vitest'+import { IDENTITY_CODE } from '../../test/customPythonFixtures'+import { CustomPythonParams } from './CustomPythonParams'++vi.mock('@monaco-editor/react', async () => {+ const { MockMonacoEditor } = await import('../../test/MockMonacoEditor')+ return { default: MockMonacoEditor }+})++function renderParams(onCodeChange = vi.fn()) {+ render(<CustomPythonParams code={IDENTITY_CODE} onCodeChange={onCodeChange} />)+ return onCodeChange+}++async function openEditor() {+ const user = userEvent.setup()+ await user.click(screen.getByRole('button', { name: /Edit code/i }))+ return user+}++describe('CustomPythonParams', () => {+ it('shows a read-only preview until Edit code is clicked', () => {+ renderParams()+ expect(screen.getByTestId('monaco-readonly')).toHaveAttribute('readonly')+ expect(screen.getByRole('button', { name: /Edit code/i })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /^Save$/i })).not.toBeInTheDocument()+ })++ it('opens an edit dialog with Save and Cancel (no close icon)', async () => {+ renderParams()+ await openEditor()+ expect(screen.getByText(/Edit Custom Python/i)).toBeInTheDocument()+ expect(screen.getByTestId('monaco-edit')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /^Save$/i })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Cancel/i })).toBeInTheDocument()+ expect(screen.queryByLabelText(/Close editor/i)).not.toBeInTheDocument()+ })++ it('commits edits on Save and discards them on Cancel', async () => {+ const onSave = renderParams()+ let user = await openEditor()+ await user.clear(screen.getByTestId('monaco-edit'))+ await user.type(screen.getByTestId('monaco-edit'), 'return image * 2')+ await user.click(screen.getByRole('button', { name: /^Save$/i }))++ await waitFor(() => expect(onSave).toHaveBeenCalled())+ expect(String(onSave.mock.calls.at(-1)?.[0])).toContain('return image * 2')+ await waitFor(() => {+ expect(screen.queryByRole('button', { name: /^Save$/i })).not.toBeInTheDocument()+ })++ onSave.mockClear()+ user = await openEditor()+ await user.clear(screen.getByTestId('monaco-edit'))+ await user.type(screen.getByTestId('monaco-edit'), 'should not persist')+ await user.click(screen.getByRole('button', { name: /Cancel/i }))++ expect(onSave).not.toHaveBeenCalled()+ await waitFor(() => {+ expect(screen.queryByRole('button', { name: /^Save$/i })).not.toBeInTheDocument()+ })+ })+})diff --git a/frontend/src/test/MockMonacoEditor.tsx b/frontend/src/test/MockMonacoEditor.tsxnew file mode 100644index 0000000..aed7b49--- /dev/null+++ b/frontend/src/test/MockMonacoEditor.tsx@@ -0,0 +1,50 @@+/** Lightweight Monaco stand-in for Custom Python tests. */++type MockEditorProps = {+ value?: string+ defaultValue?: string+ onChange?: (value: string | undefined) => void+ options?: { readOnly?: boolean }+ onMount?: (+ editor: {+ getContainerDomNode: () => HTMLElement+ addCommand: () => void+ focus: () => void+ },+ monaco: { KeyMod: { CtrlCmd: number }; KeyCode: { Space: number } },+ ) => void+}++export function MockMonacoEditor({+ value,+ defaultValue,+ onChange,+ options,+ onMount,+}: MockEditorProps) {+ const readOnly = Boolean(options?.readOnly)+ const container = document.createElement('div')++ if (onMount && !readOnly) {+ queueMicrotask(() => {+ onMount(+ {+ getContainerDomNode: () => container,+ addCommand: () => {},+ focus: () => {},+ },+ { KeyMod: { CtrlCmd: 1 }, KeyCode: { Space: 2 } },+ )+ })+ }++ return (+ <textarea+ data-testid={readOnly ? 'monaco-readonly' : 'monaco-edit'}+ readOnly={readOnly}+ defaultValue={readOnly ? undefined : defaultValue}+ value={readOnly ? value : undefined}+ onChange={(event) => onChange?.(event.target.value)}+ />+ )+}diff --git a/frontend/src/test/customPythonFixtures.ts b/frontend/src/test/customPythonFixtures.tsnew file mode 100644index 0000000..e3dcf99--- /dev/null+++ b/frontend/src/test/customPythonFixtures.ts@@ -0,0 +1,94 @@+import type { Node } from '@xyflow/react'+import { useGraphStore } from '../store/graphStore'+import type { GraphNodeData, NodeMetadata } from '../types'+import type { CustomCodeNodeLike } from '../workflow/customCodeTrust'++export const IDENTITY_CODE = 'def process(image, seed=0):\n return image\n'++export const customPythonMeta: NodeMetadata = {+ type: 'custom_python',+ label: 'Custom Python',+ category: 'script',+ description: 'User code',+ ports: [+ { id: 'image', name: 'Image', direction: 'input', data_type: 'image' },+ { id: 'image', name: 'Image', direction: 'output', data_type: 'image' },+ ],+ params: [+ {+ name: 'code',+ label: 'Code',+ type: 'string',+ default: IDENTITY_CODE,+ },+ ],+ stochastic: false,+}++export const loadImageMeta: NodeMetadata = {+ type: 'load_image',+ label: 'Load Images',+ category: 'io',+ description: 'Load',+ ports: [{ id: 'image', name: 'Image', direction: 'output', data_type: 'image' }],+ params: [],+ stochastic: false,+}++/** Lightweight shape for pure trust-helper unit tests. */+export function trustNode(+ id: string,+ type: string,+ code?: string,+): CustomCodeNodeLike {+ return {+ id,+ data: {+ type,+ label: type === 'custom_python' ? 'Custom Python' : type,+ params: code === undefined ? {} : { code },+ },+ }+}++/** Full pipeline node for store / UI tests. */+export function pipelineCustomNode(+ code: string,+ id = 'custom-1',+): Node<GraphNodeData> {+ return {+ id,+ type: 'pipeline',+ position: { x: 0, y: 0 },+ data: {+ type: 'custom_python',+ label: 'Custom Python',+ category: 'script',+ params: { code },+ ports: customPythonMeta.ports,+ },+ }+}++export function resetCustomCodeStore(+ patch: Partial<{+ nodes: Node<GraphNodeData>[]+ trustedCustomCodeHash: string | null+ customCodeTrustDialogOpen: boolean+ pendingRunAfterTrust: boolean+ pendingRunOptions: { targetNodeId?: string } | null+ }> = {},+) {+ useGraphStore.setState({+ nodes: [],+ edges: [],+ selectedNodeId: null,+ nodeCatalog: [customPythonMeta, loadImageMeta],+ trustedCustomCodeHash: null,+ customCodeTrustDialogOpen: false,+ pendingRunOptions: null,+ pendingRunAfterTrust: false,+ workflowDirty: false,+ ...patch,+ })+}diff --git a/frontend/src/workflow/customCodeTrust.store.test.ts b/frontend/src/workflow/customCodeTrust.store.test.tsnew file mode 100644index 0000000..0a830bb--- /dev/null+++ b/frontend/src/workflow/customCodeTrust.store.test.ts@@ -0,0 +1,88 @@+import { beforeEach, describe, expect, it } from 'vitest'+import { useGraphStore } from '../store/graphStore'+import { computeCustomCodeHash } from './customCodeTrust'+import {+ IDENTITY_CODE,+ customPythonMeta,+ pipelineCustomNode,+ resetCustomCodeStore,+} from '../test/customPythonFixtures'++const store = () => useGraphStore.getState()++describe('graphStore custom code trust', () => {+ beforeEach(() => resetCustomCodeStore())++ it('auto-trusts palette add and local code edits', () => {+ store().addNodeFromType(customPythonMeta, { x: 10, y: 20 })+ expect(store().isCustomCodeTrusted()).toBe(true)+ expect(store().trustedCustomCodeHash).toBe(computeCustomCodeHash(store().nodes))++ resetCustomCodeStore({+ nodes: [pipelineCustomNode(IDENTITY_CODE)],+ trustedCustomCodeHash: null,+ })+ expect(store().isCustomCodeTrusted()).toBe(false)++ store().updateNodeParams('custom-1', { code: 'return image[:, :, ::-1]' })+ expect(store().isCustomCodeTrusted()).toBe(true)+ })++ it('clears trust when loading a workflow that includes custom code', () => {+ store().addNodeFromType(customPythonMeta, { x: 0, y: 0 })+ expect(store().isCustomCodeTrusted()).toBe(true)++ store().loadWorkflow({+ version: 1,+ name: 'imported',+ seed: 0,+ iterationCount: 1,+ graph: {+ nodes: [+ { id: 'load-1', type: 'load_image', params: {}, position: { x: 0, y: 0 } },+ {+ id: 'custom-1',+ type: 'custom_python',+ params: { code: IDENTITY_CODE },+ position: { x: 220, y: 0 },+ },+ ],+ edges: [+ {+ id: 'e1',+ source: 'load-1',+ source_port: 'image',+ target: 'custom-1',+ target_port: 'image',+ },+ ],+ },+ })++ expect(store().graphHasCustomCode()).toBe(true)+ expect(store().trustedCustomCodeHash).toBeNull()+ expect(store().isCustomCodeTrusted()).toBe(false)+ })++ it('sets trust fingerprint and dialog pending-run flags', () => {+ resetCustomCodeStore({+ nodes: [pipelineCustomNode('return image')],+ trustedCustomCodeHash: null,+ })+ store().trustCustomCode()+ expect(store().isCustomCodeTrusted()).toBe(true)++ store().openCustomCodeTrustDialog({ targetNodeId: 'n1' }, true)+ expect(store()).toMatchObject({+ customCodeTrustDialogOpen: true,+ pendingRunAfterTrust: true,+ pendingRunOptions: { targetNodeId: 'n1' },+ })++ store().closeCustomCodeTrustDialog()+ expect(store().customCodeTrustDialogOpen).toBe(false)++ store().openCustomCodeTrustDialog(undefined, false)+ expect(store().pendingRunAfterTrust).toBe(false)+ })+})diff --git a/frontend/src/workflow/customCodeTrust.test.ts b/frontend/src/workflow/customCodeTrust.test.tsnew file mode 100644index 0000000..0039510--- /dev/null+++ b/frontend/src/workflow/customCodeTrust.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'+import {+ computeCustomCodeHash,+ graphHasCustomCode,+ isCustomCodeTrusted,+ listCustomPythonNodes,+ truncateCodePreview,+} from './customCodeTrust'+import { trustNode } from '../test/customPythonFixtures'++describe('customCodeTrust helpers', () => {+ it('detects and sorts custom_python nodes', () => {+ const nodes = [+ trustNode('z-1', 'custom_python', 'a'),+ trustNode('a-1', 'custom_python', 'b'),+ trustNode('mid', 'gaussian_blur'),+ ]+ expect(graphHasCustomCode(nodes)).toBe(true)+ expect(graphHasCustomCode([trustNode('x', 'load_image')])).toBe(false)+ expect(listCustomPythonNodes(nodes).map((n) => n.id)).toEqual(['a-1', 'z-1'])+ })++ it('fingerprints code and treats matching hash as trusted', () => {+ const nodes = [trustNode('c-1', 'custom_python', 'return image')]+ const hash = computeCustomCodeHash(nodes)++ expect(computeCustomCodeHash([trustNode('x', 'load_image')])).toBeNull()+ expect(hash).toBe(computeCustomCodeHash(nodes))+ expect(hash).not.toBe(+ computeCustomCodeHash([trustNode('c-1', 'custom_python', 'return image * 2')]),+ )+ expect(isCustomCodeTrusted(nodes, null)).toBe(false)+ expect(isCustomCodeTrusted(nodes, hash)).toBe(true)+ expect(isCustomCodeTrusted([trustNode('x', 'load_image')], null)).toBe(true)+ })++ it('truncates long code previews', () => {+ const preview = truncateCodePreview('a'.repeat(200), 40)+ expect(preview).toHaveLength(40)+ expect(preview.endsWith('…')).toBe(true)+ })+})diff --git a/frontend/src/workflow/templates.customPython.test.ts b/frontend/src/workflow/templates.customPython.test.tsnew file mode 100644index 0000000..e8c7174--- /dev/null+++ b/frontend/src/workflow/templates.customPython.test.ts@@ -0,0 +1,30 @@+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { describe, expect, it } from 'vitest'+import { TEMPLATE_CATEGORY_META, WORKFLOW_TEMPLATES } from './templates'++const examplesDir = join(dirname(fileURLToPath(import.meta.url)), '../../public/examples')++describe('Custom Python template', () => {+ it('registers the Script gallery entry and ships process() example code', () => {+ expect(TEMPLATE_CATEGORY_META.script.label).toBe('Script')+ expect(WORKFLOW_TEMPLATES).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: 'custom_python_sepia',+ category: 'script',+ path: '/examples/custom_python_sepia.json',+ steps: ['Load', 'Custom Python'],+ }),+ ]),+ )++ const doc = JSON.parse(+ readFileSync(join(examplesDir, 'custom_python_sepia.json'), 'utf8'),+ ) as { graph: { nodes: Array<{ type: string; params?: { code?: string } }> } }++ const custom = doc.graph.nodes.find((node) => node.type === 'custom_python')+ expect(custom?.params?.code).toMatch(/def process\s*\(/)+ })+})