Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

test(web): exercise real attachment, variable and audio owners (#45294)

Stephen Zhoub7a2d6b1a553
diff --git a/web/app/components/base/markdown-blocks/__tests__/audio-block.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/audio-block.spec.tsx
index ec9eaf3e7e3..8b8acd45b17 100644
--- a/web/app/components/base/markdown-blocks/__tests__/audio-block.spec.tsx
+++ b/web/app/components/base/markdown-blocks/__tests__/audio-block.spec.tsx
@@ -1,16 +1,7 @@
import { render } from '@testing-library/react'
-import { describe, expect, it, vi } from 'vite-plus/test'
+import { describe, expect, it } from 'vite-plus/test'
import AudioBlock from '../audio-block'
-// Mock the nested AudioPlayer used by AudioGallery (do not mock AudioGallery itself)
-const audioPlayerMock = vi.fn()
-vi.mock('@/app/components/base/audio-gallery/AudioPlayer', () => ({
- default: (props: { srcs: string[] }) => {
- audioPlayerMock(props)
- return null
- },
-})) // adjust path if AudioBlock sits elsewhere
-
describe('AudioBlock source extraction', () => {
it('renders AudioGallery with multiple srcs extracted from node.children', () => {
const node = {
@@ -22,9 +13,13 @@ describe('AudioBlock source extraction', () => {
properties: {},
}
- render(<AudioBlock node={node} />)
+ const { container } = render(<AudioBlock node={node} />)
- expect(audioPlayerMock).toHaveBeenCalledWith({ srcs: ['one.mp3', 'two.mp3'] })
+ expect(
+ Array.from(container.querySelectorAll('audio source'), (source) =>
+ source.getAttribute('src'),
+ ),
+ ).toEqual(['one.mp3', 'two.mp3'])
})
it('renders AudioGallery with single src from node.properties when no children with properties', () => {
@@ -33,9 +28,9 @@ describe('AudioBlock source extraction', () => {
properties: { src: 'single.mp3' },
}
- render(<AudioBlock node={node} />)
+ const { container } = render(<AudioBlock node={node} />)
- expect(audioPlayerMock).toHaveBeenCalledWith({ srcs: ['single.mp3'] })
+ expect(container.querySelector('audio source')).toHaveAttribute('src', 'single.mp3')
})
it('returns null when there are no audio sources', () => {
@@ -46,6 +41,5 @@ describe('AudioBlock source extraction', () => {
const { container } = render(<AudioBlock node={node} />)
expect(container.firstChild).toBeNull()
- expect(audioPlayerMock).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx
index 0cd315037cf..7d180968e0d 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx
@@ -1,41 +1,90 @@
import type { i18n as I18nType } from 'i18next'
import type { ReactNode } from 'react'
-import type { Var } from '@/app/components/workflow/types'
-import { render, screen } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import i18next from 'i18next'
import { useState } from 'react'
import { I18nextProvider, initReactI18next } from 'react-i18next'
-import { VarType } from '@/app/components/workflow/types'
+import {
+ createEdge,
+ createNode,
+ createStartNode,
+} from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { seedToolProviders } from '@/test/console/tool-providers'
import PrePopulate from '../pre-populate'
vi.unmock('react-i18next')
-type VarReferencePickerProps = {
- onChange: (value: string[]) => void
- filterVar: (v: Var) => boolean
-}
-
-vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
- default: (props: VarReferencePickerProps) => {
- return (
- <>
- {(['string', 'number', 'secret', 'object'] as const)
- .filter((type) => props.filterVar({ variable: type, type: VarType[type] }))
- .map((type) => (
- <button key={type} type="button" onClick={() => props.onChange(['node-1', type])}>
- {type} variable
- </button>
- ))}
- </>
- )
- },
-}))
-
let i18n: I18nType
-const renderWithI18n = (ui: ReactNode) => {
- return render(<I18nextProvider i18n={i18n}>{ui}</I18nextProvider>)
+const render = (ui: ReactNode) => {
+ const { queryClient } = createConsoleQueryWrapper()
+ seedToolProviders(queryClient, {
+ builtInTools: [],
+ customTools: [],
+ workflowTools: [],
+ mcpTools: [],
+ })
+ queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
+
+ const start = createStartNode({
+ id: 'start',
+ data: {
+ variables: [
+ { variable: 'title', label: 'Title', type: InputVarType.textInput, required: false },
+ { variable: 'count', label: 'Count', type: InputVarType.number, required: false },
+ ],
+ },
+ })
+ const code = createNode({
+ id: 'code',
+ data: {
+ title: 'Code output',
+ type: BlockEnum.Code,
+ outputs: {
+ payload: {
+ type: VarType.object,
+ children: [{ variable: 'label', type: VarType.string }],
+ },
+ },
+ },
+ })
+ const human = createNode({
+ id: 'human',
+ data: { title: 'Human input', type: BlockEnum.HumanInput },
+ })
+
+ return renderWorkflowFlowComponent(<I18nextProvider i18n={i18n}>{ui}</I18nextProvider>, {
+ queryClient,
+ nodes: [start, code, human],
+ edges: [
+ createEdge({
+ source: 'start',
+ target: 'code',
+ data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Code },
+ }),
+ createEdge({
+ source: 'code',
+ target: 'human',
+ data: { sourceType: BlockEnum.Code, targetType: BlockEnum.HumanInput },
+ }),
+ ],
+ initialStoreState: {
+ environmentVariables: [
+ {
+ id: 'env-secret',
+ name: 'API_KEY',
+ value: '[__HIDDEN__]',
+ value_type: 'secret',
+ description: 'Credential',
+ },
+ ],
+ },
+ })
}
describe('PrePopulate', () => {
@@ -66,77 +115,104 @@ describe('PrePopulate', () => {
})
})
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
it('keeps Tab navigation native and opens static content on activation', async () => {
const user = userEvent.setup()
- renderWithI18n(<PrePopulate nodeId="node-1" isVariable={false} value="" />)
+ render(
+ <>
+ <button type="button">Before prepopulation</button>
+ <PrePopulate nodeId="human" isVariable={false} value="" />
+ </>,
+ )
expect(screen.getByText('Static Content')).toBeInTheDocument()
-
+ await user.click(screen.getByRole('button', { name: 'Before prepopulation' }))
await user.keyboard('{Tab}')
expect(screen.getByRole('button', { name: 'Static Content' })).toHaveFocus()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
await user.keyboard('{Enter}')
- expect(screen.getByRole('textbox')).toHaveFocus()
+ expect(screen.getByRole('textbox', { name: 'Static Content' })).toHaveFocus()
})
- it('should update constant value and toggle to variable mode when type switch is clicked', async () => {
+ it('updates the constant value and switches the controlled caller to variable mode', async () => {
const user = userEvent.setup()
const onValueChange = vi.fn()
const onIsVariableChange = vi.fn()
const Wrapper = () => {
const [value, setValue] = useState('initial value')
+ const [isVariable, setIsVariable] = useState(false)
return (
<PrePopulate
- nodeId="node-1"
- isVariable={false}
+ nodeId="human"
+ isVariable={isVariable}
value={value}
onValueChange={(next) => {
onValueChange(next)
setValue(next)
}}
- onIsVariableChange={onIsVariableChange}
+ onIsVariableChange={(next) => {
+ onIsVariableChange(next)
+ setIsVariable(next)
+ }}
+ onValueSelectorChange={() => {}}
/>
)
}
- renderWithI18n(<Wrapper />)
+ render(<Wrapper />)
- await user.clear(screen.getByRole('textbox'))
- await user.type(screen.getByRole('textbox'), 'next')
- await user.click(screen.getByText('Use Variable Instead'))
+ await user.clear(screen.getByRole('textbox', { name: 'Static Content' }))
+ await user.type(screen.getByRole('textbox', { name: 'Static Content' }), 'next')
+ await user.click(screen.getByRole('button', { name: 'Use Variable Instead' }))
expect(onValueChange).toHaveBeenLastCalledWith('next')
expect(onIsVariableChange).toHaveBeenCalledWith(true)
+ expect(screen.queryByRole('textbox', { name: 'Static Content' })).not.toBeInTheDocument()
})
- it('should render variable picker mode and propagate selected value selector', async () => {
+ it('selects a supported graph variable and switches the controlled caller to constant mode', async () => {
const user = userEvent.setup()
const onValueSelectorChange = vi.fn()
const onIsVariableChange = vi.fn()
- renderWithI18n(
- <PrePopulate
- nodeId="node-2"
- isVariable
- valueSelector={['node-2', 'existing']}
- onValueSelectorChange={onValueSelectorChange}
- onIsVariableChange={onIsVariableChange}
- />,
- )
+ const Wrapper = () => {
+ const [isVariable, setIsVariable] = useState(true)
+ const [valueSelector, setValueSelector] = useState<string[]>(['start', 'title'])
+ return (
+ <PrePopulate
+ nodeId="human"
+ isVariable={isVariable}
+ valueSelector={valueSelector}
+ onValueSelectorChange={(next) => {
+ onValueSelectorChange(next)
+ if (Array.isArray(next)) setValueSelector(next)
+ }}
+ onIsVariableChange={(next) => {
+ onIsVariableChange(next)
+ setIsVariable(next)
+ }}
+ value=""
+ onValueChange={() => {}}
+ />
+ )
+ }
+
+ render(<Wrapper />)
+
+ expect(screen.getByText('title')).toBeVisible()
+ await user.click(screen.getByText('title'))
+ const picker = await screen.findByRole('dialog')
+ expect(within(picker).queryByText('payload')).not.toBeInTheDocument()
+ expect(within(picker).getByText('API_KEY')).toBeVisible()
+ await user.click(within(picker).getByText('count'))
- expect(screen.queryByRole('button', { name: 'object variable' })).not.toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'string variable' })).toBeVisible()
- expect(screen.getByRole('button', { name: 'secret variable' })).toBeVisible()
- await user.click(screen.getByRole('button', { name: 'number variable' }))
- await user.click(screen.getByText('Use Constant Instead'))
+ expect(onValueSelectorChange).toHaveBeenCalledWith(['start', 'count'])
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(screen.getByText('count')).toBeVisible()
- expect(onValueSelectorChange).toHaveBeenCalledWith(['node-1', 'number'])
+ await user.click(screen.getByRole('button', { name: 'Use Constant Instead' }))
expect(onIsVariableChange).toHaveBeenCalledWith(false)
+ expect(screen.getByRole('textbox', { name: 'Static Content' })).toBeInTheDocument()
})
})
diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsx
index b08946790c5..9b8077b76a3 100644
--- a/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsx
+++ b/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsx
@@ -1,14 +1,25 @@
import type { ComponentProps } from 'react'
-import type ImageUploader from '@/app/components/datasets/common/image-uploader/image-uploader-in-chunk'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { IndexingType } from '@/app/components/datasets/create/step-two'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
import { ChunkingMode } from '@/models/datasets'
-import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { consoleQuery } from '@/service/console'
+import {
+ createConsoleQueryClient,
+ renderWithConsoleQuery as render,
+} from '@/test/console/query-data'
+import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
import { SegmentDetail } from '../segment-detail'
+type Upload = (options: { data: FormData }) => Promise<{ id: string; [key: string]: unknown }>
+const upload = vi.hoisted(() => vi.fn<Upload>())
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ upload,
+}))
+
// Mock dataset detail context
let mockIndexingTechnique: IndexingType = IndexingType.QUALIFIED
let mockRuntimeMode = 'general'
@@ -39,27 +50,18 @@ vi.mock('../../context', () => ({
// Mock segment list context
let mockFullScreen = false
-const mockToggleFullScreen = vi.fn()
vi.mock('../index', () => ({
useSegmentListContext: (
selector: (state: { fullScreen: boolean; toggleFullScreen: () => void }) => unknown,
) => {
const state = {
fullScreen: mockFullScreen,
- toggleFullScreen: mockToggleFullScreen,
+ toggleFullScreen: () => {},
}
return selector(state)
},
}))
-// Upload transport is covered by the uploader suite. Keep its public value contract here.
-let uploaderProps: ComponentProps<typeof ImageUploader>
-vi.mock('@/app/components/datasets/common/image-uploader/image-uploader-in-chunk', () => ({
- default: (props: ComponentProps<typeof ImageUploader>) => {
- uploaderProps = props
- return null
- },
-}))
const segment = {
id: 'segment-1',
content: 'Original content',
@@ -83,13 +85,19 @@ function setup(overrides: Partial<ComponentProps<typeof SegmentDetail>> = {}) {
emit = (event) => eventEmitter!.emit(event)
return null
}
- render(
+ const queryClient = createConsoleQueryClient()
+ queryClient.setQueryData(
+ consoleQuery.files.upload.get.queryKey(),
+ createFileUploadConfigFixture(),
+ )
+ const rendered = render(
<EventEmitterContextProvider>
<CaptureEmitter />
<SegmentDetail {...props} {...overrides} />
</EventEmitterContextProvider>,
+ { queryClient },
)
- return { emit: (event: string) => act(() => emit(event)) }
+ return { ...rendered, emit: (event: string) => act(() => emit(event)) }
}
beforeEach(() => {
mockFullScreen = false
@@ -98,6 +106,7 @@ beforeEach(() => {
mockParentMode = 'paragraph'
mockDocForm = ChunkingMode.text
mockCanEdit = true
+ upload.mockReset()
})
it('saves edited content with its segment identity and blocks duplicate saves during updates', async () => {
@@ -150,7 +159,21 @@ it('saves QA edits and updated economy keywords together', async () => {
it('preserves loaded attachments and forwards uploaded attachment changes on save', async () => {
const user = userEvent.setup()
- setup({
+ upload.mockImplementation(({ data }) => {
+ const file = data.get('file') as File
+ return Promise.resolve({
+ id: 'att-2',
+ name: file.name,
+ size: file.size,
+ extension: 'png',
+ mime_type: file.type,
+ preview_url: null,
+ source_url: '/new.png',
+ created_at: 1,
+ created_by: 'test-user',
+ })
+ })
+ const { container } = setup({
segInfo: {
...segment,
attachments: [
@@ -165,36 +188,40 @@ it('preserves loaded attachments and forwards uploaded attachment changes on sav
],
},
})
- expect(uploaderProps.value).toEqual([
- expect.objectContaining({ uploadedId: 'att-1', sourceUrl: '/photo.jpg', progress: 100 }),
- ])
- const added = {
- id: 'local-2',
- uploadedId: 'att-2',
- name: 'new.jpg',
- size: 20,
- mimeType: 'image/jpeg',
- extension: 'jpg',
- progress: 100,
- }
- act(() => uploaderProps.onChange([...uploaderProps.value!, added]))
+ const loadedImage = screen.getByRole('img', { name: 'Preview' })
+ expect(loadedImage).toHaveAttribute('src', '/photo.jpg')
+
+ const file = new File(['new image'], 'new.png', { type: 'image/png' })
+ await user.upload(container.querySelector('input[type="file"]') as HTMLInputElement, file)
+ await waitFor(() => expect(upload).toHaveBeenCalledOnce())
+ await waitFor(() => expect(screen.getAllByRole('img', { name: 'Preview' })).toHaveLength(2))
+ await waitFor(() =>
+ expect(screen.queryByRole('progressbar', { name: 'custom.uploading' })).not.toBeInTheDocument(),
+ )
await user.click(screen.getByRole('button', { name: /common.operation.save/ }))
expect(props.onUpdate).toHaveBeenCalledWith(
'segment-1',
'Original content',
'Original answer',
segment.keywords,
- [expect.objectContaining({ uploadedId: 'att-1' }), added],
+ [
+ expect.objectContaining({ uploadedId: 'att-1', sourceUrl: '/photo.jpg', progress: 100 }),
+ expect.objectContaining({ uploadedId: 'att-2', originalFile: file, progress: 100 }),
+ ],
'',
false,
)
})
-it.each([false, true])('withholds editing for view mode or readonly access (%s)', (readonly) => {
- mockCanEdit = !readonly
- setup({ isEditMode: readonly })
+it.each([
+ ['view mode', false, true],
+ ['readonly access', true, false],
+])('withholds editing for %s', (_label, isEditMode, canEdit) => {
+ mockCanEdit = canEdit
+ const { container } = setup({ isEditMode })
expect(screen.queryByRole('button', { name: /common.operation.save/ })).not.toBeInTheDocument()
- expect(uploaderProps.disabled).toBe(true)
+ expect(container.querySelector('input[type="file"]')).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.remove' })).not.toBeInTheDocument()
})
it('cancels a draft without saving', async () => {