index
int64
0
0
repo_id
stringlengths
21
232
file_path
stringlengths
34
259
content
stringlengths
1
14.1M
__index_level_0__
int64
0
10k
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/PipelineList.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Tooltip from '@material-ui/core/Tooltip'; import produce from 'immer'; import * as React from 'react'; import { Link } from 'react-router-dom'; import { classes } from 'typestyle'; import { V2beta1Pipeline, V2beta1ListPipelinesResponse } from 'src/apisv2beta1/pipeline'; import CustomTable, { Column, CustomRendererProps, ExpandState, Row, } from 'src/components/CustomTable'; import { Description } from 'src/components/Description'; import { RoutePage, RouteParams } from 'src/components/Router'; import { ToolbarProps } from 'src/components/Toolbar'; import { commonCss, padding } from 'src/Css'; import { Apis, ListRequest, PipelineSortKeys } from 'src/lib/Apis'; import Buttons, { ButtonKeys } from 'src/lib/Buttons'; import { formatDateString } from 'src/lib/Utils'; import { Page } from './Page'; import PipelineVersionList from './PipelineVersionList'; interface DisplayPipeline extends V2beta1Pipeline { expandState?: ExpandState; } interface PipelineListState { displayPipelines: DisplayPipeline[]; selectedIds: string[]; // selectedVersionIds is a map from string to string array. // For each pipeline, there is a list of selected version ids. selectedVersionIds: { [pipelineId: string]: string[] }; } const descriptionCustomRenderer: React.FC<CustomRendererProps<string>> = ( props: CustomRendererProps<string>, ) => { return <Description description={props.value || ''} forceInline={true} />; }; class PipelineList extends Page<{ namespace?: string }, PipelineListState> { private _tableRef = React.createRef<CustomTable>(); constructor(props: any) { super(props); this.state = { displayPipelines: [], selectedIds: [], selectedVersionIds: {}, }; } public getInitialToolbarState(): ToolbarProps { const buttons = new Buttons(this.props, this.refresh.bind(this)); return { actions: buttons .newPipelineVersion('Upload pipeline') .refresh(this.refresh.bind(this)) .deletePipelinesAndPipelineVersions( () => this.state.selectedIds, () => this.state.selectedVersionIds, (pipelineId, ids) => this._selectionChanged(pipelineId, ids), false /* useCurrentResource */, ) .getToolbarActionMap(), breadcrumbs: [], pageTitle: 'Pipelines', }; } public render(): JSX.Element { const columns: Column[] = [ { customRenderer: this._nameCustomRenderer, flex: 1, label: 'Pipeline name', sortKey: PipelineSortKeys.NAME, }, { label: 'Description', flex: 3, customRenderer: descriptionCustomRenderer }, { label: 'Uploaded on', sortKey: PipelineSortKeys.CREATED_AT, flex: 1 }, ]; const rows: Row[] = this.state.displayPipelines.map(p => { return { expandState: p.expandState, id: p.pipeline_id!, otherFields: [p.display_name!, p.description!, formatDateString(p.created_at!)], }; }); return ( <div className={classes(commonCss.page, padding(20, 'lr'))}> <CustomTable ref={this._tableRef} columns={columns} rows={rows} initialSortColumn={PipelineSortKeys.CREATED_AT} updateSelection={this._selectionChanged.bind(this, undefined)} selectedIds={this.state.selectedIds} reload={this._reload.bind(this)} toggleExpansion={this._toggleRowExpand.bind(this)} getExpandComponent={this._getExpandedPipelineComponent.bind(this)} filterLabel='Filter pipelines' emptyMessage='No pipelines found. Click "Upload pipeline" to start.' /> </div> ); } public async refresh(): Promise<void> { if (this._tableRef.current) { await this._tableRef.current.reload(); } } private _toggleRowExpand(rowIndex: number): void { const displayPipelines = produce(this.state.displayPipelines, draft => { draft[rowIndex].expandState = draft[rowIndex].expandState === ExpandState.COLLAPSED ? ExpandState.EXPANDED : ExpandState.COLLAPSED; }); this.setState({ displayPipelines }); } private _getExpandedPipelineComponent(rowIndex: number): JSX.Element { const pipeline = this.state.displayPipelines[rowIndex]; return ( <PipelineVersionList pipelineId={pipeline.pipeline_id} onError={() => null} {...this.props} selectedIds={this.state.selectedVersionIds[pipeline.pipeline_id!] || []} noFilterBox={true} onSelectionChange={this._selectionChanged.bind(this, pipeline.pipeline_id)} disableSorting={false} disablePaging={false} /> ); } private async _reload(request: ListRequest): Promise<string> { let response: V2beta1ListPipelinesResponse | null = null; let displayPipelines: DisplayPipeline[]; try { response = await Apis.pipelineServiceApiV2.listPipelines( this.props.namespace, request.pageToken, request.pageSize, request.sortBy, request.filter, ); displayPipelines = response.pipelines || []; displayPipelines.forEach(exp => (exp.expandState = ExpandState.COLLAPSED)); this.clearBanner(); } catch (err) { await this.showPageError('Error: failed to retrieve list of pipelines.', err); } this.setStateSafe({ displayPipelines: (response && response.pipelines) || [] }); return response ? response.next_page_token || '' : ''; } private _nameCustomRenderer: React.FC<CustomRendererProps<string>> = ( props: CustomRendererProps<string>, ) => { return ( <Tooltip title={props.value || ''} enterDelay={300} placement='top-start'> <Link onClick={e => e.stopPropagation()} className={commonCss.link} to={RoutePage.PIPELINE_DETAILS_NO_VERSION.replace(':' + RouteParams.pipelineId, props.id)} > {props.value || ''} </Link> </Tooltip> ); }; // selection changes passed in via "selectedIds" can be // (1) changes of selected pipeline ids, and will be stored in "this.state.selectedIds" or // (2) changes of selected pipeline version ids, and will be stored in "selectedVersionIds" with key "pipelineId" private _selectionChanged(pipelineId: string | undefined, selectedIds: string[]): void { if (!!pipelineId) { // Update selected pipeline version ids. this.setStateSafe({ selectedVersionIds: { ...this.state.selectedVersionIds, ...{ [pipelineId!]: selectedIds } }, }); const actions = this.props.toolbarProps.actions; actions[ButtonKeys.DELETE_RUN].disabled = this.state.selectedIds.length < 1 && selectedIds.length < 1; this.props.updateToolbar({ actions }); } else { // Update selected pipeline ids. this.setStateSafe({ selectedIds }); const selectedVersionIdsCt = this._deepCountDictionary(this.state.selectedVersionIds); const actions = this.props.toolbarProps.actions; actions[ButtonKeys.DELETE_RUN].disabled = selectedIds.length < 1 && selectedVersionIdsCt < 1; this.props.updateToolbar({ actions }); } } private _deepCountDictionary(dict: { [pipelineId: string]: string[] }): number { return Object.keys(dict).reduce((count, pipelineId) => count + dict[pipelineId].length, 0); } } export default PipelineList;
0
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/RunDetailsV2.test.tsx
/* * Copyright 2021 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { act, queryByText, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import * as React from 'react'; import { V2beta1Run, V2beta1RuntimeState } from 'src/apisv2beta1/run'; import { V2beta1Experiment, V2beta1ExperimentStorageState } from 'src/apisv2beta1/experiment'; import { RoutePage, RouteParams } from 'src/components/Router'; import { Apis } from 'src/lib/Apis'; import { Api } from 'src/mlmd/Api'; import { KFP_V2_RUN_CONTEXT_TYPE } from 'src/mlmd/MlmdUtils'; import { mockResizeObserver, testBestPractices } from 'src/TestUtils'; import { CommonTestWrapper } from 'src/TestWrapper'; import { Context, GetContextByTypeAndNameRequest, GetContextByTypeAndNameResponse, GetExecutionsByContextResponse, } from 'src/third_party/mlmd'; import { GetArtifactsByContextResponse, GetEventsByExecutionIDsResponse, } from 'src/third_party/mlmd/generated/ml_metadata/proto/metadata_store_service_pb'; import { PageProps } from './Page'; import { RunDetailsInternalProps } from './RunDetails'; import { RunDetailsV2 } from './RunDetailsV2'; import fs from 'fs'; const V2_PIPELINESPEC_PATH = 'src/data/test/lightweight_python_functions_v2_pipeline_rev.yaml'; const v2YamlTemplateString = fs.readFileSync(V2_PIPELINESPEC_PATH, 'utf8'); testBestPractices(); describe('RunDetailsV2', () => { const RUN_ID = '1'; let updateBannerSpy: any; let updateDialogSpy: any; let updateSnackbarSpy: any; let updateToolbarSpy: any; let historyPushSpy: any; function generateProps(): RunDetailsInternalProps & PageProps { const pageProps: PageProps = { history: { push: historyPushSpy } as any, location: '' as any, match: { params: { [RouteParams.runId]: RUN_ID, }, isExact: true, path: '', url: '', }, toolbarProps: { actions: {}, breadcrumbs: [], pageTitle: '' }, updateBanner: updateBannerSpy, updateDialog: updateDialogSpy, updateSnackbar: updateSnackbarSpy, updateToolbar: updateToolbarSpy, }; return Object.assign(pageProps, { gkeMetadata: {}, }); } const TEST_RUN: V2beta1Run = { created_at: new Date(2018, 8, 5, 4, 3, 2), scheduled_at: new Date(2018, 8, 6, 4, 3, 2), finished_at: new Date(2018, 8, 7, 4, 3, 2), description: 'test run description', experiment_id: 'some-experiment-id', run_id: 'test-run-id', display_name: 'test run', pipeline_spec: { pipeline_id: 'some-pipeline-id', pipeline_manifest: '{some-template-string}', }, runtime_config: { parameters: { param1: 'value1' } }, state: V2beta1RuntimeState.SUCCEEDED, }; const TEST_EXPERIMENT: V2beta1Experiment = { created_at: '2021-01-24T18:03:08Z', description: 'All runs will be grouped here.', experiment_id: 'some-experiment-id', display_name: 'Default', storage_state: V2beta1ExperimentStorageState.AVAILABLE, }; beforeEach(() => { mockResizeObserver(); updateBannerSpy = jest.fn(); updateToolbarSpy = jest.fn(); }); it('Render detail page with reactflow', async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); expect(screen.getByTestId('DagCanvas')).not.toBeNull(); }); it('Shows error banner when disconnected from MLMD', async () => { jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockRejectedValue(new Error('Not connected to MLMD')); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); await waitFor(() => expect(updateBannerSpy).toHaveBeenLastCalledWith( expect.objectContaining({ additionalInfo: 'Cannot find context with {"typeName":"system.PipelineRun","contextName":"1"}: Not connected to MLMD', message: 'Cannot get MLMD objects from Metadata store.', mode: 'error', }), ), ); }); it('Shows no banner when connected from MLMD', async () => { jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockImplementation((request: GetContextByTypeAndNameRequest) => { const response = new GetContextByTypeAndNameResponse(); if ( request.getTypeName() === KFP_V2_RUN_CONTEXT_TYPE && request.getContextName() === RUN_ID ) { response.setContext(new Context()); } return response; }); jest .spyOn(Api.getInstance().metadataStoreService, 'getExecutionsByContext') .mockResolvedValue(new GetExecutionsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getArtifactsByContext') .mockResolvedValue(new GetArtifactsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getEventsByExecutionIDs') .mockResolvedValue(new GetEventsByExecutionIDsResponse()); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); await waitFor(() => expect(updateBannerSpy).toHaveBeenLastCalledWith({})); }); it("shows run title and experiments' links", async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApiV2, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockImplementation((request: GetContextByTypeAndNameRequest) => { return new GetContextByTypeAndNameResponse(); }); jest .spyOn(Api.getInstance().metadataStoreService, 'getExecutionsByContext') .mockResolvedValue(new GetExecutionsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getArtifactsByContext') .mockResolvedValue(new GetArtifactsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getEventsByExecutionIDs') .mockResolvedValue(new GetEventsByExecutionIDsResponse()); await act(async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); }); await waitFor(() => expect(updateToolbarSpy).toHaveBeenCalledWith( expect.objectContaining({ pageTitleTooltip: 'test run', }), ), ); await waitFor(() => expect(updateToolbarSpy).toHaveBeenCalledWith( expect.objectContaining({ breadcrumbs: [ { displayName: 'Experiments', href: RoutePage.EXPERIMENTS }, { displayName: 'Default', href: `/experiments/details/some-experiment-id`, }, ], }), ), ); }); it('shows top bar buttons', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApiV2, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); jest .spyOn(Api.getInstance().metadataStoreService, 'getContextByTypeAndName') .mockResolvedValue(new GetContextByTypeAndNameResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getExecutionsByContext') .mockResolvedValue(new GetExecutionsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getArtifactsByContext') .mockResolvedValue(new GetArtifactsByContextResponse()); jest .spyOn(Api.getInstance().metadataStoreService, 'getEventsByExecutionIDs') .mockResolvedValue(new GetEventsByExecutionIDsResponse()); await act(async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); }); await waitFor(() => expect(updateToolbarSpy).toHaveBeenCalledWith( expect.objectContaining({ actions: expect.objectContaining({ archive: expect.objectContaining({ disabled: false, title: 'Archive' }), retry: expect.objectContaining({ disabled: true, title: 'Retry' }), terminateRun: expect.objectContaining({ disabled: true, title: 'Terminate' }), cloneRun: expect.objectContaining({ disabled: false, title: 'Clone run' }), }), }), ), ); }); describe('topbar tabs', () => { it('switches to Detail tab', async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); screen.getByText('Run details'); screen.getByText('Run ID'); screen.getByText('Workflow name'); screen.getByText('Status'); screen.getByText('Description'); screen.getByText('Created at'); screen.getByText('Started at'); screen.getByText('Finished at'); screen.getByText('Duration'); }); it('shows content in Detail tab', async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); screen.getByText('test-run-id'); // 'Run ID' screen.getByText('test run'); // 'Workflow name' screen.getByText('test run description'); // 'Description' screen.getByText('9/5/2018, 4:03:02 AM'); //'Created at' screen.getByText('9/6/2018, 4:03:02 AM'); // 'Started at' screen.getByText('9/7/2018, 4:03:02 AM'); // 'Finished at' screen.getByText('48:00:00'); // 'Duration' }); it('handles no creation time', async () => { const noCreateTimeRun: V2beta1Run = { // created_at: new Date(2018, 8, 5, 4, 3, 2), scheduled_at: new Date(2018, 8, 6, 4, 3, 2), finished_at: new Date(2018, 8, 7, 4, 3, 2), experiment_id: 'some-experiment-id', run_id: 'test-run-id', display_name: 'test run', description: 'test run description', state: V2beta1RuntimeState.SUCCEEDED, }; render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={noCreateTimeRun} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); expect(screen.getAllByText('-').length).toEqual(2); // create time and duration are empty. }); it('handles no finish time', async () => { const noFinsihTimeRun: V2beta1Run = { created_at: new Date(2018, 8, 5, 4, 3, 2), scheduled_at: new Date(2018, 8, 6, 4, 3, 2), // finished_at: new Date(2018, 8, 7, 4, 3, 2), experiment_id: 'some-experiment-id', run_id: 'test-run-id', display_name: 'test run', description: 'test run description', state: V2beta1RuntimeState.SUCCEEDED, }; render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={noFinsihTimeRun} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); expect(screen.getAllByText('-').length).toEqual(2); // finish time and duration are empty. }); it('shows run parameters', () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Detail')); screen.getByText('param1'); // 'Parameter name' screen.getByText('value1'); // 'Parameter value' }); it('switches to Pipeline Spec tab', async () => { render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); userEvent.click(screen.getByText('Pipeline Spec')); screen.findByTestId('spec-ir'); }); it('shows Execution Sidepanel', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApiV2, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); // Default view has no side panel. expect(screen.queryByText('Input/Output')).toBeNull(); expect(screen.queryByText('Task Details')).toBeNull(); // Select execution to open side panel. userEvent.click(screen.getByText('preprocess')); screen.getByText('Input/Output'); screen.getByText('Task Details'); // Close side panel. userEvent.click(screen.getByLabelText('close')); expect(screen.queryByText('Input/Output')).toBeNull(); expect(screen.queryByText('Task Details')).toBeNull(); }); it('shows Artifact Sidepanel', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); getRunSpy.mockResolvedValue(TEST_RUN); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApiV2, 'getExperiment'); getExperimentSpy.mockResolvedValue(TEST_EXPERIMENT); render( <CommonTestWrapper> <RunDetailsV2 pipeline_job={v2YamlTemplateString} run={TEST_RUN} {...generateProps()} ></RunDetailsV2> </CommonTestWrapper>, ); // Default view has no side panel. expect(screen.queryByText('Artifact Info')).toBeNull(); expect(screen.queryByText('Visualization')).toBeNull(); // Select artifact to open side panel. userEvent.click(screen.getByText('model')); screen.getByText('Artifact Info'); screen.getByText('Visualization'); // Close side panel. userEvent.click(screen.getByLabelText('close')); expect(screen.queryByText('Artifact Info')).toBeNull(); expect(screen.queryByText('Visualization')).toBeNull(); }); }); });
1
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/AllExperimentsAndArchive.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as React from 'react'; import ExperimentList from './ExperimentList'; import ArchivedExperiments from './ArchivedExperiments'; import MD2Tabs from '../atoms/MD2Tabs'; import { Page, PageProps } from './Page'; import { RoutePage } from '../components/Router'; import { ToolbarProps } from '../components/Toolbar'; import { classes } from 'typestyle'; import { commonCss, padding } from '../Css'; export enum AllExperimentsAndArchiveTab { EXPERIMENTS = 0, ARCHIVE = 1, } export interface AllExperimentsAndArchiveProps extends PageProps { view: AllExperimentsAndArchiveTab; } interface AllExperimentsAndArchiveState { selectedTab: AllExperimentsAndArchiveTab; } class AllExperimentsAndArchive extends Page< AllExperimentsAndArchiveProps, AllExperimentsAndArchiveState > { public getInitialToolbarState(): ToolbarProps { return { actions: {}, breadcrumbs: [], pageTitle: '' }; } public render(): JSX.Element { return ( <div className={classes(commonCss.page, padding(20, 't'))}> <MD2Tabs tabs={['Active', 'Archived']} selectedTab={this.props.view} onSwitch={this._tabSwitched.bind(this)} /> {this.props.view === 0 && <ExperimentList {...this.props} />} {this.props.view === 1 && <ArchivedExperiments {...this.props} />} </div> ); } public async refresh(): Promise<void> { return; } private _tabSwitched(newTab: AllExperimentsAndArchiveTab): void { this.props.history.push( newTab === AllExperimentsAndArchiveTab.EXPERIMENTS ? RoutePage.EXPERIMENTS : RoutePage.ARCHIVED_EXPERIMENTS, ); } } export default AllExperimentsAndArchive;
2
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/ArtifactListSwitcher.test.tsx
/* * Copyright 2023 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import * as React from 'react'; import { Api } from 'src/mlmd/library'; import { Artifact, ArtifactType, GetArtifactsRequest, GetArtifactsResponse, GetArtifactTypesResponse, Value, } from 'src/third_party/mlmd'; import { RoutePage } from 'src/components/Router'; import { testBestPractices } from 'src/TestUtils'; import ArtifactListSwitcher from 'src/pages/ArtifactListSwitcher'; import { PageProps } from 'src/pages/Page'; import { CommonTestWrapper } from 'src/TestWrapper'; testBestPractices(); describe('ArtifactListSwitcher', () => { let getArtifactsSpy: jest.Mock<{}>; let getArtifactTypesSpy: jest.Mock<{}>; const getArtifactsRequest = new GetArtifactsRequest(); beforeEach(() => { getArtifactsSpy = jest.spyOn(Api.getInstance().metadataStoreService, 'getArtifacts'); getArtifactTypesSpy = jest.spyOn(Api.getInstance().metadataStoreService, 'getArtifactTypes'); getArtifactTypesSpy.mockImplementation(() => { const artifactType = new ArtifactType(); artifactType.setId(6); artifactType.setName('String'); const response = new GetArtifactTypesResponse(); response.setArtifactTypesList([artifactType]); return Promise.resolve(response); }); getArtifactsSpy.mockImplementation(() => { const artifacts = mockNArtifacts(5); const response = new GetArtifactsResponse(); response.setArtifactsList(artifacts); return Promise.resolve(response); }); }); function generateProps(): PageProps { const pageProps: PageProps = { history: {} as any, location: { pathname: RoutePage.EXECUTIONS, } as any, match: {} as any, toolbarProps: { actions: {}, breadcrumbs: [], pageTitle: '' }, updateBanner: () => null, updateDialog: () => null, updateSnackbar: () => null, updateToolbar: () => null, }; return pageProps; } function mockNArtifacts(n: number) { let artifacts: Artifact[] = []; for (let i = 1; i <= n; i++) { const artifact = new Artifact(); const pipelineValue = new Value(); const pipelineName = `pipeline ${i}`; pipelineValue.setStringValue(pipelineName); artifact.getPropertiesMap().set('pipeline_name', pipelineValue); const artifactValue = new Value(); const artifactName = `test artifact ${i}`; artifactValue.setStringValue(artifactName); artifact.getPropertiesMap().set('name', artifactValue); artifact.setName(artifactName); artifacts.push(artifact); } return artifacts; } it('shows "Flat" and "Group" tabs', () => { render( <CommonTestWrapper> <ArtifactListSwitcher {...generateProps()} /> </CommonTestWrapper>, ); screen.getByText('Default'); screen.getByText('Grouped'); }); it('disable pagination if switch to "Group" view', async () => { render( <CommonTestWrapper> <ArtifactListSwitcher {...generateProps()} /> </CommonTestWrapper>, ); const groupTab = screen.getByText('Grouped'); fireEvent.click(groupTab); // "Group" view will call getExection() without list options getArtifactsRequest.setOptions(undefined); await waitFor(() => { expect(getArtifactTypesSpy).toHaveBeenCalledTimes(2); // once for flat, once for group expect(getArtifactsSpy).toHaveBeenCalledTimes(2); // once for flat, once for group expect(getArtifactsSpy).toHaveBeenLastCalledWith(getArtifactsRequest); }); expect(screen.queryByText('Rows per page:')).toBeNull(); // no footer expect(screen.queryByText('10')).toBeNull(); // no footer }); });
3
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/ResourceSelector.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as React from 'react'; import CustomTable, { Column, Row } from '../components/CustomTable'; import Toolbar, { ToolbarActionMap } from '../components/Toolbar'; import { ListRequest } from '../lib/Apis'; import { RouteComponentProps } from 'react-router-dom'; import { logger, errorToMessage, formatDateString } from '../lib/Utils'; import { DialogProps } from '../components/Router'; interface BaseResponse { resources: BaseResource[]; nextPageToken: string; } export interface BaseResource { id?: string; created_at?: Date; description?: string; name?: string; error?: string; namespace?: string; } export interface ResourceSelectorProps extends RouteComponentProps { listApi: (...args: any[]) => Promise<BaseResponse>; columns: Column[]; emptyMessage: string; filterLabel: string; initialSortColumn: any; selectionChanged: (selectedId: string) => void; title?: string; toolbarActionMap?: ToolbarActionMap; updateDialog: (dialogProps: DialogProps) => void; } interface ResourceSelectorState { resources: BaseResource[]; rows: Row[]; selectedIds: string[]; toolbarActionMap: ToolbarActionMap; } class ResourceSelector extends React.Component<ResourceSelectorProps, ResourceSelectorState> { protected _isMounted = true; constructor(props: any) { super(props); this.state = { resources: [], rows: [], selectedIds: [], toolbarActionMap: (props && props.toolbarActionMap) || {}, }; } public render(): JSX.Element { const { rows, selectedIds, toolbarActionMap } = this.state; const { columns, title, filterLabel, emptyMessage, initialSortColumn } = this.props; return ( <React.Fragment> {title && <Toolbar actions={toolbarActionMap} breadcrumbs={[]} pageTitle={title} />} <CustomTable isCalledByV1={false} columns={columns} rows={rows} selectedIds={selectedIds} useRadioButtons={true} updateSelection={this._selectionChanged.bind(this)} filterLabel={filterLabel} initialSortColumn={initialSortColumn} reload={this._load.bind(this)} emptyMessage={emptyMessage} /> </React.Fragment> ); } public componentWillUnmount(): void { this._isMounted = false; } protected setStateSafe(newState: Partial<ResourceSelectorState>, cb?: () => void): void { if (this._isMounted) { this.setState(newState as any, cb); } } protected _selectionChanged(selectedIds: string[]): void { if (!Array.isArray(selectedIds) || selectedIds.length !== 1) { logger.error(`${selectedIds.length} resources were selected somehow`, selectedIds); return; } this.props.selectionChanged(selectedIds[0]); this.setStateSafe({ selectedIds }); } protected async _load(request: ListRequest): Promise<string> { let nextPageToken = ''; try { const response = await this.props.listApi( request.pageToken, request.pageSize, request.sortBy, request.filter, ); this.setStateSafe({ resources: response.resources, rows: this._resourcesToRow(response.resources), }); nextPageToken = response.nextPageToken; } catch (err) { const errorMessage = await errorToMessage(err); this.props.updateDialog({ buttons: [{ text: 'Dismiss' }], content: 'List request failed with:\n' + errorMessage, title: 'Error retrieving resources', }); logger.error('Could not get requested list of resources', errorMessage); } return nextPageToken; } protected _resourcesToRow(resources: BaseResource[]): Row[] { return resources.map( r => ({ error: (r as any).error, id: r.id!, otherFields: [r.name, r.description, formatDateString(r.created_at)], } as Row), ); } } export default ResourceSelector;
4
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/PipelineDetailsV2.tsx
/* * Copyright 2021 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React, { useState } from 'react'; import { Elements, FlowElement } from 'react-flow-renderer'; import { V2beta1Pipeline, V2beta1PipelineVersion } from 'src/apisv2beta1/pipeline'; import MD2Tabs from 'src/atoms/MD2Tabs'; import { FlowElementDataBase } from 'src/components/graph/Constants'; import { PipelineVersionCard } from 'src/components/navigators/PipelineVersionCard'; import { PipelineSpecTabContent } from 'src/components/PipelineSpecTabContent'; import SidePanel from 'src/components/SidePanel'; import { StaticNodeDetailsV2 } from 'src/components/tabs/StaticNodeDetailsV2'; import { PipelineFlowElement } from 'src/lib/v2/StaticFlow'; import { commonCss, padding } from 'src/Css'; import DagCanvas from './v2/DagCanvas'; const TAB_NAMES = ['Graph', 'Pipeline Spec']; interface PipelineDetailsV2Props { templateString?: string; pipelineFlowElements: PipelineFlowElement[]; setSubDagLayers: (layers: string[]) => void; pipeline: V2beta1Pipeline | null; selectedVersion: V2beta1PipelineVersion | undefined; versions: V2beta1PipelineVersion[]; handleVersionSelected: (versionId: string) => Promise<void>; } function PipelineDetailsV2({ templateString, pipelineFlowElements, setSubDagLayers, pipeline, selectedVersion, versions, handleVersionSelected, }: PipelineDetailsV2Props) { const [layers, setLayers] = useState(['root']); const [selectedTab, setSelectedTab] = useState(0); const [selectedNode, setSelectedNode] = useState<FlowElement<FlowElementDataBase> | null>(null); const layerChange = (l: string[]) => { setSelectedNode(null); setLayers(l); setSubDagLayers(l); }; const onSelectionChange = (elements: Elements<FlowElementDataBase> | null) => { if (!elements || elements?.length === 0) { setSelectedNode(null); return; } if (elements && elements.length === 1) { setSelectedNode(elements[0]); } }; const getNodeName = function(element: FlowElement<FlowElementDataBase> | null): string { if (element && element.data && element.data.label) { return element.data.label; } return 'unknown'; }; return ( <div className={commonCss.page} data-testid={'pipeline-detail-v2'}> <MD2Tabs selectedTab={selectedTab} onSwitch={setSelectedTab} tabs={TAB_NAMES} /> {selectedTab === 0 && ( <div className={commonCss.page} style={{ position: 'relative', overflow: 'hidden' }}> <DagCanvas layers={layers} onLayersUpdate={layerChange} elements={pipelineFlowElements} onSelectionChange={onSelectionChange} setFlowElements={() => {}} ></DagCanvas> <PipelineVersionCard pipeline={pipeline} selectedVersion={selectedVersion} versions={versions} handleVersionSelected={handleVersionSelected} /> {templateString && ( <div className='z-20'> <SidePanel isOpen={!!selectedNode} title={getNodeName(selectedNode)} onClose={() => onSelectionChange(null)} defaultWidth={'50%'} > <div className={commonCss.page}> <div className={padding(20, 'lr')}> <StaticNodeDetailsV2 templateString={templateString} layers={layers} onLayerChange={layerChange} element={selectedNode} /> </div> </div> </SidePanel> </div> )} </div> )} {selectedTab === 1 && ( <div className={commonCss.codeEditor} data-testid={'spec-ir'}> <PipelineSpecTabContent templateString={templateString || ''} /> </div> )} </div> ); } export default PipelineDetailsV2;
5
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/RunDetails.tsx
/* * Copyright 2018-2019 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import CircularProgress from '@material-ui/core/CircularProgress'; import InfoIcon from '@material-ui/icons/InfoOutlined'; import { flatten } from 'lodash'; import * as React from 'react'; import { Link, Redirect } from 'react-router-dom'; import { ExternalLink } from 'src/atoms/ExternalLink'; import InputOutputTab from 'src/components/tabs/InputOutputTab'; import { MetricsTab } from 'src/components/tabs/MetricsTab'; import { GkeMetadata, GkeMetadataContext } from 'src/lib/GkeMetadata'; import { useNamespaceChangeEvent } from 'src/lib/KubeflowClient'; import { ExecutionHelpers, getExecutionsFromContext, getRunContext } from 'src/mlmd/MlmdUtils'; import { isV2Pipeline } from 'src/lib/v2/WorkflowUtils'; import { Context, Execution } from 'src/third_party/mlmd'; import { classes, stylesheet } from 'typestyle'; import { NodePhase as ArgoNodePhase, NodeStatus, Workflow, } from 'src/third_party/mlmd/argo_template'; import { ApiExperiment } from 'src/apis/experiment'; import { ApiRun, ApiRunStorageState } from 'src/apis/run'; import { ApiVisualization, ApiVisualizationType } from 'src/apis/visualization'; import Hr from 'src/atoms/Hr'; import MD2Tabs from 'src/atoms/MD2Tabs'; import Separator from 'src/atoms/Separator'; import Banner, { Mode } from 'src/components/Banner'; import CompareTable from 'src/components/CompareTable'; import DetailsTable from 'src/components/DetailsTable'; import Graph from 'src/components/Graph'; import LogViewer from 'src/components/LogViewer'; import MinioArtifactPreview from 'src/components/MinioArtifactPreview'; import PlotCard from 'src/components/PlotCard'; import { PodEvents, PodInfo } from 'src/components/PodYaml'; import ReduceGraphSwitch from 'src/components/ReduceGraphSwitch'; import { RoutePage, RoutePageFactory, RouteParams } from 'src/components/Router'; import SidePanel from 'src/components/SidePanel'; import { ToolbarProps } from 'src/components/Toolbar'; import { HTMLViewerConfig } from 'src/components/viewers/HTMLViewer'; import { PlotType, ViewerConfig } from 'src/components/viewers/Viewer'; import { componentMap } from 'src/components/viewers/ViewerContainer'; import VisualizationCreator, { VisualizationCreatorConfig, } from 'src/components/viewers/VisualizationCreator'; import { color, commonCss, fonts, fontsize, padding } from 'src/Css'; import { Apis } from 'src/lib/Apis'; import Buttons, { ButtonKeys } from 'src/lib/Buttons'; import CompareUtils from 'src/lib/CompareUtils'; import { OutputArtifactLoader } from 'src/lib/OutputArtifactLoader'; import RunUtils from 'src/lib/RunUtils'; import { compareGraphEdges, KeyValue, transitiveReduction } from 'src/lib/StaticGraphParser'; import { hasFinished, NodePhase } from 'src/lib/StatusUtils'; import { decodeCompressedNodes, errorToMessage, formatDateString, getNodeNameFromNodeId, getRunDurationFromNode, getRunDurationFromWorkflow, logger, serviceErrorToString, } from 'src/lib/Utils'; import WorkflowParser from 'src/lib/WorkflowParser'; import { ExecutionDetailsContent } from './ExecutionDetails'; import { Page, PageProps } from './Page'; import { statusToIcon } from './Status'; export enum SidePanelTab { INPUT_OUTPUT, VISUALIZATIONS, TASK_DETAILS, VOLUMES, LOGS, POD, EVENTS, ML_METADATA, MANIFEST, } interface SelectedNodeDetails { id: string; logs?: string; phase?: string; phaseMessage?: string; } // exported only for testing export interface RunDetailsInternalProps { isLoading?: boolean; runId?: string; gkeMetadata: GkeMetadata; } export type RunDetailsProps = PageProps & Exclude<RunDetailsInternalProps, 'gkeMetadata'>; interface AnnotatedConfig { config: ViewerConfig; stepName: string; } interface GeneratedVisualization { config: HTMLViewerConfig; nodeId: string; } interface RunDetailsState { allArtifactConfigs: AnnotatedConfig[]; allowCustomVisualizations: boolean; experiment?: ApiExperiment; generatedVisualizations: GeneratedVisualization[]; isGeneratingVisualization: boolean; logsBannerAdditionalInfo: string; logsBannerMessage: string; logsBannerMode: Mode; graph?: dagre.graphlib.Graph; reducedGraph?: dagre.graphlib.Graph; runFinished: boolean; runMetadata?: ApiRun; selectedTab: number; selectedNodeDetails: SelectedNodeDetails | null; sidepanelBannerMode: Mode; sidepanelBusy: boolean; sidepanelSelectedTab: SidePanelTab; workflow?: Workflow; mlmdRunContext?: Context; mlmdExecutions?: Execution[]; showReducedGraph?: boolean; namespace?: string; } export const css = stylesheet({ footer: { background: color.graphBg, display: 'flex', padding: '0 0 20px 20px', }, graphPane: { backgroundColor: color.graphBg, overflow: 'hidden', position: 'relative', }, infoSpan: { color: color.lowContrast, fontFamily: fonts.secondary, fontSize: fontsize.small, letterSpacing: '0.21px', lineHeight: '24px', paddingLeft: 6, }, link: { color: '#77abda', }, outputTitle: { color: color.strong, fontSize: fontsize.title, fontWeight: 'bold', paddingLeft: 20, }, }); class RunDetails extends Page<RunDetailsInternalProps, RunDetailsState> { public state: RunDetailsState = { allArtifactConfigs: [], allowCustomVisualizations: false, generatedVisualizations: [], isGeneratingVisualization: false, logsBannerAdditionalInfo: '', logsBannerMessage: '', logsBannerMode: 'error', runFinished: false, selectedNodeDetails: null, selectedTab: 0, sidepanelBannerMode: 'warning', sidepanelBusy: false, sidepanelSelectedTab: SidePanelTab.INPUT_OUTPUT, mlmdRunContext: undefined, mlmdExecutions: undefined, showReducedGraph: false, }; private readonly AUTO_REFRESH_INTERVAL = 5000; private _interval?: NodeJS.Timeout; public getInitialToolbarState(): ToolbarProps { const buttons = new Buttons(this.props, this.refresh.bind(this)); const runIdFromParams = this.props.match.params[RouteParams.runId]; return { actions: buttons .retryRun( () => this.state.runMetadata ? [this.state.runMetadata!.id!] : runIdFromParams ? [runIdFromParams] : [], true, () => this.retry(), ) .cloneRun( () => this.state.runMetadata ? [this.state.runMetadata!.id!] : runIdFromParams ? [runIdFromParams] : [], true, ) .terminateRun( () => this.state.runMetadata ? [this.state.runMetadata!.id!] : runIdFromParams ? [runIdFromParams] : [], true, () => this.refresh(), ) .getToolbarActionMap(), breadcrumbs: [{ displayName: 'Experiments', href: RoutePage.EXPERIMENTS }], pageTitle: this.props.runId!, }; } public render(): JSX.Element { if (this.props.isLoading) { return <div>Currently loading run information</div>; } const { allArtifactConfigs, allowCustomVisualizations, isGeneratingVisualization, runFinished, runMetadata, selectedTab, sidepanelBannerMode, selectedNodeDetails, sidepanelSelectedTab, workflow, mlmdExecutions, showReducedGraph, } = this.state; const { projectId, clusterName } = this.props.gkeMetadata; const selectedNodeId = selectedNodeDetails?.id || ''; const namespace = workflow?.metadata?.namespace; const selectedNodeName = getNodeNameFromNodeId(workflow!, selectedNodeId); let stackdriverK8sLogsUrl = ''; if (projectId && clusterName && selectedNodeDetails && selectedNodeDetails.id) { stackdriverK8sLogsUrl = `https://console.cloud.google.com/logs/viewer?project=${projectId}&interval=NO_LIMIT&advancedFilter=resource.type%3D"k8s_container"%0Aresource.labels.cluster_name:"${clusterName}"%0Aresource.labels.pod_name:"${selectedNodeDetails.id}"`; } const workflowParameters = WorkflowParser.getParameters(workflow); const { inputParams, outputParams } = WorkflowParser.getNodeInputOutputParams( workflow, selectedNodeId, ); const { inputArtifacts, outputArtifacts } = WorkflowParser.getNodeInputOutputArtifacts( workflow, selectedNodeId, ); const selectedExecution = mlmdExecutions?.find( execution => ExecutionHelpers.getKfpPod(execution) === selectedNodeId, ); const hasMetrics = runMetadata && runMetadata.metrics && runMetadata.metrics.length > 0; const visualizationCreatorConfig: VisualizationCreatorConfig = { allowCustomVisualizations, isBusy: isGeneratingVisualization, onGenerate: (visualizationArguments: string, source: string, type: ApiVisualizationType) => { this._onGenerate(visualizationArguments, source, type, namespace || ''); }, type: PlotType.VISUALIZATION_CREATOR, collapsedInitially: true, }; const graphToShow = this.state.showReducedGraph && this.state.reducedGraph ? this.state.reducedGraph : this.state.graph; return ( <div className={classes(commonCss.page, padding(20, 't'))}> {!!workflow && ( <div className={commonCss.page}> <MD2Tabs selectedTab={selectedTab} tabs={['Graph', 'Run output', 'Config']} onSwitch={(tab: number) => this.setStateSafe({ selectedTab: tab })} /> <div className={commonCss.page}> {/* Graph tab */} {selectedTab === 0 && ( <div className={classes(commonCss.page, css.graphPane)}> {graphToShow && ( <div className={commonCss.page}> <Graph graph={graphToShow} selectedNodeId={selectedNodeId} onClick={id => this._selectNode(id)} onError={(message, additionalInfo) => this.props.updateBanner({ message, additionalInfo, mode: 'error' }) } /> <ReduceGraphSwitch disabled={!this.state.reducedGraph} checked={showReducedGraph} onChange={_ => { this.setState({ showReducedGraph: !this.state.showReducedGraph }); }} /> <SidePanel isBusy={this.state.sidepanelBusy} isOpen={!!selectedNodeDetails} onClose={() => this.setStateSafe({ selectedNodeDetails: null })} title={selectedNodeName} > {!!selectedNodeDetails && ( <React.Fragment> {!!selectedNodeDetails.phaseMessage && ( <Banner mode={sidepanelBannerMode} message={selectedNodeDetails.phaseMessage} /> )} <div className={commonCss.page}> <MD2Tabs tabs={this.getTabNames(workflow, selectedNodeId)} selectedTab={sidepanelSelectedTab} onSwitch={this._loadSidePaneTab.bind(this)} /> <div data-testid='run-details-node-details' className={commonCss.page} > {sidepanelSelectedTab === SidePanelTab.VISUALIZATIONS && this.state.selectedNodeDetails && this.state.workflow && !isV2Pipeline(workflow) && ( <VisualizationsTabContent execution={selectedExecution} nodeId={selectedNodeId} nodeStatus={ this.state.workflow && this.state.workflow.status ? this.state.workflow.status.nodes[ this.state.selectedNodeDetails.id ] : undefined } namespace={this.state.workflow?.metadata?.namespace} visualizationCreatorConfig={visualizationCreatorConfig} generatedVisualizations={this.state.generatedVisualizations.filter( visualization => visualization.nodeId === selectedNodeDetails.id, )} onError={this.handleError} /> )} {sidepanelSelectedTab === SidePanelTab.VISUALIZATIONS && this.state.selectedNodeDetails && this.state.workflow && isV2Pipeline(workflow) && selectedExecution && ( <MetricsTab execution={selectedExecution} namespace={this.state.workflow?.metadata?.namespace} /> )} {sidepanelSelectedTab === SidePanelTab.INPUT_OUTPUT && !isV2Pipeline(workflow) && ( <div className={padding(20)}> <DetailsTable key={`input-parameters-${selectedNodeId}`} title='Input parameters' fields={inputParams} /> <DetailsTable key={`input-artifacts-${selectedNodeId}`} title='Input artifacts' fields={inputArtifacts} valueComponent={MinioArtifactPreview} valueComponentProps={{ namespace: this.state.workflow?.metadata?.namespace, }} /> <DetailsTable key={`output-parameters-${selectedNodeId}`} title='Output parameters' fields={outputParams} /> <DetailsTable key={`output-artifacts-${selectedNodeId}`} title='Output artifacts' fields={outputArtifacts} valueComponent={MinioArtifactPreview} valueComponentProps={{ namespace: this.state.workflow?.metadata?.namespace, }} /> </div> )} {sidepanelSelectedTab === SidePanelTab.INPUT_OUTPUT && isV2Pipeline(workflow) && selectedExecution && ( <InputOutputTab execution={selectedExecution} namespace={namespace} /> )} {sidepanelSelectedTab === SidePanelTab.TASK_DETAILS && ( <div className={padding(20)}> <DetailsTable title='Task Details' fields={this._getTaskDetailsFields(workflow, selectedNodeId)} /> </div> )} {sidepanelSelectedTab === SidePanelTab.ML_METADATA && !isV2Pipeline(workflow) && ( <div className={padding(20)}> {selectedExecution && ( <> <div> This step corresponds to execution{' '} <Link className={commonCss.link} to={RoutePageFactory.executionDetails( selectedExecution.getId(), )} > "{ExecutionHelpers.getName(selectedExecution)}". </Link> </div> <ExecutionDetailsContent key={selectedExecution.getId()} id={selectedExecution.getId()} onError={ ((msg: string, ...args: any[]) => { // TODO: show a proper error banner and retry button console.warn(msg); }) as any } // No title here onTitleUpdate={() => null} /> </> )} {!selectedExecution && ( <div>Corresponding ML Metadata not found.</div> )} </div> )} {sidepanelSelectedTab === SidePanelTab.VOLUMES && ( <div className={padding(20)}> <DetailsTable title='Volume Mounts' fields={WorkflowParser.getNodeVolumeMounts( workflow, selectedNodeId, )} /> </div> )} {sidepanelSelectedTab === SidePanelTab.MANIFEST && ( <div className={padding(20)}> <DetailsTable title='Resource Manifest' fields={WorkflowParser.getNodeManifest( workflow, selectedNodeId, )} /> </div> )} {sidepanelSelectedTab === SidePanelTab.POD && selectedNodeDetails.phase !== NodePhase.SKIPPED && ( <div className={commonCss.page}> {selectedNodeId && namespace && ( <PodInfo name={selectedNodeName} namespace={namespace} /> )} </div> )} {sidepanelSelectedTab === SidePanelTab.EVENTS && selectedNodeDetails.phase !== NodePhase.SKIPPED && ( <div className={commonCss.page}> {selectedNodeId && namespace && ( <PodEvents name={selectedNodeName} namespace={namespace} /> )} </div> )} {sidepanelSelectedTab === SidePanelTab.LOGS && selectedNodeDetails.phase !== NodePhase.SKIPPED && ( <div className={commonCss.page}> {this.state.logsBannerMessage && ( <React.Fragment> <Banner message={this.state.logsBannerMessage} mode={this.state.logsBannerMode} additionalInfo={this.state.logsBannerAdditionalInfo} showTroubleshootingGuideLink={false} refresh={this._loadSelectedNodeLogs.bind(this)} /> </React.Fragment> )} {stackdriverK8sLogsUrl && ( <div className={padding(12)}> Logs can also be viewed in{' '} <a href={stackdriverK8sLogsUrl} target='_blank' rel='noopener noreferrer' className={classes(css.link, commonCss.unstyled)} > Stackdriver Kubernetes Monitoring </a> . </div> )} {!this.state.logsBannerMessage && this.state.selectedNodeDetails && ( // Overflow hidden here, because scroll is handled inside // LogViewer. <div className={commonCss.pageOverflowHidden}> <LogViewer logLines={( this.state.selectedNodeDetails.logs || '' ).split('\n')} /> </div> )} </div> )} </div> </div> </React.Fragment> )} </SidePanel> <div className={css.footer}> <div className={commonCss.flex}> <InfoIcon className={commonCss.infoIcon} /> <span className={css.infoSpan}> Runtime execution graph. Only steps that are currently running or have already completed are shown. </span> </div> </div> </div> )} {!graphToShow && ( <div> {runFinished && <span style={{ margin: '40px auto' }}>No graph to show</span>} {!runFinished && ( <CircularProgress size={30} className={commonCss.absoluteCenter} /> )} </div> )} </div> )} {/* Run outputs tab */} {selectedTab === 1 && ( <div className={padding()}> {hasMetrics && ( <div> <div className={css.outputTitle}>Metrics</div> <div className={padding(20, 'lt')}> <CompareTable {...CompareUtils.singleRunToMetricsCompareProps(runMetadata, workflow)} /> </div> </div> )} {!hasMetrics && <span>No metrics found for this run.</span>} <Separator orientation='vertical' /> <Hr /> {allArtifactConfigs.map((annotatedConfig, i) => ( <div key={i}> <PlotCard key={i} configs={[annotatedConfig.config]} title={annotatedConfig.stepName} maxDimension={400} /> <Separator orientation='vertical' /> <Hr /> </div> ))} {!allArtifactConfigs.length && ( <span>No output artifacts found for this run.</span> )} </div> )} {/* Config tab */} {selectedTab === 2 && ( <div className={padding()}> <DetailsTable title='Run details' fields={this._getDetailsFields(workflow, runMetadata)} /> {workflowParameters && !!workflowParameters.length && ( <div> <DetailsTable title='Run parameters' fields={workflowParameters.map(p => [p.name, p.value || ''])} /> </div> )} </div> )} </div> </div> )} </div> ); } getTabNames(workflow: Workflow, selectedNodeId: string): string[] { // NOTE: it's only possible to conditionally add a tab at the end const tabNameList = []; for (let tab in SidePanelTab) { // enum iterator will get both number key and string value of all cases. // Skip string value because we only switch by numeric key later. if (isNaN(Number(tab))) { continue; } // plus symbol changes enum to number. switch (+tab) { case SidePanelTab.INPUT_OUTPUT: { tabNameList.push('Input/Output'); break; } case SidePanelTab.VISUALIZATIONS: { tabNameList.push('Visualizations'); break; } case SidePanelTab.ML_METADATA: { if (isV2Pipeline(workflow)) { break; } tabNameList.push('ML Metadata'); break; } case SidePanelTab.TASK_DETAILS: { tabNameList.push('Details'); break; } case SidePanelTab.VOLUMES: { tabNameList.push('Volumes'); break; } case SidePanelTab.LOGS: { tabNameList.push('Logs'); break; } case SidePanelTab.POD: { tabNameList.push('Pod'); break; } case SidePanelTab.EVENTS: { tabNameList.push('Events'); break; } case SidePanelTab.MANIFEST: { if (WorkflowParser.getNodeManifest(workflow, selectedNodeId).length === 0) { break; } tabNameList.push('Manifest'); break; } default: { console.error(`Unable to find corresponding tab name for ${tab}`); break; } } } return tabNameList; } public async componentDidMount(): Promise<void> { window.addEventListener('focus', this.onFocusHandler); window.addEventListener('blur', this.onBlurHandler); await this._startAutoRefresh(); } public onBlurHandler = (): void => { this._stopAutoRefresh(); }; public onFocusHandler = async (): Promise<void> => { await this._startAutoRefresh(); }; public componentWillUnmount(): void { this._stopAutoRefresh(); window.removeEventListener('focus', this.onFocusHandler); window.removeEventListener('blur', this.onBlurHandler); this.clearBanner(); } public async retry(): Promise<void> { const runFinished = false; this.setStateSafe({ runFinished, }); await this._startAutoRefresh(); } public async refresh(): Promise<void> { await this.load(); } public async load(): Promise<void> { this.clearBanner(); const runId = this.props.match.params[RouteParams.runId]; try { const allowCustomVisualizations = await Apis.areCustomVisualizationsAllowed(); this.setState({ allowCustomVisualizations }); } catch (err) { this.showPageError('Error: Unable to enable custom visualizations.', err); } try { const runDetail = await Apis.runServiceApi.getRun(runId); const relatedExperimentId = RunUtils.getFirstExperimentReferenceId(runDetail.run); let experiment: ApiExperiment | undefined; let namespace: string | undefined; if (relatedExperimentId) { experiment = await Apis.experimentServiceApi.getExperiment(relatedExperimentId); namespace = RunUtils.getNamespaceReferenceName(experiment); } const runMetadata = runDetail.run!; let runFinished = this.state.runFinished; // If the run has finished, stop auto refreshing if (hasFinished(runMetadata.status as NodePhase)) { this._stopAutoRefresh(); // This prevents other events, such as onFocus, from resuming the autorefresh runFinished = true; } const jsonWorkflow = JSON.parse(runDetail.pipeline_runtime!.workflow_manifest || '{}'); if ( jsonWorkflow.status && !jsonWorkflow.status.nodes && jsonWorkflow.status.compressedNodes ) { try { jsonWorkflow.status.nodes = await decodeCompressedNodes( jsonWorkflow.status.compressedNodes, ); delete jsonWorkflow.status.compressedNodes; } catch (err) { console.error(`Failed to decode compressedNodes: ${err}`); } } const workflow = jsonWorkflow as Workflow; // Show workflow errors const workflowError = WorkflowParser.getWorkflowError(workflow); if (workflowError) { if (workflowError === 'terminated') { this.props.updateBanner({ additionalInfo: `This run's workflow included the following message: ${workflowError}`, message: 'This run was terminated', mode: 'warning', refresh: undefined, }); } else { this.showPageError( `Error: found errors when executing run: ${runId}.`, new Error(workflowError), ); } } let mlmdRunContext: Context | undefined; let mlmdExecutions: Execution[] | undefined; // Get data about this workflow from MLMD try { mlmdRunContext = await getRunContext(workflow, runId); mlmdExecutions = await getExecutionsFromContext(mlmdRunContext); } catch (err) { // Data in MLMD may not exist depending on this pipeline is a TFX pipeline. // So we only log the error in console. logger.warn(err); } // Build runtime graph const graph = workflow && workflow.status && workflow.status.nodes ? WorkflowParser.createRuntimeGraph(workflow, mlmdExecutions) : undefined; let reducedGraph = graph ? // copy graph before removing edges transitiveReduction(graph) : undefined; if (graph && reducedGraph && compareGraphEdges(graph, reducedGraph)) { reducedGraph = undefined; // disable reduction switch } const breadcrumbs: Array<{ displayName: string; href: string }> = []; // If this is an archived run, only show Archive in breadcrumbs, otherwise show // the full path, including the experiment if any. if (runMetadata.storage_state === ApiRunStorageState.ARCHIVED) { breadcrumbs.push({ displayName: 'Archive', href: RoutePage.ARCHIVED_RUNS }); } else { if (experiment) { breadcrumbs.push( { displayName: 'Experiments', href: RoutePage.EXPERIMENTS }, { displayName: experiment.name!, href: RoutePage.EXPERIMENT_DETAILS.replace( ':' + RouteParams.experimentId, experiment.id!, ), }, ); } else { breadcrumbs.push({ displayName: 'All runs', href: RoutePage.RUNS }); } } const pageTitle = ( <div className={commonCss.flex}> {statusToIcon(runMetadata.status as NodePhase, runDetail.run!.created_at)} <span style={{ marginLeft: 10 }}>{runMetadata.name!}</span> </div> ); // Update the Archive/Restore button based on the storage state of this run const buttons = new Buttons( this.props, this.refresh.bind(this), this.getInitialToolbarState().actions, ); const idGetter = () => (runMetadata ? [runMetadata!.id!] : []); runMetadata!.storage_state === ApiRunStorageState.ARCHIVED ? buttons.restore('run', idGetter, true, () => this.refresh()) : buttons.archive('run', idGetter, true, () => this.refresh()); const actions = buttons.getToolbarActionMap(); actions[ButtonKeys.TERMINATE_RUN].disabled = (runMetadata.status as NodePhase) === NodePhase.TERMINATING || runFinished; actions[ButtonKeys.RETRY].disabled = (runMetadata.status as NodePhase) !== NodePhase.FAILED && (runMetadata.status as NodePhase) !== NodePhase.ERROR; this.props.updateToolbar({ actions, breadcrumbs, pageTitle, pageTitleTooltip: runMetadata.name, }); this.setStateSafe({ experiment, graph, reducedGraph, runFinished, runMetadata, workflow, mlmdRunContext, mlmdExecutions, namespace, }); // Read optional exeuction id from query parameter. If valid, shows detail of selected node. const paramExecutionId = this.props.match.params[RouteParams.executionId]; if (mlmdExecutions) { const selectedExec = mlmdExecutions.find( exec => exec.getId().toString() === paramExecutionId, ); if (selectedExec) { const selectedNodeId = ExecutionHelpers.getKfpPod(selectedExec); if (typeof selectedNodeId === 'string') { this.setStateSafe({ selectedNodeDetails: { id: selectedNodeId } }); } } } } catch (err) { await this.showPageError(`Error: failed to retrieve run: ${runId}.`, err); logger.error('Error loading run:', runId, err); } // Make sure logs and artifacts in the side panel are refreshed when // the user hits "Refresh", either in the top toolbar or in an error banner. await this._loadSidePaneTab(this.state.sidepanelSelectedTab); // Load all run's outputs await this._loadAllOutputs(); } private handleError = async (error: Error) => { await this.showPageError(serviceErrorToString(error), error); }; private async _startAutoRefresh(): Promise<void> { // If the run was not finished last time we checked, check again in case anything changed // before proceeding to set auto-refresh interval if (!this.state.runFinished) { // refresh() updates runFinished's value await this.refresh(); } // Only set interval if run has not finished, and verify that the interval is undefined to // avoid setting multiple intervals if (!this.state.runFinished && this._interval === undefined) { this._interval = setInterval(() => this.refresh(), this.AUTO_REFRESH_INTERVAL); } } private _stopAutoRefresh(): void { if (this._interval !== undefined) { clearInterval(this._interval); // Reset interval to indicate that a new one can be set this._interval = undefined; } } private async _loadAllOutputs(): Promise<void> { const workflow = this.state.workflow; if (!workflow) { return; } const outputPathsList = WorkflowParser.loadAllOutputPathsWithStepNames(workflow); const configLists = await Promise.all( outputPathsList.map(({ stepName, path }) => OutputArtifactLoader.load(path, workflow?.metadata?.namespace).then(configs => configs.map(config => ({ config, stepName })), ), ), ); const allArtifactConfigs = flatten(configLists); this.setStateSafe({ allArtifactConfigs }); } private _getDetailsFields(workflow: Workflow, runMetadata?: ApiRun): Array<KeyValue<string>> { return !workflow.status ? [] : [ ['Run ID', runMetadata?.id || '-'], ['Workflow name', workflow.metadata?.name || '-'], ['Status', workflow.status.phase], ['Description', runMetadata ? runMetadata!.description! : ''], [ 'Created at', workflow.metadata ? formatDateString(workflow.metadata.creationTimestamp) : '-', ], ['Started at', formatDateString(workflow.status.startedAt)], ['Finished at', formatDateString(workflow.status.finishedAt)], ['Duration', getRunDurationFromWorkflow(workflow)], ]; } private _getTaskDetailsFields(workflow: Workflow, nodeId: string): Array<KeyValue<string>> { return workflow?.status?.nodes?.[nodeId] ? [ ['Task ID', workflow.status.nodes[nodeId].id || '-'], ['Task name', workflow.status.nodes[nodeId].displayName || '-'], ['Status', workflow.status.nodes[nodeId].phase || '-'], ['Started at', formatDateString(workflow.status.nodes[nodeId].startedAt) || '-'], ['Finished at', formatDateString(workflow.status.nodes[nodeId].finishedAt) || '-'], ['Duration', getRunDurationFromNode(workflow, nodeId) || '-'], ] : []; } private async _selectNode(id: string): Promise<void> { this.setStateSafe( { selectedNodeDetails: { id } }, async () => await this._loadSidePaneTab(this.state.sidepanelSelectedTab), ); } private async _loadSidePaneTab(tab: SidePanelTab): Promise<void> { const workflow = this.state.workflow; const selectedNodeDetails = this.state.selectedNodeDetails; let sidepanelBannerMode: Mode = 'warning'; if (workflow && workflow.status && workflow.status.nodes && selectedNodeDetails) { const node = workflow.status.nodes[selectedNodeDetails.id]; if (node) { selectedNodeDetails.phaseMessage = node && node.message ? `This step is in ${node.phase} state with this message: ` + node.message : undefined; selectedNodeDetails.phase = node.phase; switch (node.phase) { // TODO: make distinction between system and pipelines error clear case NodePhase.ERROR: case NodePhase.FAILED: sidepanelBannerMode = 'error'; break; default: sidepanelBannerMode = 'info'; break; } } this.setStateSafe({ selectedNodeDetails, sidepanelSelectedTab: tab, sidepanelBannerMode }); switch (tab) { case SidePanelTab.LOGS: if (node.phase !== NodePhase.PENDING && node.phase !== NodePhase.SKIPPED) { await this._loadSelectedNodeLogs(); } else { // Clear logs this.setStateSafe({ logsBannerAdditionalInfo: '', logsBannerMessage: '' }); } } } } private async _loadSelectedNodeLogs(): Promise<void> { const selectedNodeDetails = this.state.selectedNodeDetails; const namespace = this.state.workflow?.metadata?.namespace; const runId = this.state.runMetadata?.id; if (!selectedNodeDetails || !runId || !namespace) { return; } this.setStateSafe({ sidepanelBusy: true }); let logsBannerMessage = ''; let logsBannerAdditionalInfo = ''; let logsBannerMode = '' as Mode; try { const nodeName = getNodeNameFromNodeId(this.state.workflow!, selectedNodeDetails.id); selectedNodeDetails.logs = await Apis.getPodLogs(runId, nodeName, namespace, ''); } catch (err) { let errMsg = await errorToMessage(err); logsBannerMessage = 'Failed to retrieve pod logs.'; if (errMsg === 'pod not found') { logsBannerMessage += this.props.gkeMetadata.projectId ? ' Use Stackdriver Kubernetes Monitoring to view them.' : ''; logsBannerMode = 'info'; logsBannerAdditionalInfo = 'Possible reasons include pod garbage collection, cluster autoscaling and pod preemption. '; } else { logsBannerMode = 'error'; } logsBannerAdditionalInfo += 'Error response: ' + errMsg; } this.setStateSafe({ sidepanelBusy: false, logsBannerAdditionalInfo, logsBannerMessage, logsBannerMode, selectedNodeDetails, }); } private async _onGenerate( visualizationArguments: string, source: string, type: ApiVisualizationType, namespace: string, ): Promise<void> { const nodeId = this.state.selectedNodeDetails ? this.state.selectedNodeDetails.id : ''; if (nodeId.length === 0) { this.showPageError('Unable to generate visualization, no component selected.'); return; } if (visualizationArguments.length) { try { // Attempts to validate JSON, if attempt fails an error is displayed. JSON.parse(visualizationArguments); } catch (err) { this.showPageError('Unable to generate visualization, invalid JSON provided.', err); return; } } this.setState({ isGeneratingVisualization: true }); const visualizationData: ApiVisualization = { arguments: visualizationArguments, source, type, }; try { const config = await Apis.buildPythonVisualizationConfig(visualizationData, namespace); const { generatedVisualizations } = this.state; const generatedVisualization: GeneratedVisualization = { config, nodeId, }; generatedVisualizations.push(generatedVisualization); this.setState({ generatedVisualizations }); } catch (err) { this.showPageError( 'Unable to generate visualization, an unexpected error was encountered.', err, ); } finally { this.setState({ isGeneratingVisualization: false }); } } } /** * Circular progress component. The special real progress vs visual progress * logic makes the progress more lively to users. * * NOTE: onComplete handler should remain its identity, otherwise this component * doesn't work well. */ const Progress: React.FC<{ value: number; onComplete: () => void; }> = ({ value: realProgress, onComplete }) => { const [visualProgress, setVisualProgress] = React.useState(0); React.useEffect(() => { let timer: NodeJS.Timeout; function tick() { if (visualProgress >= 100) { clearInterval(timer); // After completed, leave some time to show completed progress. setTimeout(onComplete, 400); } else if (realProgress >= 100) { // When completed, fast forward visual progress to complete. setVisualProgress(oldProgress => Math.min(oldProgress + 6, 100)); } else if (visualProgress < realProgress) { // Usually, visual progress gradually grows towards real progress. setVisualProgress(oldProgress => { const step = Math.max(Math.min((realProgress - oldProgress) / 6, 0.01), 0.2); return oldProgress < realProgress ? Math.min(realProgress, oldProgress + step) : oldProgress; }); } else if (visualProgress > realProgress) { // Fix visual progress if real progress changed to smaller value. // Usually, this shouldn't happen. setVisualProgress(realProgress); } } timer = setInterval(tick, 16.6 /* 60fps -> 16.6 ms is 1 frame */); return () => { clearInterval(timer); }; }, [realProgress, visualProgress, onComplete]); return ( <CircularProgress variant='determinate' size={60} thickness={3} className={commonCss.absoluteCenter} value={visualProgress} /> ); }; const COMPLETED_NODE_PHASES: ArgoNodePhase[] = ['Succeeded', 'Failed', 'Error']; // TODO: add unit tests for this. /** * Visualizations tab content component, it handles loading progress state of * visualize progress as a circular progress icon. */ const VisualizationsTabContent: React.FC<{ visualizationCreatorConfig: VisualizationCreatorConfig; execution?: Execution; nodeId: string; nodeStatus?: NodeStatus; generatedVisualizations: GeneratedVisualization[]; namespace: string | undefined; onError: (error: Error) => void; }> = ({ visualizationCreatorConfig, generatedVisualizations, execution, nodeId, nodeStatus, namespace, onError, }) => { const [loaded, setLoaded] = React.useState(false); // Progress component expects onLoad function identity to stay the same const onLoad = React.useCallback(() => setLoaded(true), [setLoaded]); const [progress, setProgress] = React.useState(0); const [viewerConfigs, setViewerConfigs] = React.useState<ViewerConfig[]>([]); const nodeCompleted: boolean = !!nodeStatus && COMPLETED_NODE_PHASES.includes(nodeStatus.phase); React.useEffect(() => { let aborted = false; async function loadVisualizations() { if (aborted) { return; } setLoaded(false); setProgress(0); setViewerConfigs([]); if (!nodeStatus || !nodeCompleted) { setProgress(100); // Loaded will be set by Progress onComplete return; // Abort, because there is no data. } // Load runtime outputs from the selected Node const outputPaths = WorkflowParser.loadNodeOutputPaths(nodeStatus); const reportProgress = (reportedProgress: number) => { if (!aborted) { setProgress(reportedProgress); } }; const reportErrorAndReturnEmpty = (error: Error): [] => { onError(error); return []; }; // Load the viewer configurations from the output paths const builtConfigs = ( await Promise.all([ ...(!execution ? [] : [ OutputArtifactLoader.buildTFXArtifactViewerConfig({ reportProgress, execution, namespace: namespace || '', }).catch(reportErrorAndReturnEmpty), ]), ...outputPaths.map(path => OutputArtifactLoader.load(path, namespace).catch(reportErrorAndReturnEmpty), ), ]) ).flatMap(configs => configs); if (aborted) { return; } setViewerConfigs(builtConfigs); setProgress(100); // Loaded will be set by Progress onComplete return; } loadVisualizations(); const abort = () => { aborted = true; }; return abort; // Workaround: // Watches nodeStatus.phase in completed status instead of nodeStatus, // because nodeStatus data won't further change after completed, but // nodeStatus object instance will keep changing after new requests to get // workflow status. // eslint-disable-next-line react-hooks/exhaustive-deps }, [nodeId, execution ? execution.getId() : undefined, nodeCompleted, onError, namespace]); // Temporarily use verbose undefined detection instead of execution?.getId() for eslint issue. return ( <div className={commonCss.page}> {!loaded ? ( <Progress value={progress} onComplete={onLoad} /> ) : ( <> {viewerConfigs.length + generatedVisualizations.length === 0 && ( <Banner message='There are no visualizations in this step.' mode='info' /> )} {[ ...viewerConfigs, ...generatedVisualizations.map(visualization => visualization.config), ].map((config, i) => { const title = componentMap[config.type].prototype.getDisplayName(); return ( <div key={i} className={padding(20, 'lrt')}> <PlotCard configs={[config]} title={title} maxDimension={500} /> <Hr /> </div> ); })} <div className={padding(20, 'lrt')}> <PlotCard configs={[visualizationCreatorConfig]} title={VisualizationCreator.prototype.getDisplayName()} maxDimension={500} /> <Hr /> </div> <div className={padding(20)}> <p> Add visualizations to your own components following instructions in{' '} <ExternalLink href='https://www.kubeflow.org/docs/pipelines/sdk/output-viewer/'> Visualize Results in the Pipelines UI </ExternalLink> . </p> </div> </> )} </div> ); }; const EnhancedRunDetails: React.FC<RunDetailsProps> = props => { const namespaceChanged = useNamespaceChangeEvent(); const gkeMetadata = React.useContext(GkeMetadataContext); if (namespaceChanged) { // Run details page shows info about a run, when namespace changes, the run // doesn't exist in the new namespace, so we should redirect to experiment // list page. return <Redirect to={RoutePage.EXPERIMENTS} />; } return <RunDetails {...props} gkeMetadata={gkeMetadata} />; }; export default EnhancedRunDetails; export const TEST_ONLY = { RunDetails };
6
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/PipelineVersionList.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Tooltip from '@material-ui/core/Tooltip'; import CustomTable, { Column, CustomRendererProps, Row } from 'src/components/CustomTable'; import * as React from 'react'; import { Link, RouteComponentProps } from 'react-router-dom'; import { V2beta1PipelineVersion, V2beta1ListPipelineVersionsResponse, } from 'src/apisv2beta1/pipeline'; import { Description } from 'src/components/Description'; import { Apis, ListRequest, PipelineVersionSortKeys } from 'src/lib/Apis'; import { errorToMessage, formatDateString } from 'src/lib/Utils'; import { RoutePage, RouteParams } from 'src/components/Router'; import { commonCss } from 'src/Css'; export interface PipelineVersionListProps extends RouteComponentProps { pipelineId?: string; disablePaging?: boolean; disableSelection?: boolean; disableSorting?: boolean; noFilterBox?: boolean; onError: (message: string, error: Error) => void; onSelectionChange?: (selectedIds: string[]) => void; selectedIds?: string[]; } interface PipelineVersionListState { pipelineVersions: V2beta1PipelineVersion[]; } const descriptionCustomRenderer: React.FC<CustomRendererProps<string>> = ( props: CustomRendererProps<string>, ) => { return ( <Tooltip title={props.value || ''} enterDelay={300} placement='bottom-start'> <span> <Description description={props.value || ''} forceInline={true} /> </span> </Tooltip> ); }; class PipelineVersionList extends React.PureComponent< PipelineVersionListProps, PipelineVersionListState > { private _tableRef = React.createRef<CustomTable>(); constructor(props: any) { super(props); this.state = { pipelineVersions: [], }; } public _nameCustomRenderer: React.FC<CustomRendererProps<string>> = ( props: CustomRendererProps<string>, ) => { return ( <Tooltip title={props.value || ''} enterDelay={300} placement='bottom-start'> {this.props.pipelineId ? ( <Link className={commonCss.link} onClick={e => e.stopPropagation()} to={RoutePage.PIPELINE_DETAILS.replace( ':' + RouteParams.pipelineId, this.props.pipelineId, ).replace(':' + RouteParams.pipelineVersionId, props.id)} > {props.value} </Link> ) : ( <Link className={commonCss.link} onClick={e => e.stopPropagation()} to={RoutePage.PIPELINE_DETAILS.replace(':' + RouteParams.pipelineVersionId, props.id)} > {props.value} </Link> )} </Tooltip> ); }; public render(): JSX.Element { const columns: Column[] = [ { customRenderer: this._nameCustomRenderer, flex: 1, label: 'Version name', sortKey: PipelineVersionSortKeys.NAME, }, { label: 'Description', flex: 3, customRenderer: descriptionCustomRenderer }, { label: 'Uploaded on', flex: 1, sortKey: PipelineVersionSortKeys.CREATED_AT }, ]; const rows: Row[] = this.state.pipelineVersions.map(v => { const row = { id: v.pipeline_version_id!, otherFields: [v.display_name, v.description, formatDateString(v.created_at)] as any, }; return row; }); return ( <div> <CustomTable columns={columns} rows={rows} selectedIds={this.props.selectedIds} initialSortColumn={PipelineVersionSortKeys.CREATED_AT} ref={this._tableRef} updateSelection={this.props.onSelectionChange} reload={this._loadPipelineVersions.bind(this)} disablePaging={this.props.disablePaging} disableSorting={this.props.disableSorting} disableSelection={this.props.disableSelection} noFilterBox={this.props.noFilterBox} emptyMessage='No pipeline versions found.' /> </div> ); } protected async _loadPipelineVersions(request: ListRequest): Promise<string> { let response: V2beta1ListPipelineVersionsResponse | null = null; if (this.props.pipelineId) { try { response = await Apis.pipelineServiceApiV2.listPipelineVersions( this.props.pipelineId, request.pageToken, request.pageSize, request.sortBy, request.filter, ); } catch (err) { const error = new Error(await errorToMessage(err)); this.props.onError('Error: failed to fetch runs.', error); // No point in continuing if we couldn't retrieve any runs. return ''; } this.setState({ pipelineVersions: response.pipeline_versions || [], }); } return response ? response.next_page_token || '' : ''; } } export default PipelineVersionList;
7
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/CompareV2.test.tsx
/* * Copyright 2022 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { render, screen, waitFor, fireEvent } from '@testing-library/react'; import * as React from 'react'; import { CommonTestWrapper } from 'src/TestWrapper'; import TestUtils, { testBestPractices } from 'src/TestUtils'; import { Artifact, Context, Event, Execution } from 'src/third_party/mlmd'; import { Apis } from 'src/lib/Apis'; import { QUERY_PARAMS } from 'src/components/Router'; import * as mlmdUtils from 'src/mlmd/MlmdUtils'; import * as Utils from 'src/lib/Utils'; import { TEST_ONLY } from './CompareV2'; import { PageProps } from './Page'; import { METRICS_SECTION_NAME, OVERVIEW_SECTION_NAME, PARAMS_SECTION_NAME } from './Compare'; import { Struct, Value } from 'google-protobuf/google/protobuf/struct_pb'; import { V2beta1Run } from 'src/apisv2beta1/run'; const CompareV2 = TEST_ONLY.CompareV2; testBestPractices(); describe('CompareV2', () => { const MOCK_RUN_1_ID = 'mock-run-1-id'; const MOCK_RUN_2_ID = 'mock-run-2-id'; const MOCK_RUN_3_ID = 'mock-run-3-id'; const updateBannerSpy = jest.fn(); function generateProps(): PageProps { const pageProps: PageProps = { history: {} as any, location: { search: `?${QUERY_PARAMS.runlist}=${MOCK_RUN_1_ID},${MOCK_RUN_2_ID},${MOCK_RUN_3_ID}`, } as any, match: {} as any, toolbarProps: { actions: {}, breadcrumbs: [], pageTitle: '' }, updateBanner: updateBannerSpy, updateDialog: () => null, updateSnackbar: () => null, updateToolbar: () => null, }; return pageProps; } let runs: V2beta1Run[] = []; function newMockRun(id?: string, hideName?: boolean): V2beta1Run { return { run_id: id || 'test-run-id', display_name: hideName ? undefined : 'test run ' + id, pipeline_spec: { pipeline_manifest: '' }, }; } function newMockContext(name: string, id: number): Execution { const context = new Context(); context.setName(name); context.setId(id); return context; } function newMockExecution(id: number, displayName?: string): Execution { const execution = new Execution(); execution.setId(id); if (displayName) { const customPropertiesMap: Map<string, Value> = new Map(); const displayNameValue = new Value(); displayNameValue.setStringValue(displayName); customPropertiesMap.set('display_name', displayNameValue); jest.spyOn(execution, 'getCustomPropertiesMap').mockReturnValue(customPropertiesMap); } return execution; } function newMockEvent(id: number, displayName?: string): Event { const event = new Event(); event.setArtifactId(id); event.setExecutionId(id); event.setType(Event.Type.OUTPUT); if (displayName) { const path = new Event.Path(); const step = new Event.Path.Step(); step.setKey(displayName); path.addSteps(step); event.setPath(path); } return event; } function newMockArtifact( id: number, isConfusionMatrix?: boolean, isRocCurve?: boolean, displayName?: string, ): Artifact { const artifact = new Artifact(); artifact.setId(id); const customPropertiesMap: Map<string, Value> = new Map(); if (isConfusionMatrix) { const confusionMatrix: Value = new Value(); confusionMatrix.setStructValue( Struct.fromJavaScript({ struct: { annotationSpecs: [ { displayName: 'Setosa' }, { displayName: 'Versicolour' }, { displayName: 'Virginica' }, ], rows: [{ row: [31, 0, 0] }, { row: [1, 8, 12] }, { row: [0, 0, 23] }], }, }), ); customPropertiesMap.set('confusionMatrix', confusionMatrix); } if (isRocCurve) { const confidenceMetrics: Value = new Value(); confidenceMetrics.setStructValue( Struct.fromJavaScript({ list: [ { confidenceThreshold: 2, falsePositiveRate: 0, recall: 0, }, { confidenceThreshold: 1, falsePositiveRate: 0, recall: 0.33962264150943394, }, { confidenceThreshold: 0.9, falsePositiveRate: 0, recall: 0.6037735849056604, }, ], }), ); customPropertiesMap.set('confidenceMetrics', confidenceMetrics); } if (displayName) { const displayNameValue = new Value(); displayNameValue.setStringValue(displayName); customPropertiesMap.set('display_name', displayNameValue); } jest.spyOn(artifact, 'getCustomPropertiesMap').mockReturnValue(customPropertiesMap); return artifact; } it('Render Compare v2 page', async () => { render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); screen.getByText(OVERVIEW_SECTION_NAME); }); it('getRun is called with query param IDs', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); expect(getRunSpy).toHaveBeenCalledWith(MOCK_RUN_1_ID); expect(getRunSpy).toHaveBeenCalledWith(MOCK_RUN_2_ID); expect(getRunSpy).toHaveBeenCalledWith(MOCK_RUN_3_ID); }); it('Clear banner when getRun and MLMD requests succeed', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); const contexts = [ newMockContext(MOCK_RUN_1_ID, 1), newMockContext(MOCK_RUN_2_ID, 2), newMockContext(MOCK_RUN_3_ID, 3), ]; const getContextSpy = jest.spyOn(mlmdUtils, 'getKfpV2RunContext'); getContextSpy.mockImplementation((runID: string) => Promise.resolve(contexts.find(c => c.getName() === runID)), ); const executions = [[newMockExecution(1)], [newMockExecution(2)], [newMockExecution(3)]]; const getExecutionsSpy = jest.spyOn(mlmdUtils, 'getExecutionsFromContext'); getExecutionsSpy.mockImplementation((context: Context) => Promise.resolve(executions.find(e => e[0].getId() === context.getId())), ); const artifacts = [newMockArtifact(1), newMockArtifact(2), newMockArtifact(3)]; const getArtifactsSpy = jest.spyOn(mlmdUtils, 'getArtifactsFromContext'); getArtifactsSpy.mockResolvedValue(artifacts); const events = [newMockEvent(1), newMockEvent(2), newMockEvent(3)]; const getEventsSpy = jest.spyOn(mlmdUtils, 'getEventsByExecutions'); getEventsSpy.mockResolvedValue(events); const getArtifactTypesSpy = jest.spyOn(mlmdUtils, 'getArtifactTypes'); getArtifactTypesSpy.mockReturnValue([]); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); await waitFor(() => { // Spies are called twice for each artifact as runs change from undefined to a defined value. expect(getContextSpy).toBeCalledTimes(6); expect(getExecutionsSpy).toBeCalledTimes(6); expect(getArtifactsSpy).toBeCalledTimes(6); expect(getEventsSpy).toBeCalledTimes(6); expect(getArtifactTypesSpy).toBeCalledTimes(1); expect(updateBannerSpy).toHaveBeenLastCalledWith({}); }); }); it('Log warning when artifact with specified ID is not found', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); const contexts = [ newMockContext(MOCK_RUN_1_ID, 1), newMockContext(MOCK_RUN_2_ID, 2), newMockContext(MOCK_RUN_3_ID, 3), ]; const getContextSpy = jest.spyOn(mlmdUtils, 'getKfpV2RunContext'); getContextSpy.mockImplementation((runID: string) => Promise.resolve(contexts.find(c => c.getName() === runID)), ); const executions = [[newMockExecution(1)], [newMockExecution(2)], [newMockExecution(3)]]; const getExecutionsSpy = jest.spyOn(mlmdUtils, 'getExecutionsFromContext'); getExecutionsSpy.mockImplementation((context: Context) => Promise.resolve(executions.find(e => e[0].getId() === context.getId())), ); const artifacts = [newMockArtifact(1), newMockArtifact(3)]; const getArtifactsSpy = jest.spyOn(mlmdUtils, 'getArtifactsFromContext'); getArtifactsSpy.mockResolvedValue(artifacts); const events = [newMockEvent(1), newMockEvent(2), newMockEvent(3)]; const getEventsSpy = jest.spyOn(mlmdUtils, 'getEventsByExecutions'); getEventsSpy.mockResolvedValue(events); const getArtifactTypesSpy = jest.spyOn(mlmdUtils, 'getArtifactTypes'); getArtifactTypesSpy.mockReturnValue([]); const warnSpy = jest.spyOn(Utils.logger, 'warn'); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); await waitFor(() => { expect(warnSpy).toHaveBeenLastCalledWith( 'The artifact with the following ID was not found: 2', ); }); }); it('Show page error on page when getRun request fails', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation(_ => { throw { text: () => Promise.resolve('test error'), }; }); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); await waitFor(() => expect(updateBannerSpy).toHaveBeenLastCalledWith({ additionalInfo: 'test error', message: 'Error: failed loading 3 runs. Click Details for more information.', mode: 'error', }), ); }); it('Failed MLMD request creates error banner', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); jest .spyOn(mlmdUtils, 'getKfpV2RunContext') .mockRejectedValue(new Error('Not connected to MLMD')); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); await waitFor(() => { expect(updateBannerSpy).toHaveBeenLastCalledWith({ additionalInfo: 'Not connected to MLMD', message: 'Cannot get MLMD objects from Metadata store.', mode: 'error', }); }); }); it('Failed getArtifactTypes request creates error banner', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); jest.spyOn(mlmdUtils, 'getKfpV2RunContext').mockReturnValue(new Context()); jest.spyOn(mlmdUtils, 'getExecutionsFromContext').mockReturnValue([]); jest.spyOn(mlmdUtils, 'getArtifactsFromContext').mockReturnValue([]); jest.spyOn(mlmdUtils, 'getEventsByExecutions').mockReturnValue([]); jest.spyOn(mlmdUtils, 'getArtifactTypes').mockRejectedValue(new Error('Not connected to MLMD')); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); await waitFor(() => { expect(updateBannerSpy).toHaveBeenLastCalledWith({ additionalInfo: 'Not connected to MLMD', message: 'Cannot get Artifact Types for MLMD.', mode: 'error', }); }); }); it('Allows individual sections to be collapsed and expanded', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); screen.getByText('Filter runs'); screen.getByText('There are no Parameters available on the selected runs.'); screen.getByText('Scalar Metrics'); fireEvent.click(screen.getByText(OVERVIEW_SECTION_NAME)); expect(screen.queryByText('Filter runs')).toBeNull(); fireEvent.click(screen.getByText(OVERVIEW_SECTION_NAME)); screen.getByText('Filter runs'); fireEvent.click(screen.getByText(PARAMS_SECTION_NAME)); expect( screen.queryByText('There are no Parameters available on the selected runs.'), ).toBeNull(); fireEvent.click(screen.getByText(METRICS_SECTION_NAME)); expect(screen.queryByText('Scalar Metrics')).toBeNull(); }); it('All runs are initially selected', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); // Four checkboxes: three runs and one table header let runCheckboxes = screen.queryAllByRole('checkbox', { checked: true }); expect(runCheckboxes.filter(r => r.nodeName === 'INPUT')).toHaveLength(4); // Uncheck all run checkboxes fireEvent.click(runCheckboxes[0]); runCheckboxes = screen.queryAllByRole('checkbox', { checked: true }); expect(runCheckboxes.filter(r => r.nodeName === 'INPUT')).toHaveLength(0); }); it('Parameters and Scalar metrics tab initially enabled with loading then error, and switch tabs', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); expect(screen.queryAllByRole('circularprogress')).toHaveLength(2); await TestUtils.flushPromises(); await waitFor(() => { screen.getByText('There are no Parameters available on the selected runs.'); screen.getByText('An error is preventing the Scalar Metrics from being displayed.'); fireEvent.click(screen.getByText('Confusion Matrix')); screen.getByText('An error is preventing the Confusion Matrix from being displayed.'); expect( screen.queryByText('An error is preventing the Scalar Metrics from being displayed.'), ).toBeNull(); fireEvent.click(screen.getByText('Confusion Matrix')); screen.getByText('An error is preventing the Confusion Matrix from being displayed.'); fireEvent.click(screen.getByText('Scalar Metrics')); screen.getByText('An error is preventing the Scalar Metrics from being displayed.'); expect( screen.queryByText('An error is preventing the Confusion Matrix from being displayed.'), ).toBeNull(); }); }); it('Metrics tabs have no content loaded as artifacts are not present', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); jest.spyOn(mlmdUtils, 'getKfpV2RunContext').mockReturnValue(new Context()); jest.spyOn(mlmdUtils, 'getExecutionsFromContext').mockReturnValue([]); jest.spyOn(mlmdUtils, 'getArtifactsFromContext').mockReturnValue([]); jest.spyOn(mlmdUtils, 'getEventsByExecutions').mockReturnValue([]); jest.spyOn(mlmdUtils, 'getArtifactTypes').mockReturnValue([]); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); await waitFor(() => { screen.getByText('There are no Scalar Metrics artifacts available on the selected runs.'); fireEvent.click(screen.getByText('Confusion Matrix')); screen.getByText('There are no Confusion Matrix artifacts available on the selected runs.'); fireEvent.click(screen.getByText('HTML')); screen.getByText('There are no HTML artifacts available on the selected runs.'); fireEvent.click(screen.getByText('Markdown')); screen.getByText('There are no Markdown artifacts available on the selected runs.'); fireEvent.click(screen.getByText('ROC Curve')); screen.getByText('There are no ROC Curve artifacts available on the selected runs.'); }); }); it('Confusion matrix shown on select, stays after tab change or section collapse', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); const contexts = [ newMockContext(MOCK_RUN_1_ID, 1), newMockContext(MOCK_RUN_2_ID, 200), newMockContext(MOCK_RUN_3_ID, 3), ]; const getContextSpy = jest.spyOn(mlmdUtils, 'getKfpV2RunContext'); getContextSpy.mockImplementation((runID: string) => Promise.resolve(contexts.find(c => c.getName() === runID)), ); // No execution name is provided to ensure that it can be selected by ID. const executions = [[newMockExecution(1)], [newMockExecution(200)], [newMockExecution(3)]]; const getExecutionsSpy = jest.spyOn(mlmdUtils, 'getExecutionsFromContext'); getExecutionsSpy.mockImplementation((context: Context) => Promise.resolve(executions.find(e => e[0].getId() === context.getId())), ); const artifacts = [ newMockArtifact(1), newMockArtifact(200, true, false, 'artifactName'), newMockArtifact(3), ]; const getArtifactsSpy = jest.spyOn(mlmdUtils, 'getArtifactsFromContext'); getArtifactsSpy.mockResolvedValue(artifacts); const events = [newMockEvent(1), newMockEvent(200, 'artifactName'), newMockEvent(3)]; const getEventsSpy = jest.spyOn(mlmdUtils, 'getEventsByExecutions'); getEventsSpy.mockResolvedValue(events); const getArtifactTypesSpy = jest.spyOn(mlmdUtils, 'getArtifactTypes'); getArtifactTypesSpy.mockReturnValue([]); // Simulate all artifacts as type "ClassificationMetrics" (Confusion Matrix or ROC Curve). const filterLinkedArtifactsByTypeSpy = jest.spyOn(mlmdUtils, 'filterLinkedArtifactsByType'); filterLinkedArtifactsByTypeSpy.mockImplementation( (metricsFilter: string, _: ArtifactType[], linkedArtifacts: LinkedArtifact[]) => metricsFilter === 'system.ClassificationMetrics' ? linkedArtifacts : [], ); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); await waitFor(() => expect(filterLinkedArtifactsByTypeSpy).toHaveBeenCalledTimes(15)); expect(screen.queryByText(/Confusion matrix: artifactName/)).toBeNull(); fireEvent.click(screen.getByText('Confusion Matrix')); fireEvent.click(screen.getByText('Choose a first Confusion Matrix artifact')); // Get the second element that has run text: first will be the run list. fireEvent.mouseEnter(screen.queryAllByText(`test run ${MOCK_RUN_2_ID}`)[1]); fireEvent.click(screen.getByText(/artifactName/)); screen.getByText(/Confusion Matrix: artifactName/); screen.getByText(/200/); // Change the tab and return, ensure that the confusion matrix and selected item are present. fireEvent.click(screen.getByText('HTML')); fireEvent.click(screen.getByText('Confusion Matrix')); screen.getByText(/Confusion Matrix: artifactName/); screen.getByText(/200/); // Collapse and expand Metrics, ensure that the confusion matrix and selected item are present. fireEvent.click(screen.getByText('Metrics')); fireEvent.click(screen.getByText('Metrics')); screen.getByText(/Confusion Matrix: artifactName/); screen.getByText(/200/); }); it('Confusion matrix shown on select and removed after run is de-selected', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); const contexts = [ newMockContext(MOCK_RUN_1_ID, 1), newMockContext(MOCK_RUN_2_ID, 200), newMockContext(MOCK_RUN_3_ID, 3), ]; const getContextSpy = jest.spyOn(mlmdUtils, 'getKfpV2RunContext'); getContextSpy.mockImplementation((runID: string) => Promise.resolve(contexts.find(c => c.getName() === runID)), ); // No execution name is provided to ensure that it can be selected by ID. const executions = [[newMockExecution(1)], [newMockExecution(200)], [newMockExecution(3)]]; const getExecutionsSpy = jest.spyOn(mlmdUtils, 'getExecutionsFromContext'); getExecutionsSpy.mockImplementation((context: Context) => Promise.resolve(executions.find(e => e[0].getId() === context.getId())), ); const artifacts = [ newMockArtifact(1), newMockArtifact(200, true, false, 'artifactName'), newMockArtifact(3), ]; const getArtifactsSpy = jest.spyOn(mlmdUtils, 'getArtifactsFromContext'); getArtifactsSpy.mockResolvedValue(artifacts); const events = [newMockEvent(1), newMockEvent(200, 'artifactName'), newMockEvent(3)]; const getEventsSpy = jest.spyOn(mlmdUtils, 'getEventsByExecutions'); getEventsSpy.mockResolvedValue(events); const getArtifactTypesSpy = jest.spyOn(mlmdUtils, 'getArtifactTypes'); getArtifactTypesSpy.mockReturnValue([]); // Simulate all artifacts as type "ClassificationMetrics" (Confusion Matrix or ROC Curve). const filterLinkedArtifactsByTypeSpy = jest.spyOn(mlmdUtils, 'filterLinkedArtifactsByType'); filterLinkedArtifactsByTypeSpy.mockImplementation( (metricsFilter: string, _: ArtifactType[], linkedArtifacts: LinkedArtifact[]) => metricsFilter === 'system.ClassificationMetrics' ? linkedArtifacts : [], ); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); expect(screen.queryByText(/Confusion matrix: artifactName/)).toBeNull(); fireEvent.click(screen.getByText('Confusion Matrix')); fireEvent.click(screen.getByText('Choose a first Confusion Matrix artifact')); // Get the second element that has run text: first will be the run list. fireEvent.mouseEnter(screen.queryAllByText(`test run ${MOCK_RUN_2_ID}`)[1]); fireEvent.click(screen.getByText(/artifactName/)); screen.getByText(/Confusion Matrix: artifactName/); screen.getByText(/200/); // De-selecting the relevant run will remove the confusion matrix display. const runCheckboxes = screen .queryAllByRole('checkbox', { checked: true }) .filter(r => r.nodeName === 'INPUT'); fireEvent.click(runCheckboxes[1]); screen.getByText(/Confusion Matrix: artifactName/); fireEvent.click(runCheckboxes[2]); expect(screen.queryByText(/Confusion Matrix: artifactName/)).toBeNull(); }); it('One ROC Curve shown on select, hidden on run de-select', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); const contexts = [ newMockContext(MOCK_RUN_1_ID, 1), newMockContext(MOCK_RUN_2_ID, 200), newMockContext(MOCK_RUN_3_ID, 3), ]; const getContextSpy = jest.spyOn(mlmdUtils, 'getKfpV2RunContext'); getContextSpy.mockImplementation((runID: string) => Promise.resolve(contexts.find(c => c.getName() === runID)), ); // No execution name is provided to ensure that it can be selected by ID. const executions = [[newMockExecution(1)], [newMockExecution(200)], [newMockExecution(3)]]; const getExecutionsSpy = jest.spyOn(mlmdUtils, 'getExecutionsFromContext'); getExecutionsSpy.mockImplementation((context: Context) => Promise.resolve(executions.find(e => e[0].getId() === context.getId())), ); const artifacts = [ newMockArtifact(1), newMockArtifact(200, false, true, 'artifactName'), newMockArtifact(3), ]; const getArtifactsSpy = jest.spyOn(mlmdUtils, 'getArtifactsFromContext'); getArtifactsSpy.mockReturnValue(Promise.resolve(artifacts)); const events = [newMockEvent(1), newMockEvent(200, 'artifactName'), newMockEvent(3)]; const getEventsSpy = jest.spyOn(mlmdUtils, 'getEventsByExecutions'); getEventsSpy.mockReturnValue(Promise.resolve(events)); const getArtifactTypesSpy = jest.spyOn(mlmdUtils, 'getArtifactTypes'); getArtifactTypesSpy.mockReturnValue([]); // Simulate all artifacts as type "ClassificationMetrics" (Confusion Matrix or ROC Curve). const filterLinkedArtifactsByTypeSpy = jest.spyOn(mlmdUtils, 'filterLinkedArtifactsByType'); filterLinkedArtifactsByTypeSpy.mockImplementation( (metricsFilter: string, _: ArtifactType[], linkedArtifacts: LinkedArtifact[]) => metricsFilter === 'system.ClassificationMetrics' ? linkedArtifacts : [], ); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); fireEvent.click(screen.getByText('ROC Curve')); screen.getByText('ROC Curve: artifactName'); const runCheckboxes = screen .queryAllByRole('checkbox', { checked: true }) .filter(r => r.nodeName === 'INPUT'); fireEvent.click(runCheckboxes[1]); screen.getByText('ROC Curve: artifactName'); fireEvent.click(runCheckboxes[2]); expect(screen.queryByText('ROC Curve: artifactName')).toBeNull(); }); it('Multiple ROC Curves shown on select', async () => { const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); runs = [newMockRun(MOCK_RUN_1_ID), newMockRun(MOCK_RUN_2_ID), newMockRun(MOCK_RUN_3_ID)]; getRunSpy.mockImplementation((id: string) => runs.find(r => r.run_id === id)); const contexts = [ newMockContext(MOCK_RUN_1_ID, 1), newMockContext(MOCK_RUN_2_ID, 200), newMockContext(MOCK_RUN_3_ID, 300), ]; const getContextSpy = jest.spyOn(mlmdUtils, 'getKfpV2RunContext'); getContextSpy.mockImplementation((runID: string) => Promise.resolve(contexts.find(c => c.getName() === runID)), ); // No execution name is provided to ensure that it can be selected by ID. const executions = [[newMockExecution(1)], [newMockExecution(200)], [newMockExecution(300)]]; const getExecutionsSpy = jest.spyOn(mlmdUtils, 'getExecutionsFromContext'); getExecutionsSpy.mockImplementation((context: Context) => Promise.resolve(executions.find(e => e[0].getId() === context.getId())), ); const artifacts = [ newMockArtifact(1), newMockArtifact(200, false, true, 'firstArtifactName'), newMockArtifact(300, false, true, 'secondArtifactName'), ]; const getArtifactsSpy = jest.spyOn(mlmdUtils, 'getArtifactsFromContext'); getArtifactsSpy.mockReturnValue(Promise.resolve(artifacts)); const events = [ newMockEvent(1), newMockEvent(200, 'firstArtifactName'), newMockEvent(300, 'secondArtifactName'), ]; const getEventsSpy = jest.spyOn(mlmdUtils, 'getEventsByExecutions'); getEventsSpy.mockReturnValue(Promise.resolve(events)); const getArtifactTypesSpy = jest.spyOn(mlmdUtils, 'getArtifactTypes'); getArtifactTypesSpy.mockReturnValue([]); // Simulate all artifacts as type "ClassificationMetrics" (Confusion Matrix or ROC Curve). const filterLinkedArtifactsByTypeSpy = jest.spyOn(mlmdUtils, 'filterLinkedArtifactsByType'); filterLinkedArtifactsByTypeSpy.mockImplementation( (metricsFilter: string, _: ArtifactType[], linkedArtifacts: LinkedArtifact[]) => metricsFilter === 'system.ClassificationMetrics' ? linkedArtifacts : [], ); render( <CommonTestWrapper> <CompareV2 {...generateProps()} /> </CommonTestWrapper>, ); await TestUtils.flushPromises(); fireEvent.click(screen.getByText('ROC Curve')); screen.getByText('ROC Curve: multiple artifacts'); screen.getByText('Filter artifacts'); }); });
8
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/ArtifactList.test.tsx
/* * Copyright 2021 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import * as React from 'react'; import { MemoryRouter } from 'react-router-dom'; import { Api } from 'src/mlmd/library'; import { Artifact, ArtifactType, GetArtifactsRequest, GetArtifactsResponse, GetArtifactTypesResponse, Value, } from 'src/third_party/mlmd'; import { ListOperationOptions } from 'src/third_party/mlmd/generated/ml_metadata/proto/metadata_store_pb'; import { RoutePage } from 'src/components/Router'; import TestUtils from 'src/TestUtils'; import { ArtifactList } from 'src/pages/ArtifactList'; import { PageProps } from 'src/pages/Page'; import { testBestPractices } from 'src/TestUtils'; testBestPractices(); describe('ArtifactList', () => { let updateBannerSpy: jest.Mock<{}>; let updateDialogSpy: jest.Mock<{}>; let updateSnackbarSpy: jest.Mock<{}>; let updateToolbarSpy: jest.Mock<{}>; let historyPushSpy: jest.Mock<{}>; let getArtifactsSpy: jest.Mock<{}>; let getArtifactTypesSpy: jest.Mock<{}>; const listOperationOpts = new ListOperationOptions(); listOperationOpts.setMaxResultSize(10); const getArtifactsRequest = new GetArtifactsRequest(); getArtifactsRequest.setOptions(listOperationOpts), beforeEach(() => { updateBannerSpy = jest.fn(); updateDialogSpy = jest.fn(); updateSnackbarSpy = jest.fn(); updateToolbarSpy = jest.fn(); historyPushSpy = jest.fn(); getArtifactsSpy = jest.spyOn(Api.getInstance().metadataStoreService, 'getArtifacts'); getArtifactTypesSpy = jest.spyOn(Api.getInstance().metadataStoreService, 'getArtifactTypes'); getArtifactTypesSpy.mockImplementation(() => { const artifactType = new ArtifactType(); artifactType.setId(6); artifactType.setName('String'); const response = new GetArtifactTypesResponse(); response.setArtifactTypesList([artifactType]); return Promise.resolve(response); }); getArtifactsSpy.mockImplementation(() => { const artifacts = generateNArtifacts(5); const response = new GetArtifactsResponse(); response.setArtifactsList(artifacts); return Promise.resolve(response); }); }); function generateNArtifacts(n: number) { let artifacts: Artifact[] = []; for (let i = 1; i <= n; i++) { const artifact = new Artifact(); const pipelineValue = new Value(); const pipelineName = `pipeline ${i}`; pipelineValue.setStringValue(pipelineName); artifact.getPropertiesMap().set('pipeline_name', pipelineValue); const artifactValue = new Value(); const artifactName = `test artifact ${i}`; artifactValue.setStringValue(artifactName); artifact.getPropertiesMap().set('name', artifactValue); artifact.setName(artifactName); artifacts.push(artifact); } return artifacts; } function generateProps(): PageProps { return TestUtils.generatePageProps( ArtifactList, { pathname: RoutePage.ARTIFACTS } as any, '' as any, historyPushSpy, updateBannerSpy, updateDialogSpy, updateToolbarSpy, updateSnackbarSpy, ); } it('renders one artifact', async () => { getArtifactsSpy.mockImplementation(() => { const artifacts = generateNArtifacts(1); const response = new GetArtifactsResponse(); response.setArtifactsList(artifacts); return Promise.resolve(response); }); render( <MemoryRouter> <ArtifactList {...generateProps()} isGroupView={false} /> </MemoryRouter>, ); await waitFor(() => { expect(getArtifactTypesSpy).toHaveBeenCalledTimes(1); expect(getArtifactsSpy).toHaveBeenCalledTimes(1); }); screen.getByText('pipeline 1'); screen.getByText('test artifact 1'); }); it('displays footer with "10" as default value', async () => { render( <MemoryRouter> <ArtifactList {...generateProps()} isGroupView={false} /> </MemoryRouter>, ); await waitFor(() => { expect(getArtifactTypesSpy).toHaveBeenCalledTimes(1); expect(getArtifactsSpy).toHaveBeenCalledTimes(1); }); screen.getByText('Rows per page:'); screen.getByText('10'); }); it('shows 20th artifact if page size is 20', async () => { render( <MemoryRouter> <ArtifactList {...generateProps()} isGroupView={false} /> </MemoryRouter>, ); await waitFor(() => { expect(getArtifactTypesSpy).toHaveBeenCalledTimes(1); expect(getArtifactsSpy).toHaveBeenCalledTimes(1); }); expect(screen.queryByText('test artifact 20')).toBeNull(); // Can not see the 20th artifact initially getArtifactsSpy.mockImplementation(() => { const artifacts = generateNArtifacts(20); const response = new GetArtifactsResponse(); response.setArtifactsList(artifacts); return Promise.resolve(response); }); const originalRowsPerPage = screen.getByText('10'); fireEvent.click(originalRowsPerPage); const newRowsPerPage = screen.getByText('20'); // Change to render 20 rows per page. fireEvent.click(newRowsPerPage); listOperationOpts.setMaxResultSize(20); getArtifactsRequest.setOptions(listOperationOpts), await waitFor(() => { // API will be called again if "Rows per page" is changed expect(getArtifactTypesSpy).toHaveBeenCalledTimes(1); expect(getArtifactsSpy).toHaveBeenLastCalledWith(getArtifactsRequest); }); screen.getByText('test artifact 20'); // The 20th artifacts appears. }); it('finds no artifact', async () => { getArtifactsSpy.mockClear(); getArtifactsSpy.mockImplementation(() => { const response = new GetArtifactsResponse(); response.setArtifactsList([]); return Promise.resolve(response); }); render( <MemoryRouter> <ArtifactList {...generateProps()} isGroupView={false} /> </MemoryRouter>, ); await TestUtils.flushPromises(); screen.getByText('No artifacts found.'); }); });
9
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/ArtifactList.tsx
/* * Copyright 2019 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as React from 'react'; import { Link } from 'react-router-dom'; import { ListRequest } from 'src/lib/Apis'; import { Api, ArtifactCustomProperties, ArtifactProperties, getArtifactCreationTime, getArtifactTypes, getResourcePropertyViaFallBack, } from 'src/mlmd/library'; import { Artifact, ArtifactType, GetArtifactsRequest } from 'src/third_party/mlmd'; import { ListOperationOptions } from 'src/third_party/mlmd/generated/ml_metadata/proto/metadata_store_pb'; import { classes } from 'typestyle'; import { ArtifactLink } from 'src/components/ArtifactLink'; import CustomTable, { Column, CustomRendererProps, ExpandState, Row, } from 'src/components/CustomTable'; import { RoutePageFactory } from 'src/components/Router'; import { ToolbarProps } from 'src/components/Toolbar'; import { commonCss, padding } from 'src/Css'; import { CollapsedAndExpandedRows, getExpandedRow, getStringEnumKey, groupRows, rowFilterFn, serviceErrorToString, } from 'src/lib/Utils'; import { Page } from 'src/pages/Page'; interface ArtifactListProps { isGroupView: boolean; } interface ArtifactListState { artifacts: Artifact[]; rows: Row[]; expandedRows: Map<number, Row[]>; columns: Column[]; } const ARTIFACT_PROPERTY_REPOS = [ArtifactProperties, ArtifactCustomProperties]; const PIPELINE_WORKSPACE_FIELDS = ['RUN_ID', 'PIPELINE_NAME', 'WORKSPACE']; const NAME_FIELDS = [ getStringEnumKey(ArtifactCustomProperties, ArtifactCustomProperties.NAME), getStringEnumKey(ArtifactCustomProperties, ArtifactCustomProperties.DISPLAY_NAME), ]; export class ArtifactList extends Page<ArtifactListProps, ArtifactListState> { private tableRef = React.createRef<CustomTable>(); private api = Api.getInstance(); private artifactTypesMap: Map<number, ArtifactType>; constructor(props: any) { super(props); this.state = { artifacts: [], columns: [ { customRenderer: this.nameCustomRenderer, flex: 2, label: 'Pipeline/Workspace', }, { customRenderer: this.nameCustomRenderer, flex: 1, label: 'Name', }, { label: 'ID', flex: 1 }, { label: 'Type', flex: 2 }, { label: 'URI', flex: 2, customRenderer: this.uriCustomRenderer }, { label: 'Created at', flex: 1 }, ], expandedRows: new Map(), rows: [], }; this.reload = this.reload.bind(this); this.toggleRowExpand = this.toggleRowExpand.bind(this); this.getExpandedArtifactsRow = this.getExpandedArtifactsRow.bind(this); } public getInitialToolbarState(): ToolbarProps { return { actions: {}, breadcrumbs: [], pageTitle: 'Artifacts', }; } public render(): JSX.Element { const { rows, columns } = this.state; return ( <div className={classes(commonCss.page, padding(20, 'lr'))}> <CustomTable ref={this.tableRef} columns={columns} rows={rows} disablePaging={this.props.isGroupView} disableSelection={true} reload={this.reload} initialSortColumn='pipelineName' initialSortOrder='asc' getExpandComponent={this.props.isGroupView ? this.getExpandedArtifactsRow : undefined} toggleExpansion={this.props.isGroupView ? this.toggleRowExpand : undefined} emptyMessage='No artifacts found.' /> </div> ); } public async refresh(): Promise<void> { if (this.tableRef.current) { await this.tableRef.current.reload(); } } private async reload(request: ListRequest): Promise<string> { const listOperationOpts = new ListOperationOptions(); if (request.pageSize) { listOperationOpts.setMaxResultSize(request.pageSize); } if (request.pageToken) { listOperationOpts.setNextPageToken(request.pageToken); } // TODO(jlyaoyuli): Add filter functionality for "entire" artifact list. // TODO: Consider making an Api method for returning and caching types if (!this.artifactTypesMap || !this.artifactTypesMap.size) { this.artifactTypesMap = await getArtifactTypes( this.api.metadataStoreService, this.showPageError.bind(this), ); } const artifacts = this.props.isGroupView ? await this.getArtifacts() : await this.getArtifacts(listOperationOpts); this.clearBanner(); let flattenedRows = await this.getFlattenedRowsFromArtifacts(request, artifacts); let groupedRows = await this.getGroupedRowsFromArtifacts(request, artifacts); // TODO(jlyaoyuli): Consider to support grouped rows with pagination. this.setState({ artifacts, expandedRows: this.props.isGroupView ? groupedRows?.expandedRows : new Map(), rows: this.props.isGroupView ? groupedRows?.collapsedRows : flattenedRows, }); return listOperationOpts.getNextPageToken(); } private nameCustomRenderer: React.FC<CustomRendererProps<string>> = ( props: CustomRendererProps<string>, ) => { return ( <Link onClick={e => e.stopPropagation()} className={commonCss.link} to={RoutePageFactory.artifactDetails(Number(props.id))} > {props.value} </Link> ); }; private uriCustomRenderer: React.FC<CustomRendererProps<string>> = ({ value }) => ( <ArtifactLink artifactUri={value} /> ); private async getArtifacts(listOperationOpts?: ListOperationOptions): Promise<Artifact[]> { try { const response = await this.api.metadataStoreService.getArtifacts( new GetArtifactsRequest().setOptions(listOperationOpts), ); listOperationOpts?.setNextPageToken(response.getNextPageToken()); return response.getArtifactsList(); } catch (err) { // Code === 5 means no record found in backend. This is a temporary workaround. // TODO: remove err.code !== 5 check when backend is fixed. if (err.code !== 5) { this.showPageError(serviceErrorToString(err)); } } return []; } private async getFlattenedRowsFromArtifacts( request: ListRequest, artifacts: Artifact[], ): Promise<Row[]> { try { const artifactsWithCreationTimes = await Promise.all( artifacts.map(async artifact => { const artifactId = artifact.getId(); if (!artifactId) { return { artifact }; } return { artifact, creationTime: await getArtifactCreationTime(artifactId, this.api.metadataStoreService), }; }), ); const flattenedRows: Row[] = artifactsWithCreationTimes .map(({ artifact, creationTime }) => { const typeId = artifact.getTypeId(); const artifactType = this.artifactTypesMap!.get(typeId); const type = artifactType ? artifactType.getName() : artifact.getTypeId(); return { id: `${artifact.getId()}`, otherFields: [ getResourcePropertyViaFallBack( artifact, ARTIFACT_PROPERTY_REPOS, PIPELINE_WORKSPACE_FIELDS, ) || '[unknown]', getResourcePropertyViaFallBack(artifact, ARTIFACT_PROPERTY_REPOS, NAME_FIELDS) || '[unknown]', artifact.getId(), type, artifact.getUri(), creationTime || '', ], } as Row; }) .filter(rowFilterFn(request)); // TODO(jlyaoyuli): Add sort functionality for entire artifact list. return flattenedRows; } catch (err) { if (err.message) { this.showPageError(err.message, err); } else { this.showPageError('Unknown error', err); } } return []; } /** * Temporary solution to apply sorting, filtering, and pagination to the * local list of artifacts until server-side handling is available * TODO: Replace once https://github.com/kubeflow/metadata/issues/73 is done. * @param request * @param artifacts */ private async getGroupedRowsFromArtifacts( request: ListRequest, artifacts: Artifact[], ): Promise<CollapsedAndExpandedRows> { const flattenedRows = await this.getFlattenedRowsFromArtifacts(request, artifacts); return groupRows(flattenedRows); } /** * Toggles the expansion state of a row * @param index */ private toggleRowExpand(index: number): void { const { rows } = this.state; if (!rows[index]) { return; } rows[index].expandState = rows[index].expandState === ExpandState.EXPANDED ? ExpandState.COLLAPSED : ExpandState.EXPANDED; this.setState({ rows }); } private getExpandedArtifactsRow(index: number): React.ReactNode { return getExpandedRow(this.state.expandedRows, this.state.columns)(index); } } export default ArtifactList;
10
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/RunListsRouter.test.tsx
/* * Copyright 2020 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { render, screen } from '@testing-library/react'; import produce from 'immer'; import RunListsRouter, { RunListsRouterProps } from './RunListsRouter'; import React from 'react'; import { RouteParams } from 'src/components/Router'; import { V2beta1Run, V2beta1RunStorageState } from 'src/apisv2beta1/run'; import { ApiExperiment } from 'src/apis/experiment'; import { Apis } from 'src/lib/Apis'; import * as Utils from 'src/lib/Utils'; import { BrowserRouter } from 'react-router-dom'; import { PredicateOp } from 'src/apis/filter'; describe('RunListsRouter', () => { let historyPushSpy: any; let runStorageState = V2beta1RunStorageState.AVAILABLE; const onSelectionChangeMock = jest.fn(); const listRunsSpy = jest.spyOn(Apis.runServiceApiV2, 'listRuns'); const getRunSpy = jest.spyOn(Apis.runServiceApiV2, 'getRun'); const getPipelineSpy = jest.spyOn(Apis.pipelineServiceApi, 'getPipeline'); const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment'); const formatDateStringSpy = jest.spyOn(Utils, 'formatDateString'); const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => null); const MOCK_EXPERIMENT = newMockExperiment(); const archiveRunDisplayName = 'run with id: achiverunid'; const activeRunDisplayName = 'run with id: activerunid'; function newMockExperiment(): ApiExperiment { return { description: 'mock experiment description', id: 'some-mock-experiment-id', name: 'some mock experiment name', }; } function generateProps(): RunListsRouterProps { const runListsRouterProps: RunListsRouterProps = { onTabSwitch: jest.fn((newTab: number) => { // this.refresh(); if (newTab === 1) { runStorageState = V2beta1RunStorageState.ARCHIVED; } else { runStorageState = V2beta1RunStorageState.AVAILABLE; } }), hideExperimentColumn: true, history: { push: historyPushSpy } as any, location: '' as any, match: { params: { [RouteParams.experimentId]: MOCK_EXPERIMENT.id } } as any, onSelectionChange: onSelectionChangeMock, selectedIds: [], storageState: runStorageState, refreshCount: 0, noFilterBox: false, disablePaging: false, disableSorting: true, disableSelection: false, hideMetricMetadata: false, onError: consoleErrorSpy, }; return runListsRouterProps; } beforeEach(() => { getRunSpy.mockImplementation(id => Promise.resolve( produce({} as Partial<V2beta1Run>, draft => { draft = draft || {}; draft.run_id = id; draft.display_name = 'run with id: ' + id; }), ), ); listRunsSpy.mockImplementation((pageToken, pageSize, sortBy, keyType, keyId, filter) => { let filterForArchive = JSON.parse(decodeURIComponent('{"predicates": []}')); filterForArchive = encodeURIComponent( JSON.stringify({ predicates: [ { key: 'storage_state', op: PredicateOp.EQUALS, string_value: V2beta1RunStorageState.ARCHIVED.toString(), }, ], }), ); if (filter === filterForArchive) { return Promise.resolve({ runs: [ { run_id: 'achiverunid', display_name: archiveRunDisplayName, }, ], }); } return Promise.resolve({ runs: [ { run_id: 'activerunid', display_name: activeRunDisplayName, }, ], }); }); getPipelineSpy.mockImplementation(() => ({ name: 'some pipeline' })); getExperimentSpy.mockImplementation(() => ({ name: 'some experiment' })); formatDateStringSpy.mockImplementation((date?: Date) => { return date ? '1/2/2019, 12:34:56 PM' : '-'; }); }); afterEach(() => { jest.resetAllMocks(); }); it('shows Active and Archive tabs', () => { render( <BrowserRouter> <RunListsRouter {...generateProps()} /> </BrowserRouter>, ); screen.getByText('Active'); screen.getByText('Archived'); }); });
11
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/Status.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as React from 'react'; import ErrorIcon from '@material-ui/icons/Error'; import PendingIcon from '@material-ui/icons/Schedule'; import RunningIcon from '../icons/statusRunning'; import SkippedIcon from '@material-ui/icons/SkipNext'; import SuccessIcon from '@material-ui/icons/CheckCircle'; import BlockIcon from '@material-ui/icons/Block'; import CachedIcon from '../icons/statusCached'; import TerminatedIcon from '../icons/statusTerminated'; import Tooltip from '@material-ui/core/Tooltip'; import UnknownIcon from '@material-ui/icons/Help'; import { color } from '../Css'; import { logger, formatDateString } from '../lib/Utils'; import { NodePhase, checkIfTerminated } from '../lib/StatusUtils'; import { Execution } from 'src/third_party/mlmd/generated/ml_metadata/proto/metadata_store_pb'; export function statusToIcon( status?: NodePhase, startDate?: Date | string, endDate?: Date | string, nodeMessage?: string, mlmdState?: Execution.State, ): JSX.Element { status = checkIfTerminated(status, nodeMessage); // tslint:disable-next-line:variable-name let IconComponent: any = UnknownIcon; let iconColor = color.inactive; let title = 'Unknown status'; switch (status) { case NodePhase.ERROR: IconComponent = ErrorIcon; iconColor = color.errorText; title = 'Error while running this resource'; break; case NodePhase.FAILED: IconComponent = ErrorIcon; iconColor = color.errorText; title = 'Resource failed to execute'; break; case NodePhase.PENDING: IconComponent = PendingIcon; iconColor = color.weak; title = 'Pending execution'; break; case NodePhase.RUNNING: IconComponent = RunningIcon; iconColor = color.blue; title = 'Running'; break; case NodePhase.TERMINATING: IconComponent = RunningIcon; iconColor = color.blue; title = 'Run is terminating'; break; case NodePhase.SKIPPED: IconComponent = SkippedIcon; title = 'Execution has been skipped for this resource'; break; case NodePhase.SUCCEEDED: IconComponent = SuccessIcon; iconColor = color.success; title = 'Executed successfully'; break; case NodePhase.CACHED: // This is not argo native, only applies to node. IconComponent = CachedIcon; iconColor = color.success; title = 'Execution was skipped and outputs were taken from cache'; break; case NodePhase.TERMINATED: IconComponent = TerminatedIcon; iconColor = color.terminated; title = 'Run was manually terminated'; break; case NodePhase.OMITTED: IconComponent = BlockIcon; title = 'Run was omitted because the previous step failed.'; break; case NodePhase.UNKNOWN: break; default: logger.verbose('Unknown node phase:', status); } if (mlmdState === Execution.State.CACHED) { IconComponent = CachedIcon; iconColor = color.success; title = 'Execution was skipped and outputs were taken from cache'; } return ( <Tooltip title={ <div> <div>{title}</div> {/* These dates may actually be strings, not a Dates due to a bug in swagger's handling of dates */} {startDate && <div>Start: {formatDateString(startDate)}</div>} {endDate && <div>End: {formatDateString(endDate)}</div>} </div> } > <div> <IconComponent data-testid='node-status-sign' style={{ color: iconColor, height: 18, width: 18 }} /> </div> </Tooltip> ); }
12
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/RecurringRunsManager.test.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as React from 'react'; import TestUtils from 'src/TestUtils'; import { ListRequest, Apis } from 'src/lib/Apis'; import { shallow, ReactWrapper, ShallowWrapper } from 'enzyme'; import RecurringRunsManager, { RecurringRunListProps } from './RecurringRunsManager'; import { V2beta1RecurringRun, V2beta1RecurringRunStatus } from 'src/apisv2beta1/recurringrun'; describe('RecurringRunsManager', () => { class TestRecurringRunsManager extends RecurringRunsManager { public async _loadRuns(request: ListRequest): Promise<string> { return super._loadRuns(request); } public _setEnabledState(id: string, enabled: boolean): Promise<void> { return super._setEnabledState(id, enabled); } } let tree: ReactWrapper | ShallowWrapper; const updateDialogSpy = jest.fn(); const updateSnackbarSpy = jest.fn(); const listRecurringRunsSpy = jest.spyOn(Apis.recurringRunServiceApi, 'listRecurringRuns'); const enableRecurringRunSpy = jest.spyOn(Apis.recurringRunServiceApi, 'enableRecurringRun'); const disableRecurringRunSpy = jest.spyOn(Apis.recurringRunServiceApi, 'disableRecurringRun'); jest.spyOn(console, 'error').mockImplementation(); const RECURRINGRUNS: V2beta1RecurringRun[] = [ { created_at: new Date(2018, 10, 9, 8, 7, 6), display_name: 'test recurring run name', recurring_run_id: 'recurringrun1', status: V2beta1RecurringRunStatus.ENABLED, }, { created_at: new Date(2018, 10, 9, 8, 7, 6), display_name: 'test recurring run name2', recurring_run_id: 'recurringrun2', status: V2beta1RecurringRunStatus.DISABLED, }, { created_at: new Date(2018, 10, 9, 8, 7, 6), display_name: 'test recurring run name3', recurring_run_id: 'recurringrun3', status: V2beta1RecurringRunStatus.STATUSUNSPECIFIED, }, ]; function generateProps(): RecurringRunListProps { return { experimentId: 'test-experiment', history: {} as any, location: '' as any, match: {} as any, updateDialog: updateDialogSpy, updateSnackbar: updateSnackbarSpy, }; } beforeEach(() => { listRecurringRunsSpy.mockReset(); listRecurringRunsSpy.mockImplementation(() => ({ recurringRuns: RECURRINGRUNS })); enableRecurringRunSpy.mockReset(); disableRecurringRunSpy.mockReset(); updateDialogSpy.mockReset(); updateSnackbarSpy.mockReset(); }); afterEach(() => tree.unmount()); it('calls API to load recurring runs', async () => { tree = shallow(<TestRecurringRunsManager {...generateProps()} />); await (tree.instance() as TestRecurringRunsManager)._loadRuns({}); expect(listRecurringRunsSpy).toHaveBeenCalledTimes(1); expect(listRecurringRunsSpy).toHaveBeenLastCalledWith( undefined, undefined, undefined, undefined, undefined, 'test-experiment', ); expect(tree.state('runs')).toEqual(RECURRINGRUNS); expect(tree).toMatchSnapshot(); }); it('shows error dialog if listing fails', async () => { TestUtils.makeErrorResponseOnce(listRecurringRunsSpy, 'woops!'); jest.spyOn(console, 'error').mockImplementation(); tree = shallow(<TestRecurringRunsManager {...generateProps()} />); await (tree.instance() as TestRecurringRunsManager)._loadRuns({}); expect(listRecurringRunsSpy).toHaveBeenCalledTimes(1); expect(updateDialogSpy).toHaveBeenLastCalledWith( expect.objectContaining({ content: 'List recurring run configs request failed with:\nwoops!', title: 'Error retrieving recurring run configs', }), ); expect(tree.state('runs')).toEqual([]); }); it('calls API to enable run', async () => { tree = shallow(<TestRecurringRunsManager {...generateProps()} />); await (tree.instance() as TestRecurringRunsManager)._setEnabledState('test-run', true); expect(enableRecurringRunSpy).toHaveBeenCalledTimes(1); expect(enableRecurringRunSpy).toHaveBeenLastCalledWith('test-run'); }); it('calls API to disable run', async () => { tree = shallow(<TestRecurringRunsManager {...generateProps()} />); await (tree.instance() as TestRecurringRunsManager)._setEnabledState('test-run', false); expect(disableRecurringRunSpy).toHaveBeenCalledTimes(1); expect(disableRecurringRunSpy).toHaveBeenLastCalledWith('test-run'); }); it('shows error if enable API call fails', async () => { tree = shallow(<TestRecurringRunsManager {...generateProps()} />); TestUtils.makeErrorResponseOnce(enableRecurringRunSpy, 'cannot enable'); await (tree.instance() as TestRecurringRunsManager)._setEnabledState('test-run', true); expect(updateDialogSpy).toHaveBeenCalledTimes(1); expect(updateDialogSpy).toHaveBeenLastCalledWith( expect.objectContaining({ content: 'Error changing enabled state of recurring run:\ncannot enable', title: 'Error', }), ); }); it('shows error if disable API call fails', async () => { tree = shallow(<TestRecurringRunsManager {...generateProps()} />); TestUtils.makeErrorResponseOnce(disableRecurringRunSpy, 'cannot disable'); await (tree.instance() as TestRecurringRunsManager)._setEnabledState('test-run', false); expect(updateDialogSpy).toHaveBeenCalledTimes(1); expect(updateDialogSpy).toHaveBeenLastCalledWith( expect.objectContaining({ content: 'Error changing enabled state of recurring run:\ncannot disable', title: 'Error', }), ); }); it('renders run name as link to its details page', () => { tree = TestUtils.mountWithRouter(<RecurringRunsManager {...generateProps()} />); expect( (tree.instance() as RecurringRunsManager)._nameCustomRenderer({ id: 'run-id', value: 'test-run', }), ).toMatchSnapshot(); }); it('renders a disable button if the run is enabled, clicking the button calls disable API', async () => { tree = TestUtils.mountWithRouter(<RecurringRunsManager {...generateProps()} />); await TestUtils.flushPromises(); tree.update(); const enableBtn = tree.find('.tableRow Button').at(0); expect(enableBtn).toMatchSnapshot(); enableBtn.simulate('click'); await TestUtils.flushPromises(); expect(disableRecurringRunSpy).toHaveBeenCalledTimes(1); expect(disableRecurringRunSpy).toHaveBeenLastCalledWith(RECURRINGRUNS[0].recurring_run_id); }); it('renders an enable button if the run is disabled, clicking the button calls enable API', async () => { tree = TestUtils.mountWithRouter(<RecurringRunsManager {...generateProps()} />); await TestUtils.flushPromises(); tree.update(); const enableBtn = tree.find('.tableRow Button').at(1); expect(enableBtn).toMatchSnapshot(); enableBtn.simulate('click'); await TestUtils.flushPromises(); expect(enableRecurringRunSpy).toHaveBeenCalledTimes(1); expect(enableRecurringRunSpy).toHaveBeenLastCalledWith(RECURRINGRUNS[1].recurring_run_id); }); it("renders an enable button if the run's enabled field is undefined, clicking the button calls enable API", async () => { tree = TestUtils.mountWithRouter(<RecurringRunsManager {...generateProps()} />); await TestUtils.flushPromises(); tree.update(); const enableBtn = tree.find('.tableRow Button').at(2); expect(enableBtn).toMatchSnapshot(); enableBtn.simulate('click'); await TestUtils.flushPromises(); expect(enableRecurringRunSpy).toHaveBeenCalledTimes(1); expect(enableRecurringRunSpy).toHaveBeenLastCalledWith(RECURRINGRUNS[2].recurring_run_id); }); it('reloads the list of runs after enable/disabling', async () => { tree = TestUtils.mountWithRouter(<RecurringRunsManager {...generateProps()} />); await TestUtils.flushPromises(); tree.update(); const enableBtn = tree.find('.tableRow Button').at(0); expect(enableBtn).toMatchSnapshot(); expect(listRecurringRunsSpy).toHaveBeenCalledTimes(1); enableBtn.simulate('click'); await TestUtils.flushPromises(); expect(listRecurringRunsSpy).toHaveBeenCalledTimes(2); }); });
13
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/PipelineDetailsV1.test.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as JsYaml from 'js-yaml'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { graphlib } from 'dagre'; import * as React from 'react'; import { testBestPractices } from 'src/TestUtils'; import PipelineDetailsV1, { PipelineDetailsV1Props } from './PipelineDetailsV1'; import { color } from 'src/Css'; import { Constants } from 'src/lib/Constants'; import { SelectedNodeInfo } from 'src/lib/StaticGraphParser'; testBestPractices(); describe('PipelineDetailsV1', () => { const testPipeline = { created_at: new Date(2018, 8, 5, 4, 3, 2), description: '', id: 'test-pipeline-id', name: 'test pipeline', parameters: [{ name: 'param1', value: 'value1' }], default_version: { id: 'test-pipeline-version-id', description: '', name: 'test-pipeline-version', }, }; const testPipelineVersion = { id: 'test-pipeline-version-id-2', name: 'test-pipeline-version', description: '', }; const pipelineSpecTemplate = ` apiVersion: argoproj.io/v1alpha1 kind: Workflow metadata: generateName: entry-point-test- spec: arguments: parameters: [] entrypoint: entry-point-test templates: - dag: tasks: - name: recurse-1 template: recurse-1 - name: leaf-1 template: leaf-1 name: start - dag: tasks: - name: start template: start - name: recurse-2 template: recurse-2 name: recurse-1 - dag: tasks: - name: start template: start - name: leaf-2 template: leaf-2 - name: recurse-3 template: recurse-3 name: recurse-2 - dag: tasks: - name: start template: start - name: recurse-1 template: recurse-1 - name: recurse-2 template: recurse-2 name: recurse-3 - dag: tasks: - name: start template: start name: entry-point-test - container: name: leaf-1 - container: name: leaf-2 `; function generateProps( graph: graphlib.Graph | null, reducedGraph: graphlib.Graph | null, description_version: string = '', description_pipeline: string = '', description_default_version: string = '', custom_version: boolean = true, ): PipelineDetailsV1Props { testPipeline.description = description_pipeline; testPipeline.default_version.description = description_default_version; testPipelineVersion.description = description_version; const props: PipelineDetailsV1Props = { pipeline: testPipeline, selectedVersion: custom_version ? testPipelineVersion : testPipeline.default_version, versions: [testPipelineVersion], graph: graph, reducedGraph: reducedGraph, templateString: JSON.stringify({ template: JsYaml.safeDump(pipelineSpecTemplate) }), updateBanner: bannerProps => {}, handleVersionSelected: async versionId => {}, }; return props; } beforeEach(() => {}); it('shows correct versions in version selector', async () => { render(<PipelineDetailsV1 {...generateProps(new graphlib.Graph(), new graphlib.Graph())} />); expect(screen.getByText('test-pipeline-version')); expect(screen.getByTestId('version_selector').childElementCount).toEqual(1); }); it('shows description for pipeline version and pipeline with custom version', async () => { render( <PipelineDetailsV1 {...generateProps( new graphlib.Graph(), new graphlib.Graph(), 'test-pipeline-version-desc', 'test-pipeline-desc', 'test-default-version-desc', )} />, ); expect(screen.getByText('test-pipeline-desc')); expect(screen.getByText('test-pipeline-version-desc')); expect(screen.queryByText('Default Version Description')).toBeNull(); expect(screen.queryByText('test-default-version-desc')).toBeNull(); }); it('shows description for pipeline version and pipeline with default version', async () => { render( <PipelineDetailsV1 {...generateProps( new graphlib.Graph(), new graphlib.Graph(), 'test-pipeline-version-desc', 'test-pipeline-desc', 'test-default-version-desc', false, )} />, ); expect(screen.getByText('test-pipeline-desc')); expect(screen.getByText('test-default-version-desc')); expect(screen.queryByText('test-pipeline-version-desc')).toBeNull(); expect(screen.getByText('Default Version Description')); }); it('shows pipeline description even when not set with default version', async () => { render( <PipelineDetailsV1 {...generateProps( new graphlib.Graph(), new graphlib.Graph(), 'test-pipeline-version-desc', '', 'test-default-version-desc', false, )} />, ); expect(screen.getByText('test-default-version-desc')); expect(screen.getByText('Pipeline Description')); expect(screen.getByText('empty pipeline description')); }); it('shows pipeline description even when not set with custom version', async () => { render( <PipelineDetailsV1 {...generateProps( new graphlib.Graph(), new graphlib.Graph(), 'test-pipeline-version-desc', '', 'test-default-version-desc', true, )} />, ); expect(screen.getByText('test-pipeline-version-desc')); expect(screen.getByText('Pipeline Description')); expect(screen.getByText('Version Description')); expect(screen.queryByText(/Default Version Description/)).toBeNull(); expect(screen.getByText('empty pipeline description')); }); it('hides version description when not set with default version', async () => { render( <PipelineDetailsV1 {...generateProps( new graphlib.Graph(), new graphlib.Graph(), 'test-pipeline-version-desc', 'test-pipeline-desc', '', false, )} />, ); expect(screen.getByText('test-pipeline-desc')); expect(screen.queryByText(/Version Description/)).toBeNull(); }); it('hides version description when not set with custom version', async () => { render( <PipelineDetailsV1 {...generateProps( new graphlib.Graph(), new graphlib.Graph(), '', 'test-pipeline-desc', 'test-default-version-desc', true, )} />, ); expect(screen.getByText('test-pipeline-desc')); expect(screen.queryByText(/Version Description/)).toBeNull(); }); it('hides description for pipeline version when not set with custom version', async () => { render(<PipelineDetailsV1 {...generateProps(new graphlib.Graph(), new graphlib.Graph())} />); expect(screen.getByText('Pipeline Description')); expect(screen.queryByText(/Version Description/)).toBeNull(); }); it('hides description for pipeline version with default version', async () => { render( <PipelineDetailsV1 {...generateProps(new graphlib.Graph(), new graphlib.Graph(), '', '', '', false)} />, ); expect(screen.getByText('Pipeline Description')); expect(screen.queryByText(/Version Description/)).toBeNull(); }); it('shows clicked node info in the side panel if it is in the graph', async () => { // Arrange const graph = createSimpleGraph(); const reducedGraph = createSimpleGraph(); // Act render(<PipelineDetailsV1 {...generateProps(graph, reducedGraph)} />); fireEvent( screen.getByText('start'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); // Assert screen.getByText('/start'); }); it('closes side panel when close button is clicked', async () => { // Arrange const graph = createSimpleGraph(); const reducedGraph = createSimpleGraph(); // Act render(<PipelineDetailsV1 {...generateProps(graph, reducedGraph)} />); fireEvent( screen.getByText('start'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); fireEvent( screen.getByLabelText('close'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); // Assert expect(screen.queryByText('/start')).toBeNull(); }); it('shows pipeline source code when config tab is clicked', async () => { render(<PipelineDetailsV1 {...generateProps(new graphlib.Graph(), new graphlib.Graph())} />); fireEvent( screen.getByText('YAML'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); screen.getByTestId('spec-yaml'); }); it('shows the summary card when clicking Show button', async () => { const graph = createSimpleGraph(); const reducedGraph = createSimpleGraph(); render(<PipelineDetailsV1 {...generateProps(graph, reducedGraph)} />); screen.getByText('Hide'); fireEvent( screen.getByText('Hide'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); fireEvent( screen.getByText('Show summary'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); screen.getByText('Hide'); }); it('shows empty pipeline details with empty graph', async () => { render(<PipelineDetailsV1 {...generateProps(null, null)} />); screen.getByText('No graph to show'); }); }); function createSimpleGraph() { const graph = new graphlib.Graph(); graph.setGraph({ width: 1000, height: 700 }); graph.setNode('/start', { bgColor: undefined, height: Constants.NODE_HEIGHT, info: new SelectedNodeInfo(), label: 'start', width: Constants.NODE_WIDTH, }); return graph; }
14
0
kubeflow_public_repos/pipelines/frontend/src
kubeflow_public_repos/pipelines/frontend/src/pages/ArchivedRuns.test.tsx
/* * Copyright 2018 The Kubeflow Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as React from 'react'; import { ArchivedRuns } from './ArchivedRuns'; import TestUtils from 'src/TestUtils'; import { PageProps } from './Page'; import { V2beta1RunStorageState } from 'src/apisv2beta1/run'; import { ShallowWrapper, shallow } from 'enzyme'; import { ButtonKeys } from 'src/lib/Buttons'; import { Apis } from 'src/lib/Apis'; describe('ArchivedRuns', () => { const updateBannerSpy = jest.fn(); const updateToolbarSpy = jest.fn(); const historyPushSpy = jest.fn(); const deleteRunSpy = jest.spyOn(Apis.runServiceApi, 'deleteRun'); const updateDialogSpy = jest.fn(); const updateSnackbarSpy = jest.fn(); let tree: ShallowWrapper; function generateProps(): PageProps { return TestUtils.generatePageProps( ArchivedRuns, {} as any, {} as any, historyPushSpy, updateBannerSpy, updateDialogSpy, updateToolbarSpy, updateSnackbarSpy, ); } beforeEach(() => { updateBannerSpy.mockClear(); updateToolbarSpy.mockClear(); historyPushSpy.mockClear(); deleteRunSpy.mockClear(); updateDialogSpy.mockClear(); updateSnackbarSpy.mockClear(); }); afterEach(() => tree.unmount()); it('renders archived runs', () => { tree = shallow(<ArchivedRuns {...generateProps()} />); expect(tree).toMatchSnapshot(); }); it('lists archived runs in namespace', () => { tree = shallow(<ArchivedRuns {...generateProps()} namespace='test-ns' />); expect(tree.find('RunList').prop('namespaceMask')).toEqual('test-ns'); }); it('removes error banner on unmount', () => { tree = shallow(<ArchivedRuns {...generateProps()} />); tree.unmount(); expect(updateBannerSpy).toHaveBeenCalledWith({}); }); it('enables restore and delete button when at least one run is selected', () => { tree = shallow(<ArchivedRuns {...generateProps()} />); TestUtils.flushPromises(); tree.update(); expect(TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.RESTORE).disabled).toBeTruthy(); expect( TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.DELETE_RUN).disabled, ).toBeTruthy(); tree.find('RunList').simulate('selectionChange', ['run1']); expect(TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.RESTORE).disabled).toBeFalsy(); expect( TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.DELETE_RUN).disabled, ).toBeFalsy(); tree.find('RunList').simulate('selectionChange', ['run1', 'run2']); expect(TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.RESTORE).disabled).toBeFalsy(); expect( TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.DELETE_RUN).disabled, ).toBeFalsy(); tree.find('RunList').simulate('selectionChange', []); expect(TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.RESTORE).disabled).toBeTruthy(); expect( TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.DELETE_RUN).disabled, ).toBeTruthy(); }); it('refreshes the run list when refresh button is clicked', async () => { tree = shallow(<ArchivedRuns {...generateProps()} />); const spy = jest.fn(); (tree.instance() as any)._runlistRef = { current: { refresh: spy } }; await TestUtils.getToolbarButton(updateToolbarSpy, ButtonKeys.REFRESH).action(); expect(spy).toHaveBeenLastCalledWith(); }); it('shows a list of available runs', () => { tree = shallow(<ArchivedRuns {...generateProps()} />); expect(tree.find('RunList').prop('storageState')).toBe( V2beta1RunStorageState.ARCHIVED.toString(), ); }); it('cancells deletion when Cancel is clicked', async () => { tree = shallow(<ArchivedRuns {...generateProps()} />); // Click delete button to delete selected ids. const deleteBtn = (tree.instance() as ArchivedRuns).getInitialToolbarState().actions[ ButtonKeys.DELETE_RUN ]; await deleteBtn!.action(); // Dialog pops up to confirm the deletion. expect(updateDialogSpy).toHaveBeenCalledTimes(1); expect(updateDialogSpy).toHaveBeenLastCalledWith( expect.objectContaining({ content: 'Do you want to delete the selected runs? This action cannot be undone.', }), ); // Cancel deletion. const call = updateDialogSpy.mock.calls[0][0]; const cancelBtn = call.buttons.find((b: any) => b.text === 'Cancel'); await cancelBtn.onClick(); expect(deleteRunSpy).not.toHaveBeenCalled(); }); it('deletes selected ids when Confirm is clicked', async () => { tree = shallow(<ArchivedRuns {...generateProps()} />); tree.setState({ selectedIds: ['id1', 'id2', 'id3'] }); // Mock the behavior where the deletion of id1 fails, the deletion of id2 and id3 succeed. TestUtils.makeErrorResponseOnce(deleteRunSpy, 'woops'); deleteRunSpy.mockImplementation(() => Promise.resolve({})); // Click delete button to delete selected ids. const deleteBtn = (tree.instance() as ArchivedRuns).getInitialToolbarState().actions[ ButtonKeys.DELETE_RUN ]; await deleteBtn!.action(); // Dialog pops up to confirm the deletion. expect(updateDialogSpy).toHaveBeenCalledTimes(1); expect(updateDialogSpy).toHaveBeenLastCalledWith( expect.objectContaining({ content: 'Do you want to delete the selected runs? This action cannot be undone.', }), ); // Confirm. const call = updateDialogSpy.mock.calls[0][0]; const confirmBtn = call.buttons.find((b: any) => b.text === 'Delete'); await confirmBtn.onClick(); await deleteRunSpy; await TestUtils.flushPromises(); tree.update(); expect(deleteRunSpy).toHaveBeenCalledTimes(3); expect(deleteRunSpy).toHaveBeenCalledWith('id1'); expect(deleteRunSpy).toHaveBeenCalledWith('id2'); expect(deleteRunSpy).toHaveBeenCalledWith('id3'); expect(tree.state('selectedIds')).toEqual(['id1']); // id1 is left over since its deletion failed. }); });
15
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
30
Edit dataset card