Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Backport 2.x] Fix Warning Message About Custom Result Index Despite Existing Indices #761

Merged
merged 1 commit into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"babel-polyfill": "^6.26.0",
"eslint-plugin-no-unsanitized": "^3.0.2",
"eslint-plugin-prefer-object-spread": "^1.2.1",
"jest-canvas-mock": "^2.5.2",
"lint-staged": "^9.2.0",
"moment": "^2.24.0",
"redux-mock-store": "^1.5.4",
Expand Down
29 changes: 27 additions & 2 deletions public/pages/DetectorDetail/containers/DetectorDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,34 @@ export const DetectorDetail = (props: DetectorDetailProps) => {
const visibleIndices = useSelector(
(state: AppState) => state.opensearch.indices
) as CatIndex[];
const isCatIndicesRequesting = useSelector(
(state: AppState) => state.opensearch.requesting
) as boolean;

/*
Determine if the result index is missing based on several conditions:
- If the detector is still loading, the result index is not missing.
- If the result index retrieved from the detector is empty, it is not missing.
- If cat indices are being requested, the result index is not missing.
- If visible indices are empty, it is likely there is an issue retrieving existing indices.
To be safe, we'd rather not show the error message and consider the result index not missing.
- If the result index is not found in the visible indices, then it is missing.
*/
const isResultIndexMissing = isLoadingDetector
? false
: isEmpty(get(detector, 'resultIndex', ''))
? false
: isCatIndicesRequesting
? false
: isEmpty(visibleIndices)
? false
: !containsIndex(get(detector, 'resultIndex', ''), visibleIndices);

// debug message: prints visibleIndices if isResultIndexMissing is true
if (isResultIndexMissing) {
console.log(`isResultIndexMissing is true, visibleIndices: ${visibleIndices}, detector result index: ${get(detector, 'resultIndex', '')}`);
}

// String to set in the modal if the realtime detector and/or historical analysis
// are running when the user tries to edit the detector details or model config
const isRTJobRunning = get(detector, 'enabled');
Expand Down Expand Up @@ -179,10 +201,12 @@ export const DetectorDetail = (props: DetectorDetailProps) => {
// detector starts, result index recreated or user switches tabs to re-fetch detector)
useEffect(() => {
const getInitialIndices = async () => {
await dispatch(getIndices('', dataSourceId)).catch((error: any) => {
try {
await dispatch(getIndices('', dataSourceId));
} catch (error) {
console.error(error);
core.notifications.toasts.addDanger('Error getting all indices');
});
}
};
// only need to check if indices exist after detector finishes loading
if (!isLoadingDetector) {
Expand Down Expand Up @@ -464,6 +488,7 @@ export const DetectorDetail = (props: DetectorDetailProps) => {
)}', but is not found in the cluster. The index will be recreated when you start a real-time or historical job.`}
color="danger"
iconType="alert"
data-test-subj="missingResultIndexCallOut"
></EuiCallOut>
) : null}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/

import React from 'react';
import { render, screen } from '@testing-library/react';
import { DetectorDetail, DetectorRouterProps } from '../DetectorDetail';
import { Provider } from 'react-redux';
import {
HashRouter as Router,
RouteComponentProps,
Route,
Switch,
Redirect,
} from 'react-router-dom';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { httpClientMock, coreServicesMock } from '../../../../../test/mocks';
import { CoreServicesContext } from '../../../../components/CoreServices/CoreServices';
import { getRandomDetector } from '../../../../redux/reducers/__tests__/utils';
import { useFetchDetectorInfo } from '../../../CreateDetectorSteps/hooks/useFetchDetectorInfo';

jest.mock('../../hooks/useFetchMonitorInfo');

//jest.mock('../../../CreateDetectorSteps/hooks/useFetchDetectorInfo');
jest.mock('../../../CreateDetectorSteps/hooks/useFetchDetectorInfo', () => ({
// The jest.mock function is used at the top level of the test file to mock the entire module.
// Within each test, the mock implementation for useFetchDetectorInfo is set using jest.Mock.
// This ensures that the hook returns the desired values for each test case.
useFetchDetectorInfo: jest.fn(),
}));

jest.mock('../../../../services', () => ({
...jest.requireActual('../../../../services'),

getDataSourceEnabled: () => ({
enabled: false,
}),
}));

const detectorId = '4QY4YHEB5W9C7vlb3Mou';

// Configure the mock store
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

const renderWithRouter = (detectorId: string, initialState: any) => ({
...render(
<Provider store={mockStore(initialState)}>
<Router>
<Switch>
<Route
path={`/detectors/${detectorId}/results`}
render={(props: RouteComponentProps<DetectorRouterProps>) => {
const testProps = {
...props,
match: {
params: { detectorId: detectorId },
isExact: false,
path: '',
url: '',
},
};
return (
<CoreServicesContext.Provider value={coreServicesMock}>
<DetectorDetail {...testProps} />
</CoreServicesContext.Provider>
);
}}
/>
<Redirect from="/" to={`/detectors/${detectorId}/results`} />
</Switch>
</Router>
</Provider>
),
});

const resultIndex = 'opensearch-ad-plugin-result-test-query2';

describe('detector detail', () => {
beforeEach(() => {
jest.clearAllMocks();
});

test('detector info still loading', () => {
const detectorInfo = {
detector: getRandomDetector(true, resultIndex),
hasError: false,
isLoadingDetector: true,
errorMessage: undefined,
};

(useFetchDetectorInfo as jest.Mock).mockImplementation(() => detectorInfo);

const initialState = {
opensearch: {
indices: [{ health: 'green', index: resultIndex }],
requesting: false,
},
ad: {
detectors: {},
},
alerting: {
monitors: {},
},
};

renderWithRouter(detectorId, initialState);
const element = screen.queryByTestId('missingResultIndexCallOut');

// Assert that the element is not in the document
expect(element).toBeNull();
});

test('detector has no result index', () => {
const detectorInfo = {
detector: getRandomDetector(true, undefined),
hasError: false,
isLoadingDetector: true,
errorMessage: undefined,
};

(useFetchDetectorInfo as jest.Mock).mockImplementation(() => detectorInfo);

const initialState = {
opensearch: {
indices: [{ health: 'green', index: resultIndex }],
requesting: false,
},
ad: {
detectors: {},
},
alerting: {
monitors: {},
},
};

renderWithRouter(detectorId, initialState);
const element = screen.queryByTestId('missingResultIndexCallOut');

// Assert that the element is not in the document
expect(element).toBeNull();
});

test('cat indices are being requested', () => {
const detectorInfo = {
detector: getRandomDetector(true, resultIndex),
hasError: false,
isLoadingDetector: false,
errorMessage: undefined,
};

(useFetchDetectorInfo as jest.Mock).mockImplementation(() => detectorInfo);

const initialState = {
opensearch: {
indices: [],
requesting: true,
},
ad: {
detectors: {},
},
alerting: {
monitors: {},
},
};

renderWithRouter(detectorId, initialState);
const element = screen.queryByTestId('missingResultIndexCallOut');

// Assert that the element is not in the document
expect(element).toBeNull();
});

test('visible indices are empty', () => {
const detectorInfo = {
detector: getRandomDetector(true, resultIndex),
hasError: false,
isLoadingDetector: false,
errorMessage: undefined,
};

(useFetchDetectorInfo as jest.Mock).mockImplementation(() => detectorInfo);

const initialState = {
opensearch: {
indices: [],
requesting: false,
},
ad: {
detectors: {},
},
alerting: {
monitors: {},
},
};

renderWithRouter(detectorId, initialState);
const element = screen.queryByTestId('missingResultIndexCallOut');

// Assert that the element is not in the document
expect(element).toBeNull();
});

test('the result index is not found in the visible indices', () => {
const detectorInfo = {
detector: getRandomDetector(true, resultIndex),
hasError: false,
isLoadingDetector: false,
errorMessage: undefined,
};

(useFetchDetectorInfo as jest.Mock).mockImplementation(() => detectorInfo);

const initialState = {
opensearch: {
indices: [{ health: 'green', index: '.kibana_-962704462_v992471_1' }],
requesting: false,
},
ad: {
detectors: {},
},
alerting: {
monitors: {},
},
};

renderWithRouter(detectorId, initialState);
const element = screen.queryByTestId('missingResultIndexCallOut');

// Assert that the element is in the document
expect(element).not.toBeNull();
});

test('the result index is found in the visible indices', () => {
const detector = getRandomDetector(true, resultIndex);

// Set up the mock implementation for useFetchDetectorInfo
(useFetchDetectorInfo as jest.Mock).mockImplementation(() => ({
detector: detector,
hasError: false,
isLoadingDetector: false,
errorMessage: undefined,
}));

const initialState = {
opensearch: {
indices: [
{ health: 'green', index: '.kibana_-962704462_v992471_1' },
{ health: 'green', index: resultIndex },
],
requesting: false,
},
ad: {
detectors: {},
},
alerting: {
monitors: {},
},
};

renderWithRouter(detectorId, initialState);
const element = screen.queryByTestId('missingResultIndexCallOut');

// Assert that the element is not in the document
expect(element).toBeNull();
});
});
8 changes: 6 additions & 2 deletions public/redux/reducers/__tests__/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*/

import chance from 'chance';
import { snakeCase } from 'lodash';
import { isEmpty, snakeCase } from 'lodash';
import {
Detector,
FeatureAttributes,
Expand Down Expand Up @@ -82,7 +82,10 @@ const getUIMetadata = (features: FeatureAttributes[]) => {
} as UiMetaData;
};

export const getRandomDetector = (isCreate: boolean = true): Detector => {
export const getRandomDetector = (
isCreate: boolean = true,
customResultIndex: string = ''
): Detector => {
const features = new Array(detectorFaker.natural({ min: 1, max: 5 }))
.fill(null)
.map(() => getRandomFeature(isCreate ? false : true));
Expand Down Expand Up @@ -116,6 +119,7 @@ export const getRandomDetector = (isCreate: boolean = true): Detector => {
curState: DETECTOR_STATE.INIT,
stateError: '',
shingleSize: DEFAULT_SHINGLE_SIZE,
resultIndex: isEmpty(customResultIndex) ? undefined : customResultIndex
};
};

Expand Down
3 changes: 3 additions & 0 deletions test/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,7 @@ module.exports = {
'^.+\\.svg$': '<rootDir>/test/mocks/transformMock.ts',
'^.+\\.html$': '<rootDir>/test/mocks/transformMock.ts',
},
setupFiles: [
"jest-canvas-mock"
]
};
1 change: 1 addition & 0 deletions test/setupTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
*/

require('babel-polyfill');
import 'jest-canvas-mock';
Loading