From 378b8c80eaef7e1ba4d3fc3850fd9b977c42984e Mon Sep 17 00:00:00 2001 From: Jason Stoltzfus Date: Mon, 28 Sep 2020 09:39:46 -0400 Subject: [PATCH 01/19] [Enterprise Search] Added Logic for the Credentials View (#77626) --- .../enterprise_search/common/types/index.ts | 11 + .../components/credentials/constants.ts | 41 + .../credentials/credentials_logic.test.ts | 1196 +++++++++++++++++ .../credentials/credentials_logic.ts | 264 ++++ .../components/credentials/types.ts | 22 + .../public/applications/app_search/types.ts | 7 + .../utils/format_api_name/index.test.ts | 25 + .../app_search/utils/format_api_name/index.ts | 12 + .../routes/app_search/credentials.test.ts | 83 +- .../server/routes/app_search/credentials.ts | 46 +- 10 files changed, 1650 insertions(+), 57 deletions(-) create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/constants.ts create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.test.ts create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.ts create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/types.ts create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.test.ts create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.ts diff --git a/x-pack/plugins/enterprise_search/common/types/index.ts b/x-pack/plugins/enterprise_search/common/types/index.ts index d5774adc0d516c..1006d391387593 100644 --- a/x-pack/plugins/enterprise_search/common/types/index.ts +++ b/x-pack/plugins/enterprise_search/common/types/index.ts @@ -30,3 +30,14 @@ export interface IConfiguredLimits { appSearch: IAppSearchConfiguredLimits; workplaceSearch: IWorkplaceSearchConfiguredLimits; } + +export interface IMetaPage { + current: number; + size: number; + total_pages: number; + total_results: number; +} + +export interface IMeta { + page: IMetaPage; +} diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/constants.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/constants.ts new file mode 100644 index 00000000000000..92d14f72751859 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/constants.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { i18n } from '@kbn/i18n'; + +export const ADMIN = 'admin'; +export const PRIVATE = 'private'; +export const SEARCH = 'search'; + +export const TOKEN_TYPE_DESCRIPTION = { + [SEARCH]: i18n.translate('xpack.enterpriseSearch.appSearch.tokens.search.description', { + defaultMessage: 'Public Search Keys are used for search endpoints only.', + }), + [PRIVATE]: i18n.translate('xpack.enterpriseSearch.appSearch.tokens.private.description', { + defaultMessage: + 'Private API Keys are used for read and/or write access on one or more Engines.', + }), + [ADMIN]: i18n.translate('xpack.enterpriseSearch.appSearch.tokens.admin.description', { + defaultMessage: 'Private Admin Keys are used to interact with the Credentials API.', + }), +}; + +export const TOKEN_TYPE_DISPLAY_NAMES = { + [SEARCH]: i18n.translate('xpack.enterpriseSearch.appSearch.tokens.search.name', { + defaultMessage: 'Public Search Key', + }), + [PRIVATE]: i18n.translate('xpack.enterpriseSearch.appSearch.tokens.private.name', { + defaultMessage: 'Private API Key', + }), + [ADMIN]: i18n.translate('xpack.enterpriseSearch.appSearch.tokens.admin.name', { + defaultMessage: 'Private Admin Key', + }), +}; + +export const TOKEN_TYPE_INFO = [ + { value: SEARCH, text: TOKEN_TYPE_DISPLAY_NAMES[SEARCH] }, + { value: PRIVATE, text: TOKEN_TYPE_DISPLAY_NAMES[PRIVATE] }, + { value: ADMIN, text: TOKEN_TYPE_DISPLAY_NAMES[ADMIN] }, +]; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.test.ts new file mode 100644 index 00000000000000..c5cb8a2c61759a --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.test.ts @@ -0,0 +1,1196 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { resetContext } from 'kea'; + +import { CredentialsLogic } from './credentials_logic'; +import { ADMIN, PRIVATE } from './constants'; + +jest.mock('../../../shared/http', () => ({ + HttpLogic: { values: { http: { get: jest.fn(), delete: jest.fn() } } }, +})); +import { HttpLogic } from '../../../shared/http'; +jest.mock('../../../shared/flash_messages', () => ({ + flashAPIErrors: jest.fn(), +})); +import { flashAPIErrors } from '../../../shared/flash_messages'; + +describe('CredentialsLogic', () => { + const DEFAULT_VALUES = { + activeApiToken: { + name: '', + type: PRIVATE, + read: true, + write: true, + access_all_engines: true, + }, + activeApiTokenIsExisting: false, + activeApiTokenRawName: '', + apiTokens: [], + dataLoading: true, + engines: [], + formErrors: [], + isCredentialsDataComplete: false, + isCredentialsDetailsComplete: false, + meta: {}, + nameInputBlurred: false, + showCredentialsForm: false, + }; + + const mount = (defaults?: object) => { + if (!defaults) { + resetContext({}); + } else { + resetContext({ + defaults: { + enterprise_search: { + app_search: { + credentials_logic: { + ...defaults, + }, + }, + }, + }, + }); + } + CredentialsLogic.mount(); + }; + + const newToken = { + id: 1, + name: 'myToken', + type: PRIVATE, + read: true, + write: true, + access_all_engines: true, + engines: [], + }; + + const credentialsDetails = { + engines: [ + { name: 'engine1', type: 'indexed', language: 'english', result_fields: [] }, + { name: 'engine1', type: 'indexed', language: 'english', result_fields: [] }, + ], + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('has expected default values', () => { + mount(); + expect(CredentialsLogic.values).toEqual(DEFAULT_VALUES); + }); + + describe('addEngineName', () => { + const values = { + ...DEFAULT_VALUES, + activeApiToken: expect.any(Object), + }; + + describe('activeApiToken', () => { + it("should add an engine to the active api token's engine list", () => { + mount({ + activeApiToken: { + ...newToken, + engines: ['someEngine'], + }, + }); + + CredentialsLogic.actions.addEngineName('newEngine'); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { ...newToken, engines: ['someEngine', 'newEngine'] }, + }); + }); + + it("should create a new engines list if one doesn't exist", () => { + mount({ + activeApiToken: { + ...newToken, + engines: undefined, + }, + }); + + CredentialsLogic.actions.addEngineName('newEngine'); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { ...newToken, engines: ['newEngine'] }, + }); + }); + }); + }); + + describe('removeEngineName', () => { + describe('activeApiToken', () => { + const values = { + ...DEFAULT_VALUES, + activeApiToken: expect.any(Object), + }; + + it("should remove an engine from the active api token's engine list", () => { + mount({ + activeApiToken: { + ...newToken, + engines: ['someEngine', 'anotherEngine'], + }, + }); + + CredentialsLogic.actions.removeEngineName('someEngine'); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { ...newToken, engines: ['anotherEngine'] }, + }); + }); + + it('will not remove the engine if it is not found', () => { + mount({ + activeApiToken: { + ...newToken, + engines: ['someEngine', 'anotherEngine'], + }, + }); + + CredentialsLogic.actions.removeEngineName('notfound'); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { ...newToken, engines: ['someEngine', 'anotherEngine'] }, + }); + }); + + it('does not throw a type error if no engines are stored in state', () => { + mount({ + activeApiToken: {}, + }); + CredentialsLogic.actions.removeEngineName(''); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { engines: [] }, + }); + }); + }); + }); + + describe('setAccessAllEngines', () => { + const values = { + ...DEFAULT_VALUES, + activeApiToken: expect.any(Object), + }; + + describe('activeApiToken', () => { + it('should set the value of access_all_engines and clear out engines list if true', () => { + mount({ + activeApiToken: { + ...newToken, + access_all_engines: false, + engines: ['someEngine', 'anotherEngine'], + }, + }); + + CredentialsLogic.actions.setAccessAllEngines(true); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { ...newToken, engines: [], access_all_engines: true }, + }); + }); + + it('should set the value of access_all_engines and but maintain engines list if false', () => { + mount({ + activeApiToken: { + ...newToken, + access_all_engines: true, + engines: ['someEngine', 'anotherEngine'], + }, + }); + + CredentialsLogic.actions.setAccessAllEngines(false); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...newToken, + access_all_engines: false, + engines: ['someEngine', 'anotherEngine'], + }, + }); + }); + }); + }); + + describe('onApiKeyDelete', () => { + const values = { + ...DEFAULT_VALUES, + apiTokens: expect.any(Array), + }; + + describe('apiTokens', () => { + it('should remove specified token from apiTokens if name matches', () => { + mount({ + apiTokens: [newToken], + }); + + CredentialsLogic.actions.onApiKeyDelete(newToken.name); + expect(CredentialsLogic.values).toEqual({ + ...values, + apiTokens: [], + }); + }); + + it('should not remove specified token from apiTokens if name does not match', () => { + mount({ + apiTokens: [newToken], + }); + + CredentialsLogic.actions.onApiKeyDelete('foo'); + expect(CredentialsLogic.values).toEqual({ + ...values, + apiTokens: [newToken], + }); + }); + }); + }); + + describe('onApiTokenCreateSuccess', () => { + const values = { + ...DEFAULT_VALUES, + apiTokens: expect.any(Array), + activeApiToken: expect.any(Object), + activeApiTokenRawName: expect.any(String), + showCredentialsForm: expect.any(Boolean), + formErrors: expect.any(Array), + }; + + describe('apiTokens', () => { + const existingToken = { + name: 'some_token', + type: PRIVATE, + }; + + it('should add the provided token to the apiTokens list', () => { + mount({ + apiTokens: [existingToken], + }); + + CredentialsLogic.actions.onApiTokenCreateSuccess(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + apiTokens: [existingToken, newToken], + }); + }); + }); + + describe('activeApiToken', () => { + // TODO It is weird that methods like this update activeApiToken but not activeApiTokenIsExisting... + it('should reset to the default value, which effectively clears out the current form', () => { + mount({ + activeApiToken: newToken, + }); + + CredentialsLogic.actions.onApiTokenCreateSuccess(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: DEFAULT_VALUES.activeApiToken, + }); + }); + }); + + describe('activeApiTokenRawName', () => { + it('should reset to the default value, which effectively clears out the current form', () => { + mount({ + activeApiTokenRawName: 'foo', + }); + + CredentialsLogic.actions.onApiTokenCreateSuccess(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenRawName: DEFAULT_VALUES.activeApiTokenRawName, + }); + }); + }); + + describe('showCredentialsForm', () => { + it('should reset to the default value, which closes the credentials form', () => { + mount({ + showCredentialsForm: true, + }); + + CredentialsLogic.actions.onApiTokenCreateSuccess(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + showCredentialsForm: false, + }); + }); + }); + + describe('formErrors', () => { + it('should reset `formErrors`', () => { + mount({ + formErrors: ['I am an error'], + }); + + CredentialsLogic.actions.onApiTokenCreateSuccess(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + formErrors: [], + }); + }); + }); + }); + + describe('onApiTokenError', () => { + const values = { + ...DEFAULT_VALUES, + formErrors: expect.any(Array), + }; + + describe('formErrors', () => { + it('should set `formErrors`', () => { + mount({ + formErrors: ['I am an error'], + }); + + CredentialsLogic.actions.onApiTokenError(['I am the NEW error']); + expect(CredentialsLogic.values).toEqual({ + ...values, + formErrors: ['I am the NEW error'], + }); + }); + }); + }); + + describe('onApiTokenUpdateSuccess', () => { + const values = { + ...DEFAULT_VALUES, + apiTokens: expect.any(Array), + activeApiToken: expect.any(Object), + activeApiTokenRawName: expect.any(String), + showCredentialsForm: expect.any(Boolean), + }; + + describe('apiTokens', () => { + const existingToken = { + name: 'some_token', + type: PRIVATE, + }; + + it('should replace the existing token with the new token by name', () => { + mount({ + apiTokens: [newToken, existingToken], + }); + const updatedExistingToken = { + ...existingToken, + type: ADMIN, + }; + + CredentialsLogic.actions.onApiTokenUpdateSuccess(updatedExistingToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + apiTokens: [newToken, updatedExistingToken], + }); + }); + + // TODO Not sure if this is a good behavior or not + it('if for some reason the existing token is not found, it adds a new token...', () => { + mount({ + apiTokens: [newToken, existingToken], + }); + const brandNewToken = { + name: 'brand new token', + type: ADMIN, + }; + + CredentialsLogic.actions.onApiTokenUpdateSuccess(brandNewToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + apiTokens: [newToken, existingToken, brandNewToken], + }); + }); + }); + + describe('activeApiToken', () => { + it('should reset to the default value, which effectively clears out the current form', () => { + mount({ + activeApiToken: newToken, + }); + + CredentialsLogic.actions.onApiTokenUpdateSuccess({ ...newToken, type: ADMIN }); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: DEFAULT_VALUES.activeApiToken, + }); + }); + }); + + describe('activeApiTokenRawName', () => { + it('should reset to the default value, which effectively clears out the current form', () => { + mount({ + activeApiTokenRawName: 'foo', + }); + + CredentialsLogic.actions.onApiTokenUpdateSuccess({ ...newToken, type: ADMIN }); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenRawName: DEFAULT_VALUES.activeApiTokenRawName, + }); + }); + }); + + describe('showCredentialsForm', () => { + it('should reset to the default value, which closes the credentials form', () => { + mount({ + showCredentialsForm: true, + }); + + CredentialsLogic.actions.onApiTokenUpdateSuccess({ ...newToken, type: ADMIN }); + expect(CredentialsLogic.values).toEqual({ + ...values, + showCredentialsForm: false, + }); + }); + }); + }); + + describe('setCredentialsData', () => { + const meta = { + page: { + current: 1, + size: 1, + total_pages: 1, + total_results: 1, + }, + }; + + const values = { + ...DEFAULT_VALUES, + apiTokens: expect.any(Array), + meta: expect.any(Object), + isCredentialsDataComplete: expect.any(Boolean), + }; + + describe('apiTokens', () => { + it('should be set', () => { + mount(); + + CredentialsLogic.actions.setCredentialsData(meta, [newToken, newToken]); + expect(CredentialsLogic.values).toEqual({ + ...values, + apiTokens: [newToken, newToken], + }); + }); + }); + + describe('meta', () => { + it('should be set', () => { + mount(); + + CredentialsLogic.actions.setCredentialsData(meta, [newToken, newToken]); + expect(CredentialsLogic.values).toEqual({ + ...values, + meta, + }); + }); + }); + + describe('isCredentialsDataComplete', () => { + it('should be set to true so we know that data fetching has completed', () => { + mount({ + isCredentialsDataComplete: false, + }); + + CredentialsLogic.actions.setCredentialsData(meta, [newToken, newToken]); + expect(CredentialsLogic.values).toEqual({ + ...values, + isCredentialsDataComplete: true, + }); + }); + }); + }); + + describe('setCredentialsDetails', () => { + const values = { + ...DEFAULT_VALUES, + engines: expect.any(Array), + isCredentialsDetailsComplete: expect.any(Boolean), + }; + + describe('isCredentialsDataComplete', () => { + it('should be set to true so that we know data fetching has been completed', () => { + mount({ + isCredentialsDetailsComplete: false, + }); + + CredentialsLogic.actions.setCredentialsDetails(credentialsDetails); + expect(CredentialsLogic.values).toEqual({ + ...values, + isCredentialsDetailsComplete: true, + }); + }); + }); + + describe('engines', () => { + it('should set `engines` from the provided details object', () => { + mount({ + engines: [], + }); + + CredentialsLogic.actions.setCredentialsDetails(credentialsDetails); + expect(CredentialsLogic.values).toEqual({ + ...values, + engines: credentialsDetails.engines, + }); + }); + }); + }); + + describe('setNameInputBlurred', () => { + const values = { + ...DEFAULT_VALUES, + nameInputBlurred: expect.any(Boolean), + }; + + describe('nameInputBlurred', () => { + it('should set this value', () => { + mount({ + nameInputBlurred: false, + }); + + CredentialsLogic.actions.setNameInputBlurred(true); + expect(CredentialsLogic.values).toEqual({ + ...values, + nameInputBlurred: true, + }); + }); + }); + }); + + describe('setTokenReadWrite', () => { + const values = { + ...DEFAULT_VALUES, + activeApiToken: expect.any(Object), + }; + + describe('activeApiToken', () => { + it('should set "read" or "write" values', () => { + mount({ + activeApiToken: { + ...newToken, + read: false, + }, + }); + + CredentialsLogic.actions.setTokenReadWrite({ name: 'read', checked: true }); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...newToken, + read: true, + }, + }); + }); + }); + }); + + describe('setTokenName', () => { + const values = { + ...DEFAULT_VALUES, + activeApiToken: expect.any(Object), + activeApiTokenRawName: expect.any(String), + }; + + describe('activeApiToken', () => { + it('update the name property on the activeApiToken, formatted correctly', () => { + mount({ + activeApiToken: { + ...newToken, + name: 'bar', + }, + }); + + CredentialsLogic.actions.setTokenName('New Name'); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { ...newToken, name: 'new-name' }, + }); + }); + }); + + describe('activeApiTokenRawName', () => { + it('updates the raw name, with no formatting applied', () => { + mount(); + + CredentialsLogic.actions.setTokenName('New Name'); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenRawName: 'New Name', + }); + }); + }); + }); + + describe('setTokenType', () => { + const values = { + ...DEFAULT_VALUES, + activeApiToken: { + ...newToken, + type: expect.any(String), + read: expect.any(Boolean), + write: expect.any(Boolean), + access_all_engines: expect.any(Boolean), + engines: expect.any(Array), + }, + }; + + describe('activeApiToken.access_all_engines', () => { + describe('when value is ADMIN', () => { + it('updates access_all_engines to false', () => { + mount({ + activeApiToken: { + ...newToken, + access_all_engines: true, + }, + }); + + CredentialsLogic.actions.setTokenType(ADMIN); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + access_all_engines: false, + }, + }); + }); + }); + + describe('when value is not ADMIN', () => { + it('will maintain access_all_engines value when true', () => { + mount({ + activeApiToken: { + ...newToken, + access_all_engines: true, + }, + }); + + CredentialsLogic.actions.setTokenType(PRIVATE); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + access_all_engines: true, + }, + }); + }); + + it('will maintain access_all_engines value when false', () => { + mount({ + activeApiToken: { + ...newToken, + access_all_engines: false, + }, + }); + + CredentialsLogic.actions.setTokenType(PRIVATE); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + access_all_engines: false, + }, + }); + }); + }); + }); + + describe('activeApiToken.engines', () => { + describe('when value is ADMIN', () => { + it('clears the array', () => { + mount({ + activeApiToken: { + ...newToken, + engines: [{}, {}], + }, + }); + + CredentialsLogic.actions.setTokenType(ADMIN); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + engines: [], + }, + }); + }); + }); + + describe('when value is not ADMIN', () => { + it('will maintain engines array', () => { + mount({ + activeApiToken: { + ...newToken, + engines: [{}, {}], + }, + }); + + CredentialsLogic.actions.setTokenType(PRIVATE); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + engines: [{}, {}], + }, + }); + }); + }); + }); + + describe('activeApiToken.write', () => { + describe('when value is PRIVATE', () => { + it('sets this to true', () => { + mount({ + activeApiToken: { + ...newToken, + write: false, + }, + }); + + CredentialsLogic.actions.setTokenType(PRIVATE); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + write: true, + }, + }); + }); + }); + + describe('when value is not PRIVATE', () => { + it('sets this to false', () => { + mount({ + activeApiToken: { + ...newToken, + write: true, + }, + }); + + CredentialsLogic.actions.setTokenType(ADMIN); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + write: false, + }, + }); + }); + }); + }); + + describe('activeApiToken.read', () => { + describe('when value is PRIVATE', () => { + it('sets this to true', () => { + mount({ + activeApiToken: { + ...newToken, + read: false, + }, + }); + + CredentialsLogic.actions.setTokenType(PRIVATE); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + read: true, + }, + }); + }); + }); + + describe('when value is not PRIVATE', () => { + it('sets this to false', () => { + mount({ + activeApiToken: { + ...newToken, + read: true, + }, + }); + + CredentialsLogic.actions.setTokenType(ADMIN); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + read: false, + }, + }); + }); + }); + }); + + describe('activeApiToken.type', () => { + it('sets the type value', () => { + mount({ + activeApiToken: { + ...newToken, + type: ADMIN, + }, + }); + + CredentialsLogic.actions.setTokenType(PRIVATE); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: { + ...values.activeApiToken, + type: PRIVATE, + }, + }); + }); + }); + }); + + describe('toggleCredentialsForm', () => { + const values = { + ...DEFAULT_VALUES, + activeApiTokenIsExisting: expect.any(Boolean), + activeApiToken: expect.any(Object), + activeApiTokenRawName: expect.any(String), + formErrors: expect.any(Array), + showCredentialsForm: expect.any(Boolean), + }; + + describe('showCredentialsForm', () => { + it('should toggle `showCredentialsForm`', () => { + mount({ + showCredentialsForm: false, + }); + + CredentialsLogic.actions.toggleCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + showCredentialsForm: true, + }); + + CredentialsLogic.actions.toggleCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + showCredentialsForm: false, + }); + }); + }); + + describe('formErrors', () => { + it('should reset `formErrors`', () => { + mount({ + formErrors: ['I am an error'], + }); + + CredentialsLogic.actions.toggleCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + formErrors: [], + }); + }); + }); + + describe('activeApiTokenRawName', () => { + it('should set `activeApiTokenRawName` to the name of the provided token', () => { + mount(); + + CredentialsLogic.actions.toggleCredentialsForm(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenRawName: 'myToken', + }); + }); + + it('should set `activeApiTokenRawName` to the default value if no token is provided', () => { + mount(); + + CredentialsLogic.actions.toggleCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenRawName: DEFAULT_VALUES.activeApiTokenRawName, + }); + }); + + // TODO: This fails, is this an issue? Instead of reseting back to the default value, it sets it to the previously + // used value... to be honest, this should probably just be a selector + // it('should set `activeApiTokenRawName` back to the default value if no token is provided', () => { + // mount(); + // CredentialsLogic.actions.toggleCredentialsForm(newToken); + // CredentialsLogic.actions.toggleCredentialsForm(); + // expect(CredentialsLogic.values).toEqual({ + // ...values, + // activeApiTokenRawName: DEFAULT_VALUES.activeApiTokenRawName, + // }); + // }); + }); + + describe('activeApiToken', () => { + it('should set `activeApiToken` to the provided token', () => { + mount(); + + CredentialsLogic.actions.toggleCredentialsForm(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: newToken, + }); + }); + + it('should set `activeApiToken` to the default value if no token is provided', () => { + mount({ + activeApiToken: newToken, + }); + + CredentialsLogic.actions.toggleCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiToken: DEFAULT_VALUES.activeApiToken, + }); + }); + }); + + // TODO: This should probably just be a selector... + describe('activeApiTokenIsExisting', () => { + it('should set `activeApiTokenIsExisting` to true when the provided token has an id', () => { + mount({ + activeApiTokenIsExisting: false, + }); + + CredentialsLogic.actions.toggleCredentialsForm(newToken); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenIsExisting: true, + }); + }); + + it('should set `activeApiTokenIsExisting` to false when the provided token has no id', () => { + mount({ + activeApiTokenIsExisting: true, + }); + const { id, ...newTokenWithoutId } = newToken; + + CredentialsLogic.actions.toggleCredentialsForm(newTokenWithoutId); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenIsExisting: false, + }); + }); + + it('should set `activeApiTokenIsExisting` to false when no token is provided', () => { + mount({ + activeApiTokenIsExisting: true, + }); + + CredentialsLogic.actions.toggleCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenIsExisting: false, + }); + }); + }); + }); + + describe('hideCredentialsForm', () => { + const values = { + ...DEFAULT_VALUES, + showCredentialsForm: expect.any(Boolean), + activeApiTokenRawName: expect.any(String), + }; + + describe('activeApiTokenRawName', () => { + it('resets this value', () => { + mount({ + activeApiTokenRawName: 'foo', + }); + + CredentialsLogic.actions.hideCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + activeApiTokenRawName: '', + }); + }); + }); + + describe('showCredentialsForm', () => { + it('resets this value', () => { + mount({ + showCredentialsForm: true, + }); + + CredentialsLogic.actions.hideCredentialsForm(); + expect(CredentialsLogic.values).toEqual({ + ...values, + showCredentialsForm: false, + }); + }); + }); + }); + + describe('resetCredentials', () => { + const values = { + ...DEFAULT_VALUES, + isCredentialsDetailsComplete: expect.any(Boolean), + isCredentialsDataComplete: expect.any(Boolean), + formErrors: expect.any(Array), + }; + + describe('isCredentialsDetailsComplete', () => { + it('should reset to false', () => { + mount({ + isCredentialsDetailsComplete: true, + }); + + CredentialsLogic.actions.resetCredentials(); + expect(CredentialsLogic.values).toEqual({ + ...values, + isCredentialsDetailsComplete: false, + }); + }); + }); + + describe('isCredentialsDataComplete', () => { + it('should reset to false', () => { + mount({ + isCredentialsDataComplete: true, + }); + + CredentialsLogic.actions.resetCredentials(); + expect(CredentialsLogic.values).toEqual({ + ...values, + isCredentialsDataComplete: false, + }); + }); + }); + + describe('formErrors', () => { + it('should reset', () => { + mount({ + formErrors: ['I am an error'], + }); + + CredentialsLogic.actions.resetCredentials(); + expect(CredentialsLogic.values).toEqual({ + ...values, + formErrors: [], + }); + }); + }); + }); + + describe('initializeCredentialsData', () => { + it('should call fetchCredentials and fetchDetails', () => { + mount(); + jest.spyOn(CredentialsLogic.actions, 'fetchCredentials').mockImplementationOnce(() => {}); + jest.spyOn(CredentialsLogic.actions, 'fetchDetails').mockImplementationOnce(() => {}); + + CredentialsLogic.actions.initializeCredentialsData(); + expect(CredentialsLogic.actions.fetchCredentials).toHaveBeenCalled(); + expect(CredentialsLogic.actions.fetchDetails).toHaveBeenCalled(); + }); + }); + + describe('fetchCredentials', () => { + const meta = { + page: { + current: 1, + size: 1, + total_pages: 1, + total_results: 1, + }, + }; + const results: object[] = []; + + it('will call an API endpoint and set the results with the `setCredentialsData` action', async () => { + mount(); + jest.spyOn(CredentialsLogic.actions, 'setCredentialsData').mockImplementationOnce(() => {}); + const promise = Promise.resolve({ meta, results }); + (HttpLogic.values.http.get as jest.Mock).mockReturnValue(promise); + + CredentialsLogic.actions.fetchCredentials(2); + expect(HttpLogic.values.http.get).toHaveBeenCalledWith('/api/app_search/credentials', { + query: { + 'page[current]': 2, + }, + }); + await promise; + expect(CredentialsLogic.actions.setCredentialsData).toHaveBeenCalledWith(meta, results); + }); + + it('handles errors', async () => { + mount(); + const promise = Promise.reject('An error occured'); + (HttpLogic.values.http.get as jest.Mock).mockReturnValue(promise); + + CredentialsLogic.actions.fetchCredentials(); + try { + await promise; + } catch { + expect(flashAPIErrors).toHaveBeenCalledWith('An error occured'); + } + }); + }); + + describe('fetchDetails', () => { + it('will call an API endpoint and set the results with the `setCredentialsDetails` action', async () => { + mount(); + jest + .spyOn(CredentialsLogic.actions, 'setCredentialsDetails') + .mockImplementationOnce(() => {}); + const promise = Promise.resolve(credentialsDetails); + (HttpLogic.values.http.get as jest.Mock).mockReturnValue(promise); + + CredentialsLogic.actions.fetchDetails(); + expect(HttpLogic.values.http.get).toHaveBeenCalledWith('/api/app_search/credentials/details'); + await promise; + expect(CredentialsLogic.actions.setCredentialsDetails).toHaveBeenCalledWith( + credentialsDetails + ); + }); + + it('handles errors', async () => { + mount(); + const promise = Promise.reject('An error occured'); + (HttpLogic.values.http.get as jest.Mock).mockReturnValue(promise); + + CredentialsLogic.actions.fetchDetails(); + try { + await promise; + } catch { + expect(flashAPIErrors).toHaveBeenCalledWith('An error occured'); + } + }); + }); + + describe('deleteApiKey', () => { + const tokenName = 'abc123'; + + it('will call an API endpoint and set the results with the `onApiKeyDelete` action', async () => { + mount(); + jest.spyOn(CredentialsLogic.actions, 'onApiKeyDelete').mockImplementationOnce(() => {}); + const promise = Promise.resolve(); + (HttpLogic.values.http.delete as jest.Mock).mockReturnValue(promise); + + CredentialsLogic.actions.deleteApiKey(tokenName); + expect(HttpLogic.values.http.delete).toHaveBeenCalledWith( + `/api/app_search/credentials/${tokenName}` + ); + await promise; + expect(CredentialsLogic.actions.onApiKeyDelete).toHaveBeenCalledWith(tokenName); + }); + + it('handles errors', async () => { + mount(); + const promise = Promise.reject('An error occured'); + (HttpLogic.values.http.delete as jest.Mock).mockReturnValue(promise); + + CredentialsLogic.actions.deleteApiKey(tokenName); + try { + await promise; + } catch { + expect(flashAPIErrors).toHaveBeenCalledWith('An error occured'); + } + }); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.ts new file mode 100644 index 00000000000000..43f27317118235 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/credentials_logic.ts @@ -0,0 +1,264 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { kea, MakeLogicType } from 'kea'; + +import { formatApiName } from '../../utils/format_api_name'; +import { ADMIN, PRIVATE } from './constants'; + +import { HttpLogic } from '../../../shared/http'; +import { IMeta } from '../../../../../common/types'; +import { flashAPIErrors } from '../../../shared/flash_messages'; +import { IEngine } from '../../types'; +import { IApiToken, ICredentialsDetails } from './types'; + +interface ITokenReadWrite { + name: 'read' | 'write'; + checked: boolean; +} + +const defaultApiToken: IApiToken = { + name: '', + type: PRIVATE, + read: true, + write: true, + access_all_engines: true, +}; + +// TODO CREATE_MESSAGE, UPDATE_MESSAGE, and DELETE_MESSAGE from ent-search + +export interface ICredentialsLogicActions { + addEngineName(engineName: string): string; + onApiKeyDelete(tokenName: string): string; + onApiTokenCreateSuccess(apiToken: IApiToken): IApiToken; + onApiTokenError(formErrors: string[]): string[]; + onApiTokenUpdateSuccess(apiToken: IApiToken): IApiToken; + removeEngineName(engineName: string): string; + setAccessAllEngines(accessAll: boolean): boolean; + setCredentialsData(meta: IMeta, apiTokens: IApiToken[]): { meta: IMeta; apiTokens: IApiToken[] }; + setCredentialsDetails(details: ICredentialsDetails): ICredentialsDetails; + setNameInputBlurred(isBlurred: boolean): boolean; + setTokenReadWrite(tokenReadWrite: ITokenReadWrite): ITokenReadWrite; + setTokenName(name: string): string; + setTokenType(tokenType: string): string; + toggleCredentialsForm(apiToken?: IApiToken): IApiToken; + hideCredentialsForm(): { value: boolean }; + resetCredentials(): { value: boolean }; + initializeCredentialsData(): { value: boolean }; + fetchCredentials(page?: number): number; + fetchDetails(): { value: boolean }; + deleteApiKey(tokenName: string): string; +} + +export interface ICredentialsLogicValues { + activeApiToken: IApiToken; + activeApiTokenIsExisting: boolean; + activeApiTokenRawName: string; + apiTokens: IApiToken[]; + dataLoading: boolean; + engines: IEngine[]; + formErrors: string[]; + isCredentialsDataComplete: boolean; + isCredentialsDetailsComplete: boolean; + fullEngineAccessChecked: boolean; + meta: Partial; + nameInputBlurred: boolean; + showCredentialsForm: boolean; +} + +export const CredentialsLogic = kea< + MakeLogicType +>({ + path: ['enterprise_search', 'app_search', 'credentials_logic'], + actions: () => ({ + addEngineName: (engineName) => engineName, + onApiKeyDelete: (tokenName) => tokenName, + onApiTokenCreateSuccess: (apiToken) => apiToken, + onApiTokenError: (formErrors) => formErrors, + onApiTokenUpdateSuccess: (apiToken) => apiToken, + removeEngineName: (engineName) => engineName, + setAccessAllEngines: (accessAll) => accessAll, + setCredentialsData: (meta, apiTokens) => ({ meta, apiTokens }), + setCredentialsDetails: (details) => details, + setNameInputBlurred: (nameInputBlurred) => nameInputBlurred, + setTokenReadWrite: ({ name, checked }) => ({ + name, + checked, + }), + setTokenName: (name) => name, + setTokenType: (tokenType) => tokenType, + toggleCredentialsForm: (apiToken = { ...defaultApiToken }) => apiToken, + hideCredentialsForm: false, + resetCredentials: false, + initializeCredentialsData: true, + fetchCredentials: (page) => page, + fetchDetails: true, + deleteApiKey: (tokenName) => tokenName, + }), + reducers: () => ({ + apiTokens: [ + [], + { + setCredentialsData: (_, { apiTokens }) => apiTokens, + onApiTokenCreateSuccess: (apiTokens, apiToken) => [...apiTokens, apiToken], + onApiTokenUpdateSuccess: (apiTokens, apiToken) => [ + ...apiTokens.filter((token) => token.name !== apiToken.name), + apiToken, + ], + onApiKeyDelete: (apiTokens, tokenName) => + apiTokens.filter((token) => token.name !== tokenName), + }, + ], + meta: [ + {}, + { + setCredentialsData: (_, { meta }) => meta, + }, + ], + isCredentialsDetailsComplete: [ + false, + { + setCredentialsDetails: () => true, + resetCredentials: () => false, + }, + ], + isCredentialsDataComplete: [ + false, + { + setCredentialsData: () => true, + resetCredentials: () => false, + }, + ], + engines: [ + [], + { + setCredentialsDetails: (_, { engines }) => engines, + }, + ], + nameInputBlurred: [ + false, + { + setNameInputBlurred: (_, nameInputBlurred) => nameInputBlurred, + }, + ], + activeApiToken: [ + defaultApiToken, + { + addEngineName: (activeApiToken, engineName) => ({ + ...activeApiToken, + engines: [...(activeApiToken.engines || []), engineName], + }), + removeEngineName: (activeApiToken, engineName) => ({ + ...activeApiToken, + engines: (activeApiToken.engines || []).filter((name) => name !== engineName), + }), + setAccessAllEngines: (activeApiToken, accessAll) => ({ + ...activeApiToken, + access_all_engines: accessAll, + engines: accessAll ? [] : activeApiToken.engines, + }), + onApiTokenCreateSuccess: () => defaultApiToken, + onApiTokenUpdateSuccess: () => defaultApiToken, + setTokenName: (activeApiToken, name) => ({ ...activeApiToken, name: formatApiName(name) }), + setTokenReadWrite: (activeApiToken, { name, checked }) => ({ + ...activeApiToken, + [name]: checked, + }), + setTokenType: (activeApiToken, tokenType) => ({ + ...activeApiToken, + access_all_engines: tokenType === ADMIN ? false : activeApiToken.access_all_engines, + engines: tokenType === ADMIN ? [] : activeApiToken.engines, + write: tokenType === PRIVATE, + read: tokenType === PRIVATE, + type: tokenType, + }), + toggleCredentialsForm: (_, activeApiToken) => activeApiToken, + }, + ], + activeApiTokenRawName: [ + '', + { + setTokenName: (_, activeApiTokenRawName) => activeApiTokenRawName, + toggleCredentialsForm: (activeApiTokenRawName, activeApiToken) => + activeApiToken.name || activeApiTokenRawName, + hideCredentialsForm: () => '', + onApiTokenCreateSuccess: () => '', + onApiTokenUpdateSuccess: () => '', + }, + ], + activeApiTokenIsExisting: [ + false, + { + toggleCredentialsForm: (_, activeApiToken) => !!activeApiToken.id, + }, + ], + showCredentialsForm: [ + false, + { + toggleCredentialsForm: (showCredentialsForm) => !showCredentialsForm, + hideCredentialsForm: () => false, + onApiTokenCreateSuccess: () => false, + onApiTokenUpdateSuccess: () => false, + }, + ], + formErrors: [ + [], + { + onApiTokenError: (_, formErrors) => formErrors, + onApiTokenCreateSuccess: () => [], + toggleCredentialsForm: () => [], + resetCredentials: () => [], + }, + ], + }), + selectors: ({ selectors }) => ({ + // TODO fullEngineAccessChecked from ent-search + dataLoading: [ + () => [selectors.isCredentialsDetailsComplete, selectors.isCredentialsDataComplete], + (isCredentialsDetailsComplete, isCredentialsDataComplete) => { + return isCredentialsDetailsComplete === false || isCredentialsDataComplete === false; + }, + ], + }), + listeners: ({ actions, values }) => ({ + initializeCredentialsData: () => { + actions.fetchCredentials(); + actions.fetchDetails(); + }, + fetchCredentials: async (page = 1) => { + try { + const { http } = HttpLogic.values; + const query = { 'page[current]': page }; + const response = await http.get('/api/app_search/credentials', { query }); + actions.setCredentialsData(response.meta, response.results); + } catch (e) { + flashAPIErrors(e); + } + }, + fetchDetails: async () => { + try { + const { http } = HttpLogic.values; + const response = await http.get('/api/app_search/credentials/details'); + + actions.setCredentialsDetails(response); + } catch (e) { + flashAPIErrors(e); + } + }, + deleteApiKey: async (tokenName) => { + try { + const { http } = HttpLogic.values; + await http.delete(`/api/app_search/credentials/${tokenName}`); + + actions.onApiKeyDelete(tokenName); + } catch (e) { + flashAPIErrors(e); + } + }, + // TODO onApiTokenChange from ent-search + // TODO onEngineSelect from ent-search + }), +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/types.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/types.ts new file mode 100644 index 00000000000000..9b09bd13a9086c --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/credentials/types.ts @@ -0,0 +1,22 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IEngine } from '../../types'; + +export interface ICredentialsDetails { + engines: IEngine[]; +} + +export interface IApiToken { + access_all_engines?: boolean; + key?: string; + engines?: string[]; + id?: number; + name: string; + read?: boolean; + type: string; + write?: boolean; +} diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts index 3cabc1051c74aa..568a0a33659824 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts @@ -6,3 +6,10 @@ export * from '../../../common/types/app_search'; export { IRole, TRole, TAbility } from './utils/role'; + +export interface IEngine { + name: string; + type: string; + language: string; + result_fields: object[]; +} diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.test.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.test.ts new file mode 100644 index 00000000000000..352ff237e4f08a --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.test.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { formatApiName } from '.'; + +describe('formatApiName', () => { + it('replaces non-alphanumeric characters with dashes', () => { + expect(formatApiName('f1 &&o$ 1 2 *&%da')).toEqual('f1-o-1-2-da'); + }); + + it('strips leading and trailing non-alphanumeric characters', () => { + expect(formatApiName('$$hello world**')).toEqual('hello-world'); + }); + + it('strips leading and trailing whitespace', () => { + expect(formatApiName(' test ')).toEqual('test'); + }); + + it('lowercases text', () => { + expect(formatApiName('SomeName')).toEqual('somename'); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.ts new file mode 100644 index 00000000000000..cd1b1cfe156371 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/utils/format_api_name/index.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const formatApiName = (rawName: string) => + rawName + .trim() + .replace(/[^a-zA-Z0-9]+/g, '-') // Replace all special/non-alphanumerical characters with dashes + .replace(/^[-]+|[-]+$/g, '') // Strip all leading and trailing dashes + .toLowerCase(); diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.test.ts index 000e6d63b5999b..6b5f4a05b3aa67 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.test.ts @@ -25,41 +25,6 @@ describe('credentials routes', () => { it('creates a request handler', () => { expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ path: '/as/credentials/collection', - hasValidData: expect.any(Function), - }); - }); - - describe('hasValidData', () => { - it('should correctly validate that a response has data', () => { - const response = { - meta: { - page: { - current: 1, - total_pages: 1, - total_results: 1, - size: 25, - }, - }, - results: [ - { - id: 'loco_moco_account_id:5f3575de2b76ff13405f3155|name:asdfasdf', - key: 'search-fe49u2z8d5gvf9s4ekda2ad4', - name: 'asdfasdf', - type: 'search', - access_all_engines: true, - }, - ], - }; - - expect(mockRequestHandler.hasValidData(response)).toBe(true); - }); - - it('should correctly validate that a response does not have data', () => { - const response = { - foo: 'bar', - }; - - expect(mockRequestHandler.hasValidData(response)).toBe(false); }); }); @@ -75,4 +40,52 @@ describe('credentials routes', () => { }); }); }); + + describe('GET /api/app_search/credentials/details', () => { + let mockRouter: MockRouter; + + beforeEach(() => { + jest.clearAllMocks(); + mockRouter = new MockRouter({ method: 'get', payload: 'query' }); + + registerCredentialsRoutes({ + ...mockDependencies, + router: mockRouter.router, + }); + }); + + it('creates a request handler', () => { + expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ + path: '/as/credentials/details', + }); + }); + }); + + describe('DELETE /api/app_search/credentials/{name}', () => { + let mockRouter: MockRouter; + + beforeEach(() => { + jest.clearAllMocks(); + mockRouter = new MockRouter({ method: 'delete', payload: 'params' }); + + registerCredentialsRoutes({ + ...mockDependencies, + router: mockRouter.router, + }); + }); + + it('creates a request to enterprise search', () => { + const mockRequest = { + params: { + name: 'abc123', + }, + }; + + mockRouter.callRoute(mockRequest); + + expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({ + path: '/as/credentials/abc123', + }); + }); + }); }); diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.ts index 432f54c8e5b1c3..0f2c1133192c57 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/credentials.ts @@ -8,25 +8,6 @@ import { schema } from '@kbn/config-schema'; import { IRouteDependencies } from '../../plugin'; -interface ICredential { - id: string; - key: string; - name: string; - type: string; - access_all_engines: boolean; -} -interface ICredentialsResponse { - results: ICredential[]; - meta?: { - page?: { - current: number; - total_results: number; - total_pages: number; - size: number; - }; - }; -} - export function registerCredentialsRoutes({ router, enterpriseSearchRequestHandler, @@ -42,9 +23,30 @@ export function registerCredentialsRoutes({ }, enterpriseSearchRequestHandler.createRequest({ path: '/as/credentials/collection', - hasValidData: (body?: ICredentialsResponse) => { - return Array.isArray(body?.results) && typeof body?.meta?.page?.total_results === 'number'; - }, }) ); + router.get( + { + path: '/api/app_search/credentials/details', + validate: false, + }, + enterpriseSearchRequestHandler.createRequest({ + path: '/as/credentials/details', + }) + ); + router.delete( + { + path: '/api/app_search/credentials/{name}', + validate: { + params: schema.object({ + name: schema.string(), + }), + }, + }, + async (context, request, response) => { + return enterpriseSearchRequestHandler.createRequest({ + path: `/as/credentials/${request.params.name}`, + })(context, request, response); + } + ); } From e0755a7458c7f250c2e478582a4c39760b3c8b0d Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 28 Sep 2020 16:51:36 +0300 Subject: [PATCH 02/19] remove unnecessary config validations (#78527) --- src/legacy/server/config/schema.js | 27 +++++---------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/src/legacy/server/config/schema.js b/src/legacy/server/config/schema.js index a94766ef069269..feeb8e0bf6e4ca 100644 --- a/src/legacy/server/config/schema.js +++ b/src/legacy/server/config/schema.js @@ -38,12 +38,8 @@ export default () => prod: Joi.boolean().default(Joi.ref('$prod')), }).default(), - dev: Joi.object({ - basePathProxyTarget: Joi.number().default(5603), - }).default(), - + dev: HANDLED_IN_NEW_PLATFORM, pid: HANDLED_IN_NEW_PLATFORM, - csp: HANDLED_IN_NEW_PLATFORM, server: Joi.object({ @@ -125,10 +121,7 @@ export default () => ops: Joi.object({ interval: Joi.number().default(5000), - cGroupOverrides: Joi.object().keys({ - cpuPath: Joi.string().default(), - cpuAcctPath: Joi.string().default(), - }), + cGroupOverrides: HANDLED_IN_NEW_PLATFORM, }).default(), // still used by the legacy i18n mixin @@ -139,15 +132,8 @@ export default () => }).default(), path: HANDLED_IN_NEW_PLATFORM, - - stats: Joi.object({ - maximumWaitTimeForAllCollectorsInS: Joi.number().default(60), - }).default(), - - status: Joi.object({ - allowAnonymous: Joi.boolean().default(false), - }).default(), - + stats: HANDLED_IN_NEW_PLATFORM, + status: HANDLED_IN_NEW_PLATFORM, map: HANDLED_IN_NEW_PLATFORM, i18n: Joi.object({ @@ -163,8 +149,5 @@ export default () => autocompleteTimeout: Joi.number().integer().min(1).default(1000), }).default(), - savedObjects: Joi.object({ - maxImportPayloadBytes: Joi.number().default(10485760), - maxImportExportSize: Joi.number().default(10000), - }).default(), + savedObjects: HANDLED_IN_NEW_PLATFORM, }).default(); From 8841757874b0b357595640aa18bd7db95d2e03c3 Mon Sep 17 00:00:00 2001 From: Rudolf Meijering Date: Mon, 28 Sep 2020 15:53:24 +0200 Subject: [PATCH 03/19] First stab at developer-focussed saved objects docs (#71430) * First stab at developer-focussed saved objects docs * Don't introduce spelling mistakes * Add docs for SO migrations * Link to HTTP API documentation * Grammar fixes * Rendering fixes * Migrations should be tested, remove nested migration docs for now * Drop subtitle field in migration, add notes about migration version, behaviour for corrupt documents and emphasize testing Co-authored-by: Josh Dover --- .../development-plugin-saved-objects.asciidoc | 311 ++++++++++++++++++ docs/developer/architecture/index.asciidoc | 6 +- 2 files changed, 316 insertions(+), 1 deletion(-) create mode 100644 docs/developer/architecture/development-plugin-saved-objects.asciidoc diff --git a/docs/developer/architecture/development-plugin-saved-objects.asciidoc b/docs/developer/architecture/development-plugin-saved-objects.asciidoc new file mode 100644 index 00000000000000..0d31f5d90f6680 --- /dev/null +++ b/docs/developer/architecture/development-plugin-saved-objects.asciidoc @@ -0,0 +1,311 @@ +[[development-plugin-saved-objects]] +== Using Saved Objects + +Saved Objects allow {kib} plugins to use {es} like a primary +database. Think of it as an Object Document Mapper for {es}. Once a +plugin has registered one or more Saved Object types, the Saved Objects client +can be used to query or perform create, read, update and delete operations on +each type. + +By using Saved Objects your plugin can take advantage of the following +features: + +* Migrations can evolve your document's schema by transforming documents and +ensuring that the field mappings on the index are always up to date. +* a <> is automatically exposed for each type (unless +`hidden=true` is specified). +* a Saved Objects client that can be used from both the server and the browser. +* Users can import or export Saved Objects using the Saved Objects management +UI or the Saved Objects import/export API. +* By declaring `references`, an object's entire reference graph will be +exported. This makes it easy for users to export e.g. a `dashboard` object and +have all the `visualization` objects required to display the dashboard +included in the export. +* When the X-Pack security and spaces plugins are enabled these transparently +provide RBAC access control and the ability to organize Saved Objects into +spaces. + +This document contains developer guidelines and best-practices for plugins +wanting to use Saved Objects. + +=== Registering a Saved Object type +Saved object type definitions should be defined in their own `my_plugin/server/saved_objects` directory. + +The folder should contain a file per type, named after the snake_case name of the type, and an `index.ts` file exporting all the types. + +.src/plugins/my_plugin/server/saved_objects/dashboard_visualization.ts +[source,typescript] +---- +import { SavedObjectsType } from 'src/core/server'; + +export const dashboardVisualization: SavedObjectsType = { + name: 'dashboard_visualization', // <1> + hidden: false, + namespaceType: 'single', + mappings: { + dynamic: false, + properties: { + description: { + type: 'text', + }, + hits: { + type: 'integer', + }, + }, + }, + migrations: { + '1.0.0': migratedashboardVisualizationToV1, + '2.0.0': migratedashboardVisualizationToV2, + }, +}; +---- +<1> Since the name of a Saved Object type forms part of the url path for the +public Saved Objects HTTP API, these should follow our API URL path convention +and always be written as snake case. + +.src/plugins/my_plugin/server/saved_objects/index.ts +[source,typescript] +---- +export { dashboardVisualization } from './dashboard_visualization'; +export { dashboard } from './dashboard'; +---- + +.src/plugins/my_plugin/server/plugin.ts +[source,typescript] +---- +import { dashboard, dashboardVisualization } from './saved_objects'; + +export class MyPlugin implements Plugin { + setup({ savedObjects }) { + savedObjects.registerType(dashboard); + savedObjects.registerType(dashboardVisualization); + } +} +---- + +=== Mappings +Each Saved Object type can define it's own {es} field mappings. +Because multiple Saved Object types can share the same index, mappings defined +by a type will be nested under a top-level field that matches the type name. + +For example, the mappings defined by the `dashboard_visualization` Saved +Object type: + +.src/plugins/my_plugin/server/saved_objects/dashboard_visualization.ts +[source,typescript] +---- +import { SavedObjectsType } from 'src/core/server'; + +export const dashboardVisualization: SavedObjectsType = { + name: 'dashboard_visualization', + ... + mappings: { + properties: { + dynamic: false, + description: { + type: 'text', + }, + hits: { + type: 'integer', + }, + }, + }, + migrations: { ... }, +}; +---- + +Will result in the following mappings being applied to the `.kibana` index: +[source,json] +---- +{ + "mappings": { + "dynamic": "strict", + "properties": { + ... + "dashboard_vizualization": { + "dynamic": false, + "properties": { + "description": { + "type": "text", + }, + "hits": { + "type": "integer", + }, + }, + } + } + } +} +---- + +Do not use field mappings like you would use data types for the columns of a +SQL database. Instead, field mappings are analogous to a SQL index. Only +specify field mappings for the fields you wish to search on or query. By +specifying `dynamic: false` in any level of your mappings, {es} will +accept and store any other fields even if they are not specified in your mappings. + +Since {es} has a default limit of 1000 fields per index, plugins +should carefully consider the fields they add to the mappings. Similarly, +Saved Object types should never use `dynamic: true` as this can cause an +arbitrary amount of fields to be added to the `.kibana` index. + +=== References +When a Saved Object declares `references` to other Saved Objects, the +Saved Objects Export API will automatically export the target object with all +of it's references. This makes it easy for users to export the entire +reference graph of an object. + +If a Saved Object can't be used on it's own, that is, it needs other objects +to exist for a feature to function correctly, that Saved Object should declare +references to all the objects it requires. For example, a `dashboard` +object might have panels for several `visualization` objects. When these +`visualization` objects don't exist, the dashboard cannot be rendered +correctly. The `dashboard` object should declare references to all it's +visualizations. + +However, `visualization` objects can continue to be rendered or embedded into +other dashboards even if the `dashboard` it was originally embedded into +doesn't exist. As a result, `visualization` objects should not declare +references to `dashboard` objects. + +For each referenced object, an `id`, `type` and `name` are added to the +`references` array: + +[source, typescript] +---- +router.get( + { path: '/some-path', validate: false }, + async (context, req, res) => { + const object = await context.core.savedObjects.client.create( + 'dashboard', + { + title: 'my dashboard', + panels: [ + { visualization: 'vis1' }, // <1> + ], + indexPattern: 'indexPattern1' + }, + { references: [ + { id: '...', type: 'visualization', name: 'vis1' }, + { id: '...', type: 'index_pattern', name: 'indexPattern1' }, + ] + } + ) + ... + } +); +---- +<1> Note how `dashboard.panels[0].visualization` stores the `name` property of +the reference (not the `id` directly) to be able to uniquely identify this +reference. This guarantees that the id the reference points to always remains +up to date. If a visualization `id` was directly stored in +`dashboard.panels[0].visualization` there is a risk that this `id` gets +updated without updating the reference in the references array. + +==== Writing Migrations + +Saved Objects support schema changes between Kibana versions, which we call +migrations. Migrations are applied when a Kibana installation is upgraded from +one version to the next, when exports are imported via the Saved Objects +Management UI, or when a new object is created via the HTTP API. + +Each Saved Object type may define migrations for its schema. Migrations are +specified by the Kibana version number, receive an input document, and must +return the fully migrated document to be persisted to Elasticsearch. + +Let's say we want to define two migrations: +- In version 1.1.0, we want to drop the `subtitle` field and append it to the + title +- In version 1.4.0, we want to add a new `id` field to every panel with a newly + generated UUID. + +First, the current `mappings` should always reflect the latest or "target" +schema. Next, we should define a migration function for each step in the schema +evolution: + +src/plugins/my_plugin/server/saved_objects/dashboard_visualization.ts +[source,typescript] +---- +import { SavedObjectsType, SavedObjectMigrationFn } from 'src/core/server'; +import uuid from 'uuid'; + +interface DashboardVisualizationPre110 { + title: string; + subtitle: string; + panels: Array<{}>; +} +interface DashboardVisualization110 { + title: string; + panels: Array<{}>; +} + +interface DashboardVisualization140 { + title: string; + panels: Array<{ id: string }>; +} + +const migrateDashboardVisualization110: SavedObjectMigrationFn< + DashboardVisualizationPre110, // <1> + DashboardVisualization110 +> = (doc) => { + const { subtitle, ...attributesWithoutSubtitle } = doc.attributes; + return { + ...doc, // <2> + attributes: { + ...attributesWithoutSubtitle, + title: `${doc.attributes.title} - ${doc.attributes.subtitle}`, + }, + }; +}; + +const migrateDashboardVisualization140: SavedObjectMigrationFn< + DashboardVisualization110, + DashboardVisualization140 +> = (doc) => { + const outPanels = doc.attributes.panels?.map((panel) => { + return { ...panel, id: uuid.v4() }; + }); + return { + ...doc, + attributes: { + ...doc.attributes, + panels: outPanels, + }, + }; +}; + +export const dashboardVisualization: SavedObjectsType = { + name: 'dashboard_visualization', // <1> + /** ... */ + migrations: { + // Takes a pre 1.1.0 doc, and converts it to 1.1.0 + '1.1.0': migrateDashboardVisualization110, + + // Takes a 1.1.0 doc, and converts it to 1.4.0 + '1.4.0': migrateDashboardVisualization140, // <3> + }, +}; +---- +<1> It is useful to define an interface for each version of the schema. This +allows TypeScript to ensure that you are properly handling the input and output +types correctly as the schema evolves. +<2> Returning a shallow copy is necessary to avoid type errors when using +different types for the input and output shape. +<3> Migrations do not have to be defined for every version. The version number +of a migration must always be the earliest Kibana version in which this +migration was released. So if you are creating a migration which will be +part of the v7.10.0 release, but will also be backported and released as +v7.9.3, the migration version should be: 7.9.3. + +Migrations should be written defensively, an exception in a migration function +will prevent a Kibana upgrade from succeeding and will cause downtime for our +users. Having said that, if a document is encountered that is not in the +expected shape, migrations are encouraged to throw an exception to abort the +upgrade. In most scenarios, it is better to fail an upgrade than to silently +ignore a corrupt document which can cause unexpected behaviour at some future +point in time. + +It is critical that you have extensive tests to ensure that migrations behave +as expected with all possible input documents. Given how simple it is to test +all the branch conditions in a migration function and the high impact of a bug +in this code, there's really no reason not to aim for 100% test code coverage. \ No newline at end of file diff --git a/docs/developer/architecture/index.asciidoc b/docs/developer/architecture/index.asciidoc index ac25fe003df08d..dc15b90b69d1a6 100644 --- a/docs/developer/architecture/index.asciidoc +++ b/docs/developer/architecture/index.asciidoc @@ -15,12 +15,16 @@ A few services also automatically generate api documentation which can be browse A few notable services are called out below. * <> +* <> * <> * <> +include::security/index.asciidoc[leveloffset=+1] + +include::development-plugin-saved-objects.asciidoc[leveloffset=+1] + include::add-data-tutorials.asciidoc[leveloffset=+1] include::development-visualize-index.asciidoc[leveloffset=+1] -include::security/index.asciidoc[leveloffset=+1] From 8547b32bab948d157897ff6aaf243b076873ff3d Mon Sep 17 00:00:00 2001 From: Gidi Meir Morris Date: Mon, 28 Sep 2020 14:56:20 +0100 Subject: [PATCH 04/19] [Actions] avoids setting a default dedupKey on PagerDuty (#77773) The PagerDuty Action currently defaults to a dedupKey that's shared between all action executions of the same connector. To ensure we don't group unrelated executions together this PR avoids setting a default, which means each execution will result in its own incident in PD. As part of this change we've also made the `dedupKey` a required field whenever a `resolve` or `acknowledge` event_action is chosen. This ensure we don't try to resolve without a dedupKey, which would result in an error in PD. A migration has been introduced to migrate existing alerts which might not have a `dedupKey` configured. --- .../builtin_action_types/pagerduty.test.ts | 68 ++++++++++- .../server/builtin_action_types/pagerduty.ts | 61 ++++++---- .../server/saved_objects/migrations.test.ts | 114 ++++++++++++++++++ .../alerts/server/saved_objects/migrations.ts | 84 +++++++++---- .../pagerduty/pagerduty.test.tsx | 1 + .../pagerduty/pagerduty.tsx | 14 +++ .../pagerduty/pagerduty_params.test.tsx | 2 +- .../pagerduty/pagerduty_params.tsx | 26 +++- .../server/pagerduty_simulation.ts | 11 +- .../actions/builtin_action_types/pagerduty.ts | 1 - .../spaces_only/tests/alerting/migrations.ts | 43 +++++++ .../functional/es_archives/alerts/data.json | 111 +++++++++++++++++ 12 files changed, 470 insertions(+), 66 deletions(-) diff --git a/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts b/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts index 772e7df4169799..e406b37ae61fb3 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/pagerduty.test.ts @@ -169,6 +169,16 @@ describe('validateParams()', () => { }); }).toThrowError(`error validating action params: error parsing timestamp "${timestamp}"`); }); + + test('should validate and throw error when dedupKey is missing on resolve', () => { + expect(() => { + validateParams(actionType, { + eventAction: 'resolve', + }); + }).toThrowError( + `error validating action params: DedupKey is required when eventAction is "resolve"` + ); + }); }); describe('execute()', () => { @@ -199,7 +209,6 @@ describe('execute()', () => { Object { "apiUrl": "https://events.pagerduty.com/v2/enqueue", "data": Object { - "dedup_key": "action:some-action-id", "event_action": "trigger", "payload": Object { "severity": "info", @@ -509,4 +518,61 @@ describe('execute()', () => { } `); }); + + test('should not set a default dedupkey to ensure each execution is a unique PagerDuty incident', async () => { + const randoDate = new Date('1963-09-23T01:23:45Z').toISOString(); + const secrets = { + routingKey: 'super-secret', + }; + const config = { + apiUrl: 'the-api-url', + }; + const params: ActionParamsType = { + eventAction: 'trigger', + summary: 'the summary', + source: 'the-source', + severity: 'critical', + timestamp: randoDate, + }; + + postPagerdutyMock.mockImplementation(() => { + return { status: 202, data: 'data-here' }; + }); + + const actionId = 'some-action-id'; + const executorOptions: PagerDutyActionTypeExecutorOptions = { + actionId, + config, + params, + secrets, + services, + }; + const actionResponse = await actionType.executor(executorOptions); + const { apiUrl, data, headers } = postPagerdutyMock.mock.calls[0][0]; + expect({ apiUrl, data, headers }).toMatchInlineSnapshot(` + Object { + "apiUrl": "the-api-url", + "data": Object { + "event_action": "trigger", + "payload": Object { + "severity": "critical", + "source": "the-source", + "summary": "the summary", + "timestamp": "1963-09-23T01:23:45.000Z", + }, + }, + "headers": Object { + "Content-Type": "application/json", + "X-Routing-Key": "super-secret", + }, + } + `); + expect(actionResponse).toMatchInlineSnapshot(` + Object { + "actionId": "some-action-id", + "data": "data-here", + "status": "ok", + } + `); + }); }); diff --git a/x-pack/plugins/actions/server/builtin_action_types/pagerduty.ts b/x-pack/plugins/actions/server/builtin_action_types/pagerduty.ts index 640a38d77b6c2f..4574b748e60143 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/pagerduty.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/pagerduty.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { curry } from 'lodash'; +import { curry, isUndefined, pick, omitBy } from 'lodash'; import { i18n } from '@kbn/i18n'; import { schema, TypeOf } from '@kbn/config-schema'; import { postPagerduty } from './lib/post_pagerduty'; @@ -51,6 +51,10 @@ export type ActionParamsType = TypeOf; const EVENT_ACTION_TRIGGER = 'trigger'; const EVENT_ACTION_RESOLVE = 'resolve'; const EVENT_ACTION_ACKNOWLEDGE = 'acknowledge'; +const EVENT_ACTIONS_WITH_REQUIRED_DEDUPKEY = new Set([ + EVENT_ACTION_RESOLVE, + EVENT_ACTION_ACKNOWLEDGE, +]); const EventActionSchema = schema.oneOf([ schema.literal(EVENT_ACTION_TRIGGER), @@ -81,7 +85,7 @@ const ParamsSchema = schema.object( ); function validateParams(paramsObject: unknown): string | void { - const { timestamp } = paramsObject as ActionParamsType; + const { timestamp, eventAction, dedupKey } = paramsObject as ActionParamsType; if (timestamp != null) { try { const date = Date.parse(timestamp); @@ -103,6 +107,14 @@ function validateParams(paramsObject: unknown): string | void { }); } } + if (eventAction && EVENT_ACTIONS_WITH_REQUIRED_DEDUPKEY.has(eventAction) && !dedupKey) { + return i18n.translate('xpack.actions.builtin.pagerduty.missingDedupkeyErrorMessage', { + defaultMessage: `DedupKey is required when eventAction is "{eventAction}"`, + values: { + eventAction, + }, + }); + } } // action type definition @@ -230,26 +242,29 @@ async function executor( const AcknowledgeOrResolve = new Set([EVENT_ACTION_ACKNOWLEDGE, EVENT_ACTION_RESOLVE]); -function getBodyForEventAction(actionId: string, params: ActionParamsType): unknown { - const eventAction = params.eventAction || EVENT_ACTION_TRIGGER; - const dedupKey = params.dedupKey || `action:${actionId}`; - - const data: { - event_action: ActionParamsType['eventAction']; - dedup_key: string; - payload?: { - summary: string; - source: string; - severity: string; - timestamp?: string; - component?: string; - group?: string; - class?: string; - }; - } = { +interface PagerDutyPayload { + event_action: ActionParamsType['eventAction']; + dedup_key?: string; + payload?: { + summary: string; + source: string; + severity: string; + timestamp?: string; + component?: string; + group?: string; + class?: string; + }; +} + +function getBodyForEventAction(actionId: string, params: ActionParamsType): PagerDutyPayload { + const eventAction = params.eventAction ?? EVENT_ACTION_TRIGGER; + + const data: PagerDutyPayload = { event_action: eventAction, - dedup_key: dedupKey, }; + if (params.dedupKey) { + data.dedup_key = params.dedupKey; + } // for acknowledge / resolve, just send the dedup key if (AcknowledgeOrResolve.has(eventAction)) { @@ -260,12 +275,8 @@ function getBodyForEventAction(actionId: string, params: ActionParamsType): unkn summary: params.summary || 'No summary provided.', source: params.source || `Kibana Action ${actionId}`, severity: params.severity || 'info', + ...omitBy(pick(params, ['timestamp', 'component', 'group', 'class']), isUndefined), }; - if (params.timestamp != null) data.payload.timestamp = params.timestamp; - if (params.component != null) data.payload.component = params.component; - if (params.group != null) data.payload.group = params.group; - if (params.class != null) data.payload.class = params.class; - return data; } diff --git a/x-pack/plugins/alerts/server/saved_objects/migrations.test.ts b/x-pack/plugins/alerts/server/saved_objects/migrations.test.ts index 1c1261ae3fa08c..10e1a9ae421b7d 100644 --- a/x-pack/plugins/alerts/server/saved_objects/migrations.test.ts +++ b/x-pack/plugins/alerts/server/saved_objects/migrations.test.ts @@ -85,6 +85,120 @@ describe('7.10.0', () => { }, }); }); + + test('migrates PagerDuty actions to set a default dedupkey of the AlertId', () => { + const migration710 = getMigrations(encryptedSavedObjectsSetup)['7.10.0']; + const alert = getMockData({ + actions: [ + { + actionTypeId: '.pagerduty', + group: 'default', + params: { + summary: 'fired {{alertInstanceId}}', + eventAction: 'resolve', + component: '', + }, + id: 'b62ea790-5366-4abc-a7df-33db1db78410', + }, + ], + }); + expect(migration710(alert, { log })).toMatchObject({ + ...alert, + attributes: { + ...alert.attributes, + actions: [ + { + actionTypeId: '.pagerduty', + group: 'default', + params: { + summary: 'fired {{alertInstanceId}}', + eventAction: 'resolve', + dedupKey: '{{alertId}}', + component: '', + }, + id: 'b62ea790-5366-4abc-a7df-33db1db78410', + }, + ], + }, + }); + }); + + test('skips PagerDuty actions with a specified dedupkey', () => { + const migration710 = getMigrations(encryptedSavedObjectsSetup)['7.10.0']; + const alert = getMockData({ + actions: [ + { + actionTypeId: '.pagerduty', + group: 'default', + params: { + summary: 'fired {{alertInstanceId}}', + eventAction: 'trigger', + dedupKey: '{{alertInstanceId}}', + component: '', + }, + id: 'b62ea790-5366-4abc-a7df-33db1db78410', + }, + ], + }); + expect(migration710(alert, { log })).toMatchObject({ + ...alert, + attributes: { + ...alert.attributes, + actions: [ + { + actionTypeId: '.pagerduty', + group: 'default', + params: { + summary: 'fired {{alertInstanceId}}', + eventAction: 'trigger', + dedupKey: '{{alertInstanceId}}', + component: '', + }, + id: 'b62ea790-5366-4abc-a7df-33db1db78410', + }, + ], + }, + }); + }); + + test('skips PagerDuty actions with an eventAction of "trigger"', () => { + const migration710 = getMigrations(encryptedSavedObjectsSetup)['7.10.0']; + const alert = getMockData({ + actions: [ + { + actionTypeId: '.pagerduty', + group: 'default', + params: { + summary: 'fired {{alertInstanceId}}', + eventAction: 'trigger', + component: '', + }, + id: 'b62ea790-5366-4abc-a7df-33db1db78410', + }, + ], + }); + expect(migration710(alert, { log })).toEqual({ + ...alert, + attributes: { + ...alert.attributes, + meta: { + versionApiKeyLastmodified: 'pre-7.10.0', + }, + actions: [ + { + actionTypeId: '.pagerduty', + group: 'default', + params: { + summary: 'fired {{alertInstanceId}}', + eventAction: 'trigger', + component: '', + }, + id: 'b62ea790-5366-4abc-a7df-33db1db78410', + }, + ], + }, + }); + }); }); describe('7.10.0 migrates with failure', () => { diff --git a/x-pack/plugins/alerts/server/saved_objects/migrations.ts b/x-pack/plugins/alerts/server/saved_objects/migrations.ts index c88f4d786c2125..537c21e85c0bd7 100644 --- a/x-pack/plugins/alerts/server/saved_objects/migrations.ts +++ b/x-pack/plugins/alerts/server/saved_objects/migrations.ts @@ -18,10 +18,20 @@ import { export const LEGACY_LAST_MODIFIED_VERSION = 'pre-7.10.0'; +type AlertMigration = ( + doc: SavedObjectUnsanitizedDoc +) => SavedObjectUnsanitizedDoc; + export function getMigrations( encryptedSavedObjects: EncryptedSavedObjectsPluginSetup ): SavedObjectMigrationMap { - const migrationWhenRBACWasIntroduced = markAsLegacyAndChangeConsumer(encryptedSavedObjects); + const migrationWhenRBACWasIntroduced = encryptedSavedObjects.createMigration( + function shouldBeMigrated(doc): doc is SavedObjectUnsanitizedDoc { + // migrate all documents in 7.10 in order to add the "meta" RBAC field + return true; + }, + pipeMigrations(markAsLegacyAndChangeConsumer, setAlertIdAsDefaultDedupkeyOnPagerDutyActions) + ); return { '7.10.0': executeMigrationWithErrorHandling(migrationWhenRBACWasIntroduced, '7.10.0'), @@ -52,29 +62,55 @@ const consumersToChange: Map = new Map( [SIEM_APP_ID]: SIEM_SERVER_APP_ID, }) ); + function markAsLegacyAndChangeConsumer( - encryptedSavedObjects: EncryptedSavedObjectsPluginSetup -): SavedObjectMigrationFn { - return encryptedSavedObjects.createMigration( - function shouldBeMigrated(doc): doc is SavedObjectUnsanitizedDoc { - // migrate all documents in 7.10 in order to add the "meta" RBAC field - return true; + doc: SavedObjectUnsanitizedDoc +): SavedObjectUnsanitizedDoc { + const { + attributes: { consumer }, + } = doc; + return { + ...doc, + attributes: { + ...doc.attributes, + consumer: consumersToChange.get(consumer) ?? consumer, + // mark any alert predating 7.10 as a legacy alert + meta: { + versionApiKeyLastmodified: LEGACY_LAST_MODIFIED_VERSION, + }, }, - (doc: SavedObjectUnsanitizedDoc): SavedObjectUnsanitizedDoc => { - const { - attributes: { consumer }, - } = doc; - return { - ...doc, - attributes: { - ...doc.attributes, - consumer: consumersToChange.get(consumer) ?? consumer, - // mark any alert predating 7.10 as a legacy alert - meta: { - versionApiKeyLastmodified: LEGACY_LAST_MODIFIED_VERSION, - }, - }, - }; - } - ); + }; +} + +function setAlertIdAsDefaultDedupkeyOnPagerDutyActions( + doc: SavedObjectUnsanitizedDoc +): SavedObjectUnsanitizedDoc { + const { attributes } = doc; + return { + ...doc, + attributes: { + ...attributes, + ...(attributes.actions + ? { + actions: attributes.actions.map((action) => { + if (action.actionTypeId !== '.pagerduty' || action.params.eventAction === 'trigger') { + return action; + } + return { + ...action, + params: { + ...action.params, + dedupKey: action.params.dedupKey ?? '{{alertId}}', + }, + }; + }), + } + : {}), + }, + }; +} + +function pipeMigrations(...migrations: AlertMigration[]): AlertMigration { + return (doc: SavedObjectUnsanitizedDoc) => + migrations.reduce((migratedDoc, nextMigration) => nextMigration(migratedDoc), doc); } diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.test.tsx index 0674e5b35c61fb..059bae6e3ebff6 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.test.tsx @@ -91,6 +91,7 @@ describe('pagerduty action params validation', () => { expect(actionTypeModel.validateParams(actionParams)).toEqual({ errors: { + dedupKey: [], summary: [], timestamp: [], }, diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.tsx index 90d8da346c71d4..03bfbb38da6f2b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty.tsx @@ -50,8 +50,22 @@ export function getActionType(): ActionTypeModel { const errors = { summary: new Array(), timestamp: new Array(), + dedupKey: new Array(), }; validationResult.errors = errors; + if ( + !actionParams.dedupKey?.length && + (actionParams.eventAction === 'resolve' || actionParams.eventAction === 'acknowledge') + ) { + errors.dedupKey.push( + i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.error.requiredDedupKeyText', + { + defaultMessage: 'DedupKey is required when resolving or acknowledging an incident.', + } + ) + ); + } if (!actionParams.summary?.length) { errors.summary.push( i18n.translate( diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx index 6a11dc8d0d6a51..fe83054edbe07c 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx @@ -26,7 +26,7 @@ describe('PagerDutyParamsFields renders', () => { const wrapper = mountWithIntl( {}} index={0} docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.tsx index c8ad5f5b7080e8..39800865ed761b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.tsx @@ -94,6 +94,9 @@ const PagerDutyParamsFields: React.FunctionComponent @@ -144,12 +147,23 @@ const PagerDutyParamsFields: React.FunctionComponent 0} + label={ + isDedupeKeyRequired + ? i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextRequiredFieldLabel', + { + defaultMessage: 'DedupKey', + } + ) + : i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.pagerDutyAction.dedupKeyTextFieldLabel', + { + defaultMessage: 'DedupKey (optional)', + } + ) + } > > { const { body } = req; - let dedupKey = body && body.dedup_key; - const summary = body && body.payload && body.payload.summary; - - if (dedupKey == null) { - dedupKey = `kibana-ft-simulator-dedup-key-${new Date().toISOString()}`; - } + const summary = body?.payload?.summary; switch (summary) { case 'respond-with-429': @@ -67,7 +62,7 @@ export function initPlugin(router: IRouter, path: string) { return jsonResponse(res, 202, { status: 'success', message: 'Event processed', - dedup_key: dedupKey, + ...(body?.dedup_key ? { dedup_key: body?.dedup_key } : {}), }); } ); diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/pagerduty.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/pagerduty.ts index 0c4d9096aa31ab..caa18846360077 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/pagerduty.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/actions/builtin_action_types/pagerduty.ts @@ -163,7 +163,6 @@ export default function pagerdutyTest({ getService }: FtrProviderContext) { status: 'ok', actionId: simulatedActionId, data: { - dedup_key: `action:${simulatedActionId}`, message: 'Event processed', status: 'success', }, diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts index 81f7c8c97ba8cc..17070a14069ce5 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts @@ -39,5 +39,48 @@ export default function createGetTests({ getService }: FtrProviderContext) { expect(response.status).to.eql(200); expect(response.body.consumer).to.equal('infrastructure'); }); + + it('7.10.0 migrates PagerDuty actions to have a default dedupKey', async () => { + const response = await supertest.get( + `${getUrlPrefix(``)}/api/alerts/alert/b6087f72-994f-46fb-8120-c6e5c50d0f8f` + ); + + expect(response.status).to.eql(200); + + expect(response.body.actions).to.eql([ + { + actionTypeId: '.pagerduty', + id: 'a6a8ab7a-35cf-445e-ade3-215a029c2ee3', + group: 'default', + params: { + component: '', + eventAction: 'trigger', + summary: 'fired {{alertInstanceId}}', + }, + }, + { + actionTypeId: '.pagerduty', + id: 'a6a8ab7a-35cf-445e-ade3-215a029c2ee3', + group: 'default', + params: { + component: '', + dedupKey: '{{alertId}}', + eventAction: 'resolve', + summary: 'fired {{alertInstanceId}}', + }, + }, + { + actionTypeId: '.pagerduty', + id: 'a6a8ab7a-35cf-445e-ade3-215a029c2ee3', + group: 'default', + params: { + component: '', + dedupKey: '{{alertInstanceId}}', + eventAction: 'resolve', + summary: 'fired {{alertInstanceId}}', + }, + }, + ]); + }); }); } diff --git a/x-pack/test/functional/es_archives/alerts/data.json b/x-pack/test/functional/es_archives/alerts/data.json index cc246b0fe44da4..4e879116d8cda5 100644 --- a/x-pack/test/functional/es_archives/alerts/data.json +++ b/x-pack/test/functional/es_archives/alerts/data.json @@ -80,4 +80,115 @@ "updated_at": "2020-06-17T15:35:39.839Z" } } +} + +{ + "type": "doc", + "value": { + "id": "action:a6a8ab7a-35cf-445e-ade3-215a029c2ee3", + "index": ".kibana_1", + "source": { + "action": { + "actionTypeId": ".pagerduty", + "config": { + "apiUrl": "http://elastic:changeme@localhost:5620/api/_actions-FTS-external-service-simulators/pagerduty" + }, + "name": "A pagerduty action", + "secrets": "kvjaTWYKGmCqptyv4giaN+nQGgsZrKXmlULcbAP8KK3JmR8Ei9ADqh5mB+uVC+x+Q7/vTQ5SKZCj3dHv3pmNzZ5WGyZYQFBaaa63Mkp3kIcnpE1OdSAv+3Z/Y+XihHAM19zUm3JRpojnIpYegoS5/vMx1sOzcf/+miYUuZw2lgo0lNE=" + }, + "references": [ + ], + "type": "action", + "updated_at": "2020-09-22T15:16:06.924Z" + } + } +} + +{ + "type": "doc", + "value": { + "id": "alert:b6087f72-994f-46fb-8120-c6e5c50d0f8f", + "index": ".kibana_1", + "source": { + "alert": { + "actions": [ + { + "actionRef": "action_0", + "actionTypeId": ".pagerduty", + "group": "default", + "params": { + "component": "", + "eventAction": "trigger", + "summary": "fired {{alertInstanceId}}" + } + }, + { + "actionRef": "action_1", + "actionTypeId": ".pagerduty", + "group": "default", + "params": { + "component": "", + "eventAction": "resolve", + "summary": "fired {{alertInstanceId}}" + } + }, + { + "actionRef": "action_2", + "actionTypeId": ".pagerduty", + "group": "default", + "params": { + "component": "", + "dedupKey": "{{alertInstanceId}}", + "eventAction": "resolve", + "summary": "fired {{alertInstanceId}}" + } + } + ], + "alertTypeId": "test.noop", + "apiKey": null, + "apiKeyOwner": null, + "consumer": "alertsFixture", + "createdAt": "2020-09-22T15:16:07.451Z", + "createdBy": null, + "enabled": true, + "muteAll": false, + "mutedInstanceIds": [ + ], + "name": "abc", + "params": { + }, + "schedule": { + "interval": "1m" + }, + "scheduledTaskId": "8a7c6ff0-fce6-11ea-a888-9337d77a2c25", + "tags": [ + "foo" + ], + "throttle": "1m", + "updatedBy": null + }, + "migrationVersion": { + "alert": "7.9.0" + }, + "references": [ + { + "id": "a6a8ab7a-35cf-445e-ade3-215a029c2ee3", + "name": "action_0", + "type": "action" + }, + { + "id": "a6a8ab7a-35cf-445e-ade3-215a029c2ee3", + "name": "action_1", + "type": "action" + }, + { + "id": "a6a8ab7a-35cf-445e-ade3-215a029c2ee3", + "name": "action_2", + "type": "action" + } + ], + "type": "alert", + "updated_at": "2020-09-22T15:16:08.456Z" + } + } } \ No newline at end of file From 8374f136523cc307fe3b6829b2bddbc553cd3bd3 Mon Sep 17 00:00:00 2001 From: Steph Milovic Date: Mon, 28 Sep 2020 07:59:18 -0600 Subject: [PATCH 05/19] [Security Solution] [ALL] Eliminates all console.error and console.warn from Jest output (#78523) --- .../components/add_comment/index.test.tsx | 3 +- .../cases/components/all_cases/index.test.tsx | 267 +++++----- .../components/all_cases_modal/index.test.tsx | 45 +- .../cases/components/case_view/index.test.tsx | 161 +++--- .../cases/components/create/index.test.tsx | 22 +- .../components/edit_connector/index.test.tsx | 37 +- .../cases/components/tag_list/index.test.tsx | 43 +- .../user_action_tree/index.test.tsx | 261 +++++----- .../index.test.tsx | 59 +-- .../autocomplete/field_value_lists.test.tsx | 3 +- .../components/autocomplete/helpers.test.ts | 4 +- .../components/charts/barchart.test.tsx | 19 +- .../charts/draggable_legend.test.tsx | 15 +- .../charts/draggable_legend_item.test.tsx | 14 +- .../drag_and_drop/draggable_wrapper.test.tsx | 16 +- .../draggable_wrapper_hover_content.test.tsx | 16 - .../components/endpoint/link_to_app.test.tsx | 26 +- .../event_details/event_details.test.tsx | 11 +- .../components/events_viewer/index.test.tsx | 3 +- .../add_exception_modal/index.test.tsx | 35 +- .../exceptions/builder/index.test.tsx | 2 +- .../edit_exception_modal/index.test.tsx | 37 +- .../components/last_event_time/index.test.tsx | 4 +- .../common/components/link_icon/index.tsx | 57 ++- .../components/ml/entity_draggable.test.tsx | 1 - .../ml/score/anomaly_score.test.tsx | 1 - .../ml/score/anomaly_scores.test.tsx | 1 - .../get_anomalies_host_table_columns.test.tsx | 1 - ...t_anomalies_network_table_columns.test.tsx | 1 - .../ml_popover/jobs_table/job_switch.test.tsx | 16 +- .../ml_popover/jobs_table/jobs_table.test.tsx | 7 +- .../components/query_bar/index.test.tsx | 43 +- .../components/sourcerer/index.test.tsx | 9 +- .../common/components/tables/helpers.test.tsx | 1 - .../common/components/top_n/index.test.tsx | 24 +- .../common/components/top_n/top_n.test.tsx | 56 +-- .../components/url_state/index.test.tsx | 3 +- .../common/lib/kibana/kibana_react.mock.ts | 53 +- .../public/common/mock/formatted_relative.ts | 15 + .../public/common/mock/react_beautiful_dnd.ts | 53 ++ .../public/common/mock/test_providers.tsx | 2 +- .../rules/step_about_rule/index.test.tsx | 137 ++--- .../form.test.tsx | 4 +- .../modal.test.tsx | 16 +- .../detection_engine.test.tsx | 9 +- .../detection_engine/rules/all/index.test.tsx | 23 +- .../rules/details/index.test.tsx | 8 +- .../detection_engine/rules/helpers.test.tsx | 4 +- .../first_last_seen_host/index.test.tsx | 77 +-- .../store/endpoint_pagination.test.ts | 4 + .../endpoint_hosts/store/middleware.test.ts | 3 +- .../pages/endpoint_hosts/view/index.test.tsx | 23 +- .../public/management/pages/index.test.tsx | 11 + .../public/management/pages/index.tsx | 14 +- .../public/network/pages/network.test.tsx | 26 +- .../alerts_by_category/index.test.tsx | 4 +- .../endpoint_overview/index.test.tsx | 1 + .../public/resolver/view/use_camera.test.tsx | 18 +- .../fields_browser/category.test.tsx | 1 - .../fields_browser/field_name.test.tsx | 16 +- .../components/fields_browser/index.test.tsx | 60 +-- .../components/flyout/index.test.tsx | 1 + .../components/notes/note_card/index.test.tsx | 1 + .../notes/note_card/note_card_header.test.tsx | 1 + .../notes/note_card/note_created.test.tsx | 1 + .../notes/note_cards/index.test.tsx | 1 + .../components/open_timeline/index.test.tsx | 4 +- .../note_previews/index.test.tsx | 1 + .../note_previews/note_preview.test.tsx | 1 + .../open_timeline/open_timeline.test.tsx | 10 +- .../open_timeline_modal_body.test.tsx | 2 +- .../open_timeline_modal_button.test.tsx | 3 +- .../timelines_table/common_columns.test.tsx | 1 + .../header_tooltip_content/index.tsx | 3 +- .../components/timeline/body/index.test.tsx | 19 +- .../timeline/properties/index.test.tsx | 28 +- .../properties/use_create_timeline.test.tsx | 4 +- .../timeline/query_bar/index.test.tsx | 16 - .../selectable_timeline/index.test.tsx | 33 +- .../public/timelines/containers/api.test.ts | 472 ++++-------------- .../timeline/epic_local_storage.test.tsx | 2 +- 81 files changed, 1126 insertions(+), 1384 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/common/mock/formatted_relative.ts create mode 100644 x-pack/plugins/security_solution/public/common/mock/react_beautiful_dnd.ts diff --git a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.test.tsx index a800bd690f7109..a85d7a310bc068 100644 --- a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.test.tsx @@ -17,8 +17,7 @@ import { usePostComment } from '../../containers/use_post_comment'; import { useForm } from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form'; import { useFormData } from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form_data'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; jest.mock( '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form' diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx index e6e0823214195c..e301e80c9561d5 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { mount } from 'enzyme'; import moment from 'moment-timezone'; - +import { waitFor } from '@testing-library/react'; import '../../../common/mock/match_media'; import { AllCases } from '.'; import { TestProviders } from '../../../common/mock'; @@ -85,16 +85,6 @@ describe('AllCases', () => { let navigateToApp: jest.Mock; - /* eslint-disable no-console */ - // Silence until enzyme fixed to use ReactTestUtils.act() - const originalError = console.error; - beforeAll(() => { - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - }); - /* eslint-enable no-console */ beforeEach(() => { jest.clearAllMocks(); navigateToApp = jest.fn(); @@ -106,36 +96,38 @@ describe('AllCases', () => { moment.tz.setDefault('UTC'); }); - it('should render AllCases', () => { + it('should render AllCases', async () => { const wrapper = mount( ); - expect(wrapper.find(`a[data-test-subj="case-details-link"]`).first().prop('href')).toEqual( - `/${useGetCasesMockState.data.cases[0].id}` - ); - expect(wrapper.find(`a[data-test-subj="case-details-link"]`).first().text()).toEqual( - useGetCasesMockState.data.cases[0].title - ); - expect( - wrapper.find(`span[data-test-subj="case-table-column-tags-0"]`).first().prop('title') - ).toEqual(useGetCasesMockState.data.cases[0].tags[0]); - expect(wrapper.find(`[data-test-subj="case-table-column-createdBy"]`).first().text()).toEqual( - useGetCasesMockState.data.cases[0].createdBy.fullName - ); - expect( - wrapper - .find(`[data-test-subj="case-table-column-createdAt"]`) - .first() - .childAt(0) - .prop('value') - ).toBe(useGetCasesMockState.data.cases[0].createdAt); - expect(wrapper.find(`[data-test-subj="case-table-case-count"]`).first().text()).toEqual( - 'Showing 10 cases' - ); + await waitFor(() => { + expect(wrapper.find(`a[data-test-subj="case-details-link"]`).first().prop('href')).toEqual( + `/${useGetCasesMockState.data.cases[0].id}` + ); + expect(wrapper.find(`a[data-test-subj="case-details-link"]`).first().text()).toEqual( + useGetCasesMockState.data.cases[0].title + ); + expect( + wrapper.find(`span[data-test-subj="case-table-column-tags-0"]`).first().prop('title') + ).toEqual(useGetCasesMockState.data.cases[0].tags[0]); + expect(wrapper.find(`[data-test-subj="case-table-column-createdBy"]`).first().text()).toEqual( + useGetCasesMockState.data.cases[0].createdBy.fullName + ); + expect( + wrapper + .find(`[data-test-subj="case-table-column-createdAt"]`) + .first() + .childAt(0) + .prop('value') + ).toBe(useGetCasesMockState.data.cases[0].createdAt); + expect(wrapper.find(`[data-test-subj="case-table-case-count"]`).first().text()).toEqual( + 'Showing 10 cases' + ); + }); }); - it('should render empty fields', () => { + it('should render empty fields', async () => { useGetCasesMock.mockReturnValue({ ...defaultGetCases, data: { @@ -166,53 +158,63 @@ describe('AllCases', () => { expect(column.find('.euiTableRowCell--hideForDesktop').text()).toEqual(columnName); expect(column.find('span').text()).toEqual(emptyTag); }; - getCasesColumns([], 'open', false).map((i, key) => i.name != null && checkIt(`${i.name}`, key)); + await waitFor(() => { + getCasesColumns([], 'open', false).map( + (i, key) => i.name != null && checkIt(`${i.name}`, key) + ); + }); }); - it('should not render case link or actions on modal=true', () => { + it('should not render case link or actions on modal=true', async () => { const wrapper = mount( ); - const checkIt = (columnName: string) => { - expect(columnName).not.toEqual(i18n.ACTIONS); - }; - getCasesColumns([], 'open', true).map((i, key) => i.name != null && checkIt(`${i.name}`)); - expect(wrapper.find(`a[data-test-subj="case-details-link"]`).exists()).toBeFalsy(); + await waitFor(() => { + const checkIt = (columnName: string) => { + expect(columnName).not.toEqual(i18n.ACTIONS); + }; + getCasesColumns([], 'open', true).map((i, key) => i.name != null && checkIt(`${i.name}`)); + expect(wrapper.find(`a[data-test-subj="case-details-link"]`).exists()).toBeFalsy(); + }); }); - it('should tableHeaderSortButton AllCases', () => { + it('should tableHeaderSortButton AllCases', async () => { const wrapper = mount( ); - wrapper.find('[data-test-subj="tableHeaderSortButton"]').first().simulate('click'); - expect(setQueryParams).toBeCalledWith({ - page: 1, - perPage: 5, - sortField: 'createdAt', - sortOrder: 'asc', + await waitFor(() => { + wrapper.find('[data-test-subj="tableHeaderSortButton"]').first().simulate('click'); + expect(setQueryParams).toBeCalledWith({ + page: 1, + perPage: 5, + sortField: 'createdAt', + sortOrder: 'asc', + }); }); }); - it('closes case when row action icon clicked', () => { + it('closes case when row action icon clicked', async () => { const wrapper = mount( ); - wrapper.find('[data-test-subj="action-close"]').first().simulate('click'); - const firstCase = useGetCasesMockState.data.cases[0]; - expect(dispatchUpdateCaseProperty).toBeCalledWith({ - caseId: firstCase.id, - updateKey: 'status', - updateValue: 'closed', - refetchCasesStatus: fetchCasesStatus, - version: firstCase.version, + await waitFor(() => { + wrapper.find('[data-test-subj="action-close"]').first().simulate('click'); + const firstCase = useGetCasesMockState.data.cases[0]; + expect(dispatchUpdateCaseProperty).toBeCalledWith({ + caseId: firstCase.id, + updateKey: 'status', + updateValue: 'closed', + refetchCasesStatus: fetchCasesStatus, + version: firstCase.version, + }); }); }); - it('opens case when row action icon clicked', () => { + it('opens case when row action icon clicked', async () => { useGetCasesMock.mockReturnValue({ ...defaultGetCases, filterOptions: { ...defaultGetCases.filterOptions, status: 'closed' }, @@ -223,17 +225,19 @@ describe('AllCases', () => { ); - wrapper.find('[data-test-subj="action-open"]').first().simulate('click'); - const firstCase = useGetCasesMockState.data.cases[0]; - expect(dispatchUpdateCaseProperty).toBeCalledWith({ - caseId: firstCase.id, - updateKey: 'status', - updateValue: 'open', - refetchCasesStatus: fetchCasesStatus, - version: firstCase.version, + await waitFor(() => { + wrapper.find('[data-test-subj="action-open"]').first().simulate('click'); + const firstCase = useGetCasesMockState.data.cases[0]; + expect(dispatchUpdateCaseProperty).toBeCalledWith({ + caseId: firstCase.id, + updateKey: 'status', + updateValue: 'open', + refetchCasesStatus: fetchCasesStatus, + version: firstCase.version, + }); }); }); - it('Bulk delete', () => { + it('Bulk delete', async () => { useGetCasesMock.mockReturnValue({ ...defaultGetCases, selectedCases: useGetCasesMockState.data.cases, @@ -254,21 +258,23 @@ describe('AllCases', () => { ); - wrapper.find('[data-test-subj="case-table-bulk-actions"] button').first().simulate('click'); - wrapper.find('[data-test-subj="cases-bulk-delete-button"]').first().simulate('click'); - expect(handleToggleModal).toBeCalled(); + await waitFor(() => { + wrapper.find('[data-test-subj="case-table-bulk-actions"] button').first().simulate('click'); + wrapper.find('[data-test-subj="cases-bulk-delete-button"]').first().simulate('click'); + expect(handleToggleModal).toBeCalled(); - wrapper - .find( - '[data-test-subj="confirm-delete-case-modal"] [data-test-subj="confirmModalConfirmButton"]' - ) - .last() - .simulate('click'); - expect(handleOnDeleteConfirm.mock.calls[0][0]).toStrictEqual( - useGetCasesMockState.data.cases.map(({ id }) => ({ id })) - ); + wrapper + .find( + '[data-test-subj="confirm-delete-case-modal"] [data-test-subj="confirmModalConfirmButton"]' + ) + .last() + .simulate('click'); + expect(handleOnDeleteConfirm.mock.calls[0][0]).toStrictEqual( + useGetCasesMockState.data.cases.map(({ id }) => ({ id })) + ); + }); }); - it('Bulk close status update', () => { + it('Bulk close status update', async () => { useGetCasesMock.mockReturnValue({ ...defaultGetCases, selectedCases: useGetCasesMockState.data.cases, @@ -279,11 +285,13 @@ describe('AllCases', () => { ); - wrapper.find('[data-test-subj="case-table-bulk-actions"] button').first().simulate('click'); - wrapper.find('[data-test-subj="cases-bulk-close-button"]').first().simulate('click'); - expect(updateBulkStatus).toBeCalledWith(useGetCasesMockState.data.cases, 'closed'); + await waitFor(() => { + wrapper.find('[data-test-subj="case-table-bulk-actions"] button').first().simulate('click'); + wrapper.find('[data-test-subj="cases-bulk-close-button"]').first().simulate('click'); + expect(updateBulkStatus).toBeCalledWith(useGetCasesMockState.data.cases, 'closed'); + }); }); - it('Bulk open status update', () => { + it('Bulk open status update', async () => { useGetCasesMock.mockReturnValue({ ...defaultGetCases, selectedCases: useGetCasesMockState.data.cases, @@ -298,11 +306,13 @@ describe('AllCases', () => { ); - wrapper.find('[data-test-subj="case-table-bulk-actions"] button').first().simulate('click'); - wrapper.find('[data-test-subj="cases-bulk-open-button"]').first().simulate('click'); - expect(updateBulkStatus).toBeCalledWith(useGetCasesMockState.data.cases, 'open'); + await waitFor(() => { + wrapper.find('[data-test-subj="case-table-bulk-actions"] button').first().simulate('click'); + wrapper.find('[data-test-subj="cases-bulk-open-button"]').first().simulate('click'); + expect(updateBulkStatus).toBeCalledWith(useGetCasesMockState.data.cases, 'open'); + }); }); - it('isDeleted is true, refetch', () => { + it('isDeleted is true, refetch', async () => { useDeleteCasesMock.mockReturnValue({ ...defaultDeleteCases, isDeleted: true, @@ -313,11 +323,13 @@ describe('AllCases', () => { ); - expect(refetchCases).toBeCalled(); - expect(fetchCasesStatus).toBeCalled(); - expect(dispatchResetIsDeleted).toBeCalled(); + await waitFor(() => { + expect(refetchCases).toBeCalled(); + expect(fetchCasesStatus).toBeCalled(); + expect(dispatchResetIsDeleted).toBeCalled(); + }); }); - it('isUpdated is true, refetch', () => { + it('isUpdated is true, refetch', async () => { useUpdateCasesMock.mockReturnValue({ ...defaultUpdateCases, isUpdated: true, @@ -328,42 +340,51 @@ describe('AllCases', () => { ); - expect(refetchCases).toBeCalled(); - expect(fetchCasesStatus).toBeCalled(); - expect(dispatchResetIsUpdated).toBeCalled(); + await waitFor(() => { + expect(refetchCases).toBeCalled(); + expect(fetchCasesStatus).toBeCalled(); + expect(dispatchResetIsUpdated).toBeCalled(); + }); }); - it('should not render header when modal=true', () => { + it('should not render header when modal=true', async () => { const wrapper = mount( ); - - expect(wrapper.find('[data-test-subj="all-cases-header"]').exists()).toBe(false); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="all-cases-header"]').exists()).toBe(false); + }); }); - it('should not render table utility bar when modal=true', () => { + it('should not render table utility bar when modal=true', async () => { const wrapper = mount( ); - - expect(wrapper.find('[data-test-subj="case-table-utility-bar-actions"]').exists()).toBe(false); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="case-table-utility-bar-actions"]').exists()).toBe( + false + ); + }); }); - it('case table should not be selectable when modal=true', () => { + it('case table should not be selectable when modal=true', async () => { const wrapper = mount( ); - - expect(wrapper.find('[data-test-subj="cases-table"]').first().prop('isSelectable')).toBe(false); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="cases-table"]').first().prop('isSelectable')).toBe( + false + ); + }); }); - it('should call onRowClick with no cases and modal=true', () => { + it('should call onRowClick with no cases and modal=true', async () => { useGetCasesMock.mockReturnValue({ ...defaultGetCases, data: { @@ -378,12 +399,13 @@ describe('AllCases', () => { ); - - wrapper.find('[data-test-subj="cases-table-add-case"]').first().simulate('click'); - expect(onRowClick).toHaveBeenCalled(); + await waitFor(() => { + wrapper.find('[data-test-subj="cases-table-add-case"]').first().simulate('click'); + expect(onRowClick).toHaveBeenCalled(); + }); }); - it('should call navigateToApp with no cases and modal=false', () => { + it('should call navigateToApp with no cases and modal=false', async () => { useGetCasesMock.mockReturnValue({ ...defaultGetCases, data: { @@ -398,30 +420,33 @@ describe('AllCases', () => { ); - - wrapper.find('[data-test-subj="cases-table-add-case"]').first().simulate('click'); - expect(navigateToApp).toHaveBeenCalledWith('securitySolution:case', { path: '/create' }); + await waitFor(() => { + wrapper.find('[data-test-subj="cases-table-add-case"]').first().simulate('click'); + expect(navigateToApp).toHaveBeenCalledWith('securitySolution:case', { path: '/create' }); + }); }); - it('should call onRowClick when clicking a case with modal=true', () => { + it('should call onRowClick when clicking a case with modal=true', async () => { const wrapper = mount( ); - - wrapper.find('[data-test-subj="cases-table-row-1"]').first().simulate('click'); - expect(onRowClick).toHaveBeenCalledWith('1'); + await waitFor(() => { + wrapper.find('[data-test-subj="cases-table-row-1"]').first().simulate('click'); + expect(onRowClick).toHaveBeenCalledWith('1'); + }); }); - it('should NOT call onRowClick when clicking a case with modal=true', () => { + it('should NOT call onRowClick when clicking a case with modal=true', async () => { const wrapper = mount( ); - - wrapper.find('[data-test-subj="cases-table-row-1"]').first().simulate('click'); - expect(onRowClick).not.toHaveBeenCalled(); + await waitFor(() => { + wrapper.find('[data-test-subj="cases-table-row-1"]').first().simulate('click'); + expect(onRowClick).not.toHaveBeenCalled(); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx index b93de014f5c188..725759068a3eac 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx @@ -5,6 +5,7 @@ */ import { mount } from 'enzyme'; import React from 'react'; +import { waitFor } from '@testing-library/react'; import '../../../common/mock/match_media'; import { AllCasesModal } from '.'; import { TestProviders } from '../../../common/mock'; @@ -96,16 +97,6 @@ describe('AllCasesModal', () => { dispatchResetIsUpdated, updateBulkStatus, }; - /* eslint-disable no-console */ - // Silence until enzyme fixed to use ReactTestUtils.act() - const originalError = console.error; - beforeAll(() => { - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - }); - /* eslint-enable no-console */ beforeEach(() => { jest.resetAllMocks(); useUpdateCasesMock.mockImplementation(() => defaultUpdateCases); @@ -114,41 +105,49 @@ describe('AllCasesModal', () => { useGetCasesStatusMock.mockImplementation(() => defaultCasesStatus); }); - it('renders with unselectable rows', () => { + it('renders with unselectable rows', async () => { const wrapper = mount( ); - expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeTruthy(); - expect(wrapper.find(EuiTableRow).first().prop('isSelectable')).toBeFalsy(); + await waitFor(() => { + expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeTruthy(); + expect(wrapper.find(EuiTableRow).first().prop('isSelectable')).toBeFalsy(); + }); }); - it('does not render modal if showCaseModal: false', () => { + it('does not render modal if showCaseModal: false', async () => { const wrapper = mount( ); - expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeFalsy(); + await waitFor(() => { + expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeFalsy(); + }); }); - it('onRowClick called when row is clicked', () => { + it('onRowClick called when row is clicked', async () => { const wrapper = mount( ); - const firstRow = wrapper.find(EuiTableRow).first(); - firstRow.simulate('click'); - expect(onRowClick.mock.calls[0][0]).toEqual(basicCaseId); + await waitFor(() => { + const firstRow = wrapper.find(EuiTableRow).first(); + firstRow.simulate('click'); + expect(onRowClick.mock.calls[0][0]).toEqual(basicCaseId); + }); }); - it('Closing modal calls onCloseCaseModal', () => { + it('Closing modal calls onCloseCaseModal', async () => { const wrapper = mount( ); - const modalClose = wrapper.find('.euiModal__closeIcon').first(); - modalClose.simulate('click'); - expect(onCloseCaseModal).toBeCalled(); + await waitFor(() => { + const modalClose = wrapper.find('.euiModal__closeIcon').first(); + modalClose.simulate('click'); + expect(onCloseCaseModal).toBeCalled(); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx index 246df1c94b8171..3859b4527991b9 100644 --- a/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx @@ -15,9 +15,7 @@ import { TestProviders } from '../../../common/mock'; import { useUpdateCase } from '../../containers/use_update_case'; import { useGetCase } from '../../containers/use_get_case'; import { useGetCaseUserActions } from '../../containers/use_get_case_user_actions'; - -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { useConnectors } from '../../containers/configure/use_connectors'; import { connectorsMock } from '../../containers/configure/mock'; @@ -29,6 +27,7 @@ jest.mock('../../containers/use_get_case_user_actions'); jest.mock('../../containers/use_get_case'); jest.mock('../../containers/configure/use_connectors'); jest.mock('../../containers/use_post_push_to_service'); +jest.mock('../user_action_tree/user_action_timestamp'); const useUpdateCaseMock = useUpdateCase as jest.Mock; const useGetCaseUserActionsMock = useGetCaseUserActions as jest.Mock; @@ -63,16 +62,6 @@ describe('CaseView ', () => { updateCase, fetchCase, }; - /* eslint-disable no-console */ - // Silence until enzyme fixed to use ReactTestUtils.act() - const originalError = console.error; - beforeAll(() => { - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - }); - /* eslint-enable no-console */ const defaultUpdateCaseState = { isLoading: false, @@ -96,6 +85,7 @@ describe('CaseView ', () => { beforeEach(() => { jest.resetAllMocks(); useUpdateCaseMock.mockImplementation(() => defaultUpdateCaseState); + jest.spyOn(routeData, 'useLocation').mockReturnValue(mockLocation); useGetCaseUserActionsMock.mockImplementation(() => defaultUseGetCaseUserActions); usePostPushToServiceMock.mockImplementation(() => ({ isLoading: false, postPushToService })); @@ -191,7 +181,7 @@ describe('CaseView ', () => { }); }); - it('should display EditableTitle isLoading', () => { + it('should display EditableTitle isLoading', async () => { useUpdateCaseMock.mockImplementation(() => ({ ...defaultUpdateCaseState, isLoading: true, @@ -204,13 +194,17 @@ describe('CaseView ', () => { ); - expect(wrapper.find('[data-test-subj="editable-title-loading"]').first().exists()).toBeTruthy(); - expect( - wrapper.find('[data-test-subj="editable-title-edit-icon"]').first().exists() - ).toBeFalsy(); + await waitFor(() => { + expect( + wrapper.find('[data-test-subj="editable-title-loading"]').first().exists() + ).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="editable-title-edit-icon"]').first().exists() + ).toBeFalsy(); + }); }); - it('should display Toggle Status isLoading', () => { + it('should display Toggle Status isLoading', async () => { useUpdateCaseMock.mockImplementation(() => ({ ...defaultUpdateCaseState, isLoading: true, @@ -223,12 +217,14 @@ describe('CaseView ', () => { ); - expect( - wrapper.find('[data-test-subj="toggle-case-status"]').first().prop('isLoading') - ).toBeTruthy(); + await waitFor(() => { + expect( + wrapper.find('[data-test-subj="toggle-case-status"]').first().prop('isLoading') + ).toBeTruthy(); + }); }); - it('should display description isLoading', () => { + it('should display description isLoading', async () => { useUpdateCaseMock.mockImplementation(() => ({ ...defaultUpdateCaseState, isLoading: true, @@ -241,21 +237,25 @@ describe('CaseView ', () => { ); - expect( - wrapper - .find('[data-test-subj="description-action"] [data-test-subj="user-action-title-loading"]') - .first() - .exists() - ).toBeTruthy(); - expect( - wrapper - .find('[data-test-subj="description-action"] [data-test-subj="property-actions"]') - .first() - .exists() - ).toBeFalsy(); + await waitFor(() => { + expect( + wrapper + .find( + '[data-test-subj="description-action"] [data-test-subj="user-action-title-loading"]' + ) + .first() + .exists() + ).toBeTruthy(); + expect( + wrapper + .find('[data-test-subj="description-action"] [data-test-subj="property-actions"]') + .first() + .exists() + ).toBeFalsy(); + }); }); - it('should display tags isLoading', () => { + it('should display tags isLoading', async () => { useUpdateCaseMock.mockImplementation(() => ({ ...defaultUpdateCaseState, isLoading: true, @@ -268,16 +268,18 @@ describe('CaseView ', () => { ); - expect( - wrapper - .find('[data-test-subj="case-view-tag-list"] [data-test-subj="tag-list-loading"]') - .first() - .exists() - ).toBeTruthy(); - expect(wrapper.find('[data-test-subj="tag-list-edit"]').first().exists()).toBeFalsy(); + await waitFor(() => { + expect( + wrapper + .find('[data-test-subj="case-view-tag-list"] [data-test-subj="tag-list-loading"]') + .first() + .exists() + ).toBeTruthy(); + expect(wrapper.find('[data-test-subj="tag-list-edit"]').first().exists()).toBeFalsy(); + }); }); - it('should update title', () => { + it('should update title', async () => { const wrapper = mount( @@ -285,21 +287,23 @@ describe('CaseView ', () => { ); - const newTitle = 'The new title'; - wrapper.find(`[data-test-subj="editable-title-edit-icon"]`).first().simulate('click'); - wrapper.update(); - wrapper - .find(`[data-test-subj="editable-title-input-field"]`) - .last() - .simulate('change', { target: { value: newTitle } }); - - wrapper.update(); - wrapper.find(`[data-test-subj="editable-title-submit-btn"]`).first().simulate('click'); - - wrapper.update(); - const updateObject = updateCaseProperty.mock.calls[0][0]; - expect(updateObject.updateKey).toEqual('title'); - expect(updateObject.updateValue).toEqual(newTitle); + await waitFor(() => { + const newTitle = 'The new title'; + wrapper.find(`[data-test-subj="editable-title-edit-icon"]`).first().simulate('click'); + wrapper.update(); + wrapper + .find(`[data-test-subj="editable-title-input-field"]`) + .last() + .simulate('change', { target: { value: newTitle } }); + + wrapper.update(); + wrapper.find(`[data-test-subj="editable-title-submit-btn"]`).first().simulate('click'); + + wrapper.update(); + const updateObject = updateCaseProperty.mock.calls[0][0]; + expect(updateObject.updateKey).toEqual('title'); + expect(updateObject.updateValue).toEqual(newTitle); + }); }); it('should push updates on button click', async () => { @@ -329,7 +333,7 @@ describe('CaseView ', () => { }); }); - it('should return null if error', () => { + it('should return null if error', async () => { (useGetCase as jest.Mock).mockImplementation(() => ({ ...defaultGetCase, isError: true, @@ -346,10 +350,12 @@ describe('CaseView ', () => { ); - expect(wrapper).toEqual({}); + await waitFor(() => { + expect(wrapper).toEqual({}); + }); }); - it('should return spinner if loading', () => { + it('should return spinner if loading', async () => { (useGetCase as jest.Mock).mockImplementation(() => ({ ...defaultGetCase, isLoading: true, @@ -366,10 +372,12 @@ describe('CaseView ', () => { ); - expect(wrapper.find('[data-test-subj="case-view-loading"]').exists()).toBeTruthy(); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="case-view-loading"]').exists()).toBeTruthy(); + }); }); - it('should return case view when data is there', () => { + it('should return case view when data is there', async () => { (useGetCase as jest.Mock).mockImplementation(() => defaultGetCase); const wrapper = mount( @@ -383,10 +391,12 @@ describe('CaseView ', () => { ); - expect(wrapper.find('[data-test-subj="case-view-title"]').exists()).toBeTruthy(); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="case-view-title"]').exists()).toBeTruthy(); + }); }); - it('should refresh data on refresh', () => { + it('should refresh data on refresh', async () => { (useGetCase as jest.Mock).mockImplementation(() => defaultGetCase); const wrapper = mount( @@ -400,12 +410,14 @@ describe('CaseView ', () => { ); - wrapper.find('[data-test-subj="case-refresh"]').first().simulate('click'); - expect(fetchCaseUserActions).toBeCalledWith(caseProps.caseData.id); - expect(fetchCase).toBeCalled(); + await waitFor(() => { + wrapper.find('[data-test-subj="case-refresh"]').first().simulate('click'); + expect(fetchCaseUserActions).toBeCalledWith(caseProps.caseData.id); + expect(fetchCase).toBeCalled(); + }); }); - it('should disable the push button when connector is invalid', () => { + it('should disable the push button when connector is invalid', async () => { useGetCaseUserActionsMock.mockImplementation(() => ({ ...defaultUseGetCaseUserActions, hasDataToPush: true, @@ -424,10 +436,11 @@ describe('CaseView ', () => { ); - - expect( - wrapper.find('button[data-test-subj="push-to-external-service"]').first().prop('disabled') - ).toBeTruthy(); + await waitFor(() => { + expect( + wrapper.find('button[data-test-subj="push-to-external-service"]').first().prop('disabled') + ).toBeTruthy(); + }); }); it('should revert to the initial connector in case of failure', async () => { diff --git a/x-pack/plugins/security_solution/public/cases/components/create/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/create/index.test.tsx index 4f1e45ae7c1154..d27f00aacff2cb 100644 --- a/x-pack/plugins/security_solution/public/cases/components/create/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/create/index.test.tsx @@ -6,7 +6,6 @@ import React from 'react'; import { mount } from 'enzyme'; - import { Create } from '.'; import { TestProviders } from '../../../common/mock'; import { getFormMock } from '../__mock__/form'; @@ -19,9 +18,16 @@ import { useGetTags } from '../../containers/use_get_tags'; import { useForm } from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form'; import { useFormData } from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form_data'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; +jest.mock('@elastic/eui', () => { + const original = jest.requireActual('@elastic/eui'); + return { + ...original, + // eslint-disable-next-line react/display-name + EuiFieldText: () => , + }; +}); jest.mock('../../../timelines/components/timeline/insert_timeline_popover/use_insert_timeline'); jest.mock('../../containers/use_post_case'); @@ -74,16 +80,6 @@ const defaultPostCase = { postCase, }; describe('Create case', () => { - // Suppress warnings about "noSuggestions" prop - /* eslint-disable no-console */ - const originalError = console.error; - beforeAll(() => { - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - }); - /* eslint-enable no-console */ const fetchTags = jest.fn(); const formHookMock = getFormMock(sampleData); beforeEach(() => { diff --git a/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.test.tsx index e531b71e8c90c2..12d549a2f71a9a 100644 --- a/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.test.tsx @@ -11,9 +11,8 @@ import { EditConnector } from './index'; import { getFormMock, useFormMock } from '../__mock__/form'; import { TestProviders } from '../../../common/mock'; import { connectorsMock } from '../../containers/configure/mock'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; -import { act } from 'react-dom/test-utils'; +import { waitFor } from '@testing-library/react'; + jest.mock( '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form' ); @@ -67,10 +66,8 @@ describe('EditConnector ', () => { expect(wrapper.find(`[data-test-subj="edit-connectors-submit"]`).last().exists()).toBeTruthy(); - await act(async () => { - wrapper.find(`[data-test-subj="edit-connectors-submit"]`).last().simulate('click'); - await waitFor(() => expect(onSubmit.mock.calls[0][0]).toBe(sampleConnector)); - }); + wrapper.find(`[data-test-subj="edit-connectors-submit"]`).last().simulate('click'); + await waitFor(() => expect(onSubmit.mock.calls[0][0]).toBe(sampleConnector)); }); it('Revert to initial external service on error', async () => { @@ -90,12 +87,10 @@ describe('EditConnector ', () => { expect(wrapper.find(`[data-test-subj="edit-connectors-submit"]`).last().exists()).toBeTruthy(); - await act(async () => { - wrapper.find(`[data-test-subj="edit-connectors-submit"]`).last().simulate('click'); - await waitFor(() => { - wrapper.update(); - expect(formHookMock.setFieldValue).toHaveBeenCalledWith('connector', 'none'); - }); + wrapper.find(`[data-test-subj="edit-connectors-submit"]`).last().simulate('click'); + await waitFor(() => { + wrapper.update(); + expect(formHookMock.setFieldValue).toHaveBeenCalledWith('connector', 'none'); }); }); @@ -114,15 +109,13 @@ describe('EditConnector ', () => { wrapper.find('button[data-test-subj="dropdown-connector-servicenow-2"]').simulate('click'); wrapper.update(); - await act(async () => { - wrapper.find(`[data-test-subj="edit-connectors-cancel"]`).last().simulate('click'); - await waitFor(() => { - wrapper.update(); - expect(formHookMock.setFieldValue).toBeCalledWith( - 'connector', - defaultProps.selectedConnector - ); - }); + wrapper.find(`[data-test-subj="edit-connectors-cancel"]`).last().simulate('click'); + await waitFor(() => { + wrapper.update(); + expect(formHookMock.setFieldValue).toBeCalledWith( + 'connector', + defaultProps.selectedConnector + ); }); }); diff --git a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx index a60167a18762f9..013f7bd0a9ba7e 100644 --- a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.test.tsx @@ -6,13 +6,11 @@ import React from 'react'; import { mount } from 'enzyme'; -import { act } from 'react-dom/test-utils'; import { TagList } from '.'; import { getFormMock } from '../__mock__/form'; import { TestProviders } from '../../../common/mock'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { useForm } from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form'; import { useGetTags } from '../../containers/use_get_tags'; @@ -27,6 +25,14 @@ jest.mock( children({ tags: ['rad', 'dude'] }), }) ); +jest.mock('@elastic/eui', () => { + const original = jest.requireActual('@elastic/eui'); + return { + ...original, + // eslint-disable-next-line react/display-name + EuiFieldText: () => , + }; +}); const onSubmit = jest.fn(); const defaultProps = { disabled: false, @@ -36,16 +42,6 @@ const defaultProps = { }; describe('TagList ', () => { - // Suppress warnings about "noSuggestions" prop - /* eslint-disable no-console */ - const originalError = console.error; - beforeAll(() => { - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - }); - /* eslint-enable no-console */ const sampleTags = ['coke', 'pepsi']; const fetchTags = jest.fn(); const formHookMock = getFormMock({ tags: sampleTags }); @@ -78,10 +74,8 @@ describe('TagList ', () => { ); wrapper.find(`[data-test-subj="tag-list-edit-button"]`).last().simulate('click'); - await act(async () => { - wrapper.find(`[data-test-subj="edit-tags-submit"]`).last().simulate('click'); - await waitFor(() => expect(onSubmit).toBeCalledWith(sampleTags)); - }); + wrapper.find(`[data-test-subj="edit-tags-submit"]`).last().simulate('click'); + await waitFor(() => expect(onSubmit).toBeCalledWith(sampleTags)); }); it('Tag options render with new tags added', () => { @@ -96,7 +90,7 @@ describe('TagList ', () => { ).toEqual([{ label: 'coke' }, { label: 'pepsi' }, { label: 'rad' }, { label: 'dude' }]); }); - it('Cancels on cancel', async () => { + it('Cancels on cancel', () => { const props = { ...defaultProps, tags: ['pepsi'], @@ -109,14 +103,11 @@ describe('TagList ', () => { expect(wrapper.find(`[data-test-subj="tag-pepsi"]`).last().exists()).toBeTruthy(); wrapper.find(`[data-test-subj="tag-list-edit-button"]`).last().simulate('click'); - await act(async () => { - expect(wrapper.find(`[data-test-subj="tag-pepsi"]`).last().exists()).toBeFalsy(); - wrapper.find(`[data-test-subj="edit-tags-cancel"]`).last().simulate('click'); - await waitFor(() => { - wrapper.update(); - expect(wrapper.find(`[data-test-subj="tag-pepsi"]`).last().exists()).toBeTruthy(); - }); - }); + + expect(wrapper.find(`[data-test-subj="tag-pepsi"]`).last().exists()).toBeFalsy(); + wrapper.find(`[data-test-subj="edit-tags-cancel"]`).last().simulate('click'); + wrapper.update(); + expect(wrapper.find(`[data-test-subj="tag-pepsi"]`).last().exists()).toBeTruthy(); }); it('Renders disabled button', () => { diff --git a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/index.test.tsx index 0b376f26a1ae0b..4d9b7d030fec01 100644 --- a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/index.test.tsx @@ -7,7 +7,6 @@ import React from 'react'; import { mount } from 'enzyme'; import { waitFor } from '@testing-library/react'; -import { act } from 'react-dom/test-utils'; import { Router, routeData, mockHistory, mockLocation } from '../__mock__/router'; import { getFormMock, useFormMock, useFormDataMock } from '../__mock__/form'; @@ -33,6 +32,7 @@ const defaultProps = { }; const useUpdateCommentMock = useUpdateComment as jest.Mock; jest.mock('../../containers/use_update_comment'); +jest.mock('./user_action_timestamp'); const patchComment = jest.fn(); describe('UserActionTree ', () => { @@ -90,16 +90,14 @@ describe('UserActionTree ', () => { }, caseUserActions: ourActions, }; - - await act(async () => { - const wrapper = mount( - - - - - - ); - + const wrapper = mount( + + + + + + ); + await waitFor(() => { expect(wrapper.find(`[data-test-subj="top-footer"]`).exists()).toBeTruthy(); expect(wrapper.find(`[data-test-subj="bottom-footer"]`).exists()).toBeTruthy(); }); @@ -121,14 +119,14 @@ describe('UserActionTree ', () => { }, }; - await act(async () => { - const wrapper = mount( - - - - - - ); + const wrapper = mount( + + + + + + ); + await waitFor(() => { expect(wrapper.find(`[data-test-subj="top-footer"]`).exists()).toBeTruthy(); expect(wrapper.find(`[data-test-subj="bottom-footer"]`).exists()).toBeFalsy(); }); @@ -141,15 +139,15 @@ describe('UserActionTree ', () => { caseUserActions: ourActions, }; - await act(async () => { - const wrapper = mount( - - - - - - ); + const wrapper = mount( + + + + + + ); + await waitFor(() => { expect( wrapper .find(`[data-test-subj="comment-create-action-${props.data.comments[0].id}"]`) @@ -164,34 +162,32 @@ describe('UserActionTree ', () => { .first() .simulate('click'); - await waitFor(() => { - wrapper.update(); - expect( - wrapper - .find(`[data-test-subj="comment-create-action-${props.data.comments[0].id}"]`) - .first() - .hasClass('outlined') - ).toBeTruthy(); - }); + wrapper.update(); + expect( + wrapper + .find(`[data-test-subj="comment-create-action-${props.data.comments[0].id}"]`) + .first() + .hasClass('outlined') + ).toBeTruthy(); }); }); it('Switches to markdown when edit is clicked and back to panel when canceled', async () => { - await waitFor(() => { - const ourActions = [getUserAction(['comment'], 'create')]; - const props = { - ...defaultProps, - caseUserActions: ourActions, - }; - - const wrapper = mount( - - - - - - ); + const ourActions = [getUserAction(['comment'], 'create')]; + const props = { + ...defaultProps, + caseUserActions: ourActions, + }; + + const wrapper = mount( + + + + + + ); + await waitFor(() => { expect( wrapper .find( @@ -277,24 +273,22 @@ describe('UserActionTree ', () => { .first() .simulate('click'); - await act(async () => { - await waitFor(() => { - wrapper.update(); - expect( - wrapper - .find( - `[data-test-subj="comment-create-action-${props.data.comments[0].id}"] [data-test-subj="user-action-markdown-form"]` - ) - .exists() - ).toEqual(false); - expect(patchComment).toBeCalledWith({ - commentUpdate: sampleData.content, - caseId: props.data.id, - commentId: props.data.comments[0].id, - fetchUserActions, - updateCase, - version: props.data.comments[0].version, - }); + await waitFor(() => { + wrapper.update(); + expect( + wrapper + .find( + `[data-test-subj="comment-create-action-${props.data.comments[0].id}"] [data-test-subj="user-action-markdown-form"]` + ) + .exists() + ).toEqual(false); + expect(patchComment).toBeCalledWith({ + commentUpdate: sampleData.content, + caseId: props.data.id, + commentId: props.data.comments[0].id, + fetchUserActions, + updateCase, + version: props.data.comments[0].version, }); }); }); @@ -319,89 +313,86 @@ describe('UserActionTree ', () => { .first() .simulate('click'); - await act(async () => { - wrapper - .find(`[data-test-subj="description-action"] [data-test-subj="user-action-save-markdown"]`) - .first() - .simulate('click'); - }); - - wrapper.update(); + wrapper + .find(`[data-test-subj="description-action"] [data-test-subj="user-action-save-markdown"]`) + .first() + .simulate('click'); + await waitFor(() => { + wrapper.update(); - expect( - wrapper - .find(`[data-test-subj="description-action"] [data-test-subj="user-action-markdown-form"]`) - .exists() - ).toEqual(false); + expect( + wrapper + .find( + `[data-test-subj="description-action"] [data-test-subj="user-action-markdown-form"]` + ) + .exists() + ).toEqual(false); - expect(onUpdateField).toBeCalledWith({ key: 'description', value: sampleData.content }); + expect(onUpdateField).toBeCalledWith({ key: 'description', value: sampleData.content }); + }); }); it('quotes', async () => { - await act(async () => { - const commentData = { - comment: '', - }; - const setFieldValue = jest.fn(); - - const formHookMock = getFormMock(commentData); - useFormMock.mockImplementation(() => ({ form: { ...formHookMock, setFieldValue } })); - - const props = defaultProps; - const wrapper = mount( - - - - - - ); + const commentData = { + comment: '', + }; + const setFieldValue = jest.fn(); - wrapper - .find(`[data-test-subj="description-action"] [data-test-subj="property-actions-ellipses"]`) - .first() - .simulate('click'); + const formHookMock = getFormMock(commentData); + useFormMock.mockImplementation(() => ({ form: { ...formHookMock, setFieldValue } })); - await waitFor(() => { - wrapper.update(); + const props = defaultProps; + const wrapper = mount( + + + + + + ); - wrapper - .find(`[data-test-subj="description-action"] [data-test-subj="property-actions-quote"]`) - .first() - .simulate('click'); - }); + wrapper + .find(`[data-test-subj="description-action"] [data-test-subj="property-actions-ellipses"]`) + .first() + .simulate('click'); + + await waitFor(() => { + wrapper.update(); - expect(setFieldValue).toBeCalledWith('comment', `> ${props.data.description} \n`); + wrapper + .find(`[data-test-subj="description-action"] [data-test-subj="property-actions-quote"]`) + .first() + .simulate('click'); }); + + expect(setFieldValue).toBeCalledWith('comment', `> ${props.data.description} \n`); }); it('Outlines comment when url param is provided', async () => { const commentId = 'basic-comment-id'; jest.spyOn(routeData, 'useParams').mockReturnValue({ commentId }); - await act(async () => { - const ourActions = [getUserAction(['comment'], 'create')]; - const props = { - ...defaultProps, - caseUserActions: ourActions, - }; - - const wrapper = mount( - - - - - - ); - - await waitFor(() => { - wrapper.update(); - expect( - wrapper - .find(`[data-test-subj="comment-create-action-${commentId}"]`) - .first() - .hasClass('outlined') - ).toBeTruthy(); - }); + const ourActions = [getUserAction(['comment'], 'create')]; + const props = { + ...defaultProps, + caseUserActions: ourActions, + }; + + const wrapper = mount( + + + + + + ); + + await waitFor(() => { + wrapper.update(); + expect( + wrapper + .find(`[data-test-subj="comment-create-action-${commentId}"]`) + .first() + .hasClass('outlined') + ).toBeTruthy(); }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/add_filter_to_global_search_bar/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/add_filter_to_global_search_bar/index.test.tsx index eced73e9c3d679..c8e12adef656aa 100644 --- a/x-pack/plugins/security_solution/public/common/components/add_filter_to_global_search_bar/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/add_filter_to_global_search_bar/index.test.tsx @@ -6,7 +6,7 @@ import { mount, shallow } from 'enzyme'; import React from 'react'; - +import { waitFor } from '@testing-library/react'; import { apolloClientObservable, mockGlobalState, @@ -157,39 +157,40 @@ describe('AddFilterToGlobalSearchBar Component', () => { ); + await waitFor(() => { + wrapper.find('[data-test-subj="withHoverActionsButton"]').simulate('mouseenter'); + wrapper.update(); + jest.runAllTimers(); + wrapper.update(); - wrapper.find('[data-test-subj="withHoverActionsButton"]').simulate('mouseenter'); - wrapper.update(); - jest.runAllTimers(); - wrapper.update(); - - wrapper - .find('[data-test-subj="hover-actions-container"] [data-euiicon-type]') - .first() - .simulate('click'); - wrapper.update(); + wrapper + .find('[data-test-subj="hover-actions-container"] [data-euiicon-type]') + .first() + .simulate('click'); + wrapper.update(); - expect(mockAddFilters.mock.calls[0][0]).toEqual({ - meta: { - alias: null, - disabled: false, - key: 'host.name', - negate: false, - params: { - query: 'siem-kibana', - }, - type: 'phrase', - value: 'siem-kibana', - }, - query: { - match: { - 'host.name': { + expect(mockAddFilters.mock.calls[0][0]).toEqual({ + meta: { + alias: null, + disabled: false, + key: 'host.name', + negate: false, + params: { query: 'siem-kibana', - type: 'phrase', }, + type: 'phrase', + value: 'siem-kibana', }, - }, + query: { + match: { + 'host.name': { + query: 'siem-kibana', + type: 'phrase', + }, + }, + }, + }); + expect(onFilterAdded).toHaveBeenCalledTimes(1); }); - expect(onFilterAdded).toHaveBeenCalledTimes(1); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx index eef6e09d496dbe..e38aaeedad8fdd 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_lists.test.tsx @@ -8,8 +8,7 @@ import { ThemeProvider } from 'styled-components'; import { mount } from 'enzyme'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { getField } from '../../../../../../../src/plugins/data/common/index_patterns/fields/fields.mocks'; import { ListSchema } from '../../../lists_plugin_deps'; diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts index bbcbcbcf928b3a..225b407e4649e6 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import moment from 'moment'; import '../../../common/mock/match_media'; import { getField } from '../../../../../../../src/plugins/data/common/index_patterns/fields/fields.mocks'; @@ -17,6 +17,8 @@ import { import { getOperators, paramIsValid, getGenericComboBoxProps } from './helpers'; describe('helpers', () => { + // @ts-ignore + moment.suppressDeprecationWarnings = true; describe('#getOperators', () => { test('it returns "isOperator" if passed in field is "undefined"', () => { const operator = getOperators(undefined); diff --git a/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx b/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx index 64c8fde87a6bcf..aa638abf65f7ee 100644 --- a/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx @@ -13,6 +13,7 @@ import { ThemeProvider } from 'styled-components'; import { escapeDataProviderId } from '../drag_and_drop/helpers'; import { TestProviders } from '../../mock'; import '../../mock/match_media'; +import '../../mock/react_beautiful_dnd'; import { BarChartBaseComponent, BarChartComponent } from './barchart'; import { ChartSeriesData } from './common'; @@ -131,19 +132,6 @@ const mockConfig = { customHeight: 324, }; -// Suppress warnings about "react-beautiful-dnd" -/* eslint-disable no-console */ -const originalError = console.error; -const originalWarn = console.warn; -beforeAll(() => { - console.warn = jest.fn(); - console.error = jest.fn(); -}); -afterAll(() => { - console.error = originalError; - console.warn = originalWarn; -}); - describe('BarChartBaseComponent', () => { let shallowWrapper: ShallowWrapper; const mockBarChartData: ChartSeriesData[] = [ @@ -350,7 +338,10 @@ describe.each(chartDataSets)('BarChart with stackByField', () => { )}-${escapeDataProviderId(datum.key)}`; expect( - wrapper.find(`div [data-rbd-draggable-id="${dataProviderId}"]`).first().text() + wrapper + .find(`[draggableId="${dataProviderId}"] [data-test-subj="providerContainer"]`) + .first() + .text() ).toEqual(datum.key); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx index 8fd2fa1fdef12b..ffc2404bd43219 100644 --- a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { ThemeProvider } from 'styled-components'; import '../../mock/match_media'; +import '../../mock/react_beautiful_dnd'; import { TestProviders } from '../../mock'; import { MIN_LEGEND_HEIGHT, DraggableLegend } from './draggable_legend'; @@ -58,20 +59,6 @@ const legendItems: LegendItem[] = [ describe('DraggableLegend', () => { const height = 400; - - // Suppress warnings about "react-beautiful-dnd" - /* eslint-disable no-console */ - const originalError = console.error; - const originalWarn = console.warn; - beforeAll(() => { - console.warn = jest.fn(); - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - console.warn = originalWarn; - }); - describe('rendering', () => { let wrapper: ReactWrapper; diff --git a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx index 9f6e614c3c2852..72e44da3297eac 100644 --- a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { ThemeProvider } from 'styled-components'; import '../../mock/match_media'; +import '../../mock/react_beautiful_dnd'; import { TestProviders } from '../../mock'; import { DraggableLegendItem, LegendItem } from './draggable_legend_item'; @@ -17,19 +18,6 @@ import { DraggableLegendItem, LegendItem } from './draggable_legend_item'; const theme = () => ({ eui: euiDarkVars, darkMode: true }); describe('DraggableLegendItem', () => { - // Suppress warnings about "react-beautiful-dnd" - /* eslint-disable no-console */ - const originalError = console.error; - const originalWarn = console.warn; - beforeAll(() => { - console.warn = jest.fn(); - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - console.warn = originalWarn; - }); - describe('rendering a regular (non "All others") legend item', () => { const legendItem: LegendItem = { color: '#1EA593', diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx index 46e7298677f493..5223452c8b93d6 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx @@ -7,7 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; import { DraggableStateSnapshot, DraggingStyle } from 'react-beautiful-dnd'; - +import { waitFor } from '@testing-library/react'; import '../../mock/match_media'; import { mockBrowserFields } from '../../containers/source/mock'; import { TestProviders } from '../../mock'; @@ -62,7 +62,7 @@ describe('DraggableWrapper', () => { expect(wrapper.find('[data-test-subj="copy-to-clipboard"]').exists()).toBe(false); }); - test('it renders hover actions when the mouse is over the text of draggable wrapper', () => { + test('it renders hover actions when the mouse is over the text of draggable wrapper', async () => { const wrapper = mount( @@ -71,11 +71,13 @@ describe('DraggableWrapper', () => { ); - wrapper.find('[data-test-subj="withHoverActionsButton"]').simulate('mouseenter'); - wrapper.update(); - jest.runAllTimers(); - wrapper.update(); - expect(wrapper.find('[data-test-subj="copy-to-clipboard"]').exists()).toBe(true); + await waitFor(() => { + wrapper.find('[data-test-subj="withHoverActionsButton"]').simulate('mouseenter'); + wrapper.update(); + jest.runAllTimers(); + wrapper.update(); + expect(wrapper.find('[data-test-subj="copy-to-clipboard"]').exists()).toBe(true); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx index 8aa926a36988bd..af7e9ad5f14929 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx @@ -85,22 +85,6 @@ describe('DraggableWrapperHoverContent', () => { }); }); - // Suppress warnings about "react-beautiful-dnd" - /* eslint-disable no-console */ - const originalError = console.error; - const originalWarn = console.warn; - beforeEach(() => { - jest.clearAllMocks(); - }); - beforeAll(() => { - console.warn = jest.fn(); - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - console.warn = originalWarn; - }); - /** * The tests for "Filter for value" and "Filter out value" are similar enough * to combine them into "table tests" using this array diff --git a/x-pack/plugins/security_solution/public/common/components/endpoint/link_to_app.test.tsx b/x-pack/plugins/security_solution/public/common/components/endpoint/link_to_app.test.tsx index 79773630e0dc04..d791ea44f81983 100644 --- a/x-pack/plugins/security_solution/public/common/components/endpoint/link_to_app.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/endpoint/link_to_app.test.tsx @@ -44,7 +44,7 @@ describe('LinkToApp component', () => { }); it('should support onClick prop', () => { // Take `_event` (even though it is not used) so that `jest.fn` will have a type that expects to be called with an event - const spyOnClickHandler: LinkToAppOnClickMock = jest.fn((_event) => {}); + const spyOnClickHandler: LinkToAppOnClickMock = jest.fn().mockImplementation((_event) => {}); const renderResult = render( {'link'} @@ -98,20 +98,24 @@ describe('LinkToApp component', () => { }); it('should still preventDefault if onClick callback throws', () => { // Take `_event` (even though it is not used) so that `jest.fn` will have a type that expects to be called with an event - const spyOnClickHandler: LinkToAppOnClickMock = jest.fn((_event) => { + const spyOnClickHandler = jest.fn().mockImplementation((_event) => { throw new Error('test'); }); - const renderResult = render( - - {'link'} - - ); - expect(() => renderResult.find('EuiLink').simulate('click')).toThrow(); - const clickEventArg = spyOnClickHandler.mock.calls[0][0]; - expect(clickEventArg.isDefaultPrevented()).toBe(true); + // eslint-disable-next-line no-empty + try { + } catch (e) { + const renderResult = render( + + {'link'} + + ); + expect(() => renderResult.find('EuiLink').simulate('click')).toThrowError(); + const clickEventArg = spyOnClickHandler.mock.calls[0][0]; + expect(clickEventArg.isDefaultPrevented()).toBe(true); + } }); it('should not navigate if onClick callback prevents default', () => { - const spyOnClickHandler: LinkToAppOnClickMock = jest.fn((ev) => { + const spyOnClickHandler: LinkToAppOnClickMock = jest.fn().mockImplementation((ev) => { ev.preventDefault(); }); const renderResult = render( diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx index 01b0810830dd8f..c3c7c864ac99b7 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.test.tsx @@ -8,16 +8,19 @@ import { shallow } from 'enzyme'; import React from 'react'; import '../../mock/match_media'; -import { mockDetailItemData, mockDetailItemDataId } from '../../mock/mock_detail_item'; -import { TestProviders } from '../../mock/test_providers'; +import '../../mock/react_beautiful_dnd'; +import { + defaultHeaders, + mockDetailItemData, + mockDetailItemDataId, + TestProviders, +} from '../../mock'; import { EventDetails, View } from './event_details'; import { mockBrowserFields } from '../../containers/source/mock'; -import { defaultHeaders } from '../../mock/header'; import { useMountAppended } from '../../utils/use_mount_appended'; jest.mock('../link_to'); - describe('EventDetails', () => { const mount = useMountAppended(); const onEventToggled = jest.fn(); diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx index 9a3c0fa1cad2e2..928521c118ba57 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx @@ -8,8 +8,7 @@ import React from 'react'; import useResizeObserver from 'use-resize-observer/polyfilled'; import '../../mock/match_media'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { TestProviders } from '../../mock'; import { useMountAppended } from '../../utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx index ed1c1c1cdad1f9..fa9838aa370158 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx @@ -8,10 +8,11 @@ import React from 'react'; import { ThemeProvider } from 'styled-components'; import { mount, ReactWrapper } from 'enzyme'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import { act } from 'react-dom/test-utils'; +import { waitFor } from '@testing-library/react'; import { AddExceptionModal } from './'; import { useCurrentUser } from '../../../../common/lib/kibana'; +import { useAsync } from '../../../../shared_imports'; import { getExceptionListSchemaMock } from '../../../../../../lists/common/schemas/response/exception_list_schema.mock'; import { useFetchIndex } from '../../../containers/source'; import { stubIndexPattern } from 'src/plugins/data/common/index_patterns/index_pattern.stub'; @@ -33,6 +34,7 @@ jest.mock('../../../../detections/containers/detection_engine/rules'); jest.mock('../use_add_exception'); jest.mock('../use_fetch_or_create_rule_exception_list'); jest.mock('../builder'); +jest.mock('../../../../shared_imports'); describe('When the add exception modal is opened', () => { const ruleName = 'test rule'; @@ -48,6 +50,11 @@ describe('When the add exception modal is opened', () => { .spyOn(builder, 'ExceptionBuilderComponent') .mockReturnValue(<>); + (useAsync as jest.Mock).mockImplementation(() => ({ + start: jest.fn(), + loading: false, + })); + (useAddOrUpdateException as jest.Mock).mockImplementation(() => [ { isLoading: false }, jest.fn(), @@ -104,7 +111,7 @@ describe('When the add exception modal is opened', () => { describe('when there is no alert data passed to an endpoint list exception', () => { let wrapper: ReactWrapper; - beforeEach(() => { + beforeEach(async () => { wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { ); const callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [] })); + await waitFor(() => callProps.onChange({ exceptionItems: [] })); }); it('has the add exception button disabled', () => { expect( @@ -140,7 +147,7 @@ describe('When the add exception modal is opened', () => { describe('when there is alert data passed to an endpoint list exception', () => { let wrapper: ReactWrapper; - beforeEach(() => { + beforeEach(async () => { const alertDataMock: { ecsData: Ecs; nonEcsData: TimelineNonEcsData[] } = { ecsData: { _id: 'test-id' }, nonEcsData: [{ field: 'file.path', value: ['test/path'] }], @@ -159,7 +166,9 @@ describe('When the add exception modal is opened', () => { ); const callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] })); + await waitFor(() => + callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] }) + ); }); it('has the add exception button enabled', () => { expect( @@ -191,7 +200,7 @@ describe('When the add exception modal is opened', () => { describe('when there is alert data passed to a detection list exception', () => { let wrapper: ReactWrapper; - beforeEach(() => { + beforeEach(async () => { const alertDataMock: { ecsData: Ecs; nonEcsData: TimelineNonEcsData[] } = { ecsData: { _id: 'test-id' }, nonEcsData: [{ field: 'file.path', value: ['test/path'] }], @@ -210,7 +219,9 @@ describe('When the add exception modal is opened', () => { ); const callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [getExceptionListItemSchemaMock()] })); + await waitFor(() => + callProps.onChange({ exceptionItems: [getExceptionListItemSchemaMock()] }) + ); }); it('has the add exception button enabled', () => { expect( @@ -243,7 +254,7 @@ describe('When the add exception modal is opened', () => { onChange: (props: { exceptionItems: ExceptionListItemSchema[] }) => void; exceptionListItems: ExceptionListItemSchema[]; }; - beforeEach(() => { + beforeEach(async () => { // Mocks the index patterns to contain the pre-populated endpoint fields so that the exception qualifies as bulk closable (useFetchIndex as jest.Mock).mockImplementation(() => [ false, @@ -278,7 +289,9 @@ describe('When the add exception modal is opened', () => { ); callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] })); + await waitFor(() => + callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] }) + ); }); it('has the add exception button enabled', () => { expect( @@ -307,8 +320,8 @@ describe('When the add exception modal is opened', () => { ).not.toBeDisabled(); }); describe('when a "is in list" entry is added', () => { - it('should have the bulk close checkbox disabled', () => { - act(() => + it('should have the bulk close checkbox disabled', async () => { + await waitFor(() => callProps.onChange({ exceptionItems: [ ...callProps.exceptionListItems, diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.test.tsx index 2d389a7dbcee1a..e6f57fe6667802 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { ThemeProvider } from 'styled-components'; import { mount } from 'enzyme'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { fields, diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx index d5d2091cc9bc87..551a9173351fcf 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx @@ -5,10 +5,10 @@ */ import React from 'react'; +import { waitFor } from '@testing-library/react'; import { ThemeProvider } from 'styled-components'; import { mount, ReactWrapper } from 'enzyme'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import { act } from 'react-dom/test-utils'; import { EditExceptionModal } from './'; import { useCurrentUser } from '../../../../common/lib/kibana'; @@ -66,15 +66,14 @@ describe('When the edit exception modal is opened', () => { }); describe('when the modal is loading', () => { - let wrapper: ReactWrapper; - beforeEach(() => { + it('renders the loading spinner', async () => { (useFetchIndex as jest.Mock).mockImplementation(() => [ true, { indexPatterns: stubIndexPattern, }, ]); - wrapper = mount( + const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { /> ); - }); - it('renders the loading spinner', () => { - expect(wrapper.find('[data-test-subj="loadingEditExceptionModal"]').exists()).toBeTruthy(); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="loadingEditExceptionModal"]').exists()).toBeTruthy(); + }); }); }); describe('when an endpoint exception with exception data is passed', () => { describe('when exception entry fields are included in the index pattern', () => { let wrapper: ReactWrapper; - beforeEach(() => { + beforeEach(async () => { const exceptionItemMock = { ...getExceptionListItemSchemaMock(), entries: [ @@ -117,7 +116,9 @@ describe('When the edit exception modal is opened', () => { ); const callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] })); + await waitFor(() => { + callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] }); + }); }); it('has the edit exception button enabled', () => { expect( @@ -145,7 +146,7 @@ describe('When the edit exception modal is opened', () => { describe("when exception entry fields aren't included in the index pattern", () => { let wrapper: ReactWrapper; - beforeEach(() => { + beforeEach(async () => { wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { ); const callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] })); + await waitFor(() => { + callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] }); + }); }); it('has the edit exception button enabled', () => { expect( @@ -189,7 +192,7 @@ describe('When the edit exception modal is opened', () => { describe('when an detection exception with entries is passed', () => { let wrapper: ReactWrapper; - beforeEach(() => { + beforeEach(async () => { wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { ); const callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] })); + await waitFor(() => { + callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] }); + }); }); it('has the edit exception button enabled', () => { expect( @@ -228,7 +233,7 @@ describe('When the edit exception modal is opened', () => { describe('when an exception with no entries is passed', () => { let wrapper: ReactWrapper; - beforeEach(() => { + beforeEach(async () => { const exceptionItemMock = { ...getExceptionListItemSchemaMock(), entries: [] }; wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -244,7 +249,9 @@ describe('When the edit exception modal is opened', () => { ); const callProps = ExceptionBuilderComponent.mock.calls[0][0]; - act(() => callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] })); + await waitFor(() => { + callProps.onChange({ exceptionItems: [...callProps.exceptionListItems] }); + }); }); it('has the edit exception button disabled', () => { expect( diff --git a/x-pack/plugins/security_solution/public/common/components/last_event_time/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/last_event_time/index.test.tsx index cc0c4d4c837a3d..d9b5c5e10893c1 100644 --- a/x-pack/plugins/security_solution/public/common/components/last_event_time/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/last_event_time/index.test.tsx @@ -5,7 +5,7 @@ */ import React from 'react'; - +import '../../../common/mock/formatted_relative'; import { getEmptyValue } from '../empty_value'; import { LastEventIndexKey } from '../../../../common/search_strategy'; import { mockLastEventTimeQuery } from '../../containers/events/last_event_time/mock'; @@ -57,7 +57,7 @@ describe('Last Event Time Stat', () => { ); - expect(wrapper.html()).toBe('Last event: 12 minutes ago'); + expect(wrapper.html()).toBe('Last event: 20 hours ago'); }); test('Bad date time string', async () => { (useTimelineLastEventTime as jest.Mock).mockReturnValue([ diff --git a/x-pack/plugins/security_solution/public/common/components/link_icon/index.tsx b/x-pack/plugins/security_solution/public/common/components/link_icon/index.tsx index 19f1d70e6e230d..55842342c66779 100644 --- a/x-pack/plugins/security_solution/public/common/components/link_icon/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/link_icon/index.tsx @@ -6,16 +6,16 @@ import { EuiIcon, EuiLink, IconSize, IconType } from '@elastic/eui'; import { LinkAnchorProps } from '@elastic/eui/src/components/link/link'; -import React, { ReactNode } from 'react'; +import React, { ReactNode, useCallback, useMemo } from 'react'; import styled, { css } from 'styled-components'; interface LinkProps { + ariaLabel?: string; color?: LinkAnchorProps['color']; disabled?: boolean; href?: string; iconSide?: 'left' | 'right'; onClick?: Function; - ariaLabel?: string; } export const Link = styled(({ iconSide, children, ...rest }) => ( @@ -55,6 +55,7 @@ export interface LinkIconProps extends LinkProps { export const LinkIcon = React.memo( ({ + ariaLabel, children, color, dataTestSubj, @@ -64,21 +65,41 @@ export const LinkIcon = React.memo( iconSize = 's', iconType, onClick, - ariaLabel, - }) => ( - - - {children} - - ) + }) => { + const getChildrenString = useCallback((theChild: string | ReactNode): string => { + if ( + typeof theChild === 'object' && + theChild != null && + 'props' in theChild && + theChild.props && + theChild.props.children + ) { + return getChildrenString(theChild.props.children); + } + return theChild != null && Object.keys(theChild).length > 0 ? (theChild as string) : ''; + }, []); + const aria = useMemo(() => { + if (ariaLabel) { + return ariaLabel; + } + return getChildrenString(children); + }, [ariaLabel, children, getChildrenString]); + + return ( + + + {children} + + ); + } ); LinkIcon.displayName = 'LinkIcon'; diff --git a/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx index e9940d088e606b..07d148ff96dfa2 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx @@ -11,7 +11,6 @@ import '../../mock/match_media'; import { EntityDraggableComponent } from './entity_draggable'; import { TestProviders } from '../../mock/test_providers'; import { useMountAppended } from '../../utils/use_mount_appended'; - describe('entity_draggable', () => { const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx index 434cbd8ada88e2..cb10c61302d3c2 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx @@ -19,7 +19,6 @@ const startDate: string = '2020-07-07T08:20:18.966Z'; const endDate: string = '3000-01-01T00:00:00.000Z'; const narrowDateRange = jest.fn(); - describe('anomaly_scores', () => { let anomalies: Anomalies = cloneDeep(mockAnomalies); const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx index a900c3e49f912a..52151f217e01ad 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx @@ -19,7 +19,6 @@ import { useMountAppended } from '../../../utils/use_mount_appended'; const startDate: string = '2020-07-07T08:20:18.966Z'; const endDate: string = '3000-01-01T00:00:00.000Z'; const narrowDateRange = jest.fn(); - describe('anomaly_scores', () => { let anomalies: Anomalies = cloneDeep(mockAnomalies); const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx index d370a901a62627..3092cbf265ea93 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx @@ -19,7 +19,6 @@ const startDate = new Date(2001).toISOString(); const endDate = new Date(3000).toISOString(); const interval = 'days'; const narrowDateRange = jest.fn(); - describe('get_anomalies_host_table_columns', () => { const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx index 69a4e383413f28..89f94a3819e65f 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx @@ -16,7 +16,6 @@ import { useMountAppended } from '../../../utils/use_mount_appended'; const startDate = new Date(2001).toISOString(); const endDate = new Date(3000).toISOString(); - describe('get_anomalies_network_table_columns', () => { const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/job_switch.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/job_switch.test.tsx index e58d76bd1dde00..13518acdefdde3 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/job_switch.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/job_switch.test.tsx @@ -7,6 +7,7 @@ import { shallow, mount } from 'enzyme'; import React from 'react'; +import { waitFor } from '@testing-library/react'; import { JobSwitchComponent } from './job_switch'; import { cloneDeep } from 'lodash/fp'; import { mockSecurityJobs } from '../api.mock'; @@ -31,7 +32,7 @@ describe('JobSwitch', () => { expect(wrapper).toMatchSnapshot(); }); - test('should call onJobStateChange when the switch is clicked to be true/open', () => { + test('should call onJobStateChange when the switch is clicked to be true/open', async () => { const wrapper = mount( { .simulate('click', { target: { checked: true }, }); - - expect(onJobStateChangeMock.mock.calls[0][0].id).toEqual( - 'linux_anomalous_network_activity_ecs' - ); - expect(onJobStateChangeMock.mock.calls[0][1]).toEqual(1571022859393); - expect(onJobStateChangeMock.mock.calls[0][2]).toEqual(true); + await waitFor(() => { + expect(onJobStateChangeMock.mock.calls[0][0].id).toEqual( + 'linux_anomalous_network_activity_ecs' + ); + expect(onJobStateChangeMock.mock.calls[0][1]).toEqual(1571022859393); + expect(onJobStateChangeMock.mock.calls[0][2]).toEqual(true); + }); }); test('should have a switch when it is not in the loading state', () => { diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/jobs_table.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/jobs_table.test.tsx index dfcabe7b5aedf2..3d7e47a15fc1ef 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/jobs_table.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/jobs_table/jobs_table.test.tsx @@ -6,6 +6,7 @@ import { shallow, mount } from 'enzyme'; import React from 'react'; +import { waitFor } from '@testing-library/react'; import { JobsTableComponent } from './jobs_table'; import { mockSecurityJobs } from '../api.mock'; import { cloneDeep } from 'lodash/fp'; @@ -59,7 +60,7 @@ describe('JobsTableComponent', () => { ); }); - test('should call onJobStateChange when the switch is clicked to be true/open', () => { + test('should call onJobStateChange when the switch is clicked to be true/open', async () => { const wrapper = mount( { .simulate('click', { target: { checked: true }, }); - expect(onJobStateChangeMock.mock.calls[0]).toEqual([securityJobs[0], 1571022859393, true]); + await waitFor(() => { + expect(onJobStateChangeMock.mock.calls[0]).toEqual([securityJobs[0], 1571022859393, true]); + }); }); test('should have a switch when it is not in the loading state', () => { diff --git a/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx index aa61688f1f9864..12199ce5c1b661 100644 --- a/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx @@ -6,7 +6,7 @@ import { mount } from 'enzyme'; import React from 'react'; - +import { waitFor } from '@testing-library/react'; import { coreMock } from '../../../../../../../src/core/public/mocks'; import { DEFAULT_FROM, DEFAULT_TO } from '../../../../common/constants'; import { TestProviders, mockIndexPattern } from '../../mock'; @@ -16,22 +16,6 @@ import { QueryBar, QueryBarComponentProps } from '.'; const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; describe('QueryBar ', () => { - // We are doing that because we need to wrapped this component with redux - // and redux does not like to be updated and since we need to update our - // child component (BODY) and we do not want to scare anyone with this error - // we are hiding it!!! - // eslint-disable-next-line no-console - const originalError = console.error; - beforeAll(() => { - // eslint-disable-next-line no-console - console.error = (...args: string[]) => { - if (/ does not support changing `store` on the fly/.test(args[0])) { - return; - } - originalError.call(console, ...args); - }; - }); - const mockOnChangeQuery = jest.fn(); const mockOnSubmitQuery = jest.fn(); const mockOnSavedQuery = jest.fn(); @@ -372,7 +356,7 @@ describe('QueryBar ', () => { }); describe('SavedQueryManagementComponent state', () => { - test('popover should hidden when "Save current query" button was clicked', () => { + test('popover should hidden when "Save current query" button was clicked', async () => { const Proxy = (props: QueryBarComponentProps) => ( @@ -397,21 +381,24 @@ describe('QueryBar ', () => { onSavedQuery={mockOnSavedQuery} /> ); + await waitFor(() => { + const isSavedQueryPopoverOpen = () => + wrapper.find('EuiPopover[id="savedQueryPopover"]').prop('isOpen'); - const isSavedQueryPopoverOpen = () => - wrapper.find('EuiPopover[id="savedQueryPopover"]').prop('isOpen'); - - expect(isSavedQueryPopoverOpen()).toBeFalsy(); + expect(isSavedQueryPopoverOpen()).toBeFalsy(); - wrapper - .find('button[data-test-subj="saved-query-management-popover-button"]') - .simulate('click'); + wrapper + .find('button[data-test-subj="saved-query-management-popover-button"]') + .simulate('click'); - expect(isSavedQueryPopoverOpen()).toBeTruthy(); + expect(isSavedQueryPopoverOpen()).toBeTruthy(); - wrapper.find('button[data-test-subj="saved-query-management-save-button"]').simulate('click'); + wrapper + .find('button[data-test-subj="saved-query-management-save-button"]') + .simulate('click'); - expect(isSavedQueryPopoverOpen()).toBeFalsy(); + expect(isSavedQueryPopoverOpen()).toBeFalsy(); + }); }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/sourcerer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/sourcerer/index.test.tsx index bd9f2677ec966f..2696b115cdc184 100644 --- a/x-pack/plugins/security_solution/public/common/components/sourcerer/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/sourcerer/index.test.tsx @@ -20,8 +20,7 @@ import { } from '../../mock'; import { createStore, State } from '../../store'; import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; -import { act } from 'react-dom/test-utils'; -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; const mockDispatch = jest.fn(); jest.mock('react-redux', () => { @@ -126,13 +125,11 @@ describe('Sourcerer component', () => { expect(true).toBeTruthy(); wrapper.find(`[data-test-subj="sourcerer-trigger"]`).first().simulate('click'); - await act(async () => { + await waitFor(() => { ((wrapper.find(EuiComboBox).props() as unknown) as { onChange: (a: EuiComboBoxOptionOption[]) => void; }).onChange([mockOptions[0], mockOptions[1]]); - await waitFor(() => { - wrapper.update(); - }); + wrapper.update(); }); wrapper.find(`[data-test-subj="add-index"]`).first().simulate('click'); diff --git a/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx b/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx index b28c7e70b8ae85..f091f22abcb949 100644 --- a/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx @@ -17,7 +17,6 @@ import { import { TestProviders } from '../../mock'; import { getEmptyValue } from '../empty_value'; import { useMountAppended } from '../../utils/use_mount_appended'; - describe('Table Helpers', () => { const items = ['item1', 'item2', 'item3']; const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx index 594bffbd4ff63e..fd1fa1c29a8075 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx @@ -6,7 +6,7 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; - +import { waitFor } from '@testing-library/react'; import '../../mock/match_media'; import { mockBrowserFields } from '../../containers/source/mock'; import { @@ -180,19 +180,6 @@ let testProps = { }; describe('StatefulTopN', () => { - // Suppress warnings about "react-beautiful-dnd" - /* eslint-disable no-console */ - const originalError = console.error; - const originalWarn = console.warn; - beforeAll(() => { - console.warn = jest.fn(); - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - console.warn = originalWarn; - }); - describe('rendering in a global NON-timeline context', () => { let wrapper: ReactWrapper; @@ -343,7 +330,7 @@ describe('StatefulTopN', () => { }); }); describe('rendering in a NON-active timeline context', () => { - test(`defaults to the 'Alert events' option when rendering in a NON-active timeline context (e.g. the Alerts table on the Detections page) when 'documentType' from 'useTimelineTypeContext()' is 'alerts'`, () => { + test(`defaults to the 'Alert events' option when rendering in a NON-active timeline context (e.g. the Alerts table on the Detections page) when 'documentType' from 'useTimelineTypeContext()' is 'alerts'`, async () => { const filterManager = new FilterManager(mockUiSettingsForFilterManager); const manageTimelineForTesting = { @@ -365,10 +352,11 @@ describe('StatefulTopN', () => { ); + await waitFor(() => { + const props = wrapper.find('[data-test-subj="top-n"]').first().props() as Props; - const props = wrapper.find('[data-test-subj="top-n"]').first().props() as Props; - - expect(props.defaultView).toEqual('alert'); + expect(props.defaultView).toEqual('alert'); + }); }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx index 829f918ddfe1b0..f7ad35f2c5a371 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx @@ -6,15 +6,13 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; - +import { waitFor } from '@testing-library/react'; import '../../mock/match_media'; import { TestProviders, mockIndexPattern } from '../../mock'; import { setAbsoluteRangeDatePicker } from '../../store/inputs/actions'; import { allEvents, defaultOptions } from './helpers'; -import { TopN } from './top_n'; -import { TimelineEventsType } from '../../../../common/types/timeline'; -import { InputsModelId } from '../../store/inputs/constants'; +import { TopN, Props as TopNProps } from './top_n'; jest.mock('react-router-dom', () => { const original = jest.requireActual('react-router-dom'); @@ -90,28 +88,15 @@ const combinedQueries = { }; describe('TopN', () => { - // Suppress warnings about "react-beautiful-dnd" - /* eslint-disable no-console */ - const originalError = console.error; - const originalWarn = console.warn; - beforeAll(() => { - console.warn = jest.fn(); - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - console.warn = originalWarn; - }); - const query = { query: '', language: 'kuery' }; const toggleTopN = jest.fn(); - const eventTypes: { [id: string]: TimelineEventsType } = { + const eventTypes: { [id: string]: TopNProps['defaultView'] } = { raw: 'raw', alert: 'alert', all: 'all', }; - let testProps = { + let testProps: TopNProps = { defaultView: eventTypes.raw, field, filters: [], @@ -121,7 +106,7 @@ describe('TopN', () => { options: defaultOptions, query, setAbsoluteRangeDatePicker, - setAbsoluteRangeDatePickerTarget: 'global' as InputsModelId, + setAbsoluteRangeDatePickerTarget: 'global', setQuery: jest.fn(), to: '2020-04-15T00:31:47.695Z', toggleTopN, @@ -172,28 +157,35 @@ describe('TopN', () => { }); describe('alerts view', () => { - let wrapper: ReactWrapper; - - beforeEach(() => { + beforeAll(() => { testProps = { ...testProps, defaultView: eventTypes.alert, }; - wrapper = mount( + }); + + test(`it renders SignalsByCategory when defaultView is 'alert'`, async () => { + const wrapper = mount( ); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="alerts-histogram-panel"]').exists()).toBe(true); + }); }); - test(`it renders SignalsByCategory when defaultView is 'alert'`, () => { - expect(wrapper.find('[data-test-subj="alerts-histogram-panel"]').exists()).toBe(true); - }); - - test(`it does NOT render EventsByDataset when defaultView is 'alert'`, () => { - expect( - wrapper.find('[data-test-subj="eventsByDatasetOverview-uuid.v4()Panel"]').exists() - ).toBe(false); + test(`it does NOT render EventsByDataset when defaultView is 'alert'`, async () => { + const wrapper = mount( + + + + ); + await waitFor(() => { + expect( + wrapper.find('[data-test-subj="eventsByDatasetOverview-uuid.v4()Panel"]').exists() + ).toBe(false); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx index fc970c066e8a5c..f4a48eaea69c20 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx @@ -21,8 +21,7 @@ import { } from './test_dependencies'; import { UrlStateContainerPropTypes } from './types'; import { useUrlStateHooks } from './use_url_state'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; let mockProps: UrlStateContainerPropTypes; diff --git a/x-pack/plugins/security_solution/public/common/lib/kibana/kibana_react.mock.ts b/x-pack/plugins/security_solution/public/common/lib/kibana/kibana_react.mock.ts index c026b65853a4c6..6f8ff2e1bb21a2 100644 --- a/x-pack/plugins/security_solution/public/common/lib/kibana/kibana_react.mock.ts +++ b/x-pack/plugins/security_solution/public/common/lib/kibana/kibana_react.mock.ts @@ -13,20 +13,20 @@ import { KibanaContextProvider } from '../../../../../../../src/plugins/kibana_r import { dataPluginMock } from '../../../../../../../src/plugins/data/public/mocks'; import { securityMock } from '../../../../../../plugins/security/public/mocks'; import { - DEFAULT_APP_TIME_RANGE, DEFAULT_APP_REFRESH_INTERVAL, - DEFAULT_INDEX_KEY, + DEFAULT_APP_TIME_RANGE, + DEFAULT_BYTES_FORMAT, + DEFAULT_DARK_MODE, DEFAULT_DATE_FORMAT, DEFAULT_DATE_FORMAT_TZ, - DEFAULT_DARK_MODE, - DEFAULT_TIME_RANGE, - DEFAULT_REFRESH_RATE_INTERVAL, DEFAULT_FROM, - DEFAULT_TO, + DEFAULT_INDEX_KEY, + DEFAULT_INDEX_PATTERN, DEFAULT_INTERVAL_PAUSE, DEFAULT_INTERVAL_VALUE, - DEFAULT_BYTES_FORMAT, - DEFAULT_INDEX_PATTERN, + DEFAULT_REFRESH_RATE_INTERVAL, + DEFAULT_TIME_RANGE, + DEFAULT_TO, } from '../../../../common/constants'; import { StartServices } from '../../../types'; import { createSecuritySolutionStorageMock } from '../../mock/mock_local_storage'; @@ -77,14 +77,43 @@ export const createStartServicesMock = (): StartServices => { const data = dataPluginMock.createStartContract(); const security = securityMock.createSetup(); - const services = ({ + return ({ ...core, - data, + data: { + ...data, + query: { + ...data.query, + savedQueries: { + ...data.query.savedQueries, + getAllSavedQueries: jest.fn(() => + Promise.resolve({ + id: '123', + attributes: { + total: 123, + }, + }) + ), + findSavedQueries: jest.fn(() => + Promise.resolve({ + total: 123, + queries: [], + }) + ), + }, + }, + search: { + ...data.search, + search: jest.fn().mockImplementation(() => ({ + subscribe: jest.fn().mockImplementation(() => ({ + error: jest.fn(), + next: jest.fn(), + })), + })), + }, + }, security, storage, } as unknown) as StartServices; - - return services; }; export const createWithKibanaMock = () => { diff --git a/x-pack/plugins/security_solution/public/common/mock/formatted_relative.ts b/x-pack/plugins/security_solution/public/common/mock/formatted_relative.ts new file mode 100644 index 00000000000000..0eb1c9a478ca0d --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/mock/formatted_relative.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +jest.mock('@kbn/i18n/react', () => { + const originalModule = jest.requireActual('@kbn/i18n/react'); + const FormattedRelative = jest.fn().mockImplementation(() => '20 hours ago'); + + return { + ...originalModule, + FormattedRelative, + }; +}); diff --git a/x-pack/plugins/security_solution/public/common/mock/react_beautiful_dnd.ts b/x-pack/plugins/security_solution/public/common/mock/react_beautiful_dnd.ts new file mode 100644 index 00000000000000..e077d289259125 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/mock/react_beautiful_dnd.ts @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + DraggableProvided, + DraggableStateSnapshot, + DroppableProvided, + DroppableStateSnapshot, +} from 'react-beautiful-dnd'; +import React from 'react'; + +jest.mock('react-beautiful-dnd', () => ({ + Droppable: ({ + children, + }: { + children: (a: DroppableProvided, b: DroppableStateSnapshot) => void; + }) => + children( + { + droppableProps: { + 'data-rbd-droppable-context-id': '123', + 'data-rbd-droppable-id': '123', + }, + innerRef: jest.fn(), + }, + { + isDraggingOver: false, + isUsingPlaceholder: false, + } + ), + Draggable: ({ + children, + }: { + children: (a: DraggableProvided, b: DraggableStateSnapshot) => void; + }) => + children( + { + draggableProps: { + 'data-rbd-draggable-context-id': '123', + 'data-rbd-draggable-id': '123', + }, + innerRef: jest.fn(), + }, + { + isDragging: false, + isDropAnimating: false, + } + ), + DragDropContext: ({ children }: { children: React.ReactNode }) => children, +})); diff --git a/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx b/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx index 8c186addf783d8..e84f80655fbe4b 100644 --- a/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx +++ b/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx @@ -46,7 +46,7 @@ export const kibanaObservable = new BehaviorSubject(createStartServicesMock()); Object.defineProperty(window, 'localStorage', { value: localStorageMock(), }); - +window.scrollTo = jest.fn(); const MockKibanaContextProvider = createKibanaContextProviderMock(); const { storage } = createSecuritySolutionStorageMock(); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx index 4312be0b469904..2bdc8136397403 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { mount, shallow } from 'enzyme'; import { ThemeProvider } from 'styled-components'; import euiDarkVars from '@elastic/eui/dist/eui_theme_light.json'; +import { act } from '@testing-library/react'; import { stubIndexPattern } from 'src/plugins/data/common/index_patterns/index_pattern.stub'; import { StepAboutRule } from '.'; @@ -23,18 +24,17 @@ import { fillEmptySeverityMappings } from '../../../pages/detection_engine/rules jest.mock('../../../../common/containers/source'); const theme = () => ({ eui: euiDarkVars, darkMode: true }); - -/* eslint-disable no-console */ -// Silence until enzyme fixed to use ReactTestUtils.act() -const originalError = console.error; -beforeAll(() => { - console.error = jest.fn(); -}); -afterAll(() => { - console.error = originalError; +jest.mock('@elastic/eui', () => { + const original = jest.requireActual('@elastic/eui'); + return { + ...original, + // eslint-disable-next-line react/display-name, @typescript-eslint/no-explicit-any + EuiFieldText: (props: any) => { + const { isInvalid, isLoading, fullWidth, inputRef, isDisabled, ...validInputProps } = props; + return ; + }, + }; }); -/* eslint-enable no-console */ - describe('StepAboutRuleComponent', () => { let formHook: RuleStepsFormHooks[RuleStep.aboutRule] | null = null; const setFormHook = ( @@ -54,7 +54,7 @@ describe('StepAboutRuleComponent', () => { ]); }); - test('it renders StepRuleDescription if isReadOnlyView is true and "name" property exists', () => { + it('it renders StepRuleDescription if isReadOnlyView is true and "name" property exists', () => { const wrapper = shallow( { ); - if (!formHook) { - throw new Error('Form hook not set, but tests depend on it'); - } - - wrapper - .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') - .first() - .simulate('change', { target: { value: 'Test name text' } }); - - const result = await formHook(); - expect(result?.isValid).toEqual(false); + await act(async () => { + if (!formHook) { + throw new Error('Form hook not set, but tests depend on it'); + } + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') + .first() + .simulate('change', { target: { value: 'Test name text' } }); + + const result = await formHook(); + expect(result?.isValid).toEqual(false); + }); }); it('is invalid if no "name" is present', async () => { @@ -109,17 +110,18 @@ describe('StepAboutRuleComponent', () => { ); - if (!formHook) { - throw new Error('Form hook not set, but tests depend on it'); - } - - wrapper - .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') - .first() - .simulate('change', { target: { value: 'Test description text' } }); - - const result = await formHook(); - expect(result?.isValid).toEqual(false); + await act(async () => { + if (!formHook) { + throw new Error('Form hook not set, but tests depend on it'); + } + + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') + .first() + .simulate('change', { target: { value: 'Test description text' } }); + const result = await formHook(); + expect(result?.isValid).toEqual(false); + }); }); it('is valid if both "name" and "description" are present', async () => { @@ -136,10 +138,6 @@ describe('StepAboutRuleComponent', () => { ); - if (!formHook) { - throw new Error('Form hook not set, but tests depend on it'); - } - wrapper .find('[data-test-subj="detectionEngineStepAboutRuleDescription"] textarea') .first() @@ -173,12 +171,17 @@ describe('StepAboutRuleComponent', () => { ], }; - const result = await formHook(); - expect(result?.isValid).toEqual(true); - expect(result?.data).toEqual(expected); + await act(async () => { + if (!formHook) { + throw new Error('Form hook not set, but tests depend on it'); + } + const result = await formHook(); + expect(result?.isValid).toEqual(true); + expect(result?.data).toEqual(expected); + }); }); - test('it allows user to set the risk score as a number (and not a string)', async () => { + it('it allows user to set the risk score as a number (and not a string)', async () => { const wrapper = mount( { ); - if (!formHook) { - throw new Error('Form hook not set, but tests depend on it'); - } - wrapper .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') .first() @@ -235,9 +234,14 @@ describe('StepAboutRuleComponent', () => { ], }; - const result = await formHook(); - expect(result?.isValid).toEqual(true); - expect(result?.data).toEqual(expected); + await act(async () => { + if (!formHook) { + throw new Error('Form hook not set, but tests depend on it'); + } + const result = await formHook(); + expect(result?.isValid).toEqual(true); + expect(result?.data).toEqual(expected); + }); }); it('does not modify the provided risk score until the user changes the severity', async () => { @@ -254,10 +258,6 @@ describe('StepAboutRuleComponent', () => { ); - if (!formHook) { - throw new Error('Form hook not set, but tests depend on it'); - } - wrapper .find('[data-test-subj="detectionEngineStepAboutRuleName"] input') .first() @@ -268,18 +268,23 @@ describe('StepAboutRuleComponent', () => { .first() .simulate('change', { target: { value: 'Test description text' } }); - const result = await formHook(); - expect(result?.isValid).toEqual(true); - expect(result?.data?.riskScore.value).toEqual(21); - - wrapper - .find('[data-test-subj="detectionEngineStepAboutRuleSeverity"] [data-test-subj="select"]') - .last() - .simulate('click'); - wrapper.find('button#medium').simulate('click'); - - const result2 = await formHook(); - expect(result2?.isValid).toEqual(true); - expect(result2?.data?.riskScore.value).toEqual(47); + await act(async () => { + if (!formHook) { + throw new Error('Form hook not set, but tests depend on it'); + } + const result = await formHook(); + expect(result?.isValid).toEqual(true); + expect(result?.data?.riskScore.value).toEqual(21); + + wrapper + .find('[data-test-subj="detectionEngineStepAboutRuleSeverity"] [data-test-subj="select"]') + .last() + .simulate('click'); + wrapper.find('button#medium').simulate('click'); + + const result2 = await formHook(); + expect(result2?.isValid).toEqual(true); + expect(result2?.data?.riskScore.value).toEqual(47); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx index 591e1c81cd2add..bae5a237bd1246 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx @@ -5,7 +5,7 @@ */ import React, { FormEvent } from 'react'; import { mount, ReactWrapper } from 'enzyme'; -import { act } from 'react-dom/test-utils'; +import { waitFor } from '@testing-library/react'; import { TestProviders } from '../../../common/mock'; import { ValueListsForm } from './form'; @@ -24,7 +24,7 @@ const mockSelectFile:

(container: ReactWrapper

, file: File) => Promise { const fileChange = container.find('EuiFilePicker').prop('onChange'); - act(() => { + await waitFor(() => { if (fileChange) { fileChange(({ item: () => file } as unknown) as FormEvent); } diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx index ff743d1d5090a7..dc40c997bc8408 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx @@ -6,7 +6,7 @@ import React from 'react'; import { mount } from 'enzyme'; -import { act } from 'react-dom/test-utils'; +import { waitFor } from '@testing-library/react'; import { getListResponseMock } from '../../../../../lists/common/schemas/response/list_schema.mock'; import { exportList, useDeleteList, useFindLists, ListSchema } from '../../../shared_imports'; @@ -46,7 +46,6 @@ describe('ValueListsModal', () => { ); expect(container.find('EuiModal')).toHaveLength(0); - container.unmount(); }); it('renders modal if showModal is true', () => { @@ -57,7 +56,6 @@ describe('ValueListsModal', () => { ); expect(container.find('EuiModal')).toHaveLength(1); - container.unmount(); }); it('calls onClose when modal is closed', () => { @@ -71,7 +69,6 @@ describe('ValueListsModal', () => { container.find('button[data-test-subj="value-lists-modal-close-action"]').simulate('click'); expect(onClose).toHaveBeenCalled(); - container.unmount(); }); it('renders ValueListsForm and an EuiTable', () => { @@ -83,29 +80,27 @@ describe('ValueListsModal', () => { expect(container.find('ValueListsForm')).toHaveLength(1); expect(container.find('EuiBasicTable')).toHaveLength(1); - container.unmount(); }); describe('modal table actions', () => { - it('calls exportList when export is clicked', () => { + it('calls exportList when export is clicked', async () => { const container = mount( ); - act(() => { + await waitFor(() => { container .find('button[data-test-subj="action-export-value-list"]') .first() .simulate('click'); - container.unmount(); }); expect(exportList).toHaveBeenCalledWith(expect.objectContaining({ listId: 'some-list-id' })); }); - it('calls deleteList when delete is clicked', () => { + it('calls deleteList when delete is clicked', async () => { const deleteListMock = jest.fn(); (useDeleteList as jest.Mock).mockReturnValue({ start: deleteListMock, @@ -117,12 +112,11 @@ describe('ValueListsModal', () => { ); - act(() => { + await waitFor(() => { container .find('button[data-test-subj="action-delete-value-list"]') .first() .simulate('click'); - container.unmount(); }); expect(deleteListMock).toHaveBeenCalledWith(expect.objectContaining({ id: 'some-list-id' })); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx index a5d21d28475860..0982b5740b8936 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { mount } from 'enzyme'; import { useParams } from 'react-router-dom'; - +import { waitFor } from '@testing-library/react'; import '../../../common/mock/match_media'; import { apolloClientObservable, @@ -80,7 +80,7 @@ describe('DetectionEnginePageComponent', () => { }); }); - it('renders correctly', () => { + it('renders correctly', async () => { const wrapper = mount( @@ -93,7 +93,8 @@ describe('DetectionEnginePageComponent', () => { ); - - expect(wrapper.find('FiltersGlobal').exists()).toBe(true); + await waitFor(() => { + expect(wrapper.find('FiltersGlobal').exists()).toBe(true); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx index 9f486dc11e99dd..13c6985a30c2b3 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx @@ -6,12 +6,11 @@ import React from 'react'; import { shallow, mount } from 'enzyme'; -import { act } from 'react-dom/test-utils'; import '../../../../../common/mock/match_media'; +import '../../../../../common/mock/formatted_relative'; import { TestProviders } from '../../../../../common/mock'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { AllRules } from './index'; jest.mock('react-router-dom', () => { @@ -198,11 +197,9 @@ describe('AllRules', () => { ); - await act(async () => { - await waitFor(() => { - expect(wrapper.exists('[data-test-subj="monitoring-table"]')).toBeFalsy(); - expect(wrapper.exists('[data-test-subj="rules-table"]')).toBeTruthy(); - }); + await waitFor(() => { + expect(wrapper.exists('[data-test-subj="monitoring-table"]')).toBeFalsy(); + expect(wrapper.exists('[data-test-subj="rules-table"]')).toBeTruthy(); }); }); @@ -226,12 +223,10 @@ describe('AllRules', () => { const monitoringTab = wrapper.find('[data-test-subj="allRulesTableTab-monitoring"] button'); monitoringTab.simulate('click'); - await act(async () => { - await waitFor(() => { - wrapper.update(); - expect(wrapper.exists('[data-test-subj="monitoring-table"]')).toBeTruthy(); - expect(wrapper.exists('[data-test-subj="rules-table"]')).toBeFalsy(); - }); + await waitFor(() => { + wrapper.update(); + expect(wrapper.exists('[data-test-subj="monitoring-table"]')).toBeTruthy(); + expect(wrapper.exists('[data-test-subj="rules-table"]')).toBeFalsy(); }); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx index 22c3c43fb23563..afa4777e748567 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; import { mount } from 'enzyme'; +import { waitFor } from '@testing-library/react'; import '../../../../../common/mock/match_media'; import { @@ -77,7 +78,7 @@ describe('RuleDetailsPageComponent', () => { }); }); - it('renders correctly', () => { + it('renders correctly', async () => { const wrapper = mount( @@ -93,7 +94,8 @@ describe('RuleDetailsPageComponent', () => { wrappingComponent: TestProviders, } ); - - expect(wrapper.find('[data-test-subj="header-page-title"]').exists()).toBe(true); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="header-page-title"]').exists()).toBe(true); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx index f11b0ac4ec3f88..8545e5da512bbd 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import moment from 'moment'; import { GetStepsData, getDefineStepsData, @@ -31,6 +31,8 @@ import { } from './types'; describe('rule helpers', () => { + // @ts-ignore + moment.suppressDeprecationWarnings = true; describe('getStepsData', () => { test('returns object with about, define, schedule and actions step properties formatted', () => { const { diff --git a/x-pack/plugins/security_solution/public/hosts/components/first_last_seen_host/index.test.tsx b/x-pack/plugins/security_solution/public/hosts/components/first_last_seen_host/index.test.tsx index 4f64cca45d1625..4f2dff47af5a6d 100644 --- a/x-pack/plugins/security_solution/public/hosts/components/first_last_seen_host/index.test.tsx +++ b/x-pack/plugins/security_solution/public/hosts/components/first_last_seen_host/index.test.tsx @@ -6,8 +6,7 @@ import React from 'react'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { render, act, wait as waitFor } from '@testing-library/react'; +import { render, waitFor } from '@testing-library/react'; import { useFirstLastSeenHost } from '../../containers/hosts/first_last_seen'; import { TestProviders } from '../../../common/mock'; @@ -26,16 +25,6 @@ describe('FirstLastSeen Component', () => { const firstSeen = 'Apr 8, 2019 @ 16:09:40.692'; const lastSeen = 'Apr 8, 2019 @ 18:35:45.064'; - // Suppress warnings about "react-apollo" until we migrate to apollo@3 - /* eslint-disable no-console */ - const originalError = console.error; - beforeAll(() => { - console.error = jest.fn(); - }); - afterAll(() => { - console.error = originalError; - }); - test('Loading', async () => { useFirstLastSeenHostMock.mockReturnValue([true, MOCKED_RESPONSE]); const { container } = render( @@ -66,13 +55,11 @@ describe('FirstLastSeen Component', () => { ); - await act(() => - waitFor(() => { - expect(container.innerHTML).toBe( - `

${firstSeen}
` - ); - }) - ); + await waitFor(() => { + expect(container.innerHTML).toBe( + `
${firstSeen}
` + ); + }); }); test('Last Seen', async () => { @@ -87,13 +74,11 @@ describe('FirstLastSeen Component', () => { /> ); - await act(() => - waitFor(() => { - expect(container.innerHTML).toBe( - `
${lastSeen}
` - ); - }) - ); + await waitFor(() => { + expect(container.innerHTML).toBe( + `
${lastSeen}
` + ); + }); }); test('First Seen is empty but not Last Seen', async () => { @@ -115,13 +100,11 @@ describe('FirstLastSeen Component', () => { ); - await act(() => - waitFor(() => { - expect(container.innerHTML).toBe( - `
${lastSeen}
` - ); - }) - ); + await waitFor(() => { + expect(container.innerHTML).toBe( + `
${lastSeen}
` + ); + }); }); test('Last Seen is empty but not First Seen', async () => { @@ -143,13 +126,11 @@ describe('FirstLastSeen Component', () => { ); - await act(() => - waitFor(() => { - expect(container.innerHTML).toBe( - `
${firstSeen}
` - ); - }) - ); + await waitFor(() => { + expect(container.innerHTML).toBe( + `
${firstSeen}
` + ); + }); }); test('First Seen With a bad date time string', async () => { @@ -170,11 +151,9 @@ describe('FirstLastSeen Component', () => { /> ); - await act(() => - waitFor(() => { - expect(container.textContent).toBe('something-invalid'); - }) - ); + await waitFor(() => { + expect(container.textContent).toBe('something-invalid'); + }); }); test('Last Seen With a bad date time string', async () => { @@ -195,10 +174,8 @@ describe('FirstLastSeen Component', () => { /> ); - await act(() => - waitFor(() => { - expect(container.textContent).toBe('something-invalid'); - }) - ); + await waitFor(() => { + expect(container.textContent).toBe('something-invalid'); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/endpoint_pagination.test.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/endpoint_pagination.test.ts index b4e00319485e98..1e3a92e6ec1358 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/endpoint_pagination.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/endpoint_pagination.test.ts @@ -26,6 +26,10 @@ import { } from '../../../../common/store/test_utils'; import { getEndpointListPath } from '../../../common/routing'; +jest.mock('../../policy/store/policy_list/services/ingest', () => ({ + sendGetAgentPolicyList: () => Promise.resolve({ items: [] }), + sendGetEndpointSecurityPackage: () => Promise.resolve({}), +})); describe('endpoint list pagination: ', () => { let fakeCoreStart: jest.Mocked; let depsStart: DepsStartMock; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts index c4d2886f3e8e54..d19b3a0ce41778 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts @@ -24,8 +24,9 @@ import { endpointMiddlewareFactory } from './middleware'; import { getEndpointListPath } from '../../../common/routing'; jest.mock('../../policy/store/policy_list/services/ingest', () => ({ - sendGetEndpointSecurityPackage: () => Promise.resolve({}), sendGetAgentConfigList: () => Promise.resolve({ items: [] }), + sendGetAgentPolicyList: () => Promise.resolve({ items: [] }), + sendGetEndpointSecurityPackage: () => Promise.resolve({}), })); describe('endpoint list middleware', () => { diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx index 51a6be18471aa9..bb4be42b04d4ee 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx @@ -7,7 +7,8 @@ import React from 'react'; import * as reactTestingLibrary from '@testing-library/react'; import { EndpointList } from './index'; -import '../../../../common/mock/match_media.ts'; +import '../../../../common/mock/match_media'; + import { mockEndpointDetailsApiResult, mockEndpointResultList, @@ -26,8 +27,25 @@ import { EndpointDocGenerator } from '../../../../../common/endpoint/generate_da import { POLICY_STATUS_TO_HEALTH_COLOR, POLICY_STATUS_TO_TEXT } from './host_constants'; import { mockPolicyResultList } from '../../policy/store/policy_list/test_mock_utils'; -jest.mock('../../../../common/components/link_to'); +// not sure why this can't be imported from '../../../../common/mock/formatted_relative'; +// but sure enough it needs to be inline in this one file +jest.mock('@kbn/i18n/react', () => { + const originalModule = jest.requireActual('@kbn/i18n/react'); + const FormattedRelative = jest.fn().mockImplementation(() => '20 hours ago'); + return { + ...originalModule, + FormattedRelative, + }; +}); +jest.mock('../../../../common/components/link_to'); +jest.mock('../../policy/store/policy_list/services/ingest', () => { + const originalModule = jest.requireActual('../../policy/store/policy_list/services/ingest'); + return { + ...originalModule, + sendGetEndpointSecurityPackage: () => Promise.resolve({}), + }; +}); describe('when on the list page', () => { const docGenerator = new EndpointDocGenerator(); let render: () => ReturnType; @@ -35,7 +53,6 @@ describe('when on the list page', () => { let store: AppContextTestRender['store']; let coreStart: AppContextTestRender['coreStart']; let middlewareSpy: AppContextTestRender['middlewareSpy']; - beforeEach(() => { const mockedContext = createAppRootMockRenderer(); ({ history, store, coreStart, middlewareSpy } = mockedContext); diff --git a/x-pack/plugins/security_solution/public/management/pages/index.test.tsx b/x-pack/plugins/security_solution/public/management/pages/index.test.tsx index c04d3b1ec1a90e..bb947310644f88 100644 --- a/x-pack/plugins/security_solution/public/management/pages/index.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/index.test.tsx @@ -15,10 +15,21 @@ jest.mock('../../common/hooks/endpoint/ingest_enabled'); describe('when in the Admistration tab', () => { let render: () => ReturnType; + let coreStart: AppContextTestRender['coreStart']; beforeEach(() => { const mockedContext = createAppRootMockRenderer(); + coreStart = mockedContext.coreStart; render = () => mockedContext.render(); + coreStart.http.get.mockImplementation(() => + Promise.resolve({ + response: [ + { + name: 'endpoint', + }, + ], + }) + ); }); it('should display the No Permissions view when Ingest is OFF', async () => { diff --git a/x-pack/plugins/security_solution/public/management/pages/index.tsx b/x-pack/plugins/security_solution/public/management/pages/index.tsx index 959753cba7bd75..2d29e33c8d3d5a 100644 --- a/x-pack/plugins/security_solution/public/management/pages/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/index.tsx @@ -71,14 +71,12 @@ const NoPermissions = memo(() => { /> } body={ -

- - - -

+ + + } /> diff --git a/x-pack/plugins/security_solution/public/network/pages/network.test.tsx b/x-pack/plugins/security_solution/public/network/pages/network.test.tsx index 3539fe717e14dc..f600c15f4c7d8d 100644 --- a/x-pack/plugins/security_solution/public/network/pages/network.test.tsx +++ b/x-pack/plugins/security_solution/public/network/pages/network.test.tsx @@ -7,7 +7,7 @@ import { mount } from 'enzyme'; import React from 'react'; import { Router } from 'react-router-dom'; - +import { waitFor } from '@testing-library/react'; import '../../common/mock/match_media'; import { Filter } from '../../../../../../src/plugins/data/common/es_query'; import { useSourcererScope } from '../../common/containers/sourcerer'; @@ -71,7 +71,7 @@ const mockProps = { hasMlUserPermissions: true, }; const mockUseSourcererScope = useSourcererScope as jest.Mock; -describe('rendering - rendering', () => { +describe('Network page - rendering', () => { test('it renders the Setup Instructions text when no index is available', () => { mockUseSourcererScope.mockReturnValue({ selectedPatterns: [], @@ -88,7 +88,7 @@ describe('rendering - rendering', () => { expect(wrapper.find('[data-test-subj="empty-page"]').exists()).toBe(true); }); - test('it DOES NOT render the Setup Instructions text when an index is available', () => { + test('it DOES NOT render the Setup Instructions text when an index is available', async () => { mockUseSourcererScope.mockReturnValue({ selectedPatterns: [], indicesExist: true, @@ -101,10 +101,12 @@ describe('rendering - rendering', () => { ); - expect(wrapper.find('[data-test-subj="empty-page"]').exists()).toBe(false); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="empty-page"]').exists()).toBe(false); + }); }); - test('it should add the new filters after init', () => { + test('it should add the new filters after init', async () => { const newFilters: Filter[] = [ { query: { @@ -157,12 +159,14 @@ describe('rendering - rendering', () => { ); - wrapper.update(); + await waitFor(() => { + wrapper.update(); - myStore.dispatch(inputsActions.setSearchBarFilter({ id: 'global', filters: newFilters })); - wrapper.update(); - expect(wrapper.find(NetworkRoutes).props().filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"match_all":{}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"host.name":"ItRocks"}}],"minimum_should_match":1}}]}}],"should":[],"must_not":[]}}' - ); + myStore.dispatch(inputsActions.setSearchBarFilter({ id: 'global', filters: newFilters })); + wrapper.update(); + expect(wrapper.find(NetworkRoutes).props().filterQuery).toEqual( + '{"bool":{"must":[],"filter":[{"match_all":{}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"host.name":"ItRocks"}}],"minimum_should_match":1}}]}}],"should":[],"must_not":[]}}' + ); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx index 6f1b7e95e763dc..704506d9813d98 100644 --- a/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx @@ -10,9 +10,9 @@ import React from 'react'; import { ThemeProvider } from 'styled-components'; import '../../../common/mock/match_media'; +import '../../../common/mock/react_beautiful_dnd'; import { useMatrixHistogram } from '../../../common/containers/matrix_histogram'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { mockIndexPattern, TestProviders } from '../../../common/mock'; import { AlertsByCategory } from '.'; diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx index fee38ad3c62892..bb47fcd5512fc4 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx @@ -8,6 +8,7 @@ import { mount } from 'enzyme'; import React from 'react'; import '../../../../common/mock/match_media'; +import '../../../../common/mock/react_beautiful_dnd'; import { TestProviders } from '../../../../common/mock'; import { EndpointOverview } from './index'; diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx b/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx index 5406b444cee560..3d275a961bb2ac 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/use_camera.test.tsx @@ -5,8 +5,8 @@ */ import React, { FunctionComponent } from 'react'; -import { render, act, RenderResult, fireEvent } from '@testing-library/react'; -import { renderHook, act as hooksAct } from '@testing-library/react-hooks'; +import { render, waitFor, RenderResult, fireEvent } from '@testing-library/react'; +import { renderHook, act } from '@testing-library/react-hooks'; import { useCamera, useAutoUpdatingClientRect } from './use_camera'; import { Provider } from 'react-redux'; import * as selectors from '../store/selectors'; @@ -69,8 +69,8 @@ describe('useCamera on an unpainted element', () => { const topMargin = 20; const centerX = width / 2 + leftMargin; const centerY = height / 2 + topMargin; - beforeEach(() => { - act(() => { + beforeEach(async () => { + await waitFor(() => { simulator.controls.simulateElementResize(element, { width, height, @@ -97,11 +97,11 @@ describe('useCamera on an unpainted element', () => { const resizeObserverSpy = jest.spyOn(simulator.mock.ResizeObserver.prototype, 'observe'); let [rect, ref] = result.current; - hooksAct(() => ref(element)); + act(() => ref(element)); expect(resizeObserverSpy).toHaveBeenCalledWith(element); const div = document.createElement('div'); - hooksAct(() => ref(div)); + act(() => ref(div)); expect(resizeObserverSpy).toHaveBeenCalledWith(div); [rect, ref] = result.current; @@ -161,7 +161,7 @@ describe('useCamera on an unpainted element', () => { }); describe('when the camera begins animation', () => { let process: SafeResolverEvent; - beforeEach(() => { + beforeEach(async () => { const events: SafeResolverEvent[] = []; const numberOfEvents: number = 10; @@ -184,7 +184,7 @@ describe('useCamera on an unpainted element', () => { type: 'serverReturnedResolverData', payload: { result: tree, parameters: mockTreeFetcherParameters() }, }; - act(() => { + await waitFor(() => { store.dispatch(serverResponseAction); }); } else { @@ -205,7 +205,7 @@ describe('useCamera on an unpainted element', () => { process, }, }; - act(() => { + await waitFor(() => { store.dispatch(cameraAction); }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx index 62306046c7b8cc..4f5e3c814751c7 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx @@ -16,7 +16,6 @@ import { TestProviders } from '../../../common/mock'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; import * as i18n from './translations'; - describe('Category', () => { const timelineId = 'test'; const selectedCategoryId = 'client'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx index 90f4444562c5ab..a3a19d3877fa1f 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx @@ -6,7 +6,7 @@ import { mount } from 'enzyme'; import React from 'react'; - +import { waitFor } from '@testing-library/react'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { TestProviders } from '../../../common/mock'; import '../../../common/mock/match_media'; @@ -44,17 +44,19 @@ describe('FieldName', () => { ).toEqual(timestampFieldId); }); - test('it renders a copy to clipboard action menu item a user hovers over the name', () => { + test('it renders a copy to clipboard action menu item a user hovers over the name', async () => { const wrapper = mount( ); - wrapper.find('[data-test-subj="withHoverActionsButton"]').at(0).simulate('mouseenter'); - wrapper.update(); - jest.runAllTimers(); - wrapper.update(); - expect(wrapper.find('[data-test-subj="copy-to-clipboard"]').exists()).toBe(true); + await waitFor(() => { + wrapper.find('[data-test-subj="withHoverActionsButton"]').at(0).simulate('mouseenter'); + wrapper.update(); + jest.runAllTimers(); + wrapper.update(); + expect(wrapper.find('[data-test-subj="copy-to-clipboard"]').exists()).toBe(true); + }); }); test('it highlights the text specified by the `highlight` prop', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx index a3c7440bece24f..3bfeabc614ea95 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx @@ -6,8 +6,10 @@ import { mount } from 'enzyme'; import React from 'react'; +import { waitFor } from '@testing-library/react'; import '../../../common/mock/match_media'; +import '../../../common/mock/react_beautiful_dnd'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { TestProviders } from '../../../common/mock'; @@ -15,19 +17,6 @@ import { FIELD_BROWSER_HEIGHT, FIELD_BROWSER_WIDTH } from './helpers'; import { StatefulFieldsBrowserComponent } from '.'; -// Suppress warnings about "react-beautiful-dnd" until we migrate to @testing-library/react -/* eslint-disable no-console */ -const originalError = console.error; -const originalWarn = console.warn; -beforeAll(() => { - console.warn = jest.fn(); - console.error = jest.fn(); -}); -afterAll(() => { - console.error = originalError; - console.warn = originalWarn; -}); - describe('StatefulFieldsBrowser', () => { const timelineId = 'test'; @@ -93,7 +82,7 @@ describe('StatefulFieldsBrowser', () => { beforeEach(() => { jest.useFakeTimers(); }); - test('it updates the selectedCategoryId state, which makes the category bold, when the user clicks a category name in the left hand side of the field browser', () => { + test('it updates the selectedCategoryId state, which makes the category bold, when the user clicks a category name in the left hand side of the field browser', async () => { const wrapper = mount( { wrapper.find('[data-test-subj="show-field-browser"]').first().simulate('click'); wrapper.find(`.field-browser-category-pane-auditd-${timelineId}`).first().simulate('click'); - - wrapper.update(); - expect( - wrapper.find(`.field-browser-category-pane-auditd-${timelineId}`).at(1) - ).toHaveStyleRule('font-weight', 'bold', { modifier: '.euiText' }); + await waitFor(() => { + wrapper.update(); + expect( + wrapper.find(`.field-browser-category-pane-auditd-${timelineId}`).at(1) + ).toHaveStyleRule('font-weight', 'bold', { modifier: '.euiText' }); + }); }); - test('it updates the selectedCategoryId state according to most fields returned', () => { + test('it updates the selectedCategoryId state according to most fields returned', async () => { const wrapper = mount( { ); - wrapper.find('[data-test-subj="show-field-browser"]').first().simulate('click'); - expect( - wrapper.find(`.field-browser-category-pane-cloud-${timelineId}`).at(1) - ).toHaveStyleRule('font-weight', 'normal', { modifier: '.euiText' }); - wrapper - .find('[data-test-subj="field-search"]') - .last() - .simulate('change', { target: { value: 'cloud' } }); - - jest.runOnlyPendingTimers(); - wrapper.update(); - expect( - wrapper.find(`.field-browser-category-pane-cloud-${timelineId}`).at(1) - ).toHaveStyleRule('font-weight', 'bold', { modifier: '.euiText' }); + await waitFor(() => { + wrapper.find('[data-test-subj="show-field-browser"]').first().simulate('click'); + expect( + wrapper.find(`.field-browser-category-pane-cloud-${timelineId}`).at(1) + ).toHaveStyleRule('font-weight', 'normal', { modifier: '.euiText' }); + wrapper + .find('[data-test-subj="field-search"]') + .last() + .simulate('change', { target: { value: 'cloud' } }); + + jest.runOnlyPendingTimers(); + wrapper.update(); + expect( + wrapper.find(`.field-browser-category-pane-cloud-${timelineId}`).at(1) + ).toHaveStyleRule('font-weight', 'bold', { modifier: '.euiText' }); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx index aa19fb6f68ed4a..95ad5285507c5b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx @@ -8,6 +8,7 @@ import { mount, shallow } from 'enzyme'; import { set } from '@elastic/safer-lodash-set/fp'; import React from 'react'; import { ActionCreator } from 'typescript-fsa'; +import '../../../common/mock/react_beautiful_dnd'; import { apolloClientObservable, diff --git a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/index.test.tsx index a927627353f691..8aebc8519bcb75 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/index.test.tsx @@ -8,6 +8,7 @@ import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { ThemeProvider } from 'styled-components'; import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; +import '../../../../common/mock/formatted_relative'; import { NoteCard } from '.'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_card_header.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_card_header.test.tsx index fcb0d0294fa225..bc46c238c5ae86 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_card_header.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_card_header.test.tsx @@ -7,6 +7,7 @@ import moment from 'moment-timezone'; import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; +import '../../../../common/mock/formatted_relative'; import * as i18n from '../translations'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_created.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_created.test.tsx index 4bb9a6b666a87d..7b51a9eaa1a2d4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_created.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/notes/note_card/note_created.test.tsx @@ -7,6 +7,7 @@ import moment from 'moment-timezone'; import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; +import '../../../../common/mock/formatted_relative'; import { NoteCreated } from './note_created'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/notes/note_cards/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/notes/note_cards/index.test.tsx index 952295d0858eea..5506514999f35f 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/notes/note_cards/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/notes/note_cards/index.test.tsx @@ -8,6 +8,7 @@ import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { ThemeProvider } from 'styled-components'; import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; +import '../../../../common/mock/formatted_relative'; import { Note } from '../../../../common/lib/note'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx index 64b9db59467e12..f6ac1ab4cec3e0 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx @@ -14,11 +14,11 @@ import { waitFor } from '@testing-library/react'; import { useHistory, useParams } from 'react-router-dom'; import '../../../common/mock/match_media'; +import '../../../common/mock/formatted_relative'; import { SecurityPageName } from '../../../app/types'; import { TimelineType } from '../../../../common/types/timeline'; -import { TestProviders, apolloClient } from '../../../common/mock/test_providers'; -import { mockOpenTimelineQueryResults } from '../../../common/mock/timeline_results'; +import { TestProviders, apolloClient, mockOpenTimelineQueryResults } from '../../../common/mock'; import { getTimelineTabsUrl } from '../../../common/components/link_to'; import { DEFAULT_SEARCH_RESULTS_PER_PAGE } from '../../pages/timelines_page'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.test.tsx index 3f737a5ba73db8..cb0eba910c3422 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/index.test.tsx @@ -10,6 +10,7 @@ import moment from 'moment'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../../common/mock/formatted_relative'; import { mockTimelineResults } from '../../../../common/mock/timeline_results'; import { OpenTimelineResult, TimelineResultNote } from '../types'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/note_preview.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/note_preview.test.tsx index e23c9b7fe20836..feabe46edfa826 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/note_preview.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/note_previews/note_preview.test.tsx @@ -8,6 +8,7 @@ import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../../common/mock/formatted_relative'; import { getEmptyValue } from '../../../../common/components/empty_value'; import { NotePreview } from './note_preview'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx index 3d5c5f60d1d9b0..2d5849463270bf 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx @@ -9,7 +9,7 @@ import { cloneDeep } from 'lodash/fp'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; -import { act } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import '../../../common/mock/match_media'; import { DEFAULT_SEARCH_RESULTS_PER_PAGE } from '../../pages/timelines_page'; @@ -293,7 +293,7 @@ describe('OpenTimeline', () => { ); wrapper.find('[data-test-subj="utility-bar-action"]').find('EuiLink').simulate('click'); - await act(async () => { + await waitFor(() => { expect( wrapper.find('[data-test-subj="export-timeline-action"]').first().prop('disabled') ).toEqual(true); @@ -313,7 +313,7 @@ describe('OpenTimeline', () => { ); wrapper.find('[data-test-subj="utility-bar-action"]').find('EuiLink').simulate('click'); - await act(async () => { + await waitFor(() => { expect( wrapper.find('[data-test-subj="delete-timeline-action"]').first().prop('disabled') ).toEqual(true); @@ -333,7 +333,7 @@ describe('OpenTimeline', () => { ); wrapper.find('[data-test-subj="utility-bar-action"]').find('EuiLink').simulate('click'); - await act(async () => { + await waitFor(() => { expect( wrapper.find('[data-test-subj="export-timeline-action"]').first().prop('disabled') ).toEqual(false); @@ -353,7 +353,7 @@ describe('OpenTimeline', () => { ); wrapper.find('[data-test-subj="utility-bar-action"]').find('EuiLink').simulate('click'); - await act(async () => { + await waitFor(() => { expect( wrapper.find('[data-test-subj="delete-timeline-action"]').first().prop('disabled') ).toEqual(false); diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx index 9632b0e6ecea4b..2744e0b42efce6 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx @@ -49,7 +49,7 @@ describe('OpenTimelineModal', () => { sortField: DEFAULT_SORT_FIELD, timelineType: TimelineType.default, timelineStatus: TimelineStatus.active, - templateTimelineFilter: [
], + templateTimelineFilter: [
], title, totalSearchResultsCount: mockSearchResults.length, }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx index ea587aeca2061e..35b6c99c04176c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx @@ -10,8 +10,7 @@ import React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; import { ThemeProvider } from 'styled-components'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { TestProviders } from '../../../../common/mock/test_providers'; import { mockOpenTimelineQueryResults } from '../../../../common/mock/timeline_results'; import * as i18n from '../translations'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx index b8b2630e09c6e0..18270a30eb0e17 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx @@ -12,6 +12,7 @@ import { ThemeProvider } from 'styled-components'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import '../../../../common/mock/match_media'; +import '../../../../common/mock/formatted_relative'; import { getEmptyValue } from '../../../../common/components/empty_value'; import { OpenTimelineResult } from '../types'; import { mockTimelineResults } from '../../../../common/mock/timeline_results'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header_tooltip_content/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header_tooltip_content/index.tsx index efad85775a9e46..a08820e9435d37 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header_tooltip_content/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/header_tooltip_content/index.tsx @@ -20,13 +20,14 @@ const IconType = styled(EuiIcon)` `; IconType.displayName = 'IconType'; -const P = styled.p` +const P = styled.span` margin-bottom: 5px; `; P.displayName = 'P'; const ToolTipTableMetadata = styled.span` margin-right: 5px; + display: block; `; ToolTipTableMetadata.displayName = 'ToolTipTableMetadata'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx index 8b859c1746a468..8fa5d18c0c4f50 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx @@ -15,8 +15,7 @@ import { TestProviders } from '../../../../common/mock/test_providers'; import { Body, BodyProps } from '.'; import { columnRenderers, rowRenderers } from './renderers'; import { Sort } from './sort'; -// we don't have the types for waitFor just yet, so using "as waitFor" until when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { useMountAppended } from '../../../../common/utils/use_mount_appended'; import { SELECTOR_TIMELINE_BODY_CLASS_NAME, TimelineBody } from '../styles'; import { TimelineType } from '../../../../../common/types/timeline'; @@ -195,22 +194,6 @@ describe('Body', () => { wrapper.update(); }; - // We are doing that because we need to wrapped this component with redux - // and redux does not like to be updated and since we need to update our - // child component (BODY) and we do not want to scare anyone with this error - // we are hiding it!!! - // eslint-disable-next-line no-console - const originalError = console.error; - beforeAll(() => { - // eslint-disable-next-line no-console - console.error = (...args: string[]) => { - if (/ does not support changing `store` on the fly/.test(args[0])) { - return; - } - originalError.call(console, ...args); - }; - }); - beforeEach(() => { dispatchAddNoteToEvent.mockClear(); dispatchOnPinEvent.mockClear(); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx index efb19275336db4..19344a7fd7c9b4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx @@ -22,8 +22,7 @@ import { useThrottledResizeObserver } from '../../../../common/components/utils' import { Properties, showDescriptionThreshold, showNotesThreshold } from '.'; import { setInsertTimeline } from '../../../store/timeline/actions'; export { nextTick } from '../../../../../../../test_utils'; - -import { act } from 'react-dom/test-utils'; +import { waitFor } from '@testing-library/react'; jest.mock('../../../../common/components/link_to'); @@ -372,18 +371,16 @@ describe('Properties', () => { wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); wrapper.find('[data-test-subj="attach-timeline-case"]').first().simulate('click'); - await act(async () => { - await Promise.resolve({}); + await waitFor(() => { + expect(mockNavigateToApp).toBeCalledWith('securitySolution:case', { path: '/create' }); + expect(mockDispatch).toBeCalledWith( + setInsertTimeline({ + timelineId: defaultProps.timelineId, + timelineSavedObjectId: '1', + timelineTitle: 'coolness', + }) + ); }); - - expect(mockNavigateToApp).toBeCalledWith('securitySolution:case', { path: '/create' }); - expect(mockDispatch).toBeCalledWith( - setInsertTimeline({ - timelineId: defaultProps.timelineId, - timelineSavedObjectId: '1', - timelineTitle: 'coolness', - }) - ); }); test('insert timeline - existing case', async () => { @@ -397,9 +394,8 @@ describe('Properties', () => { wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click'); wrapper.find('[data-test-subj="attach-timeline-existing-case"]').first().simulate('click'); - await act(async () => { - await Promise.resolve({}); + await waitFor(() => { + expect(wrapper.find('[data-test-subj="all-cases-modal"]').exists()).toBeTruthy(); }); - expect(wrapper.find('[data-test-subj="all-cases-modal"]').exists()).toBeTruthy(); }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx index 7da3cf940da50f..c21592bed12e09 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import React from 'react'; -import { act as actDom } from 'react-dom/test-utils'; +import { waitFor } from '@testing-library/react'; import { renderHook, act } from '@testing-library/react-hooks'; import { mount, shallow } from 'enzyme'; @@ -86,7 +86,7 @@ describe('useCreateTimelineButton', () => { await waitForNextUpdate(); const button = result.current.getButton({ outline: false, title: 'mock title' }); - actDom(() => { + await waitFor(() => { const wrapper = mount(button); wrapper.update(); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx index 6c8fd4975c6578..87956647c11f18 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx @@ -24,22 +24,6 @@ const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; jest.mock('../../../../common/lib/kibana'); describe('Timeline QueryBar ', () => { - // We are doing that because we need to wrapped this component with redux - // and redux does not like to be updated and since we need to update our - // child component (BODY) and we do not want to scare anyone with this error - // we are hiding it!!! - // eslint-disable-next-line no-console - const originalError = console.error; - beforeAll(() => { - // eslint-disable-next-line no-console - console.error = (...args: string[]) => { - if (/ does not support changing `store` on the fly/.test(args[0])) { - return; - } - originalError.call(console, ...args); - }; - }); - const mockApplyKqlFilterQuery = jest.fn(); const mockSetFilters = jest.fn(); const mockSetKqlFilterQueryDraft = jest.fn(); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.test.tsx index b64ca0ccc0b356..519372d0ac7975 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/selectable_timeline/index.test.tsx @@ -7,31 +7,18 @@ import React from 'react'; import { shallow, ShallowWrapper, mount } from 'enzyme'; import { TimelineType } from '../../../../../common/types/timeline'; import { SortFieldTimeline, Direction } from '../../../../graphql/types'; -import { SearchProps } from './'; +import { SelectableTimeline, ORIGINAL_PAGE_SIZE, SearchProps } from './'; +const mockFetchAllTimeline = jest.fn(); +jest.mock('../../../containers/all', () => { + return { + useGetAllTimeline: jest.fn(() => ({ + fetchAllTimeline: mockFetchAllTimeline, + timelines: [], + })), + }; +}); describe('SelectableTimeline', () => { - const mockFetchAllTimeline = jest.fn(); - const mockEuiSelectable = jest.fn(); - - jest.doMock('@elastic/eui', () => { - const originalModule = jest.requireActual('@elastic/eui'); - return { - ...originalModule, - EuiSelectable: mockEuiSelectable.mockImplementation(({ children }) =>
{children}
), - }; - }); - - jest.doMock('../../../containers/all', () => { - return { - useGetAllTimeline: jest.fn(() => ({ - fetchAllTimeline: mockFetchAllTimeline, - timelines: [], - })), - }; - }); - - const { SelectableTimeline, ORIGINAL_PAGE_SIZE } = jest.requireActual('./'); - const props = { hideUntitled: false, getSelectableOptions: jest.fn(), diff --git a/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts b/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts index 8ef740f7bc1d70..a439699d27f6d1 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/api.test.ts @@ -11,157 +11,101 @@ import { ImportDataProps } from '../../detections/containers/detection_engine/ru jest.mock('../../common/lib/kibana', () => { return { - KibanaServices: { get: jest.fn(() => ({ http: { fetch: jest.fn() } })) }, + KibanaServices: { + get: jest.fn(() => ({ + http: { + fetch: jest.fn(), + }, + })), + }, }; }); +const timelineData = { + columns: [ + { + columnHeaderType: 'not-filtered', + id: '@timestamp', + }, + { + columnHeaderType: 'not-filtered', + id: 'message', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.category', + }, + { + columnHeaderType: 'not-filtered', + id: 'event.action', + }, + { + columnHeaderType: 'not-filtered', + id: 'host.name', + }, + { + columnHeaderType: 'not-filtered', + id: 'source.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'destination.ip', + }, + { + columnHeaderType: 'not-filtered', + id: 'user.name', + }, + ], + dataProviders: [], + description: 'x', + eventType: 'all', + filters: [], + kqlMode: 'filter', + kqlQuery: { + filterQuery: null, + }, + title: '', + timelineType: TimelineType.default, + templateTimelineVersion: null, + templateTimelineId: null, + dateRange: { + start: 1590998565409, + end: 1591084965409, + }, + savedQueryId: null, + sort: { + columnId: '@timestamp', + sortDirection: 'desc', + }, + status: TimelineStatus.active, +}; +const mockPatchTimelineResponse = { + data: { + persistTimeline: { + code: 200, + message: 'success', + timeline: { + ...timelineData, + savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', + version: 'WzM0NSwxXQ==', + }, + }, + }, +}; describe('persistTimeline', () => { describe('create draft timeline', () => { const timelineId = null; const initialDraftTimeline = { - columns: [ - { - columnHeaderType: 'not-filtered', - id: '@timestamp', - }, - { - columnHeaderType: 'not-filtered', - id: 'message', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.category', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.action', - }, - { - columnHeaderType: 'not-filtered', - id: 'host.name', - }, - { - columnHeaderType: 'not-filtered', - id: 'source.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'destination.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'user.name', - }, - ], - dataProviders: [], - description: 'x', - eventType: 'all', - filters: [], - kqlMode: 'filter', - kqlQuery: { - filterQuery: null, - }, - title: '', - timelineType: TimelineType.default, - templateTimelineVersion: null, - templateTimelineId: null, - dateRange: { - start: 1590998565409, - end: 1591084965409, - }, - savedQueryId: null, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + ...timelineData, status: TimelineStatus.draft, }; const mockDraftResponse = { data: { persistTimeline: { timeline: { + ...initialDraftTimeline, savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', version: 'WzMzMiwxXQ==', - columns: [ - { columnHeaderType: 'not-filtered', id: '@timestamp' }, - { columnHeaderType: 'not-filtered', id: 'message' }, - { columnHeaderType: 'not-filtered', id: 'event.category' }, - { columnHeaderType: 'not-filtered', id: 'event.action' }, - { columnHeaderType: 'not-filtered', id: 'host.name' }, - { columnHeaderType: 'not-filtered', id: 'source.ip' }, - { columnHeaderType: 'not-filtered', id: 'destination.ip' }, - { columnHeaderType: 'not-filtered', id: 'user.name' }, - ], - dataProviders: [], - description: '', - eventType: 'all', - filters: [], - kqlMode: 'filter', - timelineType: 'default', - kqlQuery: { filterQuery: null }, - title: '', - sort: { columnId: '@timestamp', sortDirection: 'desc' }, - status: 'draft', - created: 1591091394733, - createdBy: 'angela', - updated: 1591091394733, - updatedBy: 'angela', - templateTimelineId: null, - templateTimelineVersion: null, - dateRange: { start: 1590998565409, end: 1591084965409 }, - savedQueryId: null, - favorite: [], - eventIdToNoteIds: [], - noteIds: [], - notes: [], - pinnedEventIds: [], - pinnedEventsSaveObject: [], - }, - }, - }, - }; - const mockPatchTimelineResponse = { - data: { - persistTimeline: { - code: 200, - message: 'success', - timeline: { - savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', - version: 'WzM0NSwxXQ==', - columns: [ - { columnHeaderType: 'not-filtered', id: '@timestamp' }, - { columnHeaderType: 'not-filtered', id: 'message' }, - { columnHeaderType: 'not-filtered', id: 'event.category' }, - { columnHeaderType: 'not-filtered', id: 'event.action' }, - { columnHeaderType: 'not-filtered', id: 'host.name' }, - { columnHeaderType: 'not-filtered', id: 'source.ip' }, - { columnHeaderType: 'not-filtered', id: 'destination.ip' }, - { columnHeaderType: 'not-filtered', id: 'user.name' }, - ], - dataProviders: [], - description: 'x', - eventType: 'all', - filters: [], - kqlMode: 'filter', - timelineType: 'default', - kqlQuery: { filterQuery: null }, - title: '', - sort: { columnId: '@timestamp', sortDirection: 'desc' }, - status: 'draft', - created: 1591092702804, - createdBy: 'angela', - updated: 1591092705206, - updatedBy: 'angela', - templateTimelineId: null, - templateTimelineVersion: null, - dateRange: { start: 1590998565409, end: 1591084965409 }, - savedQueryId: null, - favorite: [], - eventIdToNoteIds: [], - noteIds: [], - notes: [], - pinnedEventIds: [], - pinnedEventsSaveObject: [], }, }, }, @@ -223,61 +167,7 @@ describe('persistTimeline', () => { describe('create draft timeline in read-only permission', () => { const timelineId = null; const initialDraftTimeline = { - columns: [ - { - columnHeaderType: 'not-filtered', - id: '@timestamp', - }, - { - columnHeaderType: 'not-filtered', - id: 'message', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.category', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.action', - }, - { - columnHeaderType: 'not-filtered', - id: 'host.name', - }, - { - columnHeaderType: 'not-filtered', - id: 'source.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'destination.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'user.name', - }, - ], - dataProviders: [], - description: 'x', - eventType: 'all', - filters: [], - kqlMode: 'filter', - kqlQuery: { - filterQuery: null, - }, - title: '', - timelineType: TimelineType.default, - templateTimelineVersion: null, - templateTimelineId: null, - dateRange: { - start: 1590998565409, - end: 1591084965409, - }, - savedQueryId: null, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, + ...timelineData, status: TimelineStatus.draft, }; @@ -325,104 +215,14 @@ describe('persistTimeline', () => { describe('create active timeline (import)', () => { const timelineId = null; - const importTimeline = { - columns: [ - { - columnHeaderType: 'not-filtered', - id: '@timestamp', - }, - { - columnHeaderType: 'not-filtered', - id: 'message', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.category', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.action', - }, - { - columnHeaderType: 'not-filtered', - id: 'host.name', - }, - { - columnHeaderType: 'not-filtered', - id: 'source.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'destination.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'user.name', - }, - ], - dataProviders: [], - description: 'x', - eventType: 'all', - filters: [], - kqlMode: 'filter', - kqlQuery: { - filterQuery: null, - }, - title: '', - timelineType: TimelineType.default, - templateTimelineVersion: null, - templateTimelineId: null, - dateRange: { - start: 1590998565409, - end: 1591084965409, - }, - savedQueryId: null, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, - status: TimelineStatus.active, - }; + const importTimeline = timelineData; const mockPostTimelineResponse = { data: { persistTimeline: { timeline: { + ...timelineData, savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', version: 'WzMzMiwxXQ==', - columns: [ - { columnHeaderType: 'not-filtered', id: '@timestamp' }, - { columnHeaderType: 'not-filtered', id: 'message' }, - { columnHeaderType: 'not-filtered', id: 'event.category' }, - { columnHeaderType: 'not-filtered', id: 'event.action' }, - { columnHeaderType: 'not-filtered', id: 'host.name' }, - { columnHeaderType: 'not-filtered', id: 'source.ip' }, - { columnHeaderType: 'not-filtered', id: 'destination.ip' }, - { columnHeaderType: 'not-filtered', id: 'user.name' }, - ], - dataProviders: [], - description: '', - eventType: 'all', - filters: [], - kqlMode: 'filter', - timelineType: 'default', - kqlQuery: { filterQuery: null }, - title: '', - sort: { columnId: '@timestamp', sortDirection: 'desc' }, - status: 'draft', - created: 1591091394733, - createdBy: 'angela', - updated: 1591091394733, - updatedBy: 'angela', - templateTimelineId: null, - templateTimelineVersion: null, - dateRange: { start: 1590998565409, end: 1591084965409 }, - savedQueryId: null, - favorite: [], - eventIdToNoteIds: [], - noteIds: [], - notes: [], - pinnedEventIds: [], - pinnedEventsSaveObject: [], }, }, }, @@ -462,104 +262,16 @@ describe('persistTimeline', () => { describe('update active timeline', () => { const timelineId = '9d5693e0-a42a-11ea-b8f4-c5434162742a'; - const inputTimeline = { - columns: [ - { - columnHeaderType: 'not-filtered', - id: '@timestamp', - }, - { - columnHeaderType: 'not-filtered', - id: 'message', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.category', - }, - { - columnHeaderType: 'not-filtered', - id: 'event.action', - }, - { - columnHeaderType: 'not-filtered', - id: 'host.name', - }, - { - columnHeaderType: 'not-filtered', - id: 'source.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'destination.ip', - }, - { - columnHeaderType: 'not-filtered', - id: 'user.name', - }, - ], - dataProviders: [], - description: 'x', - eventType: 'all', - filters: [], - kqlMode: 'filter', - kqlQuery: { - filterQuery: null, - }, - title: '', - timelineType: TimelineType.default, - templateTimelineVersion: null, - templateTimelineId: null, - dateRange: { - start: 1590998565409, - end: 1591084965409, - }, - savedQueryId: null, - sort: { - columnId: '@timestamp', - sortDirection: 'desc', - }, - status: TimelineStatus.active, - }; - const mockPatchTimelineResponse = { + const inputTimeline = timelineData; + const mockPatchTimelineResponseNew = { data: { persistTimeline: { timeline: { - savedObjectId: '9d5693e0-a42a-11ea-b8f4-c5434162742a', + ...mockPatchTimelineResponse.data.persistTimeline.timeline, version: 'WzMzMiwxXQ==', - columns: [ - { columnHeaderType: 'not-filtered', id: '@timestamp' }, - { columnHeaderType: 'not-filtered', id: 'message' }, - { columnHeaderType: 'not-filtered', id: 'event.category' }, - { columnHeaderType: 'not-filtered', id: 'event.action' }, - { columnHeaderType: 'not-filtered', id: 'host.name' }, - { columnHeaderType: 'not-filtered', id: 'source.ip' }, - { columnHeaderType: 'not-filtered', id: 'destination.ip' }, - { columnHeaderType: 'not-filtered', id: 'user.name' }, - ], - dataProviders: [], - description: '', - eventType: 'all', - filters: [], - kqlMode: 'filter', - timelineType: 'default', - kqlQuery: { filterQuery: null }, - title: '', - sort: { columnId: '@timestamp', sortDirection: 'desc' }, - status: 'draft', - created: 1591091394733, - createdBy: 'angela', - updated: 1591091394733, - updatedBy: 'angela', - templateTimelineId: null, - templateTimelineVersion: null, - dateRange: { start: 1590998565409, end: 1591084965409 }, - savedQueryId: null, - favorite: [], - eventIdToNoteIds: [], - noteIds: [], - notes: [], - pinnedEventIds: [], - pinnedEventsSaveObject: [], + description: 'x', + created: 1591092702804, + updated: 1591092705206, }, }, }, @@ -578,7 +290,7 @@ describe('persistTimeline', () => { http: { fetch: fetchMock, post: postMock, - patch: patchMock.mockReturnValue(mockPatchTimelineResponse), + patch: patchMock.mockReturnValue(mockPatchTimelineResponseNew), }, }); api.persistTimeline({ timelineId, timeline: inputTimeline, version }); @@ -674,7 +386,7 @@ describe('getDraftTimeline', () => { (KibanaServices.get as jest.Mock).mockReturnValue({ http: { - get: getMock, + get: getMock.mockImplementation(() => Promise.resolve(mockPatchTimelineResponse)), }, }); api.getDraftTimeline(timelineType); @@ -696,7 +408,7 @@ describe('cleanDraftTimeline', () => { (KibanaServices.get as jest.Mock).mockReturnValue({ http: { - post: postMock, + post: postMock.mockImplementation(() => Promise.resolve(mockPatchTimelineResponse)), }, }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx b/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx index 6507603d304447..1f79b26394a69e 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { shallow } from 'enzyme'; // we don't have the types for waitFor just yet, so using "as waitFor" for when we do -import { wait as waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import '../../../common/mock/match_media'; import { mockGlobalState, From f0a5ec98773a809c06f3d6ad2dfe946be566eb58 Mon Sep 17 00:00:00 2001 From: Matthew Kime Date: Mon, 28 Sep 2020 09:08:21 -0500 Subject: [PATCH 06/19] Index pattern class - remove unused methods (#78538) * remove unused methods --- ...ta-public.indexpattern.addscriptedfield.md | 3 +-- ...public.indexpattern.istimebasedwildcard.md | 15 ------------- ...plugin-plugins-data-public.indexpattern.md | 3 +-- ...ta-server.indexpattern.addscriptedfield.md | 3 +-- ...server.indexpattern.istimebasedwildcard.md | 15 ------------- ...plugin-plugins-data-server.indexpattern.md | 3 +-- .../index_patterns/index_pattern.test.ts | 5 ++--- .../index_patterns/index_pattern.ts | 22 +++---------------- src/plugins/data/public/public.api.md | 4 +--- src/plugins/data/server/server.api.md | 4 +--- 10 files changed, 11 insertions(+), 66 deletions(-) delete mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.istimebasedwildcard.md delete mode 100644 docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.istimebasedwildcard.md diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md index cc3468531fffae..99d2fc00a6b7b6 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md @@ -9,7 +9,7 @@ Add scripted field to field list Signature: ```typescript -addScriptedField(name: string, script: string, fieldType?: string, lang?: string): Promise; +addScriptedField(name: string, script: string, fieldType?: string): Promise; ``` ## Parameters @@ -19,7 +19,6 @@ addScriptedField(name: string, script: string, fieldType?: string, lang?: string | name | string | | | script | string | | | fieldType | string | | -| lang | string | | Returns: diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.istimebasedwildcard.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.istimebasedwildcard.md deleted file mode 100644 index 27f99f418a0780..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.istimebasedwildcard.md +++ /dev/null @@ -1,15 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPattern](./kibana-plugin-plugins-data-public.indexpattern.md) > [isTimeBasedWildcard](./kibana-plugin-plugins-data-public.indexpattern.istimebasedwildcard.md) - -## IndexPattern.isTimeBasedWildcard() method - -Signature: - -```typescript -isTimeBasedWildcard(): boolean; -``` -Returns: - -`boolean` - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md index 2ff575bc4fc225..325b97383e328d 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md @@ -41,7 +41,7 @@ export declare class IndexPattern implements IIndexPattern | Method | Modifiers | Description | | --- | --- | --- | -| [addScriptedField(name, script, fieldType, lang)](./kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md) | | Add scripted field to field list | +| [addScriptedField(name, script, fieldType)](./kibana-plugin-plugins-data-public.indexpattern.addscriptedfield.md) | | Add scripted field to field list | | [getAggregationRestrictions()](./kibana-plugin-plugins-data-public.indexpattern.getaggregationrestrictions.md) | | | | [getAsSavedObjectBody()](./kibana-plugin-plugins-data-public.indexpattern.getassavedobjectbody.md) | | Returns index pattern as saved object body for saving | | [getComputedFields()](./kibana-plugin-plugins-data-public.indexpattern.getcomputedfields.md) | | | @@ -52,7 +52,6 @@ export declare class IndexPattern implements IIndexPattern | [getSourceFiltering()](./kibana-plugin-plugins-data-public.indexpattern.getsourcefiltering.md) | | Get the source filtering configuration for that index. | | [getTimeField()](./kibana-plugin-plugins-data-public.indexpattern.gettimefield.md) | | | | [isTimeBased()](./kibana-plugin-plugins-data-public.indexpattern.istimebased.md) | | | -| [isTimeBasedWildcard()](./kibana-plugin-plugins-data-public.indexpattern.istimebasedwildcard.md) | | | | [isTimeNanosBased()](./kibana-plugin-plugins-data-public.indexpattern.istimenanosbased.md) | | | | [popularizeField(fieldName, unit)](./kibana-plugin-plugins-data-public.indexpattern.popularizefield.md) | | | | [removeScriptedField(fieldName)](./kibana-plugin-plugins-data-public.indexpattern.removescriptedfield.md) | | Remove scripted field from field list | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md index 6d206e88b5b56a..a86fea3106225a 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md @@ -9,7 +9,7 @@ Add scripted field to field list Signature: ```typescript -addScriptedField(name: string, script: string, fieldType?: string, lang?: string): Promise; +addScriptedField(name: string, script: string, fieldType?: string): Promise; ``` ## Parameters @@ -19,7 +19,6 @@ addScriptedField(name: string, script: string, fieldType?: string, lang?: string | name | string | | | script | string | | | fieldType | string | | -| lang | string | | Returns: diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.istimebasedwildcard.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.istimebasedwildcard.md deleted file mode 100644 index 7ef5e8318040a1..00000000000000 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.istimebasedwildcard.md +++ /dev/null @@ -1,15 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [IndexPattern](./kibana-plugin-plugins-data-server.indexpattern.md) > [isTimeBasedWildcard](./kibana-plugin-plugins-data-server.indexpattern.istimebasedwildcard.md) - -## IndexPattern.isTimeBasedWildcard() method - -Signature: - -```typescript -isTimeBasedWildcard(): boolean; -``` -Returns: - -`boolean` - diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.md index d877854444a090..e5a9e7d8f9f933 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.md @@ -41,7 +41,7 @@ export declare class IndexPattern implements IIndexPattern | Method | Modifiers | Description | | --- | --- | --- | -| [addScriptedField(name, script, fieldType, lang)](./kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md) | | Add scripted field to field list | +| [addScriptedField(name, script, fieldType)](./kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md) | | Add scripted field to field list | | [getAggregationRestrictions()](./kibana-plugin-plugins-data-server.indexpattern.getaggregationrestrictions.md) | | | | [getAsSavedObjectBody()](./kibana-plugin-plugins-data-server.indexpattern.getassavedobjectbody.md) | | Returns index pattern as saved object body for saving | | [getComputedFields()](./kibana-plugin-plugins-data-server.indexpattern.getcomputedfields.md) | | | @@ -52,7 +52,6 @@ export declare class IndexPattern implements IIndexPattern | [getSourceFiltering()](./kibana-plugin-plugins-data-server.indexpattern.getsourcefiltering.md) | | Get the source filtering configuration for that index. | | [getTimeField()](./kibana-plugin-plugins-data-server.indexpattern.gettimefield.md) | | | | [isTimeBased()](./kibana-plugin-plugins-data-server.indexpattern.istimebased.md) | | | -| [isTimeBasedWildcard()](./kibana-plugin-plugins-data-server.indexpattern.istimebasedwildcard.md) | | | | [isTimeNanosBased()](./kibana-plugin-plugins-data-server.indexpattern.istimenanosbased.md) | | | | [popularizeField(fieldName, unit)](./kibana-plugin-plugins-data-server.indexpattern.popularizefield.md) | | | | [removeScriptedField(fieldName)](./kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md) | | Remove scripted field from field list | diff --git a/src/plugins/data/common/index_patterns/index_patterns/index_pattern.test.ts b/src/plugins/data/common/index_patterns/index_patterns/index_pattern.test.ts index 91286a38f16a08..bfb5fd9da56e6c 100644 --- a/src/plugins/data/common/index_patterns/index_patterns/index_pattern.test.ts +++ b/src/plugins/data/common/index_patterns/index_patterns/index_pattern.test.ts @@ -179,8 +179,7 @@ describe('IndexPattern', () => { await indexPattern.addScriptedField( scriptedField.name, scriptedField.script, - scriptedField.type, - 'lang' + scriptedField.type ); const scriptedFields = indexPattern.getScriptedFields(); @@ -206,7 +205,7 @@ describe('IndexPattern', () => { const scriptedField = last(scriptedFields) as any; expect.assertions(1); try { - await indexPattern.addScriptedField(scriptedField.name, "'new script'", 'string', 'lang'); + await indexPattern.addScriptedField(scriptedField.name, "'new script'", 'string'); } catch (e) { expect(e).toBeInstanceOf(DuplicateField); } diff --git a/src/plugins/data/common/index_patterns/index_patterns/index_pattern.ts b/src/plugins/data/common/index_patterns/index_patterns/index_pattern.ts index 882235889b55c8..e880c3a9ff825a 100644 --- a/src/plugins/data/common/index_patterns/index_patterns/index_pattern.ts +++ b/src/plugins/data/common/index_patterns/index_patterns/index_pattern.ts @@ -234,12 +234,7 @@ export class IndexPattern implements IIndexPattern { * @param fieldType * @param lang */ - async addScriptedField( - name: string, - script: string, - fieldType: string = 'string', - lang: string = 'painless' - ) { + async addScriptedField(name: string, script: string, fieldType: string = 'string') { const scriptedFields = this.getScriptedFields(); const names = _.map(scriptedFields, 'name'); @@ -252,7 +247,7 @@ export class IndexPattern implements IIndexPattern { script, type: fieldType, scripted: true, - lang, + lang: 'painless', aggregatable: true, searchable: true, count: 0, @@ -322,13 +317,9 @@ export class IndexPattern implements IIndexPattern { return timeField && timeField.esTypes && timeField.esTypes.indexOf('date_nanos') !== -1; } - isTimeBasedWildcard(): boolean { - return this.isTimeBased() && this.isWildcard(); - } - getTimeField() { if (!this.timeFieldName || !this.fields || !this.fields.getByName) return undefined; - return this.fields.getByName(this.timeFieldName) || undefined; + return this.fields.getByName(this.timeFieldName); } getFieldByName(name: string): IndexPatternField | undefined { @@ -340,13 +331,6 @@ export class IndexPattern implements IIndexPattern { return this.typeMeta?.aggs; } - /** - * Does this index pattern title include a '*' - */ - private isWildcard() { - return _.includes(this.title, '*'); - } - /** * Returns index pattern as saved object body for saving */ diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 6b419f6995447a..9c059c0f358927 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -1086,7 +1086,7 @@ export type IMetricAggType = MetricAggType; export class IndexPattern implements IIndexPattern { // Warning: (ae-forgotten-export) The symbol "IndexPatternDeps" needs to be exported by the entry point index.d.ts constructor({ spec, savedObjectsClient, fieldFormats, shortDotsEnable, metaFields, }: IndexPatternDeps); - addScriptedField(name: string, script: string, fieldType?: string, lang?: string): Promise; + addScriptedField(name: string, script: string, fieldType?: string): Promise; // (undocumented) fieldFormatMap: Record; // (undocumented) @@ -1159,8 +1159,6 @@ export class IndexPattern implements IIndexPattern { // (undocumented) isTimeBased(): boolean; // (undocumented) - isTimeBasedWildcard(): boolean; - // (undocumented) isTimeNanosBased(): boolean; // (undocumented) metaFields: string[]; diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 9cf7234c4a9ffd..eefc373559afb1 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -624,7 +624,7 @@ export type IMetricAggType = MetricAggType; export class IndexPattern implements IIndexPattern { // Warning: (ae-forgotten-export) The symbol "IndexPatternDeps" needs to be exported by the entry point index.d.ts constructor({ spec, savedObjectsClient, fieldFormats, shortDotsEnable, metaFields, }: IndexPatternDeps); - addScriptedField(name: string, script: string, fieldType?: string, lang?: string): Promise; + addScriptedField(name: string, script: string, fieldType?: string): Promise; // (undocumented) fieldFormatMap: Record; // Warning: (ae-forgotten-export) The symbol "IIndexPatternFieldList" needs to be exported by the entry point index.d.ts @@ -701,8 +701,6 @@ export class IndexPattern implements IIndexPattern { // (undocumented) isTimeBased(): boolean; // (undocumented) - isTimeBasedWildcard(): boolean; - // (undocumented) isTimeNanosBased(): boolean; // (undocumented) metaFields: string[]; From 786a2d0f4fc7350b62676be3532293af17815c89 Mon Sep 17 00:00:00 2001 From: Luke Elmers Date: Mon, 28 Sep 2020 08:14:33 -0600 Subject: [PATCH 07/19] Move StubIndexPattern to data plugin and convert to TS. (#78518) --- .../stubbed_logstash_index_pattern.js | 4 +- .../index_patterns/index_pattern.stub.ts | 132 ++++++++++++++++++ src/plugins/data/public/test_utils.ts | 1 + .../sidebar/discover_field.test.tsx | 7 +- .../sidebar/discover_sidebar.test.tsx | 8 +- .../sidebar/lib/field_calculator.test.ts | 7 +- .../public/saved_object/saved_object.test.ts | 13 +- .../public/table_vis_controller.test.ts | 5 +- src/test_utils/public/stub_index_pattern.js | 76 ---------- 9 files changed, 153 insertions(+), 100 deletions(-) create mode 100644 src/plugins/data/public/index_patterns/index_pattern.stub.ts delete mode 100644 src/test_utils/public/stub_index_pattern.js diff --git a/src/fixtures/stubbed_logstash_index_pattern.js b/src/fixtures/stubbed_logstash_index_pattern.js index 5735b01eb3db42..5d6d254b9a0008 100644 --- a/src/fixtures/stubbed_logstash_index_pattern.js +++ b/src/fixtures/stubbed_logstash_index_pattern.js @@ -17,10 +17,10 @@ * under the License. */ -import StubIndexPattern from 'test_utils/stub_index_pattern'; import stubbedLogstashFields from 'fixtures/logstash_fields'; import { getKbnFieldType } from '../plugins/data/common'; +import { getStubIndexPattern } from '../plugins/data/public/test_utils'; import { uiSettingsServiceMock } from '../core/public/ui_settings/ui_settings_service.mock'; const uiSettingSetupMock = uiSettingsServiceMock.createSetupContract(); @@ -46,7 +46,7 @@ export default function stubbedLogstashIndexPatternService() { }; }); - const indexPattern = new StubIndexPattern('logstash-*', (cfg) => cfg, 'time', fields, { + const indexPattern = getStubIndexPattern('logstash-*', (cfg) => cfg, 'time', fields, { uiSettings: uiSettingSetupMock, }); diff --git a/src/plugins/data/public/index_patterns/index_pattern.stub.ts b/src/plugins/data/public/index_patterns/index_pattern.stub.ts new file mode 100644 index 00000000000000..e5c6c008e3e28e --- /dev/null +++ b/src/plugins/data/public/index_patterns/index_pattern.stub.ts @@ -0,0 +1,132 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you 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 + * + * http://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 sinon from 'sinon'; + +import { CoreSetup } from 'src/core/public'; +import { FieldFormat as FieldFormatImpl } from '../../common/field_formats'; +import { IFieldType, FieldSpec } from '../../common/index_patterns'; +import { FieldFormatsStart } from '../field_formats'; +import { IndexPattern, indexPatterns, KBN_FIELD_TYPES, fieldList } from '../'; +import { getFieldFormatsRegistry } from '../test_utils'; +import { setFieldFormats } from '../services'; + +setFieldFormats(({ + getDefaultInstance: () => + ({ + getConverterFor: () => (value: any) => value, + convert: (value: any) => JSON.stringify(value), + } as FieldFormatImpl), +} as unknown) as FieldFormatsStart); + +export function getStubIndexPattern( + pattern: string, + getConfig: (cfg: any) => any, + timeField: string | null, + fields: FieldSpec[] | IFieldType[], + core: CoreSetup +): IndexPattern { + return (new StubIndexPattern( + pattern, + getConfig, + timeField, + fields, + core + ) as unknown) as IndexPattern; +} + +export class StubIndexPattern { + id: string; + title: string; + popularizeField: Function; + timeFieldName: string | null; + isTimeBased: () => boolean; + getConfig: (cfg: any) => any; + getNonScriptedFields: Function; + getScriptedFields: Function; + getFieldByName: Function; + getSourceFiltering: Function; + metaFields: string[]; + fieldFormatMap: Record; + getComputedFields: Function; + flattenHit: Function; + formatHit: Record; + fieldsFetcher: Record; + formatField: Function; + getFormatterForField: () => { convert: Function }; + _reindexFields: Function; + stubSetFieldFormat: Function; + fields?: FieldSpec[]; + + constructor( + pattern: string, + getConfig: (cfg: any) => any, + timeField: string | null, + fields: FieldSpec[] | IFieldType[], + core: CoreSetup + ) { + const registeredFieldFormats = getFieldFormatsRegistry(core); + + this.id = pattern; + this.title = pattern; + this.popularizeField = sinon.stub(); + this.timeFieldName = timeField; + this.isTimeBased = () => Boolean(this.timeFieldName); + this.getConfig = getConfig; + this.getNonScriptedFields = sinon.spy(IndexPattern.prototype.getNonScriptedFields); + this.getScriptedFields = sinon.spy(IndexPattern.prototype.getScriptedFields); + this.getFieldByName = sinon.spy(IndexPattern.prototype.getFieldByName); + this.getSourceFiltering = sinon.stub(); + this.metaFields = ['_id', '_type', '_source']; + this.fieldFormatMap = {}; + + this.getComputedFields = IndexPattern.prototype.getComputedFields.bind(this); + this.flattenHit = indexPatterns.flattenHitWrapper( + (this as unknown) as IndexPattern, + this.metaFields + ); + this.formatHit = indexPatterns.formatHitProvider( + (this as unknown) as IndexPattern, + registeredFieldFormats.getDefaultInstance(KBN_FIELD_TYPES.STRING) + ); + this.fieldsFetcher = { apiClient: { baseUrl: '' } }; + this.formatField = this.formatHit.formatField; + this.getFormatterForField = () => ({ + convert: () => '', + }); + + this._reindexFields = function () { + this.fields = fieldList((this.fields || fields) as FieldSpec[], false); + }; + + this.stubSetFieldFormat = function ( + fieldName: string, + id: string, + params: Record + ) { + const FieldFormat = registeredFieldFormats.getType(id); + this.fieldFormatMap[fieldName] = new FieldFormat!(params); + this._reindexFields(); + }; + + this._reindexFields(); + + return this; + } +} diff --git a/src/plugins/data/public/test_utils.ts b/src/plugins/data/public/test_utils.ts index f04b20e96fa1da..03dc572d0bc80f 100644 --- a/src/plugins/data/public/test_utils.ts +++ b/src/plugins/data/public/test_utils.ts @@ -18,3 +18,4 @@ */ export { getFieldFormatsRegistry } from './field_formats/field_formats_registry.stub'; +export { getStubIndexPattern, StubIndexPattern } from './index_patterns/index_pattern.stub'; diff --git a/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx index b03b37da40908d..6211d302e7d204 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx @@ -20,13 +20,12 @@ import React from 'react'; import { findTestSubject } from '@elastic/eui/lib/test'; // @ts-ignore -import StubIndexPattern from 'test_utils/stub_index_pattern'; -// @ts-ignore import stubbedLogstashFields from 'fixtures/logstash_fields'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { DiscoverField } from './discover_field'; import { coreMock } from '../../../../../../core/public/mocks'; import { IndexPatternField } from '../../../../../data/public'; +import { getStubIndexPattern } from '../../../../../data/public/test_utils'; jest.mock('../../../kibana_services', () => ({ getServices: () => ({ @@ -53,12 +52,12 @@ jest.mock('../../../kibana_services', () => ({ })); function getComponent(selected = false, showDetails = false, useShortDots = false) { - const indexPattern = new StubIndexPattern( + const indexPattern = getStubIndexPattern( 'logstash-*', (cfg: any) => cfg, 'time', stubbedLogstashFields(), - coreMock.createStart() + coreMock.createSetup() ); const field = new IndexPatternField( diff --git a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx index 9572f35641d69b..6177b60a0a7ad3 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx @@ -21,8 +21,6 @@ import _ from 'lodash'; import { ReactWrapper } from 'enzyme'; import { findTestSubject } from '@elastic/eui/lib/test'; // @ts-ignore -import StubIndexPattern from 'test_utils/stub_index_pattern'; -// @ts-ignore import realHits from 'fixtures/real_hits.js'; // @ts-ignore import stubbedLogstashFields from 'fixtures/logstash_fields'; @@ -31,6 +29,7 @@ import React from 'react'; import { DiscoverSidebar, DiscoverSidebarProps } from './discover_sidebar'; import { coreMock } from '../../../../../../core/public/mocks'; import { IndexPatternAttributes } from '../../../../../data/common'; +import { getStubIndexPattern } from '../../../../../data/public/test_utils'; import { SavedObject } from '../../../../../../core/types'; jest.mock('../../../kibana_services', () => ({ @@ -65,14 +64,15 @@ jest.mock('./lib/get_index_pattern_field_list', () => ({ })); function getCompProps() { - const indexPattern = new StubIndexPattern( + const indexPattern = getStubIndexPattern( 'logstash-*', (cfg: any) => cfg, 'time', stubbedLogstashFields(), - coreMock.createStart() + coreMock.createSetup() ); + // @ts-expect-error _.each() is passing additional args to flattenHit const hits = _.each(_.cloneDeep(realHits), indexPattern.flattenHit) as Array< Record >; diff --git a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts index dad208c8156755..94c76f2d5f0128 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts @@ -21,11 +21,10 @@ import _ from 'lodash'; // @ts-ignore import realHits from 'fixtures/real_hits.js'; // @ts-ignore -import StubIndexPattern from 'test_utils/stub_index_pattern'; -// @ts-ignore import stubbedLogstashFields from 'fixtures/logstash_fields'; import { coreMock } from '../../../../../../../core/public/mocks'; import { IndexPattern } from '../../../../../../data/public'; +import { getStubIndexPattern } from '../../../../../../data/public/test_utils'; // @ts-ignore import { fieldCalculator } from './field_calculator'; @@ -33,12 +32,12 @@ let indexPattern: IndexPattern; describe('fieldCalculator', function () { beforeEach(function () { - indexPattern = new StubIndexPattern( + indexPattern = getStubIndexPattern( 'logstash-*', (cfg: any) => cfg, 'time', stubbedLogstashFields(), - coreMock.createStart() + coreMock.createSetup() ); }); it('should have a _countMissing that counts nulls & undefineds in an array', function () { diff --git a/src/plugins/saved_objects/public/saved_object/saved_object.test.ts b/src/plugins/saved_objects/public/saved_object/saved_object.test.ts index 53abe55ef0ea7e..849e11dc3dd9f1 100644 --- a/src/plugins/saved_objects/public/saved_object/saved_object.test.ts +++ b/src/plugins/saved_objects/public/saved_object/saved_object.test.ts @@ -26,10 +26,9 @@ import { SavedObjectSaveOpts, } from '../types'; -// @ts-ignore -import StubIndexPattern from 'test_utils/stub_index_pattern'; import { coreMock } from '../../../../core/public/mocks'; import { dataPluginMock, createSearchSourceMock } from '../../../../plugins/data/public/mocks'; +import { getStubIndexPattern, StubIndexPattern } from '../../../../plugins/data/public/test_utils'; import { SavedObjectAttributes, SimpleSavedObject } from 'kibana/public'; import { IIndexPattern } from '../../../data/common/index_patterns'; @@ -294,14 +293,14 @@ describe('Saved Object', () => { type: 'dashboard', } as SimpleSavedObject); - const indexPattern = new StubIndexPattern( + const indexPattern = getStubIndexPattern( 'my-index', getConfig, null, [], coreMock.createSetup() ); - indexPattern.title = indexPattern.id; + indexPattern.title = indexPattern.id!; savedObject.searchSource!.setField('index', indexPattern); return savedObject.save(saveOptionsMock).then(() => { const args = (savedObjectsClientStub.create as jest.Mock).mock.calls[0]; @@ -335,7 +334,7 @@ describe('Saved Object', () => { type: 'dashboard', } as SimpleSavedObject); - const indexPattern = new StubIndexPattern( + const indexPattern = getStubIndexPattern( 'non-existant-index', getConfig, null, @@ -662,14 +661,14 @@ describe('Saved Object', () => { const savedObject = new SavedObjectClass(config); savedObject.hydrateIndexPattern = jest.fn().mockImplementation(() => { - const indexPattern = new StubIndexPattern( + const indexPattern = getStubIndexPattern( indexPatternId, getConfig, null, [], coreMock.createSetup() ); - indexPattern.title = indexPattern.id; + indexPattern.title = indexPattern.id!; savedObject.searchSource!.setField('index', indexPattern); return Bluebird.resolve(indexPattern); }); diff --git a/src/plugins/vis_type_table/public/table_vis_controller.test.ts b/src/plugins/vis_type_table/public/table_vis_controller.test.ts index 7535e98d391c6c..2b4017ae0ee817 100644 --- a/src/plugins/vis_type_table/public/table_vis_controller.test.ts +++ b/src/plugins/vis_type_table/public/table_vis_controller.test.ts @@ -22,8 +22,6 @@ import 'angular-mocks'; import 'angular-sanitize'; import $ from 'jquery'; -// @ts-ignore -import StubIndexPattern from 'test_utils/stub_index_pattern'; import { getAngularModule } from './get_inner_angular'; import { initTableVisLegacyModule } from './table_vis_legacy_module'; import { getTableVisTypeDefinition } from './table_vis_type'; @@ -32,6 +30,7 @@ import { stubFields } from '../../data/public/stubs'; import { tableVisResponseHandler } from './table_vis_response_handler'; import { coreMock } from '../../../core/public/mocks'; import { IAggConfig, search } from '../../data/public'; +import { getStubIndexPattern } from '../../data/public/test_utils'; // TODO: remove linting disable import { searchServiceMock } from '../../data/public/search/mocks'; @@ -105,7 +104,7 @@ describe('Table Vis - Controller', () => { ); beforeEach(() => { - stubIndexPattern = new StubIndexPattern( + stubIndexPattern = getStubIndexPattern( 'logstash-*', (cfg: any) => cfg, 'time', diff --git a/src/test_utils/public/stub_index_pattern.js b/src/test_utils/public/stub_index_pattern.js deleted file mode 100644 index 6130a7f9f9e877..00000000000000 --- a/src/test_utils/public/stub_index_pattern.js +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you 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 - * - * http://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 sinon from 'sinon'; -// TODO: We should not be importing from the data plugin directly here; this is only necessary -// because it is one of the few places that we need to access the IndexPattern class itself, rather -// than just the type. Doing this as a temporary measure; it will be left behind when migrating to NP. - -import { getFieldFormatsRegistry } from '../../plugins/data/public/test_utils'; -import { IndexPattern, indexPatterns, KBN_FIELD_TYPES, fieldList } from '../../plugins/data/public'; - -import { setFieldFormats } from '../../plugins/data/public/services'; - -setFieldFormats({ - getDefaultInstance: () => ({ - getConverterFor: () => (value) => value, - convert: (value) => JSON.stringify(value), - }), -}); - -export default function StubIndexPattern(pattern, getConfig, timeField, fields, core) { - const registeredFieldFormats = getFieldFormatsRegistry(core); - - this.id = pattern; - this.title = pattern; - this.popularizeField = sinon.stub(); - this.timeFieldName = timeField; - this.isTimeBased = () => Boolean(this.timeFieldName); - this.getConfig = getConfig; - this.getNonScriptedFields = sinon.spy(IndexPattern.prototype.getNonScriptedFields); - this.getScriptedFields = sinon.spy(IndexPattern.prototype.getScriptedFields); - this.getFieldByName = sinon.spy(IndexPattern.prototype.getFieldByName); - this.getSourceFiltering = sinon.stub(); - this.metaFields = ['_id', '_type', '_source']; - this.fieldFormatMap = {}; - - this.getComputedFields = IndexPattern.prototype.getComputedFields.bind(this); - this.flattenHit = indexPatterns.flattenHitWrapper(this, this.metaFields); - this.formatHit = indexPatterns.formatHitProvider( - this, - registeredFieldFormats.getDefaultInstance(KBN_FIELD_TYPES.STRING) - ); - this.fieldsFetcher = { apiClient: { baseUrl: '' } }; - this.formatField = this.formatHit.formatField; - this.getFormatterForField = () => ({ - convert: () => '', - }); - - this._reindexFields = function () { - this.fields = fieldList(this.fields || fields, false); - }; - - this.stubSetFieldFormat = function (fieldName, id, params) { - const FieldFormat = registeredFieldFormats.getType(id); - this.fieldFormatMap[fieldName] = new FieldFormat(params); - this._reindexFields(); - }; - - this._reindexFields(); -} From ca48c80c385480a0709d547445bb1da79c8d0006 Mon Sep 17 00:00:00 2001 From: Pierre Gayvallet Date: Mon, 28 Sep 2020 16:27:53 +0200 Subject: [PATCH 08/19] Fix --no-basepath references in doc (#78570) --- docs/developer/advanced/development-basepath.asciidoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/developer/advanced/development-basepath.asciidoc b/docs/developer/advanced/development-basepath.asciidoc index cb341b95911741..30086288de834e 100644 --- a/docs/developer/advanced/development-basepath.asciidoc +++ b/docs/developer/advanced/development-basepath.asciidoc @@ -7,11 +7,11 @@ You can set this explicitly using `server.basePath` in <>. Use the server.rewriteBasePath setting to tell {kib} if it should remove the basePath from requests it receives, and to prevent a deprecation warning at startup. This setting cannot end in a slash (/). -If you want to turn off the basepath when in development mode, start {kib} with the `--no-basepath` flag +If you want to turn off the basepath when in development mode, start {kib} with the `--no-base-path` flag [source,bash] ---- -yarn start --no-basepath +yarn start --no-base-path ---- From e111c2ab3ec734e8f1c31844b77220a2f4b8804a Mon Sep 17 00:00:00 2001 From: ncheckin <68351161+ncheckin@users.noreply.github.com> Date: Mon, 28 Sep 2020 10:57:13 -0400 Subject: [PATCH 09/19] Update tutorial-define-index.asciidoc (#76973) * Update tutorial-define-index.asciidoc * Update docs/getting-started/tutorial-define-index.asciidoc Co-authored-by: Kaarina Tungseth Co-authored-by: Raya Fratkina Co-authored-by: Kaarina Tungseth --- docs/getting-started/tutorial-define-index.asciidoc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/getting-started/tutorial-define-index.asciidoc b/docs/getting-started/tutorial-define-index.asciidoc index cb3f6c9ff0c9bf..5a05d565ab3f81 100644 --- a/docs/getting-started/tutorial-define-index.asciidoc +++ b/docs/getting-started/tutorial-define-index.asciidoc @@ -24,7 +24,7 @@ index named `shakespeare,` and the accounts data set, which has an index named . In the *Index pattern name* field, enter `shakes*`. + [role="screenshot"] -image::images/tutorial-pattern-1.png[shakes* index patterns] +image::images/tutorial-pattern-1.png[Image showing how to enter shakes* in Index Pattern Name field] . Click *Next step*. @@ -54,4 +54,3 @@ available, open the menu, go to *Dev Tools > Console*, then enter `GET _cat/indi For Windows, run `Invoke-RestMethod -Uri "http://localhost:9200/_cat/indices"` in Powershell. - From db78d70df359f19a20d41d06975e780ea1cff998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Fern=C3=A1ndez=20Haro?= Date: Mon, 28 Sep 2020 16:13:21 +0100 Subject: [PATCH 10/19] [Usage Collection] [schema] Explicit "array" definition (#78141) Co-authored-by: Elastic Machine --- .../src/tools/__fixture__/mock_schema.json | 17 +- .../__fixture__/parsed_working_collector.ts | 33 +-- .../extract_collectors.test.ts.snap | 40 ++-- .../src/tools/manage_schema.ts | 18 +- .../src/tools/serializer.test.ts | 4 +- .../src/tools/serializer.ts | 2 +- .../telemetry_collectors/working_collector.ts | 11 +- .../services/sample_data/usage/collector.ts | 4 +- src/plugins/telemetry/schema/oss_plugins.json | 10 +- src/plugins/usage_collection/README.md | 22 ++ .../server/collector/collector.test.ts | 20 +- .../server/collector/collector.ts | 2 +- .../server/collectors/register.ts | 9 +- .../collectors/get_usage_collector.test.ts | 55 ++--- .../collectors/get_usage_collector.ts | 109 ++++----- .../security_usage_collector.ts | 10 +- .../server/usage/collector.ts | 11 +- .../schema/xpack_plugins.json | 217 ++++++++++-------- .../telemetry/kibana_telemetry_adapter.ts | 8 +- 19 files changed, 362 insertions(+), 240 deletions(-) diff --git a/packages/kbn-telemetry-tools/src/tools/__fixture__/mock_schema.json b/packages/kbn-telemetry-tools/src/tools/__fixture__/mock_schema.json index 2e69d3625d7ff0..51e5df9bf7dc09 100644 --- a/packages/kbn-telemetry-tools/src/tools/__fixture__/mock_schema.json +++ b/packages/kbn-telemetry-tools/src/tools/__fixture__/mock_schema.json @@ -35,16 +35,19 @@ } }, "my_array": { - "properties": { - "total": { - "type": "number" - }, - "type": { - "type": "boolean" + "type": "array", + "items": { + "properties": { + "total": { + "type": "number" + }, + "type": { + "type": "boolean" + } } } }, - "my_str_array": { "type": "keyword" } + "my_str_array": { "type": "array", "items": { "type": "keyword" } } } } } diff --git a/packages/kbn-telemetry-tools/src/tools/__fixture__/parsed_working_collector.ts b/packages/kbn-telemetry-tools/src/tools/__fixture__/parsed_working_collector.ts index 54983278726eb2..acf984b7d10eed 100644 --- a/packages/kbn-telemetry-tools/src/tools/__fixture__/parsed_working_collector.ts +++ b/packages/kbn-telemetry-tools/src/tools/__fixture__/parsed_working_collector.ts @@ -55,12 +55,15 @@ export const parsedWorkingCollector: ParsedUsageCollection = [ }, }, my_array: { - total: { - type: 'number', + type: 'array', + items: { + total: { + type: 'number', + }, + type: { type: 'boolean' }, }, - type: { type: 'boolean' }, }, - my_str_array: { type: 'keyword' }, + my_str_array: { type: 'array', items: { type: 'keyword' } }, }, }, fetch: { @@ -91,18 +94,22 @@ export const parsedWorkingCollector: ParsedUsageCollection = [ }, }, my_array: { - total: { - kind: SyntaxKind.NumberKeyword, - type: 'NumberKeyword', - }, - type: { - kind: SyntaxKind.BooleanKeyword, - type: 'BooleanKeyword', + items: { + total: { + kind: SyntaxKind.NumberKeyword, + type: 'NumberKeyword', + }, + type: { + kind: SyntaxKind.BooleanKeyword, + type: 'BooleanKeyword', + }, }, }, my_str_array: { - kind: SyntaxKind.StringKeyword, - type: 'StringKeyword', + items: { + kind: SyntaxKind.StringKeyword, + type: 'StringKeyword', + }, }, }, }, diff --git a/packages/kbn-telemetry-tools/src/tools/__snapshots__/extract_collectors.test.ts.snap b/packages/kbn-telemetry-tools/src/tools/__snapshots__/extract_collectors.test.ts.snap index 9868a7d31d4988..206f573b0af782 100644 --- a/packages/kbn-telemetry-tools/src/tools/__snapshots__/extract_collectors.test.ts.snap +++ b/packages/kbn-telemetry-tools/src/tools/__snapshots__/extract_collectors.test.ts.snap @@ -153,13 +153,15 @@ Array [ "type": "StringKeyword", }, "my_array": Object { - "total": Object { - "kind": 143, - "type": "NumberKeyword", - }, - "type": Object { - "kind": 131, - "type": "BooleanKeyword", + "items": Object { + "total": Object { + "kind": 143, + "type": "NumberKeyword", + }, + "type": Object { + "kind": 131, + "type": "BooleanKeyword", + }, }, }, "my_index_signature_prop": Object { @@ -183,8 +185,10 @@ Array [ "type": "StringKeyword", }, "my_str_array": Object { - "kind": 146, - "type": "StringKeyword", + "items": Object { + "kind": 146, + "type": "StringKeyword", + }, }, }, "typeName": "Usage", @@ -195,12 +199,15 @@ Array [ "type": "keyword", }, "my_array": Object { - "total": Object { - "type": "number", - }, - "type": Object { - "type": "boolean", + "items": Object { + "total": Object { + "type": "number", + }, + "type": Object { + "type": "boolean", + }, }, + "type": "array", }, "my_index_signature_prop": Object { "avg": Object { @@ -228,7 +235,10 @@ Array [ "type": "text", }, "my_str_array": Object { - "type": "keyword", + "items": Object { + "type": "keyword", + }, + "type": "array", }, }, }, diff --git a/packages/kbn-telemetry-tools/src/tools/manage_schema.ts b/packages/kbn-telemetry-tools/src/tools/manage_schema.ts index d422837140d802..7721492fdb691a 100644 --- a/packages/kbn-telemetry-tools/src/tools/manage_schema.ts +++ b/packages/kbn-telemetry-tools/src/tools/manage_schema.ts @@ -28,7 +28,7 @@ export type AllowedSchemaTypes = | 'date' | 'float'; -export function compatibleSchemaTypes(type: AllowedSchemaTypes) { +export function compatibleSchemaTypes(type: AllowedSchemaTypes | 'array') { switch (type) { case 'keyword': case 'text': @@ -40,6 +40,8 @@ export function compatibleSchemaTypes(type: AllowedSchemaTypes) { case 'float': case 'long': return 'number'; + case 'array': + return 'array'; default: throw new Error(`Unknown schema type ${type}`); } @@ -66,10 +68,22 @@ export function isObjectMapping(entity: any) { return false; } +function isArrayMapping(entity: any): entity is { type: 'array'; items: object } { + return typeof entity === 'object' && entity.type === 'array' && typeof entity.items === 'object'; +} + +function getValueMapping(value: any) { + return isObjectMapping(value) ? transformToEsMapping(value) : value; +} + function transformToEsMapping(usageMappingValue: any) { const fieldMapping: any = { properties: {} }; for (const [key, value] of Object.entries(usageMappingValue)) { - fieldMapping.properties[key] = isObjectMapping(value) ? transformToEsMapping(value) : value; + if (isArrayMapping(value)) { + fieldMapping.properties[key] = { ...value, items: getValueMapping(value.items) }; + } else { + fieldMapping.properties[key] = getValueMapping(value); + } } return fieldMapping; } diff --git a/packages/kbn-telemetry-tools/src/tools/serializer.test.ts b/packages/kbn-telemetry-tools/src/tools/serializer.test.ts index 67421172263688..02d663f4d29eb4 100644 --- a/packages/kbn-telemetry-tools/src/tools/serializer.test.ts +++ b/packages/kbn-telemetry-tools/src/tools/serializer.test.ts @@ -84,8 +84,8 @@ describe('getDescriptor', () => { expect(descriptor).toEqual({ prop1: { kind: TelemetryKinds.MomentDate, type: 'MomentDate' }, prop2: { kind: TelemetryKinds.MomentDate, type: 'MomentDate' }, - prop3: { kind: TelemetryKinds.MomentDate, type: 'MomentDate' }, - prop4: { kind: TelemetryKinds.Date, type: 'Date' }, + prop3: { items: { kind: TelemetryKinds.MomentDate, type: 'MomentDate' } }, + prop4: { items: { kind: TelemetryKinds.Date, type: 'Date' } }, }); }); diff --git a/packages/kbn-telemetry-tools/src/tools/serializer.ts b/packages/kbn-telemetry-tools/src/tools/serializer.ts index 6fe02e3824ba7d..422b298c58374d 100644 --- a/packages/kbn-telemetry-tools/src/tools/serializer.ts +++ b/packages/kbn-telemetry-tools/src/tools/serializer.ts @@ -139,7 +139,7 @@ export function getDescriptor(node: ts.Node, program: ts.Program): Descriptor | } if (ts.isArrayTypeNode(node)) { - return getDescriptor(node.elementType, program); + return { items: getDescriptor(node.elementType, program) }; } if (ts.isLiteralTypeNode(node)) { diff --git a/src/fixtures/telemetry_collectors/working_collector.ts b/src/fixtures/telemetry_collectors/working_collector.ts index bdf10b5e549193..0a3bf49638a7b3 100644 --- a/src/fixtures/telemetry_collectors/working_collector.ts +++ b/src/fixtures/telemetry_collectors/working_collector.ts @@ -90,12 +90,15 @@ export const myCollector = makeUsageCollector({ type: { type: 'boolean' }, }, my_array: { - total: { - type: 'number', + type: 'array', + items: { + total: { + type: 'number', + }, + type: { type: 'boolean' }, }, - type: { type: 'boolean' }, }, - my_str_array: { type: 'keyword' }, + my_str_array: { type: 'array', items: { type: 'keyword' } }, my_index_signature_prop: { count: { type: 'number' }, avg: { type: 'number' }, diff --git a/src/plugins/home/server/services/sample_data/usage/collector.ts b/src/plugins/home/server/services/sample_data/usage/collector.ts index d819d67a8d4324..1cece375ce59be 100644 --- a/src/plugins/home/server/services/sample_data/usage/collector.ts +++ b/src/plugins/home/server/services/sample_data/usage/collector.ts @@ -38,12 +38,12 @@ export async function makeSampleDataUsageCollector( fetch: fetchProvider(index), isReady: () => true, schema: { - installed: { type: 'keyword' }, + installed: { type: 'array', items: { type: 'keyword' } }, last_install_date: { type: 'date' }, last_install_set: { type: 'keyword' }, last_uninstall_date: { type: 'date' }, last_uninstall_set: { type: 'keyword' }, - uninstalled: { type: 'keyword' }, + uninstalled: { type: 'array', items: { type: 'keyword' } }, }, }); diff --git a/src/plugins/telemetry/schema/oss_plugins.json b/src/plugins/telemetry/schema/oss_plugins.json index 3ee0c181203aaa..6531262b6f1da9 100644 --- a/src/plugins/telemetry/schema/oss_plugins.json +++ b/src/plugins/telemetry/schema/oss_plugins.json @@ -29,7 +29,10 @@ "sample-data": { "properties": { "installed": { - "type": "keyword" + "type": "array", + "items": { + "type": "keyword" + } }, "last_install_date": { "type": "date" @@ -44,7 +47,10 @@ "type": "keyword" }, "uninstalled": { - "type": "keyword" + "type": "array", + "items": { + "type": "keyword" + } } } }, diff --git a/src/plugins/usage_collection/README.md b/src/plugins/usage_collection/README.md index d8edc5bb8d18a7..9955f9fac81ca0 100644 --- a/src/plugins/usage_collection/README.md +++ b/src/plugins/usage_collection/README.md @@ -140,6 +140,14 @@ The `AllowedSchemaTypes` is the list of allowed schema types for the usage field 'keyword', 'text', 'number', 'boolean', 'long', 'date', 'float' ``` +### Arrays + +If any of your properties is an array, the schema definition must follow the convention below: + +``` +{ type: 'array', items: {...mySchemaDefinitionOfTheEntriesInTheArray} } +``` + ### Example ```ts @@ -152,6 +160,8 @@ export const myCollector = makeUsageCollector({ some_obj: { total: 123, }, + some_array: ['value1', 'value2'], + some_array_of_obj: [{total: 123}], }; }, schema: { @@ -163,6 +173,18 @@ export const myCollector = makeUsageCollector({ type: 'number', }, }, + some_array: { + type: 'array', + items: { type: 'keyword' } + }, + some_array_of_obj: { + type: 'array', + items: { + total: { + type: 'number', + }, + }, + }, }, }); ``` diff --git a/src/plugins/usage_collection/server/collector/collector.test.ts b/src/plugins/usage_collection/server/collector/collector.test.ts index a3e2425c1f1227..375fe4f7686c0e 100644 --- a/src/plugins/usage_collection/server/collector/collector.test.ts +++ b/src/plugins/usage_collection/server/collector/collector.test.ts @@ -153,7 +153,10 @@ describe('collector', () => { isReady: () => false, fetch: () => ({ testPass: [{ name: 'a', value: 100 }] }), schema: { - testPass: { name: { type: 'keyword' }, value: { type: 'long' } }, + testPass: { + type: 'array', + items: { name: { type: 'keyword' }, value: { type: 'long' } }, + }, }, }); expect(collector).toBeDefined(); @@ -166,7 +169,10 @@ describe('collector', () => { fetch: () => ({ testPass: [{ name: 'a', value: 100 }], otherProp: 1 }), // @ts-expect-error schema: { - testPass: { name: { type: 'keyword' }, value: { type: 'long' } }, + testPass: { + type: 'array', + items: { name: { type: 'keyword' }, value: { type: 'long' } }, + }, }, }); expect(collector).toBeDefined(); @@ -185,7 +191,10 @@ describe('collector', () => { }, // @ts-expect-error schema: { - testPass: { name: { type: 'keyword' }, value: { type: 'long' } }, + testPass: { + type: 'array', + items: { name: { type: 'keyword' }, value: { type: 'long' } }, + }, }, }); expect(collector).toBeDefined(); @@ -203,7 +212,10 @@ describe('collector', () => { return { otherProp: 1 }; }, schema: { - testPass: { name: { type: 'keyword' }, value: { type: 'long' } }, + testPass: { + type: 'array', + items: { name: { type: 'keyword' }, value: { type: 'long' } }, + }, otherProp: { type: 'long' }, }, }); diff --git a/src/plugins/usage_collection/server/collector/collector.ts b/src/plugins/usage_collection/server/collector/collector.ts index 365e1ce2013370..b0bc18a0cf0ebb 100644 --- a/src/plugins/usage_collection/server/collector/collector.ts +++ b/src/plugins/usage_collection/server/collector/collector.ts @@ -40,7 +40,7 @@ export type RecursiveMakeSchemaFrom = U extends object export type MakeSchemaFrom = { [Key in keyof Base]: Base[Key] extends Array - ? RecursiveMakeSchemaFrom + ? { type: 'array'; items: RecursiveMakeSchemaFrom } : RecursiveMakeSchemaFrom; }; diff --git a/x-pack/plugins/ingest_manager/server/collectors/register.ts b/x-pack/plugins/ingest_manager/server/collectors/register.ts index 2be8eb22bc98ce..cb39e6a5be579e 100644 --- a/x-pack/plugins/ingest_manager/server/collectors/register.ts +++ b/x-pack/plugins/ingest_manager/server/collectors/register.ts @@ -50,9 +50,12 @@ export function registerIngestManagerUsageCollector( offline: { type: 'long' }, }, packages: { - name: { type: 'keyword' }, - version: { type: 'keyword' }, - enabled: { type: 'boolean' }, + type: 'array', + items: { + name: { type: 'keyword' }, + version: { type: 'keyword' }, + enabled: { type: 'boolean' }, + }, }, }, }); diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts index 17caf80eef22bd..2f63a878b0cde3 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.test.ts @@ -80,33 +80,36 @@ describe('getMonitoringUsageCollector', () => { expect(args[0].schema).toStrictEqual({ hasMonitoringData: { type: 'boolean' }, clusters: { - license: { type: 'keyword' }, - clusterUuid: { type: 'keyword' }, - metricbeatUsed: { type: 'boolean' }, - elasticsearch: { - enabled: { type: 'boolean' }, - count: { type: 'long' }, - metricbeatUsed: { type: 'boolean' }, - }, - kibana: { - enabled: { type: 'boolean' }, - count: { type: 'long' }, - metricbeatUsed: { type: 'boolean' }, - }, - logstash: { - enabled: { type: 'boolean' }, - count: { type: 'long' }, - metricbeatUsed: { type: 'boolean' }, - }, - beats: { - enabled: { type: 'boolean' }, - count: { type: 'long' }, - metricbeatUsed: { type: 'boolean' }, - }, - apm: { - enabled: { type: 'boolean' }, - count: { type: 'long' }, + type: 'array', + items: { + license: { type: 'keyword' }, + clusterUuid: { type: 'keyword' }, metricbeatUsed: { type: 'boolean' }, + elasticsearch: { + enabled: { type: 'boolean' }, + count: { type: 'long' }, + metricbeatUsed: { type: 'boolean' }, + }, + kibana: { + enabled: { type: 'boolean' }, + count: { type: 'long' }, + metricbeatUsed: { type: 'boolean' }, + }, + logstash: { + enabled: { type: 'boolean' }, + count: { type: 'long' }, + metricbeatUsed: { type: 'boolean' }, + }, + beats: { + enabled: { type: 'boolean' }, + count: { type: 'long' }, + metricbeatUsed: { type: 'boolean' }, + }, + apm: { + enabled: { type: 'boolean' }, + count: { type: 'long' }, + metricbeatUsed: { type: 'boolean' }, + }, }, }, }); diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts index b743a5f8e0b4fa..278a6c163c0adf 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/get_usage_collector.ts @@ -28,68 +28,71 @@ export function getMonitoringUsageCollector( type: 'boolean', }, clusters: { - license: { - type: 'keyword', - }, - clusterUuid: { - type: 'keyword', - }, - metricbeatUsed: { - type: 'boolean', - }, - elasticsearch: { - enabled: { - type: 'boolean', + type: 'array', + items: { + license: { + type: 'keyword', }, - count: { - type: 'long', + clusterUuid: { + type: 'keyword', }, metricbeatUsed: { type: 'boolean', }, - }, - kibana: { - enabled: { - type: 'boolean', - }, - count: { - type: 'long', + elasticsearch: { + enabled: { + type: 'boolean', + }, + count: { + type: 'long', + }, + metricbeatUsed: { + type: 'boolean', + }, }, - metricbeatUsed: { - type: 'boolean', + kibana: { + enabled: { + type: 'boolean', + }, + count: { + type: 'long', + }, + metricbeatUsed: { + type: 'boolean', + }, }, - }, - logstash: { - enabled: { - type: 'boolean', + logstash: { + enabled: { + type: 'boolean', + }, + count: { + type: 'long', + }, + metricbeatUsed: { + type: 'boolean', + }, }, - count: { - type: 'long', - }, - metricbeatUsed: { - type: 'boolean', + beats: { + enabled: { + type: 'boolean', + }, + count: { + type: 'long', + }, + metricbeatUsed: { + type: 'boolean', + }, }, - }, - beats: { - enabled: { - type: 'boolean', - }, - count: { - type: 'long', - }, - metricbeatUsed: { - type: 'boolean', - }, - }, - apm: { - enabled: { - type: 'boolean', - }, - count: { - type: 'long', - }, - metricbeatUsed: { - type: 'boolean', + apm: { + enabled: { + type: 'boolean', + }, + count: { + type: 'long', + }, + metricbeatUsed: { + type: 'boolean', + }, }, }, }, diff --git a/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts b/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts index 11e58f7f95fc2a..90483d7c0a4d53 100644 --- a/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts +++ b/x-pack/plugins/security/server/usage_collector/security_usage_collector.ts @@ -62,10 +62,16 @@ export function registerSecurityUsageCollector({ usageCollection, config, licens type: 'number', }, enabledAuthProviders: { - type: 'keyword', + type: 'array', + items: { + type: 'keyword', + }, }, httpAuthSchemes: { - type: 'keyword', + type: 'array', + items: { + type: 'keyword', + }, }, }, fetch: () => { diff --git a/x-pack/plugins/security_solution/server/usage/collector.ts b/x-pack/plugins/security_solution/server/usage/collector.ts index 6fadf956ccaf1e..9514233bdfa86d 100644 --- a/x-pack/plugins/security_solution/server/usage/collector.ts +++ b/x-pack/plugins/security_solution/server/usage/collector.ts @@ -59,10 +59,13 @@ export const registerCollector: RegisterCollector = ({ total_installed: { type: 'long' }, active_within_last_24_hours: { type: 'long' }, os: { - full_name: { type: 'keyword' }, - platform: { type: 'keyword' }, - version: { type: 'keyword' }, - count: { type: 'long' }, + type: 'array', + items: { + full_name: { type: 'keyword' }, + platform: { type: 'keyword' }, + version: { type: 'keyword' }, + count: { type: 'long' }, + }, }, policies: { malware: { diff --git a/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json b/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json index 1236f2ad9b5596..bc89d9e0c812d1 100644 --- a/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json +++ b/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json @@ -141,15 +141,18 @@ } }, "packages": { - "properties": { - "name": { - "type": "keyword" - }, - "version": { - "type": "keyword" - }, - "enabled": { - "type": "boolean" + "type": "array", + "items": { + "properties": { + "name": { + "type": "keyword" + }, + "version": { + "type": "keyword" + }, + "enabled": { + "type": "boolean" + } } } } @@ -546,78 +549,81 @@ "type": "boolean" }, "clusters": { - "properties": { - "license": { - "type": "keyword" - }, - "clusterUuid": { - "type": "keyword" - }, - "metricbeatUsed": { - "type": "boolean" - }, - "elasticsearch": { - "properties": { - "enabled": { - "type": "boolean" - }, - "count": { - "type": "long" - }, - "metricbeatUsed": { - "type": "boolean" + "type": "array", + "items": { + "properties": { + "license": { + "type": "keyword" + }, + "clusterUuid": { + "type": "keyword" + }, + "metricbeatUsed": { + "type": "boolean" + }, + "elasticsearch": { + "properties": { + "enabled": { + "type": "boolean" + }, + "count": { + "type": "long" + }, + "metricbeatUsed": { + "type": "boolean" + } } - } - }, - "kibana": { - "properties": { - "enabled": { - "type": "boolean" - }, - "count": { - "type": "long" - }, - "metricbeatUsed": { - "type": "boolean" + }, + "kibana": { + "properties": { + "enabled": { + "type": "boolean" + }, + "count": { + "type": "long" + }, + "metricbeatUsed": { + "type": "boolean" + } } - } - }, - "logstash": { - "properties": { - "enabled": { - "type": "boolean" - }, - "count": { - "type": "long" - }, - "metricbeatUsed": { - "type": "boolean" + }, + "logstash": { + "properties": { + "enabled": { + "type": "boolean" + }, + "count": { + "type": "long" + }, + "metricbeatUsed": { + "type": "boolean" + } } - } - }, - "beats": { - "properties": { - "enabled": { - "type": "boolean" - }, - "count": { - "type": "long" - }, - "metricbeatUsed": { - "type": "boolean" + }, + "beats": { + "properties": { + "enabled": { + "type": "boolean" + }, + "count": { + "type": "long" + }, + "metricbeatUsed": { + "type": "boolean" + } } - } - }, - "apm": { - "properties": { - "enabled": { - "type": "boolean" - }, - "count": { - "type": "long" - }, - "metricbeatUsed": { - "type": "boolean" + }, + "apm": { + "properties": { + "enabled": { + "type": "boolean" + }, + "count": { + "type": "long" + }, + "metricbeatUsed": { + "type": "boolean" + } } } } @@ -720,18 +726,21 @@ "type": "long" }, "os": { - "properties": { - "full_name": { - "type": "keyword" - }, - "platform": { - "type": "keyword" - }, - "version": { - "type": "keyword" - }, - "count": { - "type": "long" + "type": "array", + "items": { + "properties": { + "full_name": { + "type": "keyword" + }, + "platform": { + "type": "keyword" + }, + "version": { + "type": "keyword" + }, + "count": { + "type": "long" + } } } }, @@ -771,10 +780,16 @@ "type": "number" }, "enabledAuthProviders": { - "type": "keyword" + "type": "array", + "items": { + "type": "keyword" + } }, "httpAuthSchemes": { - "type": "keyword" + "type": "array", + "items": { + "type": "keyword" + } } } }, @@ -906,16 +921,28 @@ "type": "boolean" }, "autorefreshInterval": { - "type": "long" + "type": "array", + "items": { + "type": "long" + } }, "dateRangeEnd": { - "type": "date" + "type": "array", + "items": { + "type": "date" + } }, "dateRangeStart": { - "type": "date" + "type": "array", + "items": { + "type": "date" + } }, "monitor_frequency": { - "type": "long" + "type": "array", + "items": { + "type": "long" + } }, "monitor_name_stats": { "properties": { diff --git a/x-pack/plugins/uptime/server/lib/adapters/telemetry/kibana_telemetry_adapter.ts b/x-pack/plugins/uptime/server/lib/adapters/telemetry/kibana_telemetry_adapter.ts index 149dbb4244c869..106aab35154702 100644 --- a/x-pack/plugins/uptime/server/lib/adapters/telemetry/kibana_telemetry_adapter.ts +++ b/x-pack/plugins/uptime/server/lib/adapters/telemetry/kibana_telemetry_adapter.ts @@ -47,10 +47,10 @@ export class KibanaTelemetryAdapter { autoRefreshEnabled: { type: 'boolean', }, - autorefreshInterval: { type: 'long' }, - dateRangeEnd: { type: 'date' }, - dateRangeStart: { type: 'date' }, - monitor_frequency: { type: 'long' }, + autorefreshInterval: { type: 'array', items: { type: 'long' } }, + dateRangeEnd: { type: 'array', items: { type: 'date' } }, + dateRangeStart: { type: 'array', items: { type: 'date' } }, + monitor_frequency: { type: 'array', items: { type: 'long' } }, monitor_name_stats: { avg_length: { type: 'float' }, max_length: { type: 'long' }, From 0ebaf92a6a8a3a4626eb362a9005c4674b965923 Mon Sep 17 00:00:00 2001 From: Wylie Conlon Date: Mon, 28 Sep 2020 11:22:03 -0400 Subject: [PATCH 11/19] [Lens] Fieldless operations (#78080) * [Lens] Fieldless operations * Overhaul types * Fix invalid state and add tests * Fix types * Small cleanup * Add additional error message * Reset field selector to empty state when invalid Co-authored-by: Elastic Machine --- .../dimension_panel/dimension_editor.tsx | 233 +++++---- .../dimension_panel/dimension_panel.test.tsx | 446 ++++++++---------- .../dimension_panel/dimension_panel.tsx | 46 +- .../dimension_panel/field_select.tsx | 24 +- .../indexpattern_suggestions.ts | 12 +- .../operations/definitions/cardinality.tsx | 9 +- .../operations/definitions/column_types.ts | 20 +- .../operations/definitions/count.tsx | 12 +- .../operations/definitions/date_histogram.tsx | 8 +- .../definitions/filters/filters.test.tsx | 25 +- .../definitions/filters/filters.tsx | 30 +- .../operations/definitions/index.ts | 98 ++-- .../operations/definitions/metrics.tsx | 12 +- .../operations/definitions/ranges/ranges.tsx | 3 +- .../operations/definitions/terms.tsx | 39 +- .../operations/index.ts | 2 +- .../operations/operations.test.ts | 27 +- .../operations/operations.ts | 75 +-- .../indexpattern_datasource/state_helpers.ts | 3 +- .../test/functional/apps/lens/smokescreen.ts | 3 + 20 files changed, 569 insertions(+), 558 deletions(-) diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx index 2f64a36e0462ee..2572f732aa1b3f 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_editor.tsx @@ -17,7 +17,7 @@ import { } from '@elastic/eui'; import { EuiFormLabel } from '@elastic/eui'; import { IndexPatternColumn, OperationType } from '../indexpattern'; -import { IndexPatternDimensionEditorProps, OperationFieldSupportMatrix } from './dimension_panel'; +import { IndexPatternDimensionEditorProps, OperationSupportMatrix } from './dimension_panel'; import { operationDefinitionMap, getOperationDisplay, @@ -36,7 +36,7 @@ const operationPanels = getOperationDisplay(); export interface DimensionEditorProps extends IndexPatternDimensionEditorProps { selectedColumn?: IndexPatternColumn; - operationFieldSupportMatrix: OperationFieldSupportMatrix; + operationSupportMatrix: OperationSupportMatrix; currentIndexPattern: IndexPattern; } @@ -90,7 +90,7 @@ const LabelInput = ({ value, onChange }: { value: string; onChange: (value: stri export function DimensionEditor(props: DimensionEditorProps) { const { selectedColumn, - operationFieldSupportMatrix, + operationSupportMatrix, state, columnId, setState, @@ -98,14 +98,16 @@ export function DimensionEditor(props: DimensionEditorProps) { currentIndexPattern, hideGrouping, } = props; - const { operationByField, fieldByOperation } = operationFieldSupportMatrix; + const { operationByField, fieldByOperation } = operationSupportMatrix; const [ incompatibleSelectedOperationType, setInvalidOperationType, ] = useState(null); - const ParamEditor = - selectedColumn && operationDefinitionMap[selectedColumn.operationType].paramEditor; + const selectedOperationDefinition = + selectedColumn && operationDefinitionMap[selectedColumn.operationType]; + + const ParamEditor = selectedOperationDefinition?.paramEditor; const fieldMap: Record = useMemo(() => { const fields: Record = {}; @@ -129,6 +131,10 @@ export function DimensionEditor(props: DimensionEditorProps) { [ ...asOperationOptions(validOperationTypes, true), ...asOperationOptions(possibleOperationTypes, false), + ...asOperationOptions( + operationSupportMatrix.operationWithoutField, + !selectedColumn || !hasField(selectedColumn) + ), ], 'operationType' ); @@ -166,12 +172,30 @@ export function DimensionEditor(props: DimensionEditorProps) { compatibleWithCurrentField ? '' : ' incompatible' }`, onClick() { - // todo: when moving from terms agg to filters, we want to create a filter `$field.name : *` - // it probably has to be re-thought when removing the field name. - const isTermsToFilters = - selectedColumn?.operationType === 'terms' && operationType === 'filters'; - - if (!selectedColumn || !compatibleWithCurrentField) { + if (operationDefinitionMap[operationType].input === 'none') { + // Clear invalid state because we are creating a valid column + setInvalidOperationType(null); + if (selectedColumn?.operationType === operationType) { + return; + } + setState( + changeColumn({ + state, + layerId, + columnId, + newColumn: buildColumn({ + columns: props.state.layers[props.layerId].columns, + suggestedPriority: props.suggestedPriority, + layerId: props.layerId, + op: operationType, + indexPattern: currentIndexPattern, + previousColumn: selectedColumn, + }), + }) + ); + trackUiEvent(`indexpattern_dimension_operation_${operationType}`); + return; + } else if (!selectedColumn || !compatibleWithCurrentField) { const possibleFields = fieldByOperation[operationType] || []; if (possibleFields.length === 1) { @@ -197,19 +221,20 @@ export function DimensionEditor(props: DimensionEditorProps) { trackUiEvent(`indexpattern_dimension_operation_${operationType}`); return; } - if (incompatibleSelectedOperationType && !isTermsToFilters) { - setInvalidOperationType(null); - } - if (selectedColumn.operationType === operationType) { + + setInvalidOperationType(null); + + if (selectedColumn?.operationType === operationType) { return; } + const newColumn: IndexPatternColumn = buildColumn({ columns: props.state.layers[props.layerId].columns, suggestedPriority: props.suggestedPriority, layerId: props.layerId, op: operationType, indexPattern: currentIndexPattern, - field: fieldMap[selectedColumn.sourceField], + field: hasField(selectedColumn) ? fieldMap[selectedColumn.sourceField] : undefined, previousColumn: selectedColumn, }); @@ -244,93 +269,101 @@ export function DimensionEditor(props: DimensionEditorProps) {
- - { - setState( - deleteColumn({ - state, - layerId, - columnId, - }) - ); - }} - onChoose={(choice) => { - let column: IndexPatternColumn; - if ( - !incompatibleSelectedOperationType && - selectedColumn && - 'field' in choice && - choice.operationType === selectedColumn.operationType - ) { - // If we just changed the field are not in an error state and the operation didn't change, - // we use the operations onFieldChange method to calculate the new column. - column = changeField(selectedColumn, currentIndexPattern, fieldMap[choice.field]); - } else { - // Otherwise we'll use the buildColumn method to calculate a new column - const compatibleOperations = - ('field' in choice && - operationFieldSupportMatrix.operationByField[choice.field]) || - []; - let operation; - if (compatibleOperations.length > 0) { - operation = - incompatibleSelectedOperationType && - compatibleOperations.includes(incompatibleSelectedOperationType) - ? incompatibleSelectedOperationType - : compatibleOperations[0]; - } else if ('field' in choice) { - operation = choice.operationType; - } - column = buildColumn({ - columns: props.state.layers[props.layerId].columns, - field: fieldMap[choice.field], - indexPattern: currentIndexPattern, - layerId: props.layerId, - suggestedPriority: props.suggestedPriority, - op: operation as OperationType, - previousColumn: selectedColumn, - }); + > + { + setState( + deleteColumn({ + state, + layerId, + columnId, + }) + ); + }} + onChoose={(choice) => { + let column: IndexPatternColumn; + if ( + !incompatibleSelectedOperationType && + selectedColumn && + 'field' in choice && + choice.operationType === selectedColumn.operationType + ) { + // If we just changed the field are not in an error state and the operation didn't change, + // we use the operations onFieldChange method to calculate the new column. + column = changeField(selectedColumn, currentIndexPattern, fieldMap[choice.field]); + } else { + // Otherwise we'll use the buildColumn method to calculate a new column + const compatibleOperations = + ('field' in choice && operationSupportMatrix.operationByField[choice.field]) || + []; + let operation; + if (compatibleOperations.length > 0) { + operation = + incompatibleSelectedOperationType && + compatibleOperations.includes(incompatibleSelectedOperationType) + ? incompatibleSelectedOperationType + : compatibleOperations[0]; + } else if ('field' in choice) { + operation = choice.operationType; + } + column = buildColumn({ + columns: props.state.layers[props.layerId].columns, + field: fieldMap[choice.field], + indexPattern: currentIndexPattern, + layerId: props.layerId, + suggestedPriority: props.suggestedPriority, + op: operation as OperationType, + previousColumn: selectedColumn, + }); + } - setState( - changeColumn({ - state, - layerId, - columnId, - newColumn: column, - keepParams: false, - }) - ); - setInvalidOperationType(null); - }} - /> - + setState( + changeColumn({ + state, + layerId, + columnId, + newColumn: column, + keepParams: false, + }) + ); + setInvalidOperationType(null); + }} + /> + + ) : null} - {!incompatibleSelectedOperationType && ParamEditor && ( + {!incompatibleSelectedOperationType && selectedColumn && ParamEditor && ( <> { let state: IndexPatternPrivateState; let setState: jest.Mock; let defaultProps: IndexPatternDimensionEditorProps; let dragDropContext: DragContextState; + function getStateWithColumns(columns: Record) { + return { ...state, layers: { first: { ...state.layers.first, columns } } }; + } + beforeEach(() => { state = { indexPatternRefs: [], @@ -179,7 +207,7 @@ describe('IndexPatternDimensionEditorPanel', () => { expect(filterOperations).toBeCalled(); }); - it('should show field select combo box on click', () => { + it('should show field select', () => { wrapper = mount(); expect( @@ -187,6 +215,29 @@ describe('IndexPatternDimensionEditorPanel', () => { ).toHaveLength(1); }); + it('should not show field select on fieldless operation', () => { + wrapper = mount( + + ); + + expect( + wrapper.find(EuiComboBox).filter('[data-test-subj="indexPattern-dimension-field"]') + ).toHaveLength(0); + }); + it('should not show any choices if the filter returns false', () => { wrapper = mount( { wrapper = mount( ); @@ -292,26 +324,7 @@ describe('IndexPatternDimensionEditorPanel', () => { wrapper = mount( ); @@ -324,30 +337,15 @@ describe('IndexPatternDimensionEditorPanel', () => { expect(items.find(({ label }) => label === 'Date histogram')!['data-test-subj']).toContain( 'incompatible' ); + + // Fieldless operation is compatible with field + expect(items.find(({ label }) => label === 'Filters')!['data-test-subj']).toContain( + 'compatible' + ); }); it('should keep the operation when switching to another field compatible with this operation', () => { - const initialState: IndexPatternPrivateState = { - ...state, - layers: { - first: { - ...state.layers.first, - columns: { - ...state.layers.first.columns, - col1: { - label: 'Max of bytes', - dataType: 'number', - isBucketed: false, - - // Private - operationType: 'max', - sourceField: 'bytes', - params: { format: { id: 'bytes' } }, - }, - }, - }, - }, - }; + const initialState: IndexPatternPrivateState = getStateWithColumns({ col1: bytesColumn }); wrapper = mount( @@ -415,27 +413,7 @@ describe('IndexPatternDimensionEditorPanel', () => { wrapper = mount( ); @@ -505,27 +483,7 @@ describe('IndexPatternDimensionEditorPanel', () => { wrapper = mount( ); @@ -553,28 +511,13 @@ describe('IndexPatternDimensionEditorPanel', () => { wrapper = mount( ); @@ -640,6 +583,62 @@ describe('IndexPatternDimensionEditorPanel', () => { expect(wrapper.find('[data-test-subj="indexPattern-invalid-operation"]')).toHaveLength(0); }); + it('should leave error state if the original operation is re-selected', () => { + wrapper = mount(); + + wrapper + .find('button[data-test-subj="lns-indexPatternDimension-terms incompatible"]') + .simulate('click'); + + wrapper + .find('button[data-test-subj="lns-indexPatternDimension-date_histogram"]') + .simulate('click'); + + expect(wrapper.find('[data-test-subj="indexPattern-invalid-operation"]')).toHaveLength(0); + }); + + it('should leave error state when switching from incomplete state to fieldless operation', () => { + wrapper = mount(); + + wrapper + .find('button[data-test-subj="lns-indexPatternDimension-terms incompatible"]') + .simulate('click'); + + wrapper + .find('button[data-test-subj="lns-indexPatternDimension-filters incompatible"]') + .simulate('click'); + + expect(wrapper.find('[data-test-subj="indexPattern-invalid-operation"]')).toHaveLength(0); + }); + + it('should leave error state when re-selecting the original fieldless function', () => { + wrapper = mount( + + ); + + wrapper + .find('button[data-test-subj="lns-indexPatternDimension-terms incompatible"]') + .simulate('click'); + + wrapper + .find('button[data-test-subj="lns-indexPatternDimension-filters"]') + .simulate('click'); + + expect(wrapper.find('[data-test-subj="indexPattern-invalid-operation"]')).toHaveLength(0); + }); + it('should indicate fields compatible with selected operation', () => { wrapper = mount(); @@ -701,28 +700,18 @@ describe('IndexPatternDimensionEditorPanel', () => { }); it('should select the Records field when count is selected', () => { - const initialState: IndexPatternPrivateState = { - ...state, - layers: { - first: { - ...state.layers.first, - columns: { - ...state.layers.first.columns, - col2: { - dataType: 'number', - isBucketed: false, - label: '', - operationType: 'avg', - sourceField: 'bytes', - }, - }, - }, - }, - }; wrapper = mount( ); @@ -737,28 +726,18 @@ describe('IndexPatternDimensionEditorPanel', () => { }); it('should indicate document and field compatibility with selected document operation', () => { - const initialState: IndexPatternPrivateState = { - ...state, - layers: { - first: { - ...state.layers.first, - columns: { - ...state.layers.first.columns, - col2: { - dataType: 'number', - isBucketed: false, - label: '', - operationType: 'count', - sourceField: 'Records', - }, - }, - }, - }, - }; wrapper = mount( ); @@ -942,28 +921,18 @@ describe('IndexPatternDimensionEditorPanel', () => { }); it('should indicate document compatibility when document operation is selected', () => { - const initialState: IndexPatternPrivateState = { - ...state, - layers: { - first: { - ...state.layers.first, - columns: { - ...state.layers.first.columns, - col2: { - dataType: 'number', - isBucketed: false, - label: '', - operationType: 'count', - sourceField: 'Records', - }, - }, - }, - }, - }; wrapper = mount( ); @@ -1031,26 +1000,9 @@ describe('IndexPatternDimensionEditorPanel', () => { }); it('should use helper function when changing the function', () => { - const initialState: IndexPatternPrivateState = { - ...state, - layers: { - first: { - ...state.layers.first, - columns: { - ...state.layers.first.columns, - col1: { - label: 'Max of bytes', - dataType: 'number', - isBucketed: false, - - // Private - operationType: 'max', - sourceField: 'bytes', - }, - }, - }, - }, - }; + const initialState: IndexPatternPrivateState = getStateWithColumns({ + col1: bytesColumn, + }); wrapper = mount( ); @@ -1095,25 +1047,16 @@ describe('IndexPatternDimensionEditorPanel', () => { }); it('allows custom format', () => { - const stateWithNumberCol: IndexPatternPrivateState = { - ...state, - layers: { - first: { - indexPatternId: '1', - columnOrder: ['col1'], - columns: { - col1: { - label: 'Average of memory', - dataType: 'number', - isBucketed: false, - // Private - operationType: 'avg', - sourceField: 'memory', - }, - }, - }, + const stateWithNumberCol: IndexPatternPrivateState = getStateWithColumns({ + col1: { + label: 'Average of memory', + dataType: 'number', + isBucketed: false, + // Private + operationType: 'avg', + sourceField: 'memory', }, - }; + }); wrapper = mount( @@ -1145,29 +1088,19 @@ describe('IndexPatternDimensionEditorPanel', () => { }); it('keeps decimal places while switching', () => { - const stateWithNumberCol: IndexPatternPrivateState = { - ...state, - layers: { - first: { - indexPatternId: '1', - columnOrder: ['col1'], - columns: { - col1: { - label: 'Average of memory', - dataType: 'number', - isBucketed: false, - // Private - operationType: 'avg', - sourceField: 'memory', - params: { - format: { id: 'bytes', params: { decimals: 0 } }, - }, - }, - }, + const stateWithNumberCol: IndexPatternPrivateState = getStateWithColumns({ + col1: { + label: 'Average of memory', + dataType: 'number', + isBucketed: false, + // Private + operationType: 'avg', + sourceField: 'memory', + params: { + format: { id: 'bytes', params: { decimals: 0 } }, }, }, - }; - + }); wrapper = mount( ); @@ -1195,28 +1128,19 @@ describe('IndexPatternDimensionEditorPanel', () => { }); it('allows custom format with number of decimal places', () => { - const stateWithNumberCol: IndexPatternPrivateState = { - ...state, - layers: { - first: { - indexPatternId: '1', - columnOrder: ['col1'], - columns: { - col1: { - label: 'Average of memory', - dataType: 'number', - isBucketed: false, - // Private - operationType: 'avg', - sourceField: 'memory', - params: { - format: { id: 'bytes', params: { decimals: 2 } }, - }, - }, - }, + const stateWithNumberCol: IndexPatternPrivateState = getStateWithColumns({ + col1: { + label: 'Average of memory', + dataType: 'number', + isBucketed: false, + // Private + operationType: 'avg', + sourceField: 'memory', + params: { + format: { id: 'bytes', params: { decimals: 2 } }, }, }, - }; + }); wrapper = mount( diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx index 923f7145d1c64c..c4d8300722f83c 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx @@ -46,8 +46,9 @@ export type IndexPatternDimensionEditorProps = DatasourceDimensionEditorProps< dateRange: DateRange; }; -export interface OperationFieldSupportMatrix { +export interface OperationSupportMatrix { operationByField: Partial>; + operationWithoutField: OperationType[]; fieldByOperation: Partial>; } @@ -58,7 +59,7 @@ type Props = Pick< // TODO: This code has historically been memoized, as a potentially performance // sensitive task. If we can add memoization without breaking the behavior, we should. -const getOperationFieldSupportMatrix = (props: Props): OperationFieldSupportMatrix => { +const getOperationSupportMatrix = (props: Props): OperationSupportMatrix => { const layerId = props.layerId; const currentIndexPattern = props.state.indexPatterns[props.state.layers[layerId].indexPatternId]; @@ -67,37 +68,43 @@ const getOperationFieldSupportMatrix = (props: Props): OperationFieldSupportMatr ).filter((operation) => props.filterOperations(operation.operationMetaData)); const supportedOperationsByField: Partial> = {}; + const supportedOperationsWithoutField: OperationType[] = []; const supportedFieldsByOperation: Partial> = {}; filteredOperationsByMetadata.forEach(({ operations }) => { operations.forEach((operation) => { - if (supportedOperationsByField[operation.field]) { - supportedOperationsByField[operation.field]!.push(operation.operationType); - } else { - supportedOperationsByField[operation.field] = [operation.operationType]; - } - - if (supportedFieldsByOperation[operation.operationType]) { - supportedFieldsByOperation[operation.operationType]!.push(operation.field); - } else { - supportedFieldsByOperation[operation.operationType] = [operation.field]; + if (operation.type === 'field') { + if (supportedOperationsByField[operation.field]) { + supportedOperationsByField[operation.field]!.push(operation.operationType); + } else { + supportedOperationsByField[operation.field] = [operation.operationType]; + } + + if (supportedFieldsByOperation[operation.operationType]) { + supportedFieldsByOperation[operation.operationType]!.push(operation.field); + } else { + supportedFieldsByOperation[operation.operationType] = [operation.field]; + } + } else if (operation.type === 'none') { + supportedOperationsWithoutField.push(operation.operationType); } }); }); return { operationByField: _.mapValues(supportedOperationsByField, _.uniq), + operationWithoutField: _.uniq(supportedOperationsWithoutField), fieldByOperation: _.mapValues(supportedFieldsByOperation, _.uniq), }; }; export function canHandleDrop(props: DatasourceDimensionDropProps) { - const operationFieldSupportMatrix = getOperationFieldSupportMatrix(props); + const operationSupportMatrix = getOperationSupportMatrix(props); const { dragging } = props.dragDropContext; const layerIndexPatternId = props.state.layers[props.layerId].indexPatternId; function hasOperationForField(field: IndexPatternField) { - return Boolean(operationFieldSupportMatrix.operationByField[field.name]); + return Boolean(operationSupportMatrix.operationByField[field.name]); } if (isDraggedField(dragging)) { @@ -119,11 +126,11 @@ export function canHandleDrop(props: DatasourceDimensionDropProps) { - const operationFieldSupportMatrix = getOperationFieldSupportMatrix(props); + const operationSupportMatrix = getOperationSupportMatrix(props); const droppedItem = props.droppedItem; function hasOperationForField(field: IndexPatternField) { - return Boolean(operationFieldSupportMatrix.operationByField[field.name]); + return Boolean(operationSupportMatrix.operationByField[field.name]); } if (isDraggedOperation(droppedItem) && droppedItem.layerId === props.layerId) { @@ -167,8 +174,7 @@ export function onDrop(props: DatasourceDimensionDropHandlerProps ); }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx index e71a85868b8552..de472cb09cdfee 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx @@ -20,7 +20,7 @@ import { EuiHighlight } from '@elastic/eui'; import { OperationType } from '../indexpattern'; import { LensFieldIcon } from '../lens_field_icon'; import { DataType } from '../../types'; -import { OperationFieldSupportMatrix } from './dimension_panel'; +import { OperationSupportMatrix } from './dimension_panel'; import { IndexPattern, IndexPatternField, IndexPatternPrivateState } from '../types'; import { trackUiEvent } from '../../lens_ui_telemetry'; import { fieldExists } from '../pure_helpers'; @@ -37,7 +37,7 @@ export interface FieldSelectProps extends EuiComboBoxProps<{}> { incompatibleSelectedOperationType: OperationType | null; selectedColumnOperationType?: OperationType; selectedColumnSourceField?: string; - operationFieldSupportMatrix: OperationFieldSupportMatrix; + operationSupportMatrix: OperationSupportMatrix; onChoose: (choice: FieldChoice) => void; onDeleteColumn: () => void; existingFields: IndexPatternPrivateState['existingFields']; @@ -49,13 +49,13 @@ export function FieldSelect({ incompatibleSelectedOperationType, selectedColumnOperationType, selectedColumnSourceField, - operationFieldSupportMatrix, + operationSupportMatrix, onChoose, onDeleteColumn, existingFields, ...rest }: FieldSelectProps) { - const { operationByField } = operationFieldSupportMatrix; + const { operationByField } = operationSupportMatrix; const memoizedFieldOptions = useMemo(() => { const fields = Object.keys(operationByField).sort(); @@ -173,15 +173,13 @@ export function FieldSelect({ options={(memoizedFieldOptions as unknown) as EuiComboBoxOptionOption[]} isInvalid={Boolean(incompatibleSelectedOperationType)} selectedOptions={ - ((selectedColumnOperationType - ? selectedColumnSourceField - ? [ - { - label: fieldMap[selectedColumnSourceField].displayName, - value: { type: 'field', field: selectedColumnSourceField }, - }, - ] - : [memoizedFieldOptions[0]] + ((selectedColumnOperationType && selectedColumnSourceField + ? [ + { + label: fieldMap[selectedColumnSourceField].displayName, + value: { type: 'field', field: selectedColumnSourceField }, + }, + ] : []) as unknown) as EuiComboBoxOptionOption[] } singleSelection={{ asPlainText: true }} diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts index f3aa9c4f51c82f..f5e64149c2c769 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts @@ -483,11 +483,15 @@ function createChangedNestingSuggestion(state: IndexPatternPrivateState, layerId const updatedLayer = { ...layer, columnOrder: [secondBucket, firstBucket, ...rest] }; const currentFields = state.indexPatterns[state.currentIndexPatternId].fields; const firstBucketLabel = - currentFields.find((field) => field.name === layer.columns[firstBucket].sourceField) - ?.displayName || ''; + currentFields.find((field) => { + const column = layer.columns[firstBucket]; + return hasField(column) && column.sourceField === field.name; + })?.displayName || ''; const secondBucketLabel = - currentFields.find((field) => field.name === layer.columns[secondBucket].sourceField) - ?.displayName || ''; + currentFields.find((field) => { + const column = layer.columns[secondBucket]; + return hasField(column) && column.sourceField === field.name; + })?.displayName || ''; return buildSuggestion({ state, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx index b0777c7febd7d6..65119d3978ee6b 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx @@ -6,7 +6,7 @@ import { i18n } from '@kbn/i18n'; import { OperationDefinition } from './index'; -import { FormattedIndexPatternColumn } from './column_types'; +import { FormattedIndexPatternColumn, FieldBasedIndexPatternColumn } from './column_types'; const supportedTypes = new Set(['string', 'boolean', 'number', 'ip', 'date']); @@ -21,15 +21,18 @@ function ofName(name: string) { }); } -export interface CardinalityIndexPatternColumn extends FormattedIndexPatternColumn { +export interface CardinalityIndexPatternColumn + extends FormattedIndexPatternColumn, + FieldBasedIndexPatternColumn { operationType: 'cardinality'; } -export const cardinalityOperation: OperationDefinition = { +export const cardinalityOperation: OperationDefinition = { type: OPERATION_TYPE, displayName: i18n.translate('xpack.lens.indexPattern.cardinality', { defaultMessage: 'Unique count', }), + input: 'field', getPossibleOperationForField: ({ aggregationRestrictions, aggregatable, type }) => { if ( supportedTypes.has(type) && diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/column_types.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/column_types.ts index 3244eeb94d1e27..2e95e3fd4250fc 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/column_types.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/column_types.ts @@ -14,7 +14,6 @@ import { Operation, DimensionPriority } from '../../../types'; export interface BaseIndexPatternColumn extends Operation { // Private operationType: string; - sourceField: string; suggestedPriority?: DimensionPriority; customLabel?: boolean; } @@ -31,23 +30,6 @@ export interface FormattedIndexPatternColumn extends BaseIndexPatternColumn { }; } -/** - * Base type for a column that doesn't have additional parameter. - * - * * `TOperationType` should be a string type containing just the type - * of the operation (e.g. `"sum"`). - * * `TBase` is the base column interface the operation type is set for - - * by default this is `FieldBasedIndexPatternColumn`, so - * `ParameterlessIndexPatternColumn<'foo'>` will give you a column type - * for an operation named foo that operates on a field. - * By passing in another `TBase` (e.g. just `BaseIndexPatternColumn`), - * you can also create other column types. - */ -export type ParameterlessIndexPatternColumn< - TOperationType extends string, - TBase extends BaseIndexPatternColumn = FieldBasedIndexPatternColumn -> = TBase & { operationType: TOperationType }; - export interface FieldBasedIndexPatternColumn extends BaseIndexPatternColumn { - suggestedPriority?: DimensionPriority; + sourceField: string; } diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx index bb1aef856de780..cdf1a6b7604930 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/count.tsx @@ -6,23 +6,25 @@ import { i18n } from '@kbn/i18n'; import { OperationDefinition } from './index'; -import { FormattedIndexPatternColumn } from './column_types'; +import { FormattedIndexPatternColumn, FieldBasedIndexPatternColumn } from './column_types'; import { IndexPatternField } from '../../types'; const countLabel = i18n.translate('xpack.lens.indexPattern.countOf', { defaultMessage: 'Count of records', }); -export type CountIndexPatternColumn = FormattedIndexPatternColumn & { - operationType: 'count'; -}; +export type CountIndexPatternColumn = FormattedIndexPatternColumn & + FieldBasedIndexPatternColumn & { + operationType: 'count'; + }; -export const countOperation: OperationDefinition = { +export const countOperation: OperationDefinition = { type: 'count', priority: 2, displayName: i18n.translate('xpack.lens.indexPattern.count', { defaultMessage: 'Count', }), + input: 'field', onFieldChange: (oldColumn, indexPattern, field) => { return { ...oldColumn, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx index 7784024b031324..185f44405bb4b1 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx @@ -36,11 +36,15 @@ export interface DateHistogramIndexPatternColumn extends FieldBasedIndexPatternC }; } -export const dateHistogramOperation: OperationDefinition = { +export const dateHistogramOperation: OperationDefinition< + DateHistogramIndexPatternColumn, + 'field' +> = { type: 'date_histogram', displayName: i18n.translate('xpack.lens.indexPattern.dateHistogram', { defaultMessage: 'Date histogram', }), + input: 'field', priority: 5, // Highest priority level used getPossibleOperationForField: ({ aggregationRestrictions, aggregatable, type }) => { if ( @@ -136,7 +140,7 @@ export const dateHistogramOperation: OperationDefinition { + paramEditor: ({ state, setState, currentColumn, layerId, dateRange, data }) => { const field = currentColumn && state.indexPatterns[state.layers[layerId].indexPatternId].fields.find( diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.test.tsx index 2d79c5faf74fe2..3ac01886537dca 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.test.tsx @@ -59,7 +59,6 @@ describe('filters', () => { operationType: 'filters', scale: 'ordinal', isBucketed: true, - sourceField: 'Records', params: { filters: [ { @@ -112,34 +111,14 @@ describe('filters', () => { }); }); - describe('getPossibleOperationForField', () => { + describe('getPossibleOperation', () => { it('should return operation with the right type for document', () => { - expect( - filtersOperation.getPossibleOperationForField({ - aggregatable: true, - searchable: true, - name: 'test', - displayName: 'test', - type: 'document', - }) - ).toEqual({ + expect(filtersOperation.getPossibleOperation()).toEqual({ dataType: 'string', isBucketed: true, scale: 'ordinal', }); }); - - it('should not return operation if field type is not document', () => { - expect( - filtersOperation.getPossibleOperationForField({ - aggregatable: false, - searchable: true, - name: 'test', - displayName: 'test', - type: 'string', - }) - ).toEqual(undefined); - }); }); describe('popover param editor', () => { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx index 9985ad7229ecc8..ad0b9f2dbb0ab0 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/filters/filters.tsx @@ -11,7 +11,7 @@ import { i18n } from '@kbn/i18n'; import { EuiFormRow, EuiLink, htmlIdGenerator } from '@elastic/eui'; import { updateColumnParam } from '../../../state_helpers'; import { OperationDefinition } from '../index'; -import { FieldBasedIndexPatternColumn } from '../column_types'; +import { BaseIndexPatternColumn } from '../column_types'; import { FilterPopover } from './filter_popover'; import { IndexPattern } from '../../../types'; import { Query, esKuery, esQuery } from '../../../../../../../../src/plugins/data/public'; @@ -61,31 +61,22 @@ export const isQueryValid = (input: Query, indexPattern: IndexPattern) => { } }; -export interface FiltersIndexPatternColumn extends FieldBasedIndexPatternColumn { +export interface FiltersIndexPatternColumn extends BaseIndexPatternColumn { operationType: 'filters'; params: { filters: Filter[]; }; } -export const filtersOperation: OperationDefinition = { +export const filtersOperation: OperationDefinition = { type: 'filters', displayName: filtersLabel, priority: 3, // Higher than any metric - getPossibleOperationForField: ({ type }) => { - if (type === 'document') { - return { - dataType: 'string', - isBucketed: true, - scale: 'ordinal', - }; - } - }, - isTransferable: () => false, - onFieldChange: (oldColumn, indexPattern, field) => oldColumn, + input: 'none', + isTransferable: () => true, - buildColumn({ suggestedPriority, field, previousColumn }) { + buildColumn({ suggestedPriority, previousColumn }) { let params = { filters: [defaultFilter] }; if (previousColumn?.operationType === 'terms') { params = { @@ -108,11 +99,18 @@ export const filtersOperation: OperationDefinition = scale: 'ordinal', suggestedPriority, isBucketed: true, - sourceField: field.name, params, }; }, + getPossibleOperation() { + return { + dataType: 'string', + isBucketed: true, + scale: 'ordinal', + }; + }, + toEsAggsConfig: (column, columnId, indexPattern) => { const validFilters = column.params.filters?.filter((f: Filter) => isQueryValid(f.input, indexPattern) diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts index 19523b550af5a6..38aec866ca5cb1 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts @@ -28,22 +28,6 @@ import { DateRange } from '../../../../common'; import { DataPublicPluginStart } from '../../../../../../../src/plugins/data/public'; import { RangeIndexPatternColumn, rangeOperation } from './ranges'; -// List of all operation definitions registered to this data source. -// If you want to implement a new operation, add the definition to this array and -// the column type to the `IndexPatternColumn` union type below. -const internalOperationDefinitions = [ - filtersOperation, - termsOperation, - dateHistogramOperation, - minOperation, - maxOperation, - averageOperation, - cardinalityOperation, - sumOperation, - countOperation, - rangeOperation, -]; - /** * A union type of all available column types. If a column is of an unknown type somewhere * withing the indexpattern data source it should be typed as `IndexPatternColumn` to make @@ -61,6 +45,24 @@ export type IndexPatternColumn = | SumIndexPatternColumn | CountIndexPatternColumn; +export type FieldBasedIndexPatternColumn = Extract; + +// List of all operation definitions registered to this data source. +// If you want to implement a new operation, add the definition to this array and +// the column type to the `IndexPatternColumn` union type below. +const internalOperationDefinitions = [ + filtersOperation, + termsOperation, + dateHistogramOperation, + minOperation, + maxOperation, + averageOperation, + cardinalityOperation, + sumOperation, + countOperation, + rangeOperation, +]; + export { termsOperation } from './terms'; export { rangeOperation } from './ranges'; export { filtersOperation } from './filters'; @@ -71,7 +73,7 @@ export { countOperation } from './count'; /** * Properties passed to the operation-specific part of the popover editor */ -export interface ParamEditorProps { +export interface ParamEditorProps { currentColumn: C; state: IndexPatternPrivateState; setState: StateSetter; @@ -138,13 +140,25 @@ interface BaseBuildColumnArgs { indexPattern: IndexPattern; } -/** - * Shape of an operation definition. If the type parameter of the definition - * indicates a field based column, `getPossibleOperationForField` has to be - * specified, otherwise `getPossibleOperationForDocument` has to be defined. - */ -export interface OperationDefinition - extends BaseOperationDefinitionProps { +interface FieldlessOperationDefinition { + input: 'none'; + /** + * Builds the column object for the given parameters. Should include default p + */ + buildColumn: ( + arg: BaseBuildColumnArgs & { + previousColumn?: IndexPatternColumn; + } + ) => C; + /** + * Returns the meta data of the operation if applied. Undefined + * if the field is not applicable. + */ + getPossibleOperation: () => OperationMetadata | undefined; +} + +interface FieldBasedOperationDefinition { + input: 'field'; /** * Returns the meta data of the operation if applied to the given field. Undefined * if the field is not applicable to the operation. @@ -156,7 +170,8 @@ export interface OperationDefinition buildColumn: ( arg: BaseBuildColumnArgs & { field: IndexPatternField; - previousColumn?: IndexPatternColumn; + // previousColumn?: IndexPatternColumn; + previousColumn?: C; } ) => C; /** @@ -175,9 +190,29 @@ export interface OperationDefinition * @param indexPattern The index pattern that field is on. * @param field The field that the user changed to. */ - onFieldChange: (oldColumn: C, indexPattern: IndexPattern, field: IndexPatternField) => C; + onFieldChange: ( + // oldColumn: FieldBasedIndexPatternColumn, + oldColumn: C, + indexPattern: IndexPattern, + field: IndexPatternField + ) => C; } +interface OperationDefinitionMap { + field: FieldBasedOperationDefinition; + none: FieldlessOperationDefinition; +} + +/** + * Shape of an operation definition. If the type parameter of the definition + * indicates a field based column, `getPossibleOperationForField` has to be + * specified, otherwise `getPossibleOperation` has to be defined. + */ +export type OperationDefinition< + C extends BaseIndexPatternColumn, + Input extends keyof OperationDefinitionMap +> = BaseOperationDefinitionProps & OperationDefinitionMap[Input]; + /** * A union type of all available operation types. The operation type is a unique id of an operation. * Each column is assigned to exactly one operation type. @@ -188,7 +223,9 @@ export type OperationType = typeof internalOperationDefinitions[number]['type']; * This is an operation definition of an unspecified column out of all possible * column types. */ -export type GenericOperationDefinition = OperationDefinition; +export type GenericOperationDefinition = + | OperationDefinition + | OperationDefinition; /** * List of all available operation definitions @@ -206,7 +243,10 @@ export const operationDefinitions = internalOperationDefinitions as GenericOpera * (e.g. `import { termsOperation } from './operations/definitions'`). This map is * intended to be used in situations where the operation type is not known during compile time. */ -export const operationDefinitionMap = internalOperationDefinitions.reduce( +export const operationDefinitionMap: Record< + string, + GenericOperationDefinition +> = internalOperationDefinitions.reduce( (definitionMap, definition) => ({ ...definitionMap, [definition.type]: definition }), {} -) as Record; +); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx index 4c37d95f6b0509..c02f7bcb7d2cda 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx @@ -6,11 +6,12 @@ import { i18n } from '@kbn/i18n'; import { OperationDefinition } from './index'; -import { FormattedIndexPatternColumn } from './column_types'; +import { FormattedIndexPatternColumn, FieldBasedIndexPatternColumn } from './column_types'; -type MetricColumn = FormattedIndexPatternColumn & { - operationType: T; -}; +type MetricColumn = FormattedIndexPatternColumn & + FieldBasedIndexPatternColumn & { + operationType: T; + }; function buildMetricOperation>({ type, @@ -27,6 +28,7 @@ function buildMetricOperation>({ type, priority, displayName, + input: 'field', getPossibleOperationForField: ({ aggregationRestrictions, aggregatable, type: fieldType }) => { if ( fieldType === 'number' && @@ -78,7 +80,7 @@ function buildMetricOperation>({ missing: 0, }, }), - } as OperationDefinition; + } as OperationDefinition; } export type SumIndexPatternColumn = MetricColumn<'sum'>; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx index 530c2e962759b8..1971fb2875bed5 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/ranges/ranges.tsx @@ -76,12 +76,13 @@ function getEsAggsParams({ sourceField, params }: RangeIndexPatternColumn) { }; } -export const rangeOperation: OperationDefinition = { +export const rangeOperation: OperationDefinition = { type: 'range', displayName: i18n.translate('xpack.lens.indexPattern.ranges', { defaultMessage: 'Ranges', }), priority: 4, // Higher than terms, so numbers get histogram + input: 'field', getPossibleOperationForField: ({ aggregationRestrictions, aggregatable, type }) => { if ( type === 'number' && diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx index c1a87a2013747e..c147029bbd3c77 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx @@ -48,12 +48,13 @@ export interface TermsIndexPatternColumn extends FieldBasedIndexPatternColumn { }; } -export const termsOperation: OperationDefinition = { +export const termsOperation: OperationDefinition = { type: 'terms', displayName: i18n.translate('xpack.lens.indexPattern.terms', { defaultMessage: 'Top values', }), priority: 3, // Higher than any metric + input: 'field', getPossibleOperationForField: ({ aggregationRestrictions, aggregatable, type }) => { if ( supportedTypes.has(type) && @@ -95,23 +96,25 @@ export const termsOperation: OperationDefinition = { }, }; }, - toEsAggsConfig: (column, columnId, _indexPattern) => ({ - id: columnId, - enabled: true, - type: 'terms', - schema: 'segment', - params: { - field: column.sourceField, - orderBy: - column.params.orderBy.type === 'alphabetical' ? '_key' : column.params.orderBy.columnId, - order: column.params.orderDirection, - size: column.params.size, - otherBucket: false, - otherBucketLabel: 'Other', - missingBucket: false, - missingBucketLabel: 'Missing', - }, - }), + toEsAggsConfig: (column, columnId, _indexPattern) => { + return { + id: columnId, + enabled: true, + type: 'terms', + schema: 'segment', + params: { + field: column.sourceField, + orderBy: + column.params.orderBy.type === 'alphabetical' ? '_key' : column.params.orderBy.columnId, + order: column.params.orderDirection, + size: column.params.size, + otherBucket: false, + otherBucketLabel: 'Other', + missingBucket: false, + missingBucketLabel: 'Missing', + }, + }; + }, onFieldChange: (oldColumn, indexPattern, field) => { return { ...oldColumn, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts index 1e2bc5dcb6b623..31a36c59274da7 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts @@ -5,4 +5,4 @@ */ export * from './operations'; -export { OperationType, IndexPatternColumn } from './definitions'; +export { OperationType, IndexPatternColumn, FieldBasedIndexPatternColumn } from './definitions'; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.test.ts index 703431f724c5dd..c1bd4b84099b74 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.test.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.test.ts @@ -182,7 +182,7 @@ describe('getOperationTypesForField', () => { }, }; - it('should build a column for the given operation type if it is passed in', () => { + it('should build a column for the given field-based operation type if it is passed in', () => { const column = buildColumn({ layerId: 'first', indexPattern: expectedIndexPatterns[1], @@ -194,6 +194,17 @@ describe('getOperationTypesForField', () => { expect(column.operationType).toEqual('count'); }); + it('should build a column for the given no-input operation type if it is passed in', () => { + const column = buildColumn({ + layerId: 'first', + indexPattern: expectedIndexPatterns[1], + columns: state.layers.first.columns, + suggestedPriority: 0, + op: 'filters', + }); + expect(column.operationType).toEqual('filters'); + }); + it('should build a column for the given operation type and field if it is passed in', () => { const field = expectedIndexPatterns[1].fields[1]; const column = buildColumn({ @@ -222,7 +233,7 @@ describe('getOperationTypesForField', () => { ); }); - it('should list out all field-operation tuples for different operation meta data', () => { + it('should list out all operation tuples', () => { expect(getAvailableOperationsByMetadata(expectedIndexPatterns[1])).toMatchInlineSnapshot(` Array [ Object { @@ -255,13 +266,17 @@ describe('getOperationTypesForField', () => { }, Object { "operationMetaData": Object { - "dataType": "number", + "dataType": "string", "isBucketed": true, "scale": "ordinal", }, "operations": Array [ Object { - "field": "bytes", + "operationType": "filters", + "type": "none", + }, + Object { + "field": "source", "operationType": "terms", "type": "field", }, @@ -269,13 +284,13 @@ describe('getOperationTypesForField', () => { }, Object { "operationMetaData": Object { - "dataType": "string", + "dataType": "number", "isBucketed": true, "scale": "ordinal", }, "operations": Array [ Object { - "field": "source", + "field": "bytes", "operationType": "terms", "type": "field", }, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts index 9e5a0f496357d4..46dd73ba849a26 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts @@ -63,7 +63,7 @@ export function getOperationTypesForField(field: IndexPatternField): OperationTy return operationDefinitions .filter( (operationDefinition) => - 'getPossibleOperationForField' in operationDefinition && + operationDefinition.input === 'field' && operationDefinition.getPossibleOperationForField(field) ) .sort(getSortScoreByPriority) @@ -80,11 +80,16 @@ export function isDocumentOperation(type: string) { return documentOperations.has(type); } -interface OperationFieldTuple { - type: 'field'; - operationType: OperationType; - field: string; -} +type OperationFieldTuple = + | { + type: 'field'; + operationType: OperationType; + field: string; + } + | { + type: 'none'; + operationType: OperationType; + }; /** * Returns all possible operations (matches between operations and fields of the index @@ -100,11 +105,18 @@ interface OperationFieldTuple { * [ * { * operationMetaData: { dataType: 'string', isBucketed: true }, - * operations: ['terms'] + * operations: [{ + * type: 'field', + * operationType: ['terms'], + * field: 'keyword' + * }] * }, * { - * operationMetaData: { dataType: 'number', isBucketed: false }, - * operations: ['avg', 'min', 'max'] + * operationMetaData: { dataType: 'string', isBucketed: true }, + * operations: [{ + * type: 'none', + * operationType: ['filters'], + * }] * }, * ] * ``` @@ -133,30 +145,31 @@ export function getAvailableOperationsByMetadata(indexPattern: IndexPattern) { }; operationDefinitions.sort(getSortScoreByPriority).forEach((operationDefinition) => { - indexPattern.fields.forEach((field) => { + if (operationDefinition.input === 'field') { + indexPattern.fields.forEach((field) => { + addToMap( + { + type: 'field', + operationType: operationDefinition.type, + field: field.name, + }, + operationDefinition.getPossibleOperationForField(field) + ); + }); + } else if (operationDefinition.input === 'none') { addToMap( { - type: 'field', + type: 'none', operationType: operationDefinition.type, - field: field.name, }, - getPossibleOperationForField(operationDefinition, field) + operationDefinition.getPossibleOperation() ); - }); + } }); return Object.values(operationByMetadata); } -function getPossibleOperationForField( - operationDefinition: GenericOperationDefinition, - field: IndexPatternField -): OperationMetadata | undefined { - return 'getPossibleOperationForField' in operationDefinition - ? operationDefinition.getPossibleOperationForField(field) - : undefined; -} - /** * Changes the field of the passed in colum. To do so, this method uses the `onFieldChange` function of * the operation definition of the column. Returns a new column object with the field changed. @@ -171,13 +184,13 @@ export function changeField( ) { const operationDefinition = operationDefinitionMap[column.operationType]; - if (!('onFieldChange' in operationDefinition)) { + if (operationDefinition.input === 'field' && 'sourceField' in column) { + return operationDefinition.onFieldChange(column, indexPattern, newField); + } else { throw new Error( "Invariant error: Cannot change field if operation isn't a field based operaiton" ); } - - return operationDefinition.onFieldChange(column, indexPattern, newField); } /** @@ -203,7 +216,7 @@ export function buildColumn({ suggestedPriority: DimensionPriority | undefined; layerId: string; indexPattern: IndexPattern; - field: IndexPatternField; + field?: IndexPatternField; previousColumn?: IndexPatternColumn; }): IndexPatternColumn { const operationDefinition = operationDefinitionMap[op]; @@ -220,16 +233,18 @@ export function buildColumn({ previousColumn, }; + if (operationDefinition.input === 'none') { + return operationDefinition.buildColumn(baseOptions); + } + if (!field) { throw new Error(`Invariant error: ${operationDefinition.type} operation requires field`); } - const newColumn = operationDefinition.buildColumn({ + return operationDefinition.buildColumn({ ...baseOptions, field, }); - - return newColumn; } export { operationDefinitionMap } from './definitions'; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts b/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts index 51691ae18a99a8..c977a7e0fa3703 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts @@ -5,8 +5,7 @@ */ import _ from 'lodash'; -import { isColumnTransferable } from './operations'; -import { operationDefinitionMap, IndexPatternColumn } from './operations'; +import { isColumnTransferable, operationDefinitionMap, IndexPatternColumn } from './operations'; import { IndexPattern, IndexPatternPrivateState, IndexPatternLayer } from './types'; export function updateColumnParam({ diff --git a/x-pack/test/functional/apps/lens/smokescreen.ts b/x-pack/test/functional/apps/lens/smokescreen.ts index 05047fab2517d6..1ed3a0864c2442 100644 --- a/x-pack/test/functional/apps/lens/smokescreen.ts +++ b/x-pack/test/functional/apps/lens/smokescreen.ts @@ -67,11 +67,13 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { // legend item(s), so we're using a class selector here. expect(await find.allByCssSelector('.echLegendItem')).to.have.length(3); }); + it('should create an xy visualization with filters aggregation', async () => { await PageObjects.visualize.gotoVisualizationLandingPage(); await listingTable.searchForItemWithName('lnsXYvis'); await PageObjects.lens.clickVisualizeListItemTitle('lnsXYvis'); await PageObjects.lens.goToTimeRange(); + // Change the IP field to filters await PageObjects.lens.configureDimension({ dimension: 'lnsXY_splitDimensionPanel > lns-dimensionTrigger', operation: 'filters', @@ -79,6 +81,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { }); await PageObjects.lens.addFilterToAgg(`geo.src : CN`); + // Verify that the field was persisted from the transition expect(await PageObjects.lens.getFiltersAggLabels()).to.eql([`ip : *`, `geo.src : CN`]); expect(await find.allByCssSelector('.echLegendItem')).to.have.length(2); }); From 97fd0dfbef543d74f972cfd494a56dfbad823238 Mon Sep 17 00:00:00 2001 From: ncheckin <68351161+ncheckin@users.noreply.github.com> Date: Mon, 28 Sep 2020 11:27:27 -0400 Subject: [PATCH 12/19] Update tutorial-define-index.asciidoc (#76975) * Update tutorial-define-index.asciidoc Forgot to update alt text in previous pr. Additionally, it is unclear in the image where the "time field" dropdown is located. * Update docs/getting-started/tutorial-define-index.asciidoc Co-authored-by: Kaarina Tungseth --- docs/getting-started/tutorial-define-index.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/getting-started/tutorial-define-index.asciidoc b/docs/getting-started/tutorial-define-index.asciidoc index 5a05d565ab3f81..215952c2d35953 100644 --- a/docs/getting-started/tutorial-define-index.asciidoc +++ b/docs/getting-started/tutorial-define-index.asciidoc @@ -45,7 +45,7 @@ contains the time series data. . From the *Time field* dropdown, select *@timestamp, then click *Create index pattern*. + [role="screenshot"] -image::images/tutorial_index_patterns.png[All tutorial index patterns] +image::images/tutorial_index_patterns.png[Image showing how to create an index pattern] NOTE: When you define an index pattern, the indices that match that pattern must exist in Elasticsearch and they must contain data. To check if the indices are From 689e1e32f17a53fa004c6c7fc147b73e17e6b2c2 Mon Sep 17 00:00:00 2001 From: Liza Katz Date: Mon, 28 Sep 2020 18:33:48 +0300 Subject: [PATCH 13/19] [Search] Error notification alignment (#77788) * OSS error alignemnt * Adjust error messages in xpack * Add getErrorMessage * Use showError in vizualize Add original error to expression exception * Cleanup * ts, doc and i18n fixes * Fix jest tests * Fix functional test * functional test * ts * Update functional tests * Add unit tests to interceptor and timeout error * expose toasts test function * doc * typos * review 1 * Code review * doc * doc fix * visualization type fix * fix jest * Fix xpack functional test * fix xpack test * code review * delete debubg flag * Update texts by @gchaps * docs and ts Co-authored-by: Elastic Machine --- ...plugin-plugins-data-public.isearchstart.md | 1 + ...gins-data-public.isearchstart.showerror.md | 11 ++ .../kibana-plugin-plugins-data-public.md | 4 +- ...data-public.painlesserror._constructor_.md | 21 ++ ...ta-public.painlesserror.geterrormessage.md | 22 +++ ...lugin-plugins-data-public.painlesserror.md | 30 +++ ...data-public.painlesserror.painlessstack.md | 11 ++ ...ublic.requesttimeouterror._constructor_.md | 20 -- ...plugins-data-public.requesttimeouterror.md | 20 -- ...public.searchinterceptor.gettimeoutmode.md | 15 ++ ...lic.searchinterceptor.handlesearcherror.md | 25 +++ ...n-plugins-data-public.searchinterceptor.md | 4 +- ...ns-data-public.searchinterceptor.search.md | 6 +- ...ata-public.searchinterceptor.showerror.md} | 17 +- ...public.searchtimeouterror._constructor_.md | 21 ++ ...blic.searchtimeouterror.geterrormessage.md | 22 +++ ...-plugins-data-public.searchtimeouterror.md | 32 +++ ...ins-data-public.searchtimeouterror.mode.md | 11 ++ ...in-plugins-data-public.timeouterrormode.md | 20 ++ .../search_examples/server/my_strategy.ts | 2 +- src/plugins/data/public/index.ts | 7 +- src/plugins/data/public/public.api.md | 92 ++++++--- .../public/search/errors}/index.ts | 3 +- .../public/search/errors/painless_error.tsx | 89 +++++++++ .../search/errors/timeout_error.test.tsx | 62 ++++++ .../public/search/errors/timeout_error.tsx | 111 +++++++++++ .../public/search/errors/types.ts} | 47 +---- src/plugins/data/public/search/index.ts | 2 +- src/plugins/data/public/search/mocks.ts | 1 + .../public/search/request_timeout_error.ts | 30 --- .../public/search/search_interceptor.test.ts | 114 ++++++----- .../data/public/search/search_interceptor.ts | 187 +++++++++++------- .../data/public/search/search_service.ts | 3 + src/plugins/data/public/search/types.ts | 2 + .../public/application/angular/discover.js | 28 +-- .../components/discover_legacy.tsx | 6 +- .../components/fetch_error/fetch_error.scss | 3 - .../components/fetch_error/fetch_error.tsx | 96 --------- .../common/expression_types/specs/error.ts | 1 + .../expressions/common/util/create_error.ts | 3 +- .../utils/get_visualization_instance.test.ts | 4 +- .../utils/get_visualization_instance.ts | 19 +- test/functional/apps/discover/_errors.ts | 7 +- test/functional/services/toasts.ts | 2 +- .../public/search/search_interceptor.test.ts | 5 +- .../public/search/search_interceptor.ts | 54 ++--- .../components/alerts_table/actions.test.tsx | 1 + .../translations/translations/ja-JP.json | 6 - .../translations/translations/zh-CN.json | 6 - .../apps/discover/error_handling.ts | 8 +- 50 files changed, 849 insertions(+), 465 deletions(-) create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.showerror.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror._constructor_.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.geterrormessage.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.painlessstack.md delete mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror._constructor_.md delete mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.gettimeoutmode.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.handlesearcherror.md rename docs/development/plugins/data/public/{kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md => kibana-plugin-plugins-data-public.searchinterceptor.showerror.md} (53%) create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror._constructor_.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.geterrormessage.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.mode.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.timeouterrormode.md rename src/plugins/{discover/public/application/components/fetch_error => data/public/search/errors}/index.ts (92%) create mode 100644 src/plugins/data/public/search/errors/painless_error.tsx create mode 100644 src/plugins/data/public/search/errors/timeout_error.test.tsx create mode 100644 src/plugins/data/public/search/errors/timeout_error.tsx rename src/plugins/{discover/public/application/angular/get_painless_error.ts => data/public/search/errors/types.ts} (61%) delete mode 100644 src/plugins/data/public/search/request_timeout_error.ts delete mode 100644 src/plugins/discover/public/application/components/fetch_error/fetch_error.scss delete mode 100644 src/plugins/discover/public/application/components/fetch_error/fetch_error.tsx diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.md index cee213fc6e7e3c..5defe4a6476142 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.md @@ -19,4 +19,5 @@ export interface ISearchStart | [aggs](./kibana-plugin-plugins-data-public.isearchstart.aggs.md) | AggsStart | agg config sub service [AggsStart](./kibana-plugin-plugins-data-public.aggsstart.md) | | [search](./kibana-plugin-plugins-data-public.isearchstart.search.md) | ISearchGeneric | low level search [ISearchGeneric](./kibana-plugin-plugins-data-public.isearchgeneric.md) | | [searchSource](./kibana-plugin-plugins-data-public.isearchstart.searchsource.md) | ISearchStartSearchSource | high level search [ISearchStartSearchSource](./kibana-plugin-plugins-data-public.isearchstartsearchsource.md) | +| [showError](./kibana-plugin-plugins-data-public.isearchstart.showerror.md) | (e: Error) => void | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.showerror.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.showerror.md new file mode 100644 index 00000000000000..fb14057d83d5c2 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.isearchstart.showerror.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ISearchStart](./kibana-plugin-plugins-data-public.isearchstart.md) > [showError](./kibana-plugin-plugins-data-public.isearchstart.showerror.md) + +## ISearchStart.showError property + +Signature: + +```typescript +showError: (e: Error) => void; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md index 0f45b5a727676e..e5f56a1ec387fb 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md @@ -19,10 +19,11 @@ | [IndexPatternSelect](./kibana-plugin-plugins-data-public.indexpatternselect.md) | | | [IndexPatternsService](./kibana-plugin-plugins-data-public.indexpatternsservice.md) | | | [OptionedParamType](./kibana-plugin-plugins-data-public.optionedparamtype.md) | | +| [PainlessError](./kibana-plugin-plugins-data-public.painlesserror.md) | | | [Plugin](./kibana-plugin-plugins-data-public.plugin.md) | | -| [RequestTimeoutError](./kibana-plugin-plugins-data-public.requesttimeouterror.md) | Class used to signify that a request timed out. Useful for applications to conditionally handle this type of error differently than other errors. | | [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) | | | [SearchSource](./kibana-plugin-plugins-data-public.searchsource.md) | \* | +| [SearchTimeoutError](./kibana-plugin-plugins-data-public.searchtimeouterror.md) | Request Failure - When an entire multi request fails | | [TimeHistory](./kibana-plugin-plugins-data-public.timehistory.md) | | ## Enumerations @@ -35,6 +36,7 @@ | [METRIC\_TYPES](./kibana-plugin-plugins-data-public.metric_types.md) | | | [QuerySuggestionTypes](./kibana-plugin-plugins-data-public.querysuggestiontypes.md) | | | [SortDirection](./kibana-plugin-plugins-data-public.sortdirection.md) | | +| [TimeoutErrorMode](./kibana-plugin-plugins-data-public.timeouterrormode.md) | | ## Functions diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror._constructor_.md new file mode 100644 index 00000000000000..f8966572afbb66 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror._constructor_.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [PainlessError](./kibana-plugin-plugins-data-public.painlesserror.md) > [(constructor)](./kibana-plugin-plugins-data-public.painlesserror._constructor_.md) + +## PainlessError.(constructor) + +Constructs a new instance of the `PainlessError` class + +Signature: + +```typescript +constructor(err: EsError, request: IKibanaSearchRequest); +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| err | EsError | | +| request | IKibanaSearchRequest | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.geterrormessage.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.geterrormessage.md new file mode 100644 index 00000000000000..a3b4c51c6c3313 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.geterrormessage.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [PainlessError](./kibana-plugin-plugins-data-public.painlesserror.md) > [getErrorMessage](./kibana-plugin-plugins-data-public.painlesserror.geterrormessage.md) + +## PainlessError.getErrorMessage() method + +Signature: + +```typescript +getErrorMessage(application: ApplicationStart): JSX.Element; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| application | ApplicationStart | | + +Returns: + +`JSX.Element` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.md new file mode 100644 index 00000000000000..306211cd602599 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.md @@ -0,0 +1,30 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [PainlessError](./kibana-plugin-plugins-data-public.painlesserror.md) + +## PainlessError class + +Signature: + +```typescript +export declare class PainlessError extends KbnError +``` + +## Constructors + +| Constructor | Modifiers | Description | +| --- | --- | --- | +| [(constructor)(err, request)](./kibana-plugin-plugins-data-public.painlesserror._constructor_.md) | | Constructs a new instance of the PainlessError class | + +## Properties + +| Property | Modifiers | Type | Description | +| --- | --- | --- | --- | +| [painlessStack](./kibana-plugin-plugins-data-public.painlesserror.painlessstack.md) | | string | | + +## Methods + +| Method | Modifiers | Description | +| --- | --- | --- | +| [getErrorMessage(application)](./kibana-plugin-plugins-data-public.painlesserror.geterrormessage.md) | | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.painlessstack.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.painlessstack.md new file mode 100644 index 00000000000000..a7e6920b2ae219 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.painlesserror.painlessstack.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [PainlessError](./kibana-plugin-plugins-data-public.painlesserror.md) > [painlessStack](./kibana-plugin-plugins-data-public.painlesserror.painlessstack.md) + +## PainlessError.painlessStack property + +Signature: + +```typescript +painlessStack?: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror._constructor_.md deleted file mode 100644 index 25e472817b46d2..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror._constructor_.md +++ /dev/null @@ -1,20 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [RequestTimeoutError](./kibana-plugin-plugins-data-public.requesttimeouterror.md) > [(constructor)](./kibana-plugin-plugins-data-public.requesttimeouterror._constructor_.md) - -## RequestTimeoutError.(constructor) - -Constructs a new instance of the `RequestTimeoutError` class - -Signature: - -```typescript -constructor(message?: string); -``` - -## Parameters - -| Parameter | Type | Description | -| --- | --- | --- | -| message | string | | - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror.md deleted file mode 100644 index 84b2fc3fe0b177..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.requesttimeouterror.md +++ /dev/null @@ -1,20 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [RequestTimeoutError](./kibana-plugin-plugins-data-public.requesttimeouterror.md) - -## RequestTimeoutError class - -Class used to signify that a request timed out. Useful for applications to conditionally handle this type of error differently than other errors. - -Signature: - -```typescript -export declare class RequestTimeoutError extends Error -``` - -## Constructors - -| Constructor | Modifiers | Description | -| --- | --- | --- | -| [(constructor)(message)](./kibana-plugin-plugins-data-public.requesttimeouterror._constructor_.md) | | Constructs a new instance of the RequestTimeoutError class | - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.gettimeoutmode.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.gettimeoutmode.md new file mode 100644 index 00000000000000..8ecd8b8c5ac226 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.gettimeoutmode.md @@ -0,0 +1,15 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) > [getTimeoutMode](./kibana-plugin-plugins-data-public.searchinterceptor.gettimeoutmode.md) + +## SearchInterceptor.getTimeoutMode() method + +Signature: + +```typescript +protected getTimeoutMode(): TimeoutErrorMode; +``` +Returns: + +`TimeoutErrorMode` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.handlesearcherror.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.handlesearcherror.md new file mode 100644 index 00000000000000..02db74b1a9e914 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.handlesearcherror.md @@ -0,0 +1,25 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) > [handleSearchError](./kibana-plugin-plugins-data-public.searchinterceptor.handlesearcherror.md) + +## SearchInterceptor.handleSearchError() method + +Signature: + +```typescript +protected handleSearchError(e: any, request: IKibanaSearchRequest, timeoutSignal: AbortSignal, appAbortSignal?: AbortSignal): Error; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| e | any | | +| request | IKibanaSearchRequest | | +| timeoutSignal | AbortSignal | | +| appAbortSignal | AbortSignal | | + +Returns: + +`Error` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md index 5cee345db6cd2a..a02a6116d7ae00 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.md @@ -21,11 +21,13 @@ export declare class SearchInterceptor | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [deps](./kibana-plugin-plugins-data-public.searchinterceptor.deps.md) | | SearchInterceptorDeps | | -| [showTimeoutError](./kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md) | | ((e: Error) => void) & import("lodash").Cancelable | | ## Methods | Method | Modifiers | Description | | --- | --- | --- | +| [getTimeoutMode()](./kibana-plugin-plugins-data-public.searchinterceptor.gettimeoutmode.md) | | | +| [handleSearchError(e, request, timeoutSignal, appAbortSignal)](./kibana-plugin-plugins-data-public.searchinterceptor.handlesearcherror.md) | | | | [search(request, options)](./kibana-plugin-plugins-data-public.searchinterceptor.search.md) | | Searches using the given search method. Overrides the AbortSignal with one that will abort either when cancelPending is called, when the request times out, or when the original AbortSignal is aborted. Updates pendingCount$ when the request is started/finalized. | +| [showError(e)](./kibana-plugin-plugins-data-public.searchinterceptor.showerror.md) | | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.search.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.search.md index 1a71b5808f485b..672ff5065c456c 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.search.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.search.md @@ -9,17 +9,19 @@ Searches using the given `search` method. Overrides the `AbortSignal` with one t Signature: ```typescript -search(request: IEsSearchRequest, options?: ISearchOptions): Observable; +search(request: IKibanaSearchRequest, options?: ISearchOptions): Observable; ``` ## Parameters | Parameter | Type | Description | | --- | --- | --- | -| request | IEsSearchRequest | | +| request | IKibanaSearchRequest | | | options | ISearchOptions | | Returns: `Observable` +`Observalbe` emitting the search response or an error. + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showerror.md similarity index 53% rename from docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md rename to docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showerror.md index 91ecb2821acbfb..92e851c783dd06 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptor.showerror.md @@ -1,11 +1,22 @@ -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) > [showTimeoutError](./kibana-plugin-plugins-data-public.searchinterceptor.showtimeouterror.md) +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchInterceptor](./kibana-plugin-plugins-data-public.searchinterceptor.md) > [showError](./kibana-plugin-plugins-data-public.searchinterceptor.showerror.md) -## SearchInterceptor.showTimeoutError property +## SearchInterceptor.showError() method Signature: ```typescript -protected showTimeoutError: ((e: Error) => void) & import("lodash").Cancelable; +showError(e: Error): void; ``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| e | Error | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror._constructor_.md new file mode 100644 index 00000000000000..1c6370c7d03561 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror._constructor_.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchTimeoutError](./kibana-plugin-plugins-data-public.searchtimeouterror.md) > [(constructor)](./kibana-plugin-plugins-data-public.searchtimeouterror._constructor_.md) + +## SearchTimeoutError.(constructor) + +Constructs a new instance of the `SearchTimeoutError` class + +Signature: + +```typescript +constructor(err: Error, mode: TimeoutErrorMode); +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| err | Error | | +| mode | TimeoutErrorMode | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.geterrormessage.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.geterrormessage.md new file mode 100644 index 00000000000000..58ef953c9d7dbd --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.geterrormessage.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchTimeoutError](./kibana-plugin-plugins-data-public.searchtimeouterror.md) > [getErrorMessage](./kibana-plugin-plugins-data-public.searchtimeouterror.geterrormessage.md) + +## SearchTimeoutError.getErrorMessage() method + +Signature: + +```typescript +getErrorMessage(application: ApplicationStart): JSX.Element; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| application | ApplicationStart | | + +Returns: + +`JSX.Element` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.md new file mode 100644 index 00000000000000..5c0bec04dcfbc1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.md @@ -0,0 +1,32 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchTimeoutError](./kibana-plugin-plugins-data-public.searchtimeouterror.md) + +## SearchTimeoutError class + +Request Failure - When an entire multi request fails + +Signature: + +```typescript +export declare class SearchTimeoutError extends KbnError +``` + +## Constructors + +| Constructor | Modifiers | Description | +| --- | --- | --- | +| [(constructor)(err, mode)](./kibana-plugin-plugins-data-public.searchtimeouterror._constructor_.md) | | Constructs a new instance of the SearchTimeoutError class | + +## Properties + +| Property | Modifiers | Type | Description | +| --- | --- | --- | --- | +| [mode](./kibana-plugin-plugins-data-public.searchtimeouterror.mode.md) | | TimeoutErrorMode | | + +## Methods + +| Method | Modifiers | Description | +| --- | --- | --- | +| [getErrorMessage(application)](./kibana-plugin-plugins-data-public.searchtimeouterror.geterrormessage.md) | | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.mode.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.mode.md new file mode 100644 index 00000000000000..d534a73eca2ec2 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchtimeouterror.mode.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchTimeoutError](./kibana-plugin-plugins-data-public.searchtimeouterror.md) > [mode](./kibana-plugin-plugins-data-public.searchtimeouterror.mode.md) + +## SearchTimeoutError.mode property + +Signature: + +```typescript +mode: TimeoutErrorMode; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.timeouterrormode.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.timeouterrormode.md new file mode 100644 index 00000000000000..8ad63e2c1e9b4f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.timeouterrormode.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [TimeoutErrorMode](./kibana-plugin-plugins-data-public.timeouterrormode.md) + +## TimeoutErrorMode enum + +Signature: + +```typescript +export declare enum TimeoutErrorMode +``` + +## Enumeration Members + +| Member | Value | Description | +| --- | --- | --- | +| CHANGE | 2 | | +| CONTACT | 1 | | +| UPGRADE | 0 | | + diff --git a/examples/search_examples/server/my_strategy.ts b/examples/search_examples/server/my_strategy.ts index 1f59d0a5d8f3a6..169982544e6e81 100644 --- a/examples/search_examples/server/my_strategy.ts +++ b/examples/search_examples/server/my_strategy.ts @@ -25,7 +25,7 @@ export const mySearchStrategyProvider = ( ): ISearchStrategy => { const es = data.search.getSearchStrategy('es'); return { - search: async (context, request, options) => { + search: async (context, request, options): Promise => { const esSearchRes = await es.search(context, request, options); return { ...esSearchRes, diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index f7dceffa9fdbc3..0e21f6f6955514 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -365,8 +365,6 @@ export { ISearchGeneric, ISearchSource, parseSearchSourceJSON, - RequestTimeoutError, - SearchError, SearchInterceptor, SearchInterceptorDeps, SearchRequest, @@ -375,6 +373,11 @@ export { // expression functions and types EsdslExpressionFunctionDefinition, EsRawResponseExpressionTypeDefinition, + // errors + SearchError, + SearchTimeoutError, + TimeoutErrorMode, + PainlessError, } from './search'; export type { SearchSource } from './search'; diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 9c059c0f358927..1ee453a0f14115 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -8,6 +8,7 @@ import { $Values } from '@kbn/utility-types'; import _ from 'lodash'; import { Action } from 'history'; import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; +import { ApplicationStart } from 'kibana/public'; import { Assign } from '@kbn/utility-types'; import { BehaviorSubject } from 'rxjs'; import Boom from 'boom'; @@ -69,7 +70,6 @@ import { SavedObjectsClientContract } from 'src/core/public'; import { Search } from '@elastic/elasticsearch/api/requestParams'; import { SearchResponse } from 'elasticsearch'; import { SerializedFieldFormat as SerializedFieldFormat_2 } from 'src/plugins/expressions/common'; -import { Subscription } from 'rxjs'; import { ToastInputFields } from 'src/core/public/notifications'; import { ToastsSetup } from 'kibana/public'; import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport'; @@ -1462,6 +1462,8 @@ export interface ISearchStart { aggs: AggsStart; search: ISearchGeneric; searchSource: ISearchStartSearchSource; + // (undocumented) + showError: (e: Error) => void; } // @public @@ -1628,6 +1630,19 @@ export interface OptionedValueProp { value: string; } +// Warning: (ae-forgotten-export) The symbol "KbnError" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "PainlessError" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export class PainlessError extends KbnError { + // Warning: (ae-forgotten-export) The symbol "EsError" needs to be exported by the entry point index.d.ts + constructor(err: EsError, request: IKibanaSearchRequest); + // (undocumented) + getErrorMessage(application: ApplicationStart): JSX.Element; + // (undocumented) + painlessStack?: string; +} + // Warning: (ae-forgotten-export) The symbol "parseEsInterval" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "ParsedInterval" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -1893,13 +1908,6 @@ export interface RefreshInterval { value: number; } -// Warning: (ae-missing-release-tag) "RequestTimeoutError" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) -// -// @public -export class RequestTimeoutError extends Error { - constructor(message?: string); -} - // Warning: (ae-missing-release-tag) "SavedQuery" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -2023,24 +2031,27 @@ export class SearchInterceptor { protected application: CoreStart['application']; // (undocumented) protected readonly deps: SearchInterceptorDeps; + // (undocumented) + protected getTimeoutMode(): TimeoutErrorMode; + // (undocumented) + protected handleSearchError(e: any, request: IKibanaSearchRequest, timeoutSignal: AbortSignal, appAbortSignal?: AbortSignal): Error; // @internal protected pendingCount$: BehaviorSubject; // @internal (undocumented) - protected runSearch(request: IEsSearchRequest, signal: AbortSignal, strategy?: string): Observable; - search(request: IEsSearchRequest, options?: ISearchOptions): Observable; + protected runSearch(request: IKibanaSearchRequest, signal: AbortSignal, strategy?: string): Observable; + search(request: IKibanaSearchRequest, options?: ISearchOptions): Observable; // @internal (undocumented) protected setupAbortSignal({ abortSignal, timeout, }: { abortSignal?: AbortSignal; timeout?: number; }): { combinedSignal: AbortSignal; + timeoutSignal: AbortSignal; cleanup: () => void; }; // (undocumented) - protected showTimeoutError: ((e: Error) => void) & import("lodash").Cancelable; - // @internal - protected timeoutSubscriptions: Subscription; -} + showError(e: Error): void; + } // Warning: (ae-missing-release-tag) "SearchInterceptorDeps" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -2153,6 +2164,17 @@ export interface SearchSourceFields { version?: boolean; } +// Warning: (ae-missing-release-tag) "SearchTimeoutError" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public +export class SearchTimeoutError extends KbnError { + constructor(err: Error, mode: TimeoutErrorMode); + // (undocumented) + getErrorMessage(application: ApplicationStart): JSX.Element; + // (undocumented) + mode: TimeoutErrorMode; + } + // Warning: (ae-missing-release-tag) "SortDirection" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -2225,6 +2247,18 @@ export class TimeHistory { // @public (undocumented) export type TimeHistoryContract = PublicMethodsOf; +// Warning: (ae-missing-release-tag) "TimeoutErrorMode" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export enum TimeoutErrorMode { + // (undocumented) + CHANGE = 2, + // (undocumented) + CONTACT = 1, + // (undocumented) + UPGRADE = 0 +} + // Warning: (ae-missing-release-tag) "TimeRange" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -2314,21 +2348,21 @@ export const UI_SETTINGS: { // src/plugins/data/public/index.ts:236:27 - (ae-forgotten-export) The symbol "getFromSavedObject" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:236:27 - (ae-forgotten-export) The symbol "flattenHitWrapper" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:236:27 - (ae-forgotten-export) The symbol "formatHitProvider" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:385:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:385:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:385:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:385:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:387:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:388:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:397:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:398:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:399:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:400:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:404:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:405:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:408:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:409:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:412:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:388:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:388:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:388:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:388:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:390:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:391:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:400:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:401:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:402:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:403:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:407:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:408:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:411:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:412:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:415:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // src/plugins/data/public/query/state_sync/connect_to_query_state.ts:45:5 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts // (No @packageDocumentation comment for this package) diff --git a/src/plugins/discover/public/application/components/fetch_error/index.ts b/src/plugins/data/public/search/errors/index.ts similarity index 92% rename from src/plugins/discover/public/application/components/fetch_error/index.ts rename to src/plugins/data/public/search/errors/index.ts index 0206bc48257ac3..6082e758a8badb 100644 --- a/src/plugins/discover/public/application/components/fetch_error/index.ts +++ b/src/plugins/data/public/search/errors/index.ts @@ -17,4 +17,5 @@ * under the License. */ -import './fetch_error'; +export * from './painless_error'; +export * from './timeout_error'; diff --git a/src/plugins/data/public/search/errors/painless_error.tsx b/src/plugins/data/public/search/errors/painless_error.tsx new file mode 100644 index 00000000000000..244f205469a2f4 --- /dev/null +++ b/src/plugins/data/public/search/errors/painless_error.tsx @@ -0,0 +1,89 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you 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 + * + * http://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 from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiButton, EuiSpacer, EuiText, EuiCodeBlock } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { ApplicationStart } from 'kibana/public'; +import { KbnError } from '../../../../kibana_utils/common'; +import { EsError, isEsError } from './types'; +import { IKibanaSearchRequest } from '..'; + +export class PainlessError extends KbnError { + painlessStack?: string; + constructor(err: EsError, request: IKibanaSearchRequest) { + const rootCause = getRootCause(err as EsError); + + super( + i18n.translate('data.painlessError.painlessScriptedFieldErrorMessage', { + defaultMessage: "Error executing Painless script: '{script}'.", + values: { script: rootCause?.script }, + }) + ); + this.painlessStack = rootCause?.script_stack ? rootCause?.script_stack.join('\n') : undefined; + } + + public getErrorMessage(application: ApplicationStart) { + function onClick() { + application.navigateToApp('management', { + path: `/kibana/indexPatterns`, + }); + } + + return ( + <> + {this.message} + + + {this.painlessStack ? ( + + {this.painlessStack} + + ) : null} + + + + + + + ); + } +} + +function getFailedShards(err: EsError) { + const failedShards = + err.body?.attributes?.error?.failed_shards || + err.body?.attributes?.error?.caused_by?.failed_shards; + return failedShards ? failedShards[0] : undefined; +} + +function getRootCause(err: EsError) { + return getFailedShards(err)?.reason; +} + +export function isPainlessError(err: Error | EsError) { + if (!isEsError(err)) return false; + + const rootCause = getRootCause(err as EsError); + if (!rootCause) return false; + + const { lang } = rootCause; + return lang === 'painless'; +} diff --git a/src/plugins/data/public/search/errors/timeout_error.test.tsx b/src/plugins/data/public/search/errors/timeout_error.test.tsx new file mode 100644 index 00000000000000..87b491b976ebc1 --- /dev/null +++ b/src/plugins/data/public/search/errors/timeout_error.test.tsx @@ -0,0 +1,62 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you 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 + * + * http://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 { SearchTimeoutError, TimeoutErrorMode } from './timeout_error'; + +import { coreMock } from '../../../../../core/public/mocks'; +const startMock = coreMock.createStart(); + +import { mount } from 'enzyme'; +import { AbortError } from 'src/plugins/data/common'; + +describe('SearchTimeoutError', () => { + beforeEach(() => { + jest.clearAllMocks(); + startMock.application.navigateToApp.mockImplementation(jest.fn()); + }); + + it('Should navigate to upgrade', () => { + const e = new SearchTimeoutError(new AbortError(), TimeoutErrorMode.UPGRADE); + const component = mount(e.getErrorMessage(startMock.application)); + + expect(component.find('EuiButton').length).toBe(1); + component.find('EuiButton').simulate('click'); + expect(startMock.application.navigateToApp).toHaveBeenCalledWith('management', { + path: '/kibana/indexPatterns', + }); + }); + + it('Should create contact admin message', () => { + const e = new SearchTimeoutError(new AbortError(), TimeoutErrorMode.CONTACT); + const component = mount(e.getErrorMessage(startMock.application)); + + expect(component.find('EuiButton').length).toBe(0); + }); + + it('Should navigate to settings', () => { + const e = new SearchTimeoutError(new AbortError(), TimeoutErrorMode.CHANGE); + const component = mount(e.getErrorMessage(startMock.application)); + + expect(component.find('EuiButton').length).toBe(1); + component.find('EuiButton').simulate('click'); + expect(startMock.application.navigateToApp).toHaveBeenCalledWith('management', { + path: '/kibana/settings', + }); + }); +}); diff --git a/src/plugins/data/public/search/errors/timeout_error.tsx b/src/plugins/data/public/search/errors/timeout_error.tsx new file mode 100644 index 00000000000000..56aecb42f5326e --- /dev/null +++ b/src/plugins/data/public/search/errors/timeout_error.tsx @@ -0,0 +1,111 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you 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 + * + * http://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 from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiButton, EuiSpacer, EuiText } from '@elastic/eui'; +import { ApplicationStart } from 'kibana/public'; +import { KbnError } from '../../../../kibana_utils/common'; + +export enum TimeoutErrorMode { + UPGRADE, + CONTACT, + CHANGE, +} + +/** + * Request Failure - When an entire multi request fails + * @param {Error} err - the Error that came back + */ +export class SearchTimeoutError extends KbnError { + public mode: TimeoutErrorMode; + constructor(err: Error, mode: TimeoutErrorMode) { + super(`Request timeout: ${JSON.stringify(err?.message)}`); + this.mode = mode; + } + + private getMessage() { + switch (this.mode) { + case TimeoutErrorMode.UPGRADE: + return i18n.translate('data.search.upgradeLicense', { + defaultMessage: + 'Your query has timed out. With our free Basic tier, your queries never time out.', + }); + case TimeoutErrorMode.CONTACT: + return i18n.translate('data.search.timeoutContactAdmin', { + defaultMessage: + 'Your query has timed out. Contact your system administrator to increase the run time.', + }); + case TimeoutErrorMode.CHANGE: + return i18n.translate('data.search.timeoutIncreaseSetting', { + defaultMessage: + 'Your query has timed out. Increase run time with the search timeout advanced setting.', + }); + } + } + + private getActionText() { + switch (this.mode) { + case TimeoutErrorMode.UPGRADE: + return i18n.translate('data.search.upgradeLicenseActionText', { + defaultMessage: 'Upgrade now', + }); + break; + case TimeoutErrorMode.CHANGE: + return i18n.translate('data.search.timeoutIncreaseSettingActionText', { + defaultMessage: 'Edit setting', + }); + break; + } + } + + private onClick(application: ApplicationStart) { + switch (this.mode) { + case TimeoutErrorMode.UPGRADE: + application.navigateToApp('management', { + path: `/kibana/indexPatterns`, + }); + break; + case TimeoutErrorMode.CHANGE: + application.navigateToApp('management', { + path: `/kibana/settings`, + }); + break; + } + } + + public getErrorMessage(application: ApplicationStart) { + const actionText = this.getActionText(); + return ( + <> + {this.getMessage()} + {actionText && ( + <> + + + this.onClick(application)} size="s"> + {actionText} + + + + )} + + ); + } +} diff --git a/src/plugins/discover/public/application/angular/get_painless_error.ts b/src/plugins/data/public/search/errors/types.ts similarity index 61% rename from src/plugins/discover/public/application/angular/get_painless_error.ts rename to src/plugins/data/public/search/errors/types.ts index 162dacd3ac3b7c..4182209eb68a5a 100644 --- a/src/plugins/discover/public/application/angular/get_painless_error.ts +++ b/src/plugins/data/public/search/errors/types.ts @@ -17,9 +17,7 @@ * under the License. */ -import { i18n } from '@kbn/i18n'; - -interface FailedShards { +interface FailedShard { shard: number; index: string; node: string; @@ -41,7 +39,7 @@ interface FailedShards { }; } -interface EsError { +export interface EsError { body: { statusCode: number; error: string; @@ -56,51 +54,20 @@ interface EsError { ]; type: string; reason: string; + failed_shards: FailedShard[]; caused_by: { type: string; reason: string; phase: string; grouped: boolean; - failed_shards: FailedShards[]; + failed_shards: FailedShard[]; + script_stack: string[]; }; }; }; }; } -export function getCause(error: EsError) { - const cause = error.body?.attributes?.error?.root_cause; - if (cause) { - return cause[0]; - } - - const failedShards = error.body?.attributes?.error?.caused_by?.failed_shards; - - if (failedShards && failedShards[0] && failedShards[0].reason) { - return error.body?.attributes?.error?.caused_by?.failed_shards[0].reason; - } -} - -export function getPainlessError(error: EsError) { - const cause = getCause(error); - - if (!cause) { - return; - } - - const { lang, script } = cause; - - if (lang !== 'painless') { - return; - } - - return { - lang, - script, - message: i18n.translate('discover.painlessError.painlessScriptedFieldErrorMessage', { - defaultMessage: "Error with Painless scripted field '{script}'.", - values: { script }, - }), - error: error.body?.message, - }; +export function isEsError(e: any): e is EsError { + return !!e.body?.attributes; } diff --git a/src/plugins/data/public/search/index.ts b/src/plugins/data/public/search/index.ts index fc3d71936a8594..86804a819cb0e5 100644 --- a/src/plugins/data/public/search/index.ts +++ b/src/plugins/data/public/search/index.ts @@ -46,4 +46,4 @@ export { export { getEsPreference } from './es_search'; export { SearchInterceptor, SearchInterceptorDeps } from './search_interceptor'; -export { RequestTimeoutError } from './request_timeout_error'; +export * from './errors'; diff --git a/src/plugins/data/public/search/mocks.ts b/src/plugins/data/public/search/mocks.ts index fdd6a900134133..e931b39eae2a58 100644 --- a/src/plugins/data/public/search/mocks.ts +++ b/src/plugins/data/public/search/mocks.ts @@ -34,6 +34,7 @@ function createStartContract(): jest.Mocked { return { aggs: searchAggsStartMock(), search: jest.fn(), + showError: jest.fn(), searchSource: searchSourceMock, }; } diff --git a/src/plugins/data/public/search/request_timeout_error.ts b/src/plugins/data/public/search/request_timeout_error.ts deleted file mode 100644 index 92894deb4f0ffa..00000000000000 --- a/src/plugins/data/public/search/request_timeout_error.ts +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you 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 - * - * http://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. - */ - -/** - * Class used to signify that a request timed out. Useful for applications to conditionally handle - * this type of error differently than other errors. - */ -export class RequestTimeoutError extends Error { - constructor(message = 'Request timed out') { - super(message); - this.message = message; - this.name = 'RequestTimeoutError'; - } -} diff --git a/src/plugins/data/public/search/search_interceptor.test.ts b/src/plugins/data/public/search/search_interceptor.test.ts index 7bfa6f0ab1bc57..ade15adc1c3a3f 100644 --- a/src/plugins/data/public/search/search_interceptor.test.ts +++ b/src/plugins/data/public/search/search_interceptor.test.ts @@ -22,6 +22,7 @@ import { coreMock } from '../../../../core/public/mocks'; import { IEsSearchRequest } from '../../common/search'; import { SearchInterceptor } from './search_interceptor'; import { AbortError } from '../../common'; +import { SearchTimeoutError, PainlessError } from './errors'; let searchInterceptor: SearchInterceptor; let mockCoreSetup: MockedKeys; @@ -53,8 +54,8 @@ describe('SearchInterceptor', () => { expect(result).toBe(mockResponse); }); - test('Observable should fail if fetch has an error', async () => { - const mockResponse: any = { result: 500 }; + test('Observable should fail if fetch has an internal error', async () => { + const mockResponse: any = { result: 500, message: 'Internal Error' }; mockCoreSetup.http.fetch.mockRejectedValueOnce(mockResponse); const mockRequest: IEsSearchRequest = { params: {}, @@ -68,64 +69,83 @@ describe('SearchInterceptor', () => { } }); - test('Observable should fail if fetch times out (test merged signal)', async () => { - mockCoreSetup.http.fetch.mockImplementationOnce((options: any) => { - return new Promise((resolve, reject) => { - options.signal.addEventListener('abort', () => { - reject(new AbortError()); - }); - - setTimeout(resolve, 5000); - }); - }); + test('Should throw SearchTimeoutError on server timeout AND show toast', async (done) => { + const mockResponse: any = { + result: 500, + body: { + message: 'Request timed out', + }, + }; + mockCoreSetup.http.fetch.mockRejectedValueOnce(mockResponse); const mockRequest: IEsSearchRequest = { params: {}, }; const response = searchInterceptor.search(mockRequest); - const next = jest.fn(); - const error = (e: any) => { - expect(next).not.toBeCalled(); - expect(e).toBeInstanceOf(AbortError); - }; - response.subscribe({ next, error }); - - jest.advanceTimersByTime(5000); - - await flushPromises(); + try { + await response.toPromise(); + } catch (e) { + expect(e).toBeInstanceOf(SearchTimeoutError); + expect(mockCoreSetup.notifications.toasts.addDanger).toBeCalledTimes(1); + done(); + } }); - test('Should not timeout if requestTimeout is undefined', async () => { - searchInterceptor = new SearchInterceptor({ - startServices: mockCoreSetup.getStartServices(), - uiSettings: mockCoreSetup.uiSettings, - http: mockCoreSetup.http, - toasts: mockCoreSetup.notifications.toasts, - }); - mockCoreSetup.http.fetch.mockImplementationOnce((options: any) => { - return new Promise((resolve, reject) => { - options.signal.addEventListener('abort', () => { - reject(new AbortError()); - }); - - setTimeout(resolve, 5000); - }); - }); + test('Search error should be debounced', async (done) => { + const mockResponse: any = { + result: 500, + body: { + message: 'Request timed out', + }, + }; + mockCoreSetup.http.fetch.mockRejectedValue(mockResponse); const mockRequest: IEsSearchRequest = { params: {}, }; - const response = searchInterceptor.search(mockRequest); + try { + await searchInterceptor.search(mockRequest).toPromise(); + } catch (e) { + expect(e).toBeInstanceOf(SearchTimeoutError); + try { + await searchInterceptor.search(mockRequest).toPromise(); + } catch (e2) { + expect(mockCoreSetup.notifications.toasts.addDanger).toBeCalledTimes(1); + done(); + } + } + }); - expect.assertions(1); - const next = jest.fn(); - const complete = () => { - expect(next).toBeCalled(); + test('Should throw Painless error on server error with OSS format', async (done) => { + const mockResponse: any = { + result: 500, + body: { + attributes: { + error: { + failed_shards: [ + { + reason: { + lang: 'painless', + script_stack: ['a', 'b'], + reason: 'banana', + }, + }, + ], + }, + }, + }, }; - response.subscribe({ next, complete }); - - jest.advanceTimersByTime(5000); + mockCoreSetup.http.fetch.mockRejectedValueOnce(mockResponse); + const mockRequest: IEsSearchRequest = { + params: {}, + }; + const response = searchInterceptor.search(mockRequest); - await flushPromises(); + try { + await response.toPromise(); + } catch (e) { + expect(e).toBeInstanceOf(PainlessError); + done(); + } }); test('Observable should fail if user aborts (test merged signal)', async () => { diff --git a/src/plugins/data/public/search/search_interceptor.ts b/src/plugins/data/public/search/search_interceptor.ts index 802ee6db9433e9..2e42635a7f811c 100644 --- a/src/plugins/data/public/search/search_interceptor.ts +++ b/src/plugins/data/public/search/search_interceptor.ts @@ -17,29 +17,21 @@ * under the License. */ -import { trimEnd, debounce } from 'lodash'; -import { - BehaviorSubject, - throwError, - timer, - Subscription, - defer, - from, - Observable, - NEVER, -} from 'rxjs'; +import { get, trimEnd, debounce } from 'lodash'; +import { BehaviorSubject, throwError, timer, defer, from, Observable, NEVER } from 'rxjs'; import { catchError, finalize } from 'rxjs/operators'; import { CoreStart, CoreSetup, ToastsSetup } from 'kibana/public'; -import { i18n } from '@kbn/i18n'; import { getCombinedSignal, AbortError, - IEsSearchRequest, + IKibanaSearchRequest, IKibanaSearchResponse, ISearchOptions, ES_SEARCH_STRATEGY, } from '../../common'; import { SearchUsageCollector } from './collectors'; +import { SearchTimeoutError, PainlessError, isPainlessError, TimeoutErrorMode } from './errors'; +import { toMountPoint } from '../../../kibana_react/public'; export interface SearchInterceptorDeps { http: CoreSetup['http']; @@ -62,12 +54,6 @@ export class SearchInterceptor { */ protected pendingCount$ = new BehaviorSubject(0); - /** - * The subscriptions from scheduling the automatic timeout for each request. - * @internal - */ - protected timeoutSubscriptions: Subscription = new Subscription(); - /** * @internal */ @@ -84,11 +70,46 @@ export class SearchInterceptor { }); } + /* + * @returns `TimeoutErrorMode` indicating what action should be taken in case of a request timeout based on license and permissions. + * @internal + */ + protected getTimeoutMode() { + return TimeoutErrorMode.UPGRADE; + } + + /* + * @returns `Error` a search service specific error or the original error, if a specific error can't be recognized. + * @internal + */ + protected handleSearchError( + e: any, + request: IKibanaSearchRequest, + timeoutSignal: AbortSignal, + appAbortSignal?: AbortSignal + ): Error { + if (timeoutSignal.aborted || get(e, 'body.message') === 'Request timed out') { + // Handle a client or a server side timeout + const err = new SearchTimeoutError(e, this.getTimeoutMode()); + + // Show the timeout error here, so that it's shown regardless of how an application chooses to handle errors. + this.showTimeoutError(err); + return err; + } else if (appAbortSignal?.aborted) { + // In the case an application initiated abort, throw the existing AbortError. + return e; + } else if (isPainlessError(e)) { + return new PainlessError(e, request); + } else { + return e; + } + } + /** * @internal */ protected runSearch( - request: IEsSearchRequest, + request: IKibanaSearchRequest, signal: AbortSignal, strategy?: string ): Observable { @@ -105,41 +126,6 @@ export class SearchInterceptor { ); } - /** - * Searches using the given `search` method. Overrides the `AbortSignal` with one that will abort - * either when `cancelPending` is called, when the request times out, or when the original - * `AbortSignal` is aborted. Updates `pendingCount$` when the request is started/finalized. - */ - public search( - request: IEsSearchRequest, - options?: ISearchOptions - ): Observable { - // Defer the following logic until `subscribe` is actually called - return defer(() => { - if (options?.abortSignal?.aborted) { - return throwError(new AbortError()); - } - - const { combinedSignal, cleanup } = this.setupAbortSignal({ - abortSignal: options?.abortSignal, - }); - this.pendingCount$.next(this.pendingCount$.getValue() + 1); - - return this.runSearch(request, combinedSignal, options?.strategy).pipe( - catchError((e: any) => { - if (e.body?.attributes?.error === 'Request timed out') { - this.showTimeoutError(e); - } - return throwError(e); - }), - finalize(() => { - this.pendingCount$.next(this.pendingCount$.getValue() - 1); - cleanup(); - }) - ); - }); - } - /** * @internal */ @@ -156,9 +142,7 @@ export class SearchInterceptor { const timeout$ = timeout ? timer(timeout) : NEVER; const subscription = timeout$.subscribe(() => { timeoutController.abort(); - this.showTimeoutError(new AbortError()); }); - this.timeoutSubscriptions.add(subscription); // Get a combined `AbortSignal` that will be aborted whenever the first of the following occurs: // 1. The user manually aborts (via `cancelPending`) @@ -172,34 +156,95 @@ export class SearchInterceptor { const combinedSignal = getCombinedSignal(signals); const cleanup = () => { - this.timeoutSubscriptions.remove(subscription); + subscription.unsubscribe(); }; combinedSignal.addEventListener('abort', cleanup); return { combinedSignal, + timeoutSignal, cleanup, }; } - // Right now we are debouncing but we will hook this up with background sessions to show only one - // error notification per session. - protected showTimeoutError = debounce( - (e: Error) => { - this.deps.toasts.addError(e, { + /** + * Right now we are throttling but we will hook this up with background sessions to show only one + * error notification per session. + * @internal + */ + private showTimeoutError = debounce( + (e: SearchTimeoutError) => { + this.deps.toasts.addDanger({ title: 'Timed out', - toastMessage: i18n.translate('data.search.upgradeLicense', { - defaultMessage: - 'One or more queries timed out. With our free Basic tier, your queries never time out.', - }), + text: toMountPoint(e.getErrorMessage(this.application)), }); }, - 60000, - { - leading: true, - } + 30000, + { leading: true, trailing: false } ); + + /** + * Searches using the given `search` method. Overrides the `AbortSignal` with one that will abort + * either when `cancelPending` is called, when the request times out, or when the original + * `AbortSignal` is aborted. Updates `pendingCount$` when the request is started/finalized. + * + * @param request + * @options + * @returns `Observalbe` emitting the search response or an error. + */ + public search( + request: IKibanaSearchRequest, + options?: ISearchOptions + ): Observable { + // Defer the following logic until `subscribe` is actually called + return defer(() => { + if (options?.abortSignal?.aborted) { + return throwError(new AbortError()); + } + + const { timeoutSignal, combinedSignal, cleanup } = this.setupAbortSignal({ + abortSignal: options?.abortSignal, + }); + this.pendingCount$.next(this.pendingCount$.getValue() + 1); + + return this.runSearch(request, combinedSignal, options?.strategy).pipe( + catchError((e: any) => { + return throwError( + this.handleSearchError(e, request, timeoutSignal, options?.abortSignal) + ); + }), + finalize(() => { + this.pendingCount$.next(this.pendingCount$.getValue() - 1); + cleanup(); + }) + ); + }); + } + + /* + * + */ + public showError(e: Error) { + if (e instanceof AbortError) return; + + if (e instanceof SearchTimeoutError) { + // The SearchTimeoutError is shown by the interceptor in getSearchError (regardless of how the app chooses to handle errors) + return; + } + + if (e instanceof PainlessError) { + this.deps.toasts.addDanger({ + title: 'Search Error', + text: toMountPoint(e.getErrorMessage(this.application)), + }); + return; + } + + this.deps.toasts.addError(e, { + title: 'Search Error', + }); + } } export type ISearchInterceptor = PublicMethodsOf; diff --git a/src/plugins/data/public/search/search_service.ts b/src/plugins/data/public/search/search_service.ts index d8937ed30e401b..173baba5cab6fb 100644 --- a/src/plugins/data/public/search/search_service.ts +++ b/src/plugins/data/public/search/search_service.ts @@ -111,6 +111,9 @@ export class SearchService implements Plugin { return { aggs: this.aggsService.start({ fieldFormats, uiSettings }), search, + showError: (e: Error) => { + this.searchInterceptor.showError(e); + }, searchSource: { /** * creates searchsource based on serialized search source fields diff --git a/src/plugins/data/public/search/types.ts b/src/plugins/data/public/search/types.ts index 6ae5d83499aa6b..a133a8cd4be93b 100644 --- a/src/plugins/data/public/search/types.ts +++ b/src/plugins/data/public/search/types.ts @@ -73,6 +73,8 @@ export interface ISearchStart { * {@link ISearchGeneric} */ search: ISearchGeneric; + + showError: (e: Error) => void; /** * high level search * {@link ISearchStartSearchSource} diff --git a/src/plugins/discover/public/application/angular/discover.js b/src/plugins/discover/public/application/angular/discover.js index 7871cc4b16464e..a396033e5dedb3 100644 --- a/src/plugins/discover/public/application/angular/discover.js +++ b/src/plugins/discover/public/application/angular/discover.js @@ -27,6 +27,12 @@ import { i18n } from '@kbn/i18n'; import { getState, splitState } from './discover_state'; import { RequestAdapter } from '../../../../inspector/public'; +import { + esFilters, + indexPatterns as indexPatternsUtils, + connectToQueryState, + syncQueryStateWithUrl, +} from '../../../../data/public'; import { SavedObjectSaveModal, showSaveModal } from '../../../../saved_objects/public'; import { getSortArray, getSortForSearchSource } from './doc_table'; import { createFixedScroll } from './directives/fixed_scroll'; @@ -34,7 +40,6 @@ import * as columnActions from './doc_table/actions/columns'; import indexTemplateLegacy from './discover_legacy.html'; import { showOpenSearchPanel } from '../components/top_nav/show_open_search_panel'; import { addHelpMenuToAppChrome } from '../components/help_menu/help_menu_util'; -import { getPainlessError } from './get_painless_error'; import { discoverResponseHandler } from './response_handler'; import { getRequestInspectorStats, @@ -65,12 +70,7 @@ const { import { getRootBreadcrumbs, getSavedSearchBreadcrumbs } from '../helpers/breadcrumbs'; import { validateTimeRange } from '../helpers/validate_time_range'; -import { - esFilters, - indexPatterns as indexPatternsUtils, - connectToQueryState, - syncQueryStateWithUrl, -} from '../../../../data/public'; + import { getIndexPatternId } from '../helpers/get_index_pattern_id'; import { addFatalError } from '../../../../kibana_legacy/public'; import { @@ -786,18 +786,10 @@ function discoverController($element, $route, $scope, $timeout, $window, Promise // If the request was aborted then no need to surface this error in the UI if (error instanceof Error && error.name === 'AbortError') return; - const fetchError = getPainlessError(error); + $scope.fetchStatus = fetchStatuses.NO_RESULTS; + $scope.rows = []; - if (fetchError) { - $scope.fetchError = fetchError; - } else { - toastNotifications.addError(error, { - title: i18n.translate('discover.errorLoadingData', { - defaultMessage: 'Error loading data', - }), - toastMessage: error.shortMessage || error.body?.message, - }); - } + data.search.showError(error); }); }; diff --git a/src/plugins/discover/public/application/components/discover_legacy.tsx b/src/plugins/discover/public/application/components/discover_legacy.tsx index 9c3d833d73b237..de1faaf9fc19d4 100644 --- a/src/plugins/discover/public/application/components/discover_legacy.tsx +++ b/src/plugins/discover/public/application/components/discover_legacy.tsx @@ -31,7 +31,6 @@ import { DiscoverNoResults } from '../angular/directives/no_results'; import { DiscoverUninitialized } from '../angular/directives/uninitialized'; import { DiscoverHistogram } from '../angular/directives/histogram'; import { LoadingSpinner } from './loading_spinner/loading_spinner'; -import { DiscoverFetchError, FetchError } from './fetch_error/fetch_error'; import { DocTableLegacy } from '../angular/doc_table/create_doc_table_react'; import { SkipBottomButton } from './skip_bottom_button'; import { @@ -54,7 +53,6 @@ export interface DiscoverLegacyProps { addColumn: (column: string) => void; fetch: () => void; fetchCounter: number; - fetchError: FetchError; fieldCounts: Record; histogramData: Chart; hits: number; @@ -95,7 +93,6 @@ export function DiscoverLegacy({ addColumn, fetch, fetchCounter, - fetchError, fieldCounts, histogramData, hits, @@ -216,8 +213,7 @@ export function DiscoverLegacy({ {resultState === 'uninitialized' && } {/* @TODO: Solved in the Angular way to satisfy functional test - should be improved*/} - {fetchError && } -
+
diff --git a/src/plugins/discover/public/application/components/fetch_error/fetch_error.scss b/src/plugins/discover/public/application/components/fetch_error/fetch_error.scss deleted file mode 100644 index a587b2897e3a02..00000000000000 --- a/src/plugins/discover/public/application/components/fetch_error/fetch_error.scss +++ /dev/null @@ -1,3 +0,0 @@ -.discoverFetchError { - max-width: 1000px; -} diff --git a/src/plugins/discover/public/application/components/fetch_error/fetch_error.tsx b/src/plugins/discover/public/application/components/fetch_error/fetch_error.tsx deleted file mode 100644 index dc8f1238eac6fd..00000000000000 --- a/src/plugins/discover/public/application/components/fetch_error/fetch_error.tsx +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you 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 - * - * http://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 './fetch_error.scss'; -import React, { Fragment } from 'react'; -import { FormattedMessage, I18nProvider } from '@kbn/i18n/react'; -import { EuiFlexGroup, EuiFlexItem, EuiCallOut, EuiCodeBlock, EuiSpacer } from '@elastic/eui'; -import { getServices } from '../../../kibana_services'; - -export interface FetchError { - lang: string; - script: string; - message: string; - error: string; -} - -interface Props { - fetchError: FetchError; -} - -export const DiscoverFetchError = ({ fetchError }: Props) => { - if (!fetchError) { - return null; - } - - let body; - - if (fetchError.lang === 'painless') { - const { chrome } = getServices(); - const mangagementUrlObj = chrome.navLinks.get('kibana:stack_management'); - const managementUrl = mangagementUrlObj ? mangagementUrlObj.url : ''; - const url = `${managementUrl}/kibana/indexPatterns`; - - body = ( -

- - ), - managementLink: ( - - - - ), - }} - /> -

- ); - } - - return ( - - - - - - - - {body} - - {fetchError.error} - - - - - - - - ); -}; diff --git a/src/plugins/expressions/common/expression_types/specs/error.ts b/src/plugins/expressions/common/expression_types/specs/error.ts index 35554954d08282..c95a019f4e8d22 100644 --- a/src/plugins/expressions/common/expression_types/specs/error.ts +++ b/src/plugins/expressions/common/expression_types/specs/error.ts @@ -30,6 +30,7 @@ export type ExpressionValueError = ExpressionValueBoxed< message: string; name?: string; stack?: string; + original?: Error; }; info?: unknown; } diff --git a/src/plugins/expressions/common/util/create_error.ts b/src/plugins/expressions/common/util/create_error.ts index 876e7dfec799c9..9bdab74efd6f96 100644 --- a/src/plugins/expressions/common/util/create_error.ts +++ b/src/plugins/expressions/common/util/create_error.ts @@ -21,7 +21,7 @@ import { ExpressionValueError } from '../../common'; type ErrorLike = Partial>; -export const createError = (err: string | ErrorLike): ExpressionValueError => ({ +export const createError = (err: string | Error | ErrorLike): ExpressionValueError => ({ type: 'error', error: { stack: @@ -32,5 +32,6 @@ export const createError = (err: string | ErrorLike): ExpressionValueError => ({ : undefined, message: typeof err === 'string' ? err : String(err.message), name: typeof err === 'object' ? err.name || 'Error' : 'Error', + original: err instanceof Error ? err : undefined, }, }); diff --git a/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts b/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts index 31f0fc5f94479a..bb4fabb189a274 100644 --- a/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts +++ b/src/plugins/visualize/public/application/utils/get_visualization_instance.test.ts @@ -50,6 +50,8 @@ describe('getVisualizationInstance', () => { }; savedVisMock = {}; // @ts-expect-error + mockServices.data.search.showError.mockImplementation(() => {}); + // @ts-expect-error mockServices.savedVisualizations.get.mockImplementation(() => savedVisMock); // @ts-expect-error mockServices.visualizations.convertToSerializedVis.mockImplementation(() => serializedVisMock); @@ -119,6 +121,6 @@ describe('getVisualizationInstance', () => { error: 'error', }); - expect(mockServices.toastNotifications.addError).toHaveBeenCalled(); + expect(mockServices.data.search.showError).toHaveBeenCalled(); }); }); diff --git a/src/plugins/visualize/public/application/utils/get_visualization_instance.ts b/src/plugins/visualize/public/application/utils/get_visualization_instance.ts index 3ffca578f8052f..c5cfa5a4c639b3 100644 --- a/src/plugins/visualize/public/application/utils/get_visualization_instance.ts +++ b/src/plugins/visualize/public/application/utils/get_visualization_instance.ts @@ -17,7 +17,6 @@ * under the License. */ -import { i18n } from '@kbn/i18n'; import { SerializedVis, Vis, @@ -28,6 +27,7 @@ import { import { SearchSourceFields } from 'src/plugins/data/public'; import { SavedObject } from 'src/plugins/saved_objects/public'; import { cloneDeep } from 'lodash'; +import { ExpressionValueError } from 'src/plugins/expressions/public'; import { createSavedSearchesLoader } from '../../../../discover/public'; import { VisualizeServices } from '../types'; @@ -35,14 +35,7 @@ const createVisualizeEmbeddableAndLinkSavedSearch = async ( vis: Vis, visualizeServices: VisualizeServices ) => { - const { - chrome, - data, - overlays, - createVisEmbeddableFromObject, - savedObjects, - toastNotifications, - } = visualizeServices; + const { chrome, data, overlays, createVisEmbeddableFromObject, savedObjects } = visualizeServices; const embeddableHandler = (await createVisEmbeddableFromObject(vis, { timeRange: data.query.timefilter.timefilter.getTime(), filters: data.query.filterManager.getFilters(), @@ -51,11 +44,9 @@ const createVisualizeEmbeddableAndLinkSavedSearch = async ( embeddableHandler.getOutput$().subscribe((output) => { if (output.error) { - toastNotifications.addError(output.error, { - title: i18n.translate('visualize.error.title', { - defaultMessage: 'Visualization error', - }), - }); + data.search.showError( + ((output.error as unknown) as ExpressionValueError['error']).original || output.error + ); } }); diff --git a/test/functional/apps/discover/_errors.ts b/test/functional/apps/discover/_errors.ts index 9520d652a65d56..7f1552b90668b7 100644 --- a/test/functional/apps/discover/_errors.ts +++ b/test/functional/apps/discover/_errors.ts @@ -22,7 +22,7 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); - const testSubjects = getService('testSubjects'); + const toasts = getService('toasts'); const PageObjects = getPageObjects(['common', 'discover', 'timePicker']); describe('errors', function describeIndexTests() { @@ -39,8 +39,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { describe('invalid scripted field error', () => { it('is rendered', async () => { - const isFetchErrorVisible = await testSubjects.exists('discoverFetchError'); - expect(isFetchErrorVisible).to.be(true); + const toast = await toasts.getToastElement(1); + const painlessStackTrace = await toast.findByTestSubject('painlessStackTrace'); + expect(painlessStackTrace).not.to.be(undefined); }); }); }); diff --git a/test/functional/services/toasts.ts b/test/functional/services/toasts.ts index a70e4ba464ae85..f5416a44e3b5a9 100644 --- a/test/functional/services/toasts.ts +++ b/test/functional/services/toasts.ts @@ -63,7 +63,7 @@ export function ToastsProvider({ getService }: FtrProviderContext) { } } - private async getToastElement(index: number) { + public async getToastElement(index: number) { const list = await this.getGlobalToastList(); return await list.findByCssSelector(`.euiToast:nth-child(${index})`); } diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts index af2fc85602541a..6e34e4c1964c59 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts @@ -8,6 +8,7 @@ import { coreMock } from '../../../../../src/core/public/mocks'; import { EnhancedSearchInterceptor } from './search_interceptor'; import { CoreSetup, CoreStart } from 'kibana/public'; import { AbortError, UI_SETTINGS } from '../../../../../src/plugins/data/common'; +import { SearchTimeoutError } from 'src/plugins/data/public'; const timeTravel = (msToRun = 0) => { jest.advanceTimersByTime(msToRun); @@ -265,7 +266,7 @@ describe('EnhancedSearchInterceptor', () => { await timeTravel(1000); expect(error).toHaveBeenCalled(); - expect(error.mock.calls[0][0]).toBeInstanceOf(AbortError); + expect(error.mock.calls[0][0]).toBeInstanceOf(SearchTimeoutError); expect(mockCoreSetup.http.fetch).toHaveBeenCalled(); expect(mockCoreSetup.http.delete).not.toHaveBeenCalled(); }); @@ -305,7 +306,7 @@ describe('EnhancedSearchInterceptor', () => { await timeTravel(1000); expect(error).toHaveBeenCalled(); - expect(error.mock.calls[0][0]).toBeInstanceOf(AbortError); + expect(error.mock.calls[0][0]).toBeInstanceOf(SearchTimeoutError); expect(mockCoreSetup.http.fetch).toHaveBeenCalledTimes(2); expect(mockCoreSetup.http.delete).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts index c8fe72e6f2c1e9..cca87c85e326c4 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts @@ -5,9 +5,7 @@ */ import { throwError, EMPTY, timer, from, Subscription } from 'rxjs'; -import { mergeMap, expand, takeUntil, finalize, tap } from 'rxjs/operators'; -import { debounce } from 'lodash'; -import { i18n } from '@kbn/i18n'; +import { mergeMap, expand, takeUntil, finalize, catchError } from 'rxjs/operators'; import { SearchInterceptor, SearchInterceptorDeps, @@ -15,6 +13,7 @@ import { } from '../../../../../src/plugins/data/public'; import { isErrorResponse, isCompleteResponse } from '../../../../../src/plugins/data/public'; import { AbortError, toPromise } from '../../../../../src/plugins/data/common'; +import { TimeoutErrorMode } from '../../../../../src/plugins/data/public'; import { IAsyncSearchOptions } from '.'; import { IAsyncSearchRequest, ENHANCED_ES_SEARCH_STRATEGY } from '../../common'; @@ -40,6 +39,12 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { this.uiSettingsSub.unsubscribe(); } + protected getTimeoutMode() { + return this.application.capabilities.advancedSettings?.save + ? TimeoutErrorMode.CHANGE + : TimeoutErrorMode.CONTACT; + } + /** * Abort our `AbortController`, which in turn aborts any intercepted searches. */ @@ -55,7 +60,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { ) { let { id } = request; - const { combinedSignal, cleanup } = this.setupAbortSignal({ + const { combinedSignal, timeoutSignal, cleanup } = this.setupAbortSignal({ abortSignal: options.abortSignal, timeout: this.searchTimeout, }); @@ -86,15 +91,14 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { ); }), takeUntil(aborted$), - tap({ - error: () => { - // If we haven't received the response to the initial request, including the ID, then - // we don't need to send a follow-up request to delete this search. Otherwise, we - // send the follow-up request to delete this search, then throw an abort error. - if (id !== undefined) { - this.deps.http.delete(`/internal/search/${strategy}/${id}`); - } - }, + catchError((e: any) => { + // If we haven't received the response to the initial request, including the ID, then + // we don't need to send a follow-up request to delete this search. Otherwise, we + // send the follow-up request to delete this search, then throw an abort error. + if (id !== undefined) { + this.deps.http.delete(`/internal/search/${strategy}/${id}`); + } + return throwError(this.handleSearchError(e, request, timeoutSignal, options?.abortSignal)); }), finalize(() => { this.pendingCount$.next(this.pendingCount$.getValue() - 1); @@ -102,28 +106,4 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { }) ); } - - // Right now we are debouncing but we will hook this up with background sessions to show only one - // error notification per session. - protected showTimeoutError = debounce( - (e: Error) => { - const message = this.application.capabilities.advancedSettings?.save - ? i18n.translate('xpack.data.search.timeoutIncreaseSetting', { - defaultMessage: - 'One or more queries timed out. Increase run time with the search.timeout advanced setting.', - }) - : i18n.translate('xpack.data.search.timeoutContactAdmin', { - defaultMessage: - 'One or more queries timed out. Contact your system administrator to increase the run time.', - }); - this.deps.toasts.addError(e, { - title: 'Timed out', - toastMessage: message, - }); - }, - 60000, - { - leading: true, - } - ); } diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx index f326d5ad54ef29..47da1e93cf004b 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx @@ -44,6 +44,7 @@ describe('alert actions', () => { updateTimelineIsLoading = jest.fn() as jest.Mocked; searchStrategyClient = { aggs: {} as ISearchStart['aggs'], + showError: jest.fn(), search: jest.fn().mockResolvedValue({ data: mockTimelineDetails }), searchSource: {} as ISearchStart['searchSource'], }; diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index fd743400133a7d..1c2c4c78504f0c 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -1367,10 +1367,6 @@ "discover.embeddable.inspectorRequestDataTitle": "データ", "discover.embeddable.inspectorRequestDescription": "このリクエストはElasticsearchにクエリをかけ、検索データを取得します。", "discover.embeddable.search.displayName": "検索", - "discover.errorLoadingData": "データの読み込み中にエラーが発生", - "discover.fetchError.howToAddressErrorDescription": "このエラーは、{scriptedFields}タブにある {managementLink}の{fetchErrorScript}フィールドを編集することで解決できます。", - "discover.fetchError.managmentLinkText": "管理>インデックスパターン", - "discover.fetchError.scriptedFieldsText": "「スクリプトフィールド」", "discover.fieldChooser.detailViews.emptyStringText": "空の文字列", "discover.fieldChooser.detailViews.filterOutValueButtonAriaLabel": "{field}を除外:\"{value}\"", "discover.fieldChooser.detailViews.filterValueButtonAriaLabel": "{field}を除外:\"{value}\"", @@ -1445,7 +1441,6 @@ "discover.notifications.invalidTimeRangeTitle": "無効な時間範囲", "discover.notifications.notSavedSearchTitle": "検索「{savedSearchTitle}」は保存されませんでした。", "discover.notifications.savedSearchTitle": "検索「{savedSearchTitle}」が保存されました。", - "discover.painlessError.painlessScriptedFieldErrorMessage": "Painlessスクリプトのフィールド「{script}」のエラー.", "discover.reloadSavedSearchButton": "検索をリセット", "discover.rootBreadcrumb": "発見", "discover.savedSearch.savedObjectName": "保存検索", @@ -4380,7 +4375,6 @@ "visualize.createVisualization.noIndexPatternOrSavedSearchIdErrorMessage": "indexPatternまたはsavedSearchIdが必要です", "visualize.createVisualization.noVisTypeErrorMessage": "有効なビジュアライゼーションタイプを指定してください", "visualize.editor.createBreadcrumb": "作成", - "visualize.error.title": "ビジュアライゼーションエラー", "visualize.helpMenu.appName": "可視化", "visualize.linkedToSearch.unlinkSuccessNotificationText": "保存された検索「{searchTitle}」からリンクが解除されました", "visualize.listing.betaTitle": "ベータ", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 104fc70f5dd715..5738b440a9e925 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -1368,10 +1368,6 @@ "discover.embeddable.inspectorRequestDataTitle": "数据", "discover.embeddable.inspectorRequestDescription": "此请求将查询 Elasticsearch 以获取搜索的数据。", "discover.embeddable.search.displayName": "搜索", - "discover.errorLoadingData": "加载数据时出错", - "discover.fetchError.howToAddressErrorDescription": "您可以通过编辑{managementLink}中{scriptedFields}选项卡下的“{fetchErrorScript}”字段来解决此错误。", - "discover.fetchError.managmentLinkText": "“管理”>“索引模式”", - "discover.fetchError.scriptedFieldsText": "“脚本字段”", "discover.fieldChooser.detailViews.emptyStringText": "空字符串", "discover.fieldChooser.detailViews.filterOutValueButtonAriaLabel": "筛除 {field}:“{value}”", "discover.fieldChooser.detailViews.filterValueButtonAriaLabel": "筛留 {field}:“{value}”", @@ -1446,7 +1442,6 @@ "discover.notifications.invalidTimeRangeTitle": "时间范围无效", "discover.notifications.notSavedSearchTitle": "搜索“{savedSearchTitle}”未保存。", "discover.notifications.savedSearchTitle": "搜索“{savedSearchTitle}”已保存", - "discover.painlessError.painlessScriptedFieldErrorMessage": "Painless 脚本字段“{script}”有错误。", "discover.reloadSavedSearchButton": "重置搜索", "discover.rootBreadcrumb": "Discover", "discover.savedSearch.savedObjectName": "已保存搜索", @@ -4381,7 +4376,6 @@ "visualize.createVisualization.noIndexPatternOrSavedSearchIdErrorMessage": "必须提供 indexPattern 或 savedSearchId", "visualize.createVisualization.noVisTypeErrorMessage": "必须提供有效的可视化类型", "visualize.editor.createBreadcrumb": "创建", - "visualize.error.title": "可视化错误", "visualize.helpMenu.appName": "Visualize", "visualize.linkedToSearch.unlinkSuccessNotificationText": "已取消与已保存搜索“{searchTitle}”的链接", "visualize.listing.betaTitle": "公测版", diff --git a/x-pack/test/functional/apps/discover/error_handling.ts b/x-pack/test/functional/apps/discover/error_handling.ts index 515e5e293ae280..40aa8cd5c06069 100644 --- a/x-pack/test/functional/apps/discover/error_handling.ts +++ b/x-pack/test/functional/apps/discover/error_handling.ts @@ -9,7 +9,7 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { const esArchiver = getService('esArchiver'); - const testSubjects = getService('testSubjects'); + const toasts = getService('toasts'); const PageObjects = getPageObjects(['common', 'discover', 'timePicker']); describe('errors', function describeIndexTests() { @@ -23,11 +23,13 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { after(async function () { await esArchiver.unload('invalid_scripted_field'); }); + // this is the same test as in OSS but it catches different error message issue in different licences describe('invalid scripted field error', () => { it('is rendered', async () => { - const isFetchErrorVisible = await testSubjects.exists('discoverFetchError'); - expect(isFetchErrorVisible).to.be(true); + const toast = await toasts.getToastElement(1); + const painlessStackTrace = await toast.findByTestSubject('painlessStackTrace'); + expect(painlessStackTrace).not.to.be(undefined); }); }); }); From 8ce96e3ce4345c67142faf88280eba2bd709b003 Mon Sep 17 00:00:00 2001 From: ncheckin <68351161+ncheckin@users.noreply.github.com> Date: Mon, 28 Sep 2020 11:35:33 -0400 Subject: [PATCH 14/19] Update tutorial-discovering.asciidoc (#76976) * Update tutorial-discovering.asciidoc Adds alt text to images in doc. * Update docs/getting-started/tutorial-discovering.asciidoc * Update docs/getting-started/tutorial-discovering.asciidoc Co-authored-by: Kaarina Tungseth --- docs/getting-started/tutorial-discovering.asciidoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/getting-started/tutorial-discovering.asciidoc b/docs/getting-started/tutorial-discovering.asciidoc index ec07a74b8ac0db..99a07acf987917 100644 --- a/docs/getting-started/tutorial-discovering.asciidoc +++ b/docs/getting-started/tutorial-discovering.asciidoc @@ -21,7 +21,7 @@ The search returns all account numbers between zero and 99 with balances in excess of 47,500. Results appear for account numbers 8, 32, 78, 85, and 97. + [role="screenshot"] -image::images/tutorial-discover-2.png[] +image::images/tutorial-discover-2.png[Image showing the search results for account numbers between zero and 99, with balances in excess of 47,500] + . Hover over the list of *Available fields*, then click *Add* next to each field you want include in the table. @@ -30,6 +30,6 @@ For example, when you add the `account_number` field, the display changes to a l account numbers. + [role="screenshot"] -image::images/tutorial-discover-3.png[] +image::images/tutorial-discover-3.png[Image showing a dropdown with five account numbers, which match the previous query for account balance] Now that you know what your documents contain, it's time to gain insight into your data with visualizations. From 68912875c4c4879c4723dae648d74b46ca9136fa Mon Sep 17 00:00:00 2001 From: ncheckin <68351161+ncheckin@users.noreply.github.com> Date: Mon, 28 Sep 2020 11:41:03 -0400 Subject: [PATCH 15/19] Update tutorial-visualizing.asciidoc (#76977) * Update tutorial-visualizing.asciidoc adds alt text to images * Update docs/getting-started/tutorial-visualizing.asciidoc * Update docs/getting-started/tutorial-visualizing.asciidoc * Update docs/getting-started/tutorial-visualizing.asciidoc * Update docs/getting-started/tutorial-visualizing.asciidoc * Update docs/getting-started/tutorial-visualizing.asciidoc * Update docs/getting-started/tutorial-visualizing.asciidoc Co-authored-by: Elastic Machine Co-authored-by: Kaarina Tungseth --- .../tutorial-visualizing.asciidoc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/getting-started/tutorial-visualizing.asciidoc b/docs/getting-started/tutorial-visualizing.asciidoc index 33a70351602477..a53c8cb6bc23d7 100644 --- a/docs/getting-started/tutorial-visualizing.asciidoc +++ b/docs/getting-started/tutorial-visualizing.asciidoc @@ -16,7 +16,7 @@ To visualize the Shakespeare data and compare the number of speaking parts in th . Click *Create new*, then click *Lens* on the *New Visualization* window. + [role="screenshot"] -image::images/tutorial-visualize-wizard-step-1.png[Bar chart] +image::images/tutorial-visualize-wizard-step-1.png[Image showing different options for your new visualization] . Make sure the index pattern is *shakes*. @@ -39,7 +39,7 @@ image::images/tutorial-visualize-wizard-step-1.png[Bar chart] .. In the *Label* field, enter `Speaking Parts`. + [role="screenshot"] -image::images/tutorial-visualize-bar-1.5.png[Bar chart] +image::images/tutorial-visualize-bar-1.5.png[Bar chart showing the speaking parts data] . *Save* the chart with the name `Bar Example`. + @@ -85,7 +85,7 @@ Since the default search matches all documents, the pie contains a single slice. The pie chart displays the proportion of the 1,000 accounts that fall into each of the ranges. + [role="screenshot"] -image::images/tutorial-visualize-pie-2.png[Pie chart] +image::images/tutorial-visualize-pie-2.png[Pie chart displaying accounts that fall into each of the ranges, scaled to 1000 accounts] . Add another bucket aggregation that displays the ages of the account holders. @@ -99,7 +99,7 @@ The break down of the ages of the account holders are displayed in a ring around the balance ranges. + [role="screenshot"] -image::images/tutorial-visualize-pie-3.png[Final pie chart] +image::images/tutorial-visualize-pie-3.png[Final pie chart showing all of the changes] . Click *Save*, then enter `Pie Example` in the *Title* field. @@ -119,7 +119,7 @@ To visualize geographic information in the log file data, use <>. .. Set the *End date* to `May 20, 2015 @ 12:00:00.000`. + [role="screenshot"] -image::images/gs_maps_time_filter.png[Time filter for Maps tutorial] +image::images/gs_maps_time_filter.png[Image showing the time filter for Maps tutorial] .. Click *Update* @@ -140,7 +140,7 @@ image::images/gs_maps_time_filter.png[Time filter for Maps tutorial] .. From the *Border color* dropdown, select *#FFF*, then click *Save & close*. + [role="screenshot"] -image::images/tutorial-visualize-map-2.png[Map] +image::images/tutorial-visualize-map-2.png[Example of a map visualization] . Click *Save*, then enter `Map Example` in the *Title* field. @@ -170,12 +170,12 @@ The Markdown widget uses **markdown** syntax. The Markdown renders in the preview pane. + [role="screenshot"] -image::images/tutorial-visualize-md-2.png[] +image::images/tutorial-visualize-md-2.png[Image showing example markdown editing field] . Click *Save*, then enter `Markdown Example` in the *Title* field. [role="screenshot"] -image::images/tutorial-dashboard.png[] +image::images/tutorial-dashboard.png[Final visualization with bar chart, pie chart, map, and markdown text field] [float] === Next steps From 93248808b33d2ab8bafcff73a3c47c409d2a4700 Mon Sep 17 00:00:00 2001 From: Daniil Suleiman <31325372+sulemanof@users.noreply.github.com> Date: Mon, 28 Sep 2020 18:47:53 +0300 Subject: [PATCH 16/19] Fix types (#78619) --- src/plugins/visualizations/public/types.ts | 4 ++-- .../public/vis_types/base_vis_type.ts | 16 +++++++++------- .../public/vis_types/types_service.ts | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/plugins/visualizations/public/types.ts b/src/plugins/visualizations/public/types.ts index 897a8c1e323194..68ab3561d375c1 100644 --- a/src/plugins/visualizations/public/types.ts +++ b/src/plugins/visualizations/public/types.ts @@ -73,7 +73,7 @@ export interface VisToExpressionAstParams { abortSignal?: AbortSignal; } -export type VisToExpressionAst = ( - vis: Vis, +export type VisToExpressionAst = ( + vis: Vis, params: VisToExpressionAstParams ) => ExpressionAstExpression; diff --git a/src/plugins/visualizations/public/vis_types/base_vis_type.ts b/src/plugins/visualizations/public/vis_types/base_vis_type.ts index 283286648ff16f..27a4f299c1e9ca 100644 --- a/src/plugins/visualizations/public/vis_types/base_vis_type.ts +++ b/src/plugins/visualizations/public/vis_types/base_vis_type.ts @@ -18,7 +18,7 @@ */ import _ from 'lodash'; -import { VisToExpressionAst, VisualizationControllerConstructor } from '../types'; +import { VisParams, VisToExpressionAst, VisualizationControllerConstructor } from '../types'; import { TriggerContextMapping } from '../../../ui_actions/public'; import { Adapters } from '../../../inspector/public'; @@ -43,8 +43,8 @@ interface CommonBaseVisTypeOptions { inspectorAdapters?: Adapters | (() => Adapters); } -interface ExpressionBaseVisTypeOptions extends CommonBaseVisTypeOptions { - toExpressionAst: VisToExpressionAst; +interface ExpressionBaseVisTypeOptions extends CommonBaseVisTypeOptions { + toExpressionAst: VisToExpressionAst; visualization?: undefined; } @@ -53,9 +53,11 @@ interface VisualizationBaseVisTypeOptions extends CommonBaseVisTypeOptions { visualization: VisualizationControllerConstructor | undefined; } -export type BaseVisTypeOptions = ExpressionBaseVisTypeOptions | VisualizationBaseVisTypeOptions; +export type BaseVisTypeOptions = + | ExpressionBaseVisTypeOptions + | VisualizationBaseVisTypeOptions; -export class BaseVisType { +export class BaseVisType { name: string; title: string; description: string; @@ -77,9 +79,9 @@ export class BaseVisType { setup?: unknown; useCustomNoDataScreen: boolean; inspectorAdapters?: Adapters | (() => Adapters); - toExpressionAst?: VisToExpressionAst; + toExpressionAst?: VisToExpressionAst; - constructor(opts: BaseVisTypeOptions) { + constructor(opts: BaseVisTypeOptions) { if (!opts.icon && !opts.image) { throw new Error('vis_type must define its icon or image'); } diff --git a/src/plugins/visualizations/public/vis_types/types_service.ts b/src/plugins/visualizations/public/vis_types/types_service.ts index 157dbd41ce8a21..1afbd6901a1959 100644 --- a/src/plugins/visualizations/public/vis_types/types_service.ts +++ b/src/plugins/visualizations/public/vis_types/types_service.ts @@ -71,7 +71,7 @@ export class TypesService { * registers a visualization type * @param config - visualization type definition */ - createBaseVisualization: (config: BaseVisTypeOptions): void => { + createBaseVisualization: (config: BaseVisTypeOptions): void => { const vis = new BaseVisType(config); registerVisualization(() => vis); }, From 37d49b00524e547daab8557fb5b9b80243b47753 Mon Sep 17 00:00:00 2001 From: ncheckin <68351161+ncheckin@users.noreply.github.com> Date: Mon, 28 Sep 2020 11:53:38 -0400 Subject: [PATCH 17/19] updated discover with alt text (#77660) * Update context.asciidoc * Update document-data.asciidoc * Update field-filter.asciidoc * Update search.asciidoc * Update set-time-filter.asciidoc * Update viewing-field-stats.asciidoc * Update canvas-edit-workpads.asciidoc * Update canvas-expression-lifecycle.asciidoc * Update canvas-present-workpad.asciidoc * Update canvas-share-workpad.asciidoc * Update canvas-tutorial.asciidoc * Update docs/canvas/canvas-share-workpad.asciidoc * Update docs/canvas/canvas-share-workpad.asciidoc * Update docs/canvas/canvas-tutorial.asciidoc * Update docs/canvas/canvas-tutorial.asciidoc * Update docs/canvas/canvas-tutorial.asciidoc * Update docs/canvas/canvas-tutorial.asciidoc * Update docs/discover/search.asciidoc * Update docs/discover/set-time-filter.asciidoc * Update docs/discover/viewing-field-stats.asciidoc * Update docs/discover/field-filter.asciidoc * Update docs/discover/document-data.asciidoc Co-authored-by: Kaarina Tungseth --- docs/canvas/canvas-edit-workpads.asciidoc | 6 +++--- docs/canvas/canvas-expression-lifecycle.asciidoc | 8 ++++---- docs/canvas/canvas-present-workpad.asciidoc | 4 ++-- docs/canvas/canvas-share-workpad.asciidoc | 8 ++++---- docs/canvas/canvas-tutorial.asciidoc | 8 ++++---- docs/discover/context.asciidoc | 2 +- docs/discover/document-data.asciidoc | 2 +- docs/discover/field-filter.asciidoc | 2 +- docs/discover/search.asciidoc | 2 +- docs/discover/set-time-filter.asciidoc | 4 ++-- docs/discover/viewing-field-stats.asciidoc | 2 +- 11 files changed, 24 insertions(+), 24 deletions(-) diff --git a/docs/canvas/canvas-edit-workpads.asciidoc b/docs/canvas/canvas-edit-workpads.asciidoc index 6558def8a74748..6ad2d89be4a423 100644 --- a/docs/canvas/canvas-edit-workpads.asciidoc +++ b/docs/canvas/canvas-edit-workpads.asciidoc @@ -25,12 +25,12 @@ For example, to change the index pattern for a set of charts: Specify the variable options. [role="screenshot"] -image::images/specify_variable_syntax.png[Specify the variable syntax] +image::images/specify_variable_syntax.png[Image describing how to specify the variable syntax] Copy the variable, then apply it to each element you want to update in the *Expression editor*. [role="screenshot"] -image::images/copy_variable_syntax.png[Copy the variable syntax] +image::images/copy_variable_syntax.png[Image demonstrating expression editor] [float] [[apply-changes-to-the-entire-workpad]] @@ -85,7 +85,7 @@ To use an element with the same functionality and appearance in multiple places, Select the element, then click *Edit > Clone*. [role="screenshot"] -image::images/clone_element.gif[Clone elements] +image::images/clone_element.gif[Image showing how to clone elements] [float] [[move-and-resize-elements]] diff --git a/docs/canvas/canvas-expression-lifecycle.asciidoc b/docs/canvas/canvas-expression-lifecycle.asciidoc index 895c1382c4d360..7d48c593f9e188 100644 --- a/docs/canvas/canvas-expression-lifecycle.asciidoc +++ b/docs/canvas/canvas-expression-lifecycle.asciidoc @@ -30,7 +30,7 @@ The filtered <> becomes the _context_ of the next functi Let’s look at another expression, which uses the same <> function, but instead produces a pie chart. -image::images/canvas-functions-can-take-arguments-pie-chart.png[Pie Chart, height=400] +image::images/canvas-functions-can-take-arguments-pie-chart.png[Pie chart showing output of demodata function] [source,text] ---- filters @@ -47,7 +47,7 @@ If the expression stopped there, it would produce a `pointseries` data type as t The end result is a simple pie chart that uses the default color palette, but the <> function can take additional arguments that control how it gets rendered. For example, you can provide a `hole` argument to turn your pie chart into a donut chart by changing the expression to: -image::images/canvas-functions-can-take-arguments-donut-chart.png[Donut Chart, height=400] +image::images/canvas-functions-can-take-arguments-donut-chart.png[Alternative output as donut chart] [source,text] ---- filters @@ -83,7 +83,7 @@ You can substitute one function for another to change the output. For example, y Let’s change that last pie chart into a bubble chart by replacing the <> function with the <> function. This is possible because both functions can accept a `pointseries` data type as their _context_. Switching the functions will work, but it won’t produce a useful visualization on its own since you don’t have the x-axis and y-axis defined. You will also need to modify the <> function to change its output. In this case, you can change the `size` argument to `y`, so the maximum price values are plotted on the y-axis, and add an `x` argument using the `@timestamp` field in the data to plot those values over time. This leaves you with the following expression and produces a bubble chart showing the max price of each state over time: -image::images/canvas-change-your-expression-chart.png[Bubble Chart, height=400] +image::images/canvas-change-your-expression-chart.png[Bubble Chart, with price along x axis, and time along y axis] [source,text] ---- filters @@ -95,7 +95,7 @@ filters Similar to the <> function, the <> function takes arguments that control the design elements of the visualization. As one example, passing a `legend` argument with a value of `false` to the function will hide the legend on the chart. -image::images/canvas-change-your-expression-chart-no-legend.png[Bubble Chart Without Legend, height=400] +image::images/canvas-change-your-expression-chart-no-legend.png[Bubble Chart Without Legend] [source,text,subs=+quotes] ---- filters diff --git a/docs/canvas/canvas-present-workpad.asciidoc b/docs/canvas/canvas-present-workpad.asciidoc index a6d801b74fce16..b1492f57e46f8e 100644 --- a/docs/canvas/canvas-present-workpad.asciidoc +++ b/docs/canvas/canvas-present-workpad.asciidoc @@ -18,7 +18,7 @@ image::images/canvas-autoplay-interval.png[Element autoplay interval] . To start your presentation, click *View > Enter fullscreen mode*. + [role="screenshot"] -image::images/canvas-fullscreen.png[Fullscreen mode] +image::images/canvas-fullscreen.png[Image showing how to enter fullscreen mode from view dropdown] . When you are ready to exit fullscreen mode, press the Esc (Escape) key. @@ -33,7 +33,7 @@ To get a closer look at a portion of your workpad, use the zoom options. . Select the zoom option. + [role="screenshot"] -image::images/canvas-zoom-controls.png[Zoom controls] +image::images/canvas-zoom-controls.png[Zoom controls, also in view dropdown] [float] [[configure-auto-refresh-interval]] diff --git a/docs/canvas/canvas-share-workpad.asciidoc b/docs/canvas/canvas-share-workpad.asciidoc index f6cd2d93a9372c..4887eb6ca870d3 100644 --- a/docs/canvas/canvas-share-workpad.asciidoc +++ b/docs/canvas/canvas-share-workpad.asciidoc @@ -13,7 +13,7 @@ Create a JSON file of your workpad that you can export outside of {kib}. Click *Share > Download as JSON*. [role="screenshot"] -image::images/canvas-export-workpad.png[Export single workpad] +image::images/canvas-export-workpad.png[Export single workpad through JSON, from Share dropdown] Want to export multiple workpads? Go to the *Canvas* home page, select the workpads you want to export, then click *Export*. @@ -26,7 +26,7 @@ If you have a subscription that supports the {report-features}, you can create a Click *Share > PDF reports > Generate PDF*. [role="screenshot"] -image::images/canvas-generate-pdf.gif[Generate PDF] +image::images/canvas-generate-pdf.gif[Image showing how to generate a PDF] For more information, refer to <>. @@ -39,7 +39,7 @@ If you have a subscription that supports the {report-features}, you can create a Click *Share > PDF reports > Copy POST URL*. [role="screenshot"] -image::images/canvas-create-URL.gif[Create POST URL] +image::images/canvas-create-URL.gif[Image showing how to create POST URL] For more information, refer to <>. @@ -58,7 +58,7 @@ beta[] Canvas allows you to create _shareables_, which are workpads that you dow To make sure that your data remains secure, the data in the JSON file is not connected to {kib}. Canvas does not display elements that manipulate the data on the workpad. + [role="screenshot"] -image::canvas/images/canvas-embed_workpad.gif[Share the workpad on a website] +image::canvas/images/canvas-embed_workpad.gif[Image showing how to share the workpad on a website] + NOTE: Shareable workpads encode the current state of the workpad in a JSON file. When you make changes to the workpad, the changes do not appear in the shareable workpad on your website. diff --git a/docs/canvas/canvas-tutorial.asciidoc b/docs/canvas/canvas-tutorial.asciidoc index a861b30db784f3..ea4d2c8cc6a837 100644 --- a/docs/canvas/canvas-tutorial.asciidoc +++ b/docs/canvas/canvas-tutorial.asciidoc @@ -30,7 +30,7 @@ The default Elastic logo image appears on the page. . To replace the Elastic logo with your own image, select the image, then use the editor. [role="screenshot"] -image::images/canvas-image-element.png[] +image::images/canvas-image-element.png[Image showing how to add the image element] [float] === Customize your data with metrics @@ -70,7 +70,7 @@ You're now looking at the raw data syntax that Canvas uses to display the elemen .. Click *Run*. [role="screenshot"] -image::images/canvas-metric-element.png[] +image::images/canvas-metric-element.png[Image showing changes to the Canvas workpad] [float] === Show off your data with charts @@ -96,7 +96,7 @@ To show what your data can do, add charts, graphs, progress monitors, and more t .. From the *Y-axis* drop-down lists, select *Value*, then select *taxless_total_price*. [role="screenshot"] -image::images/canvas-chart-element.png[] +image::images/canvas-chart-element.png[Image showing Canvas workpad with sample data graph] [float] === Show how your data changes over time @@ -110,7 +110,7 @@ To focus your data on a specific time range, add the time filter. . To use the date time field from the sample data, enter `order_date` in the *Column* field, then click *Set*. [role="screenshot"] -image::images/canvas-timefilter-element.png[] +image::images/canvas-timefilter-element.png[Image showing Canvas workpad with filtered sample data graph] To see how the data changes, set the time filter to *Last 7 days*. As you change the time filter options, the elements automatically update. diff --git a/docs/discover/context.asciidoc b/docs/discover/context.asciidoc index 17ed78a1635713..e26c91bfef0755 100644 --- a/docs/discover/context.asciidoc +++ b/docs/discover/context.asciidoc @@ -16,7 +16,7 @@ The anchor document is highlighted in blue. [role="screenshot"] -image::images/Discover-ContextView.png[Context View] +image::images/Discover-ContextView.png[Image showing context view feature, with anchor documents highlighted in blue] [float] [[filter-context]] diff --git a/docs/discover/document-data.asciidoc b/docs/discover/document-data.asciidoc index ee130e84054832..dd245e4b4558f2 100644 --- a/docs/discover/document-data.asciidoc +++ b/docs/discover/document-data.asciidoc @@ -44,7 +44,7 @@ immediately before and after your event. share the link for direct access to a particular document. [role="screenshot"] -image::images/Expanded-Document.png[] +image::images/Expanded-Document.png[Image showing expanded view, with JSON and table viewing options] [float] diff --git a/docs/discover/field-filter.asciidoc b/docs/discover/field-filter.asciidoc index 949cab2c2f976d..0c521b401e4b88 100644 --- a/docs/discover/field-filter.asciidoc +++ b/docs/discover/field-filter.asciidoc @@ -19,7 +19,7 @@ the field, the top 5 values for the field, and the percentage of documents that contain each value. + [role="screenshot"] -image::images/filter-field.png[height=317] +image::images/filter-field.png[Picture showing top 5 values for each field, and correspnding percentage of documents that contain each value] . Use the image:images/PositiveFilter.jpg[Positive Filter] icon to show only documents that contain that value, diff --git a/docs/discover/search.asciidoc b/docs/discover/search.asciidoc index da58382deb89a5..ee1e1526f9d6fb 100644 --- a/docs/discover/search.asciidoc +++ b/docs/discover/search.asciidoc @@ -28,7 +28,7 @@ configure a refresh interval to periodically resubmit your searches to retrieve the latest results. [role="screenshot"] -image::images/autorefresh-interval.png[] +image::images/autorefresh-interval.png[Image showing what refresh interval option looks like. The configurable time interval is located in the dropdown] You can also manually refresh the search results by clicking the *Refresh* button. diff --git a/docs/discover/set-time-filter.asciidoc b/docs/discover/set-time-filter.asciidoc index a5b81b0fa461cd..93fdf9ffd695ab 100644 --- a/docs/discover/set-time-filter.asciidoc +++ b/docs/discover/set-time-filter.asciidoc @@ -14,7 +14,7 @@ range in the histogram. Use the time filter to change the time range. By default, the time filter is set to the last 15 minutes. -. Click image:images/time-filter-calendar.png[]. +. Click image:images/time-filter-calendar.png[Calendar icon]. . Choose one of the following: @@ -53,4 +53,4 @@ when you hover over a valid start point. * Click the dropdown, then select an interval. [role="screenshot"] -image::images/Histogram-Time.png[Time range selector in Histogram] +image::images/Histogram-Time.png[Time range selector in Histogram dropdown] diff --git a/docs/discover/viewing-field-stats.asciidoc b/docs/discover/viewing-field-stats.asciidoc index 5ada5839fd3449..5c461773475306 100644 --- a/docs/discover/viewing-field-stats.asciidoc +++ b/docs/discover/viewing-field-stats.asciidoc @@ -11,4 +11,4 @@ they are available in the side bar if you uncheck "Hide missing fields". To view field data statistics, click the name of a field in the fields list. -image:images/filter-field.png[Field Statistics,height=317] +image:images/filter-field.png[Fields list that displays the top five search results] From c285287da39abe4c9f091c02f5ae3ffd10ca25a7 Mon Sep 17 00:00:00 2001 From: Marco Liberati Date: Mon, 28 Sep 2020 18:50:48 +0200 Subject: [PATCH 18/19] Fix Lens smokescreen flaky tests (#78566) Co-authored-by: Elastic Machine --- .../dashboard_mode/dashboard_empty_screen.js | 3 --- x-pack/test/functional/apps/lens/rollup.ts | 3 --- x-pack/test/functional/apps/lens/smokescreen.ts | 17 +---------------- .../test/functional/page_objects/lens_page.ts | 16 +++++++++++++++- 4 files changed, 16 insertions(+), 23 deletions(-) diff --git a/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js b/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js index b74df717010263..bd35374643e9b8 100644 --- a/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js +++ b/x-pack/test/functional/apps/dashboard_mode/dashboard_empty_screen.js @@ -40,21 +40,18 @@ export default function ({ getPageObjects, getService }) { operation: 'date_histogram', field: '@timestamp', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', operation: 'avg', field: 'bytes', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_splitDimensionPanel > lns-empty-dimension', operation: 'terms', field: 'ip', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.save(title, saveAsNew, redirectToOrigin); } diff --git a/x-pack/test/functional/apps/lens/rollup.ts b/x-pack/test/functional/apps/lens/rollup.ts index 8e1dc231b6b1a9..f6882c8aed2144 100644 --- a/x-pack/test/functional/apps/lens/rollup.ts +++ b/x-pack/test/functional/apps/lens/rollup.ts @@ -34,21 +34,18 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { operation: 'date_histogram', field: '@timestamp', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', operation: 'sum', field: 'bytes', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_splitDimensionPanel > lns-empty-dimension', operation: 'terms', field: 'geo.src', }); - await PageObjects.lens.closeDimensionEditor(); expect(await find.allByCssSelector('.echLegendItem')).to.have.length(2); await PageObjects.lens.save('Afancilenstest'); diff --git a/x-pack/test/functional/apps/lens/smokescreen.ts b/x-pack/test/functional/apps/lens/smokescreen.ts index 1ed3a0864c2442..d26c92a2bcd63e 100644 --- a/x-pack/test/functional/apps/lens/smokescreen.ts +++ b/x-pack/test/functional/apps/lens/smokescreen.ts @@ -25,21 +25,18 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { operation: 'date_histogram', field: '@timestamp', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', operation: 'avg', field: 'bytes', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_splitDimensionPanel > lns-empty-dimension', operation: 'terms', field: '@message.raw', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.switchToVisualization('lnsDatatable'); await PageObjects.lens.removeDimension('lnsDatatable_column'); @@ -50,7 +47,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { operation: 'terms', field: 'ip', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.save('Afancilenstest'); @@ -78,6 +74,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { dimension: 'lnsXY_splitDimensionPanel > lns-dimensionTrigger', operation: 'filters', isPreviousIncompatible: true, + keepOpen: true, }); await PageObjects.lens.addFilterToAgg(`geo.src : CN`); @@ -110,14 +107,12 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { field: '@timestamp', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', operation: 'avg', field: 'bytes', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.createLayer(); expect(await PageObjects.lens.hasChartSwitchWarning('line')).to.eql(false); @@ -132,7 +127,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { 1 ); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension( { dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', @@ -142,7 +136,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { 1 ); - await PageObjects.lens.closeDimensionEditor(); expect(await PageObjects.lens.getLayerCount()).to.eql(2); await testSubjects.click('lnsLayerRemove'); await testSubjects.click('lnsLayerRemove'); @@ -171,8 +164,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await testSubjects.existOrFail('indexPattern-dimension-formatDecimals'); - await PageObjects.lens.closeDimensionEditor(); - expect(await PageObjects.lens.getDimensionTriggerText('lnsXY_yDimensionPanel')).to.eql( 'Test of label' ); @@ -189,14 +180,12 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { field: 'geo.dest', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', operation: 'avg', field: 'bytes', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.createLayer(); await PageObjects.lens.configureDimension( @@ -208,7 +197,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { 1 ); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension( { dimension: 'lnsXY_yDimensionPanel > lns-empty-dimension', @@ -218,7 +206,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { 1 ); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.save('twolayerchart'); await testSubjects.click('lnsSuggestion-asDonut > lnsSuggestion'); @@ -304,7 +291,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { operation: 'date_histogram', field: '@timestamp', }); - await PageObjects.lens.closeDimensionEditor(); await PageObjects.lens.configureDimension({ dimension: 'lnsPie_sizeByDimensionPanel > lns-empty-dimension', @@ -312,7 +298,6 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { field: 'bytes', }); - await PageObjects.lens.closeDimensionEditor(); expect(await PageObjects.lens.hasChartSwitchWarning('lnsDatatable')).to.eql(false); await PageObjects.lens.switchToVisualization('lnsDatatable'); diff --git a/x-pack/test/functional/page_objects/lens_page.ts b/x-pack/test/functional/page_objects/lens_page.ts index a1e62afbe14c80..ec7281e53c5e15 100644 --- a/x-pack/test/functional/page_objects/lens_page.ts +++ b/x-pack/test/functional/page_objects/lens_page.ts @@ -90,6 +90,7 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont operation: string; field?: string; isPreviousIncompatible?: boolean; + keepOpen?: boolean; }, layerIndex = 0 ) { @@ -107,6 +108,10 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont await comboBox.openOptionsList(target); await comboBox.setElement(target, opts.field); } + + if (!opts.keepOpen) { + this.closeDimensionEditor(); + } }, // closes the dimension editor flyout @@ -127,7 +132,16 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont await testSubjects.click('lns-newBucket-add'); const queryInput = await testSubjects.find('indexPattern-filters-queryStringInput'); await queryInput.type(queryString); - await PageObjects.common.pressEnterKey(); + // Problem here is that after typing in the queryInput a dropdown will fetch the server + // with suggestions and show up. Depending on the cursor position and some other factors + // pressing Enter at this point may lead to auto-complete the queryInput with random stuff from the + // dropdown which was not intended originally. + // To close the Filter popover we need to move to the label input and then press Enter: + // solution is to press Tab 2 twice (first Tab will close the dropdown) instead of Enter to avoid + // race condition with the dropdown + await PageObjects.common.pressTabKey(); + await PageObjects.common.pressTabKey(); + // Now it is safe to press Enter as we're in the label input await PageObjects.common.pressEnterKey(); await PageObjects.common.sleep(1000); // give time for debounced components to rerender }, From 54a2c75097bf7851fc6e10fe1ed26c22cd2ba470 Mon Sep 17 00:00:00 2001 From: Nathan Reese Date: Mon, 28 Sep 2020 11:31:53 -0600 Subject: [PATCH 19/19] Add deprecated message to tile_map and region_map visualizations. (#77683) * Add deprecation message to coordinate map and region map * clean up text * add default distro link and view in maps link * move url generation into onClick handler * create tile map layer descritor * set metrics and color and scaling * lazy load createTileMapLayerDescriptor * tslint fixes * tslint cleanup for OSS code * add region map deprecation message * tslint cleanup * consolidate logic into LegacyMapDeprecationMessage * fix jest test * fix tile-map and region_map in OSS distro * tslint fixes * assert urlGenerator exists * update message text * ensure legacy-ids get correctly evaluated (#37) * handle 6.x region map saved objects * turn off field meta * fix type Co-authored-by: Elastic Machine Co-authored-by: Thomas Neirynck --- .../legacy_map_deprecation_message.tsx | 79 +++++++ src/plugins/maps_legacy/public/index.ts | 1 + src/plugins/region_map/kibana.json | 3 +- .../public/get_deprecation_message.tsx | 93 ++++++++ .../region_map/public/kibana_services.ts | 10 + src/plugins/region_map/public/plugin.ts | 22 +- .../region_map/public/region_map_type.js | 3 + src/plugins/tile_map/kibana.json | 3 +- .../public/get_deprecation_message.tsx | 89 ++++++++ src/plugins/tile_map/public/plugin.ts | 20 +- src/plugins/tile_map/public/services.ts | 6 + src/plugins/tile_map/public/tile_map_type.js | 3 + .../public/vis_types/base_vis_type.ts | 8 + .../components/visualize_editor_common.tsx | 44 ++-- .../create_region_map_layer_descriptor.ts | 117 ++++++++++ .../create_tile_map_layer_descriptor.test.ts | 43 ++++ .../create_tile_map_layer_descriptor.ts | 159 ++++++++++++++ .../observability/create_layer_descriptor.ts | 1 - .../ems_file_source/ems_file_source.tsx | 4 +- .../maps/public/lazy_load_bundle/index.ts | 42 ++++ .../public/lazy_load_bundle/lazy/index.ts | 2 + x-pack/plugins/maps/public/plugin.ts | 27 ++- .../plugins/maps/public/url_generator.test.ts | 5 +- x-pack/plugins/maps/public/url_generator.ts | 199 ++++++++++++++---- 24 files changed, 899 insertions(+), 84 deletions(-) create mode 100644 src/plugins/maps_legacy/public/components/legacy_map_deprecation_message.tsx create mode 100644 src/plugins/region_map/public/get_deprecation_message.tsx create mode 100644 src/plugins/tile_map/public/get_deprecation_message.tsx create mode 100644 x-pack/plugins/maps/public/classes/layers/create_region_map_layer_descriptor.ts create mode 100644 x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.test.ts create mode 100644 x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.ts diff --git a/src/plugins/maps_legacy/public/components/legacy_map_deprecation_message.tsx b/src/plugins/maps_legacy/public/components/legacy_map_deprecation_message.tsx new file mode 100644 index 00000000000000..3fae842663fdde --- /dev/null +++ b/src/plugins/maps_legacy/public/components/legacy_map_deprecation_message.tsx @@ -0,0 +1,79 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you 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 + * + * http://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 from 'react'; +import { EuiButton, EuiCallOut, EuiLink } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; + +interface Props { + isMapsAvailable: boolean; + onClick: (e: React.MouseEvent) => Promise; + visualizationLabel: string; +} + +export function LegacyMapDeprecationMessage(props: Props) { + const getMapsMessage = !props.isMapsAvailable ? ( + + default distribution + + ), + }} + /> + ) : null; + + const button = props.isMapsAvailable ? ( +
+ + + +
+ ) : null; + + return ( + +

+ +

+ {button} +
+ ); +} diff --git a/src/plugins/maps_legacy/public/index.ts b/src/plugins/maps_legacy/public/index.ts index d31f23f4bc4a66..fe5338b890ec83 100644 --- a/src/plugins/maps_legacy/public/index.ts +++ b/src/plugins/maps_legacy/public/index.ts @@ -63,6 +63,7 @@ export * from './common/types'; export { ORIGIN } from './common/constants/origin'; export { WmsOptions } from './components/wms_options'; +export { LegacyMapDeprecationMessage } from './components/legacy_map_deprecation_message'; export { lazyLoadMapsLegacyModules } from './lazy_load_bundle'; diff --git a/src/plugins/region_map/kibana.json b/src/plugins/region_map/kibana.json index bd5517d2a5bf7f..e679baf6d6f065 100644 --- a/src/plugins/region_map/kibana.json +++ b/src/plugins/region_map/kibana.json @@ -10,7 +10,8 @@ "expressions", "mapsLegacy", "kibanaLegacy", - "data" + "data", + "share" ], "requiredBundles": [ "kibanaUtils", diff --git a/src/plugins/region_map/public/get_deprecation_message.tsx b/src/plugins/region_map/public/get_deprecation_message.tsx new file mode 100644 index 00000000000000..ea5cdf42c3111a --- /dev/null +++ b/src/plugins/region_map/public/get_deprecation_message.tsx @@ -0,0 +1,93 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you 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 + * + * http://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 { i18n } from '@kbn/i18n'; +import React from 'react'; +import { UrlGeneratorContract } from 'src/plugins/share/public'; +import { getCoreService, getQueryService, getShareService } from './kibana_services'; +import { Vis } from '../../visualizations/public'; +import { LegacyMapDeprecationMessage } from '../../maps_legacy/public'; + +function getEmsLayerId(id: string | number, layerId: string) { + if (typeof id === 'string') { + return id; + } + + // Region maps from 6.x will have numerical EMS id refering to S3 bucket id. + // In this case, use layerId with contains the EMS layer name. + const split = layerId.split('.'); + return split.length === 2 ? split[1] : undefined; +} + +export function getDeprecationMessage(vis: Vis) { + let mapsRegionMapUrlGenerator: + | UrlGeneratorContract<'MAPS_APP_REGION_MAP_URL_GENERATOR'> + | undefined; + try { + mapsRegionMapUrlGenerator = getShareService().urlGenerators.getUrlGenerator( + 'MAPS_APP_REGION_MAP_URL_GENERATOR' + ); + } catch (error) { + // ignore error thrown when url generator is not available + } + + const title = i18n.translate('regionMap.mapVis.regionMapTitle', { defaultMessage: 'Region Map' }); + + async function onClick(e: React.MouseEvent) { + e.preventDefault(); + + const query = getQueryService(); + const createUrlParams: { [key: string]: any } = { + label: vis.title ? vis.title : title, + emsLayerId: vis.params.selectedLayer.isEMS + ? getEmsLayerId(vis.params.selectedLayer.id, vis.params.selectedLayer.layerId) + : undefined, + leftFieldName: vis.params.selectedLayer.isEMS ? vis.params.selectedJoinField.name : undefined, + colorSchema: vis.params.colorSchema, + indexPatternId: vis.data.indexPattern?.id, + indexPatternTitle: vis.data.indexPattern?.title, + metricAgg: 'count', + filters: query.filterManager.getFilters(), + query: query.queryString.getQuery(), + timeRange: query.timefilter.timefilter.getTime(), + }; + + const bucketAggs = vis.data?.aggs?.byType('buckets'); + if (bucketAggs?.length && bucketAggs[0].type.dslName === 'terms') { + createUrlParams.termsFieldName = bucketAggs[0].getField()?.name; + } + + const metricAggs = vis.data?.aggs?.byType('metrics'); + if (metricAggs?.length) { + createUrlParams.metricAgg = metricAggs[0].type.dslName; + createUrlParams.metricFieldName = metricAggs[0].getField()?.name; + } + + const url = await mapsRegionMapUrlGenerator!.createUrl(createUrlParams); + getCoreService().application.navigateToUrl(url); + } + + return ( + + ); +} diff --git a/src/plugins/region_map/public/kibana_services.ts b/src/plugins/region_map/public/kibana_services.ts index 8367325c7415b8..7edbf2da36fc78 100644 --- a/src/plugins/region_map/public/kibana_services.ts +++ b/src/plugins/region_map/public/kibana_services.ts @@ -17,10 +17,14 @@ * under the License. */ +import { CoreStart } from 'kibana/public'; import { NotificationsStart } from 'kibana/public'; import { createGetterSetter } from '../../kibana_utils/public'; import { DataPublicPluginStart } from '../../data/public'; import { KibanaLegacyStart } from '../../kibana_legacy/public'; +import { SharePluginStart } from '../../share/public'; + +export const [getCoreService, setCoreService] = createGetterSetter('Core'); export const [getFormatService, setFormatService] = createGetterSetter< DataPublicPluginStart['fieldFormats'] @@ -30,6 +34,12 @@ export const [getNotifications, setNotifications] = createGetterSetter('Query'); + +export const [getShareService, setShareService] = createGetterSetter('Share'); + export const [getKibanaLegacy, setKibanaLegacy] = createGetterSetter( 'KibanaLegacy' ); diff --git a/src/plugins/region_map/public/plugin.ts b/src/plugins/region_map/public/plugin.ts index c641c16a8112bd..e9978803ad5e2f 100644 --- a/src/plugins/region_map/public/plugin.ts +++ b/src/plugins/region_map/public/plugin.ts @@ -31,11 +31,19 @@ import { createRegionMapFn } from './region_map_fn'; // @ts-ignore import { createRegionMapTypeDefinition } from './region_map_type'; import { IServiceSettings, MapsLegacyPluginSetup } from '../../maps_legacy/public'; -import { setFormatService, setNotifications, setKibanaLegacy } from './kibana_services'; +import { + setCoreService, + setFormatService, + setNotifications, + setKibanaLegacy, + setQueryService, + setShareService, +} from './kibana_services'; import { DataPublicPluginStart } from '../../data/public'; import { RegionMapsConfigType } from './index'; import { MapsLegacyConfig } from '../../maps_legacy/config'; import { KibanaLegacyStart } from '../../kibana_legacy/public'; +import { SharePluginStart } from '../../share/public'; /** @private */ interface RegionMapVisualizationDependencies { @@ -57,6 +65,7 @@ export interface RegionMapPluginStartDependencies { data: DataPublicPluginStart; notifications: NotificationsStart; kibanaLegacy: KibanaLegacyStart; + share: SharePluginStart; } /** @internal */ @@ -108,10 +117,13 @@ export class RegionMapPlugin implements Plugin | undefined; + try { + mapsTileMapUrlGenerator = getShareService().urlGenerators.getUrlGenerator( + 'MAPS_APP_TILE_MAP_URL_GENERATOR' + ); + } catch (error) { + // ignore error thrown when url generator is not available + } + + const title = i18n.translate('tileMap.vis.mapTitle', { + defaultMessage: 'Coordinate Map', + }); + + async function onClick(e: React.MouseEvent) { + e.preventDefault(); + + const query = getQueryService(); + const createUrlParams: { [key: string]: any } = { + label: vis.title ? vis.title : title, + mapType: vis.params.mapType, + colorSchema: vis.params.colorSchema, + indexPatternId: vis.data.indexPattern?.id, + metricAgg: 'count', + filters: query.filterManager.getFilters(), + query: query.queryString.getQuery(), + timeRange: query.timefilter.timefilter.getTime(), + }; + + const bucketAggs = vis.data?.aggs?.byType('buckets'); + if (bucketAggs?.length && bucketAggs[0].type.dslName === 'geohash_grid') { + createUrlParams.geoFieldName = bucketAggs[0].getField()?.name; + } else if (vis.data.indexPattern) { + // attempt to default to first geo point field when geohash is not configured yet + const geoField = vis.data.indexPattern.fields.find((field) => { + return ( + !indexPatterns.isNestedField(field) && field.aggregatable && field.type === 'geo_point' + ); + }); + if (geoField) { + createUrlParams.geoFieldName = geoField.name; + } + } + + const metricAggs = vis.data?.aggs?.byType('metrics'); + if (metricAggs?.length) { + createUrlParams.metricAgg = metricAggs[0].type.dslName; + createUrlParams.metricFieldName = metricAggs[0].getField()?.name; + } + + const url = await mapsTileMapUrlGenerator!.createUrl(createUrlParams); + getCoreService().application.navigateToUrl(url); + } + + return ( + + ); +} diff --git a/src/plugins/tile_map/public/plugin.ts b/src/plugins/tile_map/public/plugin.ts index 07add6901fb498..dfcafafbe47f7f 100644 --- a/src/plugins/tile_map/public/plugin.ts +++ b/src/plugins/tile_map/public/plugin.ts @@ -34,8 +34,15 @@ import { createTileMapFn } from './tile_map_fn'; import { createTileMapTypeDefinition } from './tile_map_type'; import { IServiceSettings, MapsLegacyPluginSetup } from '../../maps_legacy/public'; import { DataPublicPluginStart } from '../../data/public'; -import { setFormatService, setQueryService, setKibanaLegacy } from './services'; +import { + setCoreService, + setFormatService, + setQueryService, + setKibanaLegacy, + setShareService, +} from './services'; import { KibanaLegacyStart } from '../../kibana_legacy/public'; +import { SharePluginStart } from '../../share/public'; export interface TileMapConfigType { tilemap: any; @@ -61,6 +68,7 @@ export interface TileMapPluginSetupDependencies { export interface TileMapPluginStartDependencies { data: DataPublicPluginStart; kibanaLegacy: KibanaLegacyStart; + share: SharePluginStart; } export interface TileMapPluginSetup { @@ -100,10 +108,12 @@ export class TileMapPlugin implements Plugin('Core'); export const [getFormatService, setFormatService] = createGetterSetter< DataPublicPluginStart['fieldFormats'] @@ -29,6 +33,8 @@ export const [getQueryService, setQueryService] = createGetterSetter< DataPublicPluginStart['query'] >('Query'); +export const [getShareService, setShareService] = createGetterSetter('Share'); + export const [getKibanaLegacy, setKibanaLegacy] = createGetterSetter( 'KibanaLegacy' ); diff --git a/src/plugins/tile_map/public/tile_map_type.js b/src/plugins/tile_map/public/tile_map_type.js index 2b23f345f012e4..7073958a1b3184 100644 --- a/src/plugins/tile_map/public/tile_map_type.js +++ b/src/plugins/tile_map/public/tile_map_type.js @@ -25,6 +25,7 @@ import { createTileMapVisualization } from './tile_map_visualization'; import { TileMapOptions } from './components/tile_map_options'; import { supportsCssFilters } from './css_filters'; import { truncatedColorSchemas } from '../../charts/public'; +import { getDeprecationMessage } from './get_deprecation_message'; export function createTileMapTypeDefinition(dependencies) { const CoordinateMapsVisualization = createTileMapVisualization(dependencies); @@ -32,6 +33,8 @@ export function createTileMapTypeDefinition(dependencies) { return { name: 'tile_map', + isDeprecated: true, + getDeprecationMessage, title: i18n.translate('tileMap.vis.mapTitle', { defaultMessage: 'Coordinate Map', }), diff --git a/src/plugins/visualizations/public/vis_types/base_vis_type.ts b/src/plugins/visualizations/public/vis_types/base_vis_type.ts index 27a4f299c1e9ca..149146bf77e73a 100644 --- a/src/plugins/visualizations/public/vis_types/base_vis_type.ts +++ b/src/plugins/visualizations/public/vis_types/base_vis_type.ts @@ -18,9 +18,11 @@ */ import _ from 'lodash'; +import { ReactElement } from 'react'; import { VisParams, VisToExpressionAst, VisualizationControllerConstructor } from '../types'; import { TriggerContextMapping } from '../../../ui_actions/public'; import { Adapters } from '../../../inspector/public'; +import { Vis } from '../vis'; interface CommonBaseVisTypeOptions { name: string; @@ -41,6 +43,8 @@ interface CommonBaseVisTypeOptions { setup?: unknown; useCustomNoDataScreen?: boolean; inspectorAdapters?: Adapters | (() => Adapters); + isDeprecated?: boolean; + getDeprecationMessage?: (vis: Vis) => ReactElement; } interface ExpressionBaseVisTypeOptions extends CommonBaseVisTypeOptions { @@ -80,6 +84,8 @@ export class BaseVisType { useCustomNoDataScreen: boolean; inspectorAdapters?: Adapters | (() => Adapters); toExpressionAst?: VisToExpressionAst; + isDeprecated: boolean; + getDeprecationMessage?: (vis: Vis) => ReactElement; constructor(opts: BaseVisTypeOptions) { if (!opts.icon && !opts.image) { @@ -117,6 +123,8 @@ export class BaseVisType { this.useCustomNoDataScreen = opts.useCustomNoDataScreen || false; this.inspectorAdapters = opts.inspectorAdapters; this.toExpressionAst = opts.toExpressionAst; + this.isDeprecated = opts.isDeprecated || false; + this.getDeprecationMessage = opts.getDeprecationMessage; } public get schemas() { diff --git a/src/plugins/visualize/public/application/components/visualize_editor_common.tsx b/src/plugins/visualize/public/application/components/visualize_editor_common.tsx index b811936c63b140..4321d7dd1a6ca1 100644 --- a/src/plugins/visualize/public/application/components/visualize_editor_common.tsx +++ b/src/plugins/visualize/public/application/components/visualize_editor_common.tsx @@ -79,28 +79,34 @@ export const VisualizeEditorCommon = ({ /> )} {visInstance?.vis?.type?.isExperimental && } + {visInstance?.vis?.type?.isDeprecated && + visInstance?.vis?.type?.getDeprecationMessage && + visInstance.vis.type.getDeprecationMessage(visInstance?.vis)} {visInstance && (

- {'savedVis' in visInstance && visInstance.savedVis.id ? ( - - ) : ( - - )} + { + // @ts-expect-error + 'savedVis' in visInstance && visInstance.savedVis.id ? ( + + ) : ( + + ) + }

)} diff --git a/x-pack/plugins/maps/public/classes/layers/create_region_map_layer_descriptor.ts b/x-pack/plugins/maps/public/classes/layers/create_region_map_layer_descriptor.ts new file mode 100644 index 00000000000000..8bf078806cfbc1 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/layers/create_region_map_layer_descriptor.ts @@ -0,0 +1,117 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import uuid from 'uuid/v4'; +import { + AggDescriptor, + ColorDynamicOptions, + LayerDescriptor, +} from '../../../common/descriptor_types'; +import { + AGG_TYPE, + COLOR_MAP_TYPE, + FIELD_ORIGIN, + SOURCE_TYPES, + STYLE_TYPE, + VECTOR_STYLES, +} from '../../../common/constants'; +import { VectorStyle } from '../styles/vector/vector_style'; +import { EMSFileSource } from '../sources/ems_file_source'; +// @ts-ignore +import { ESGeoGridSource } from '../sources/es_geo_grid_source'; +import { VectorLayer } from './vector_layer/vector_layer'; +import { getDefaultDynamicProperties } from '../styles/vector/vector_style_defaults'; +import { NUMERICAL_COLOR_PALETTES } from '../styles/color_palettes'; +import { getJoinAggKey } from '../../../common/get_agg_key'; + +const defaultDynamicProperties = getDefaultDynamicProperties(); + +export function createAggDescriptor(metricAgg: string, metricFieldName?: string): AggDescriptor { + const aggTypeKey = Object.keys(AGG_TYPE).find((key) => { + return AGG_TYPE[key as keyof typeof AGG_TYPE] === metricAgg; + }); + const aggType = aggTypeKey ? AGG_TYPE[aggTypeKey as keyof typeof AGG_TYPE] : undefined; + + return aggType && metricFieldName + ? { type: aggType, field: metricFieldName } + : { type: AGG_TYPE.COUNT }; +} + +export function createRegionMapLayerDescriptor({ + label, + emsLayerId, + leftFieldName, + termsFieldName, + colorSchema, + indexPatternId, + indexPatternTitle, + metricAgg, + metricFieldName, +}: { + label: string; + emsLayerId?: string; + leftFieldName?: string; + termsFieldName?: string; + colorSchema: string; + indexPatternId?: string; + indexPatternTitle?: string; + metricAgg: string; + metricFieldName?: string; +}): LayerDescriptor | null { + if (!indexPatternId || !emsLayerId || !leftFieldName || !termsFieldName) { + return null; + } + + const metricsDescriptor = createAggDescriptor(metricAgg, metricFieldName); + const joinId = uuid(); + const joinKey = getJoinAggKey({ + aggType: metricsDescriptor.type, + aggFieldName: metricsDescriptor.field ? metricsDescriptor.field : '', + rightSourceId: joinId, + }); + const colorPallette = NUMERICAL_COLOR_PALETTES.find((pallette) => { + return pallette.value.toLowerCase() === colorSchema.toLowerCase(); + }); + return VectorLayer.createDescriptor({ + label, + joins: [ + { + leftField: leftFieldName, + right: { + type: SOURCE_TYPES.ES_TERM_SOURCE, + id: joinId, + indexPatternId, + indexPatternTitle: indexPatternTitle ? indexPatternTitle : indexPatternId, + term: termsFieldName, + metrics: [metricsDescriptor], + }, + }, + ], + sourceDescriptor: EMSFileSource.createDescriptor({ + id: emsLayerId, + tooltipProperties: ['name', leftFieldName], + }), + style: VectorStyle.createDescriptor({ + [VECTOR_STYLES.FILL_COLOR]: { + type: STYLE_TYPE.DYNAMIC, + options: { + ...(defaultDynamicProperties[VECTOR_STYLES.FILL_COLOR]!.options as ColorDynamicOptions), + field: { + name: joinKey, + origin: FIELD_ORIGIN.JOIN, + }, + color: colorPallette ? colorPallette.value : 'Yellow to Red', + type: COLOR_MAP_TYPE.ORDINAL, + fieldMetaOptions: { + ...(defaultDynamicProperties[VECTOR_STYLES.FILL_COLOR]!.options as ColorDynamicOptions) + .fieldMetaOptions, + isEnabled: false, + }, + }, + }, + }), + }); +} diff --git a/x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.test.ts b/x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.test.ts new file mode 100644 index 00000000000000..18e5f462bb3106 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.test.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { createAggDescriptor } from './create_tile_map_layer_descriptor'; + +describe('createAggDescriptor', () => { + test('Should allow supported metric aggs', () => { + expect(createAggDescriptor('Scaled Circle Markers', 'sum', 'bytes')).toEqual({ + type: 'sum', + field: 'bytes', + }); + }); + + test('Should fallback to count when field not provided', () => { + expect(createAggDescriptor('Scaled Circle Markers', 'sum', undefined)).toEqual({ + type: 'count', + }); + }); + + test('Should fallback to count when metric agg is not supported in maps', () => { + expect(createAggDescriptor('Scaled Circle Markers', 'top_hits', 'bytes')).toEqual({ + type: 'count', + }); + }); + + describe('heatmap', () => { + test('Should allow countable metric aggs', () => { + expect(createAggDescriptor('Heatmap', 'sum', 'bytes')).toEqual({ + type: 'sum', + field: 'bytes', + }); + }); + + test('Should fallback to count for non-countable metric aggs', () => { + expect(createAggDescriptor('Heatmap', 'avg', 'bytes')).toEqual({ + type: 'count', + }); + }); + }); +}); diff --git a/x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.ts b/x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.ts new file mode 100644 index 00000000000000..05a8620e436d54 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/layers/create_tile_map_layer_descriptor.ts @@ -0,0 +1,159 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + AggDescriptor, + ColorDynamicOptions, + LayerDescriptor, + SizeDynamicOptions, + VectorStylePropertiesDescriptor, +} from '../../../common/descriptor_types'; +import { + AGG_TYPE, + COLOR_MAP_TYPE, + FIELD_ORIGIN, + GRID_RESOLUTION, + RENDER_AS, + STYLE_TYPE, + VECTOR_STYLES, +} from '../../../common/constants'; +import { VectorStyle } from '../styles/vector/vector_style'; +// @ts-ignore +import { ESGeoGridSource } from '../sources/es_geo_grid_source'; +import { VectorLayer } from './vector_layer/vector_layer'; +// @ts-ignore +import { HeatmapLayer } from './heatmap_layer/heatmap_layer'; +import { getDefaultDynamicProperties } from '../styles/vector/vector_style_defaults'; +import { NUMERICAL_COLOR_PALETTES } from '../styles/color_palettes'; +import { getSourceAggKey } from '../../../common/get_agg_key'; +import { isMetricCountable } from '../util/is_metric_countable'; + +const defaultDynamicProperties = getDefaultDynamicProperties(); + +function isHeatmap(mapType: string): boolean { + return mapType.toLowerCase() === 'heatmap'; +} + +function getGeoGridRequestType(mapType: string): RENDER_AS { + if (isHeatmap(mapType)) { + return RENDER_AS.HEATMAP; + } + + if (mapType.toLowerCase() === 'shaded geohash grid') { + return RENDER_AS.GRID; + } + + return RENDER_AS.POINT; +} + +export function createAggDescriptor( + mapType: string, + metricAgg: string, + metricFieldName?: string +): AggDescriptor { + const aggTypeKey = Object.keys(AGG_TYPE).find((key) => { + return AGG_TYPE[key as keyof typeof AGG_TYPE] === metricAgg; + }); + const aggType = aggTypeKey ? AGG_TYPE[aggTypeKey as keyof typeof AGG_TYPE] : undefined; + + return aggType && metricFieldName && (!isHeatmap(mapType) || isMetricCountable(aggType)) + ? { type: aggType, field: metricFieldName } + : { type: AGG_TYPE.COUNT }; +} + +export function createTileMapLayerDescriptor({ + label, + mapType, + colorSchema, + indexPatternId, + geoFieldName, + metricAgg, + metricFieldName, +}: { + label: string; + mapType: string; + colorSchema: string; + indexPatternId?: string; + geoFieldName?: string; + metricAgg: string; + metricFieldName?: string; +}): LayerDescriptor | null { + if (!indexPatternId || !geoFieldName) { + return null; + } + + const metricsDescriptor = createAggDescriptor(mapType, metricAgg, metricFieldName); + const geoGridSourceDescriptor = ESGeoGridSource.createDescriptor({ + indexPatternId, + geoField: geoFieldName, + metrics: [metricsDescriptor], + requestType: getGeoGridRequestType(mapType), + resolution: GRID_RESOLUTION.MOST_FINE, + }); + + if (isHeatmap(mapType)) { + return HeatmapLayer.createDescriptor({ + label, + sourceDescriptor: geoGridSourceDescriptor, + }); + } + + const metricSourceKey = getSourceAggKey({ + aggType: metricsDescriptor.type, + aggFieldName: metricsDescriptor.field, + }); + const metricStyleField = { + name: metricSourceKey, + origin: FIELD_ORIGIN.SOURCE, + }; + + const colorPallette = NUMERICAL_COLOR_PALETTES.find((pallette) => { + return pallette.value.toLowerCase() === colorSchema.toLowerCase(); + }); + const styleProperties: VectorStylePropertiesDescriptor = { + [VECTOR_STYLES.FILL_COLOR]: { + type: STYLE_TYPE.DYNAMIC, + options: { + ...(defaultDynamicProperties[VECTOR_STYLES.FILL_COLOR]!.options as ColorDynamicOptions), + field: metricStyleField, + color: colorPallette ? colorPallette.value : 'Yellow to Red', + type: COLOR_MAP_TYPE.ORDINAL, + fieldMetaOptions: { + ...(defaultDynamicProperties[VECTOR_STYLES.FILL_COLOR]!.options as ColorDynamicOptions) + .fieldMetaOptions, + isEnabled: false, + }, + }, + }, + [VECTOR_STYLES.LINE_COLOR]: { + type: STYLE_TYPE.STATIC, + options: { + color: '#3d3d3d', + }, + }, + }; + if (mapType.toLowerCase() === 'scaled circle markers') { + styleProperties[VECTOR_STYLES.ICON_SIZE] = { + type: STYLE_TYPE.DYNAMIC, + options: { + ...(defaultDynamicProperties[VECTOR_STYLES.ICON_SIZE]!.options as SizeDynamicOptions), + maxSize: 18, + field: metricStyleField, + fieldMetaOptions: { + ...(defaultDynamicProperties[VECTOR_STYLES.ICON_SIZE]!.options as SizeDynamicOptions) + .fieldMetaOptions, + isEnabled: false, + }, + }, + }; + } + + return VectorLayer.createDescriptor({ + label, + sourceDescriptor: geoGridSourceDescriptor, + style: VectorStyle.createDescriptor(styleProperties), + }); +} diff --git a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.ts b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.ts index 85601cfc17e8f1..bdd86d78b53000 100644 --- a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.ts +++ b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.ts @@ -29,7 +29,6 @@ import { OBSERVABILITY_LAYER_TYPE } from './layer_select'; import { OBSERVABILITY_METRIC_TYPE } from './metric_select'; import { DISPLAY } from './display_select'; import { VectorStyle } from '../../../styles/vector/vector_style'; -// @ts-ignore import { EMSFileSource } from '../../../sources/ems_file_source'; // @ts-ignore import { ESGeoGridSource } from '../../../sources/es_geo_grid_source'; diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx b/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx index 5f73a9e23431b8..38e13a68437c7c 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx @@ -72,9 +72,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc async getEMSFileLayer(): Promise { const emsFileLayers = await getEmsFileLayers(); - const emsFileLayer = emsFileLayers.find( - (fileLayer) => fileLayer.getId() === this._descriptor.id - ); + const emsFileLayer = emsFileLayers.find((fileLayer) => fileLayer.hasId(this._descriptor.id)); if (!emsFileLayer) { throw new Error( i18n.translate('xpack.maps.source.emsFile.unableToFindIdErrorMessage', { diff --git a/x-pack/plugins/maps/public/lazy_load_bundle/index.ts b/x-pack/plugins/maps/public/lazy_load_bundle/index.ts index 03752a1c3e11e8..9bced75b613d72 100644 --- a/x-pack/plugins/maps/public/lazy_load_bundle/index.ts +++ b/x-pack/plugins/maps/public/lazy_load_bundle/index.ts @@ -48,6 +48,44 @@ interface LazyLoadedMapModules { registerLayerWizard: (layerWizard: LayerWizard) => void; registerSource(entry: SourceRegistryEntry): void; getIndexPatternsFromIds: (indexPatternIds: string[]) => Promise; + createTileMapLayerDescriptor: ({ + label, + mapType, + colorSchema, + indexPatternId, + geoFieldName, + metricAgg, + metricFieldName, + }: { + label: string; + mapType: string; + colorSchema: string; + indexPatternId?: string; + geoFieldName?: string; + metricAgg: string; + metricFieldName?: string; + }) => LayerDescriptor | null; + createRegionMapLayerDescriptor: ({ + label, + emsLayerId, + leftFieldName, + termsFieldName, + colorSchema, + indexPatternId, + indexPatternTitle, + metricAgg, + metricFieldName, + }: { + label: string; + emsLayerId?: string; + leftFieldName?: string; + termsFieldName?: string; + colorSchema: string; + indexPatternId?: string; + indexPatternTitle?: string; + metricAgg: string; + metricFieldName?: string; + }) => LayerDescriptor | null; } export async function lazyLoadMapModules(): Promise { @@ -72,6 +110,8 @@ export async function lazyLoadMapModules(): Promise { registerLayerWizard, registerSource, getIndexPatternsFromIds, + createTileMapLayerDescriptor, + createRegionMapLayerDescriptor, } = await import('./lazy'); resolve({ @@ -90,6 +130,8 @@ export async function lazyLoadMapModules(): Promise { registerLayerWizard, registerSource, getIndexPatternsFromIds, + createTileMapLayerDescriptor, + createRegionMapLayerDescriptor, }); }); return loadModulesPromise; diff --git a/x-pack/plugins/maps/public/lazy_load_bundle/lazy/index.ts b/x-pack/plugins/maps/public/lazy_load_bundle/lazy/index.ts index 28f5acdc17656a..782d645dc230a1 100644 --- a/x-pack/plugins/maps/public/lazy_load_bundle/lazy/index.ts +++ b/x-pack/plugins/maps/public/lazy_load_bundle/lazy/index.ts @@ -20,3 +20,5 @@ export * from '../../classes/layers/solution_layers/security'; export { registerLayerWizard } from '../../classes/layers/layer_wizard_registry'; export { registerSource } from '../../classes/sources/source_registry'; export { getIndexPatternsFromIds } from '../../index_pattern_util'; +export { createTileMapLayerDescriptor } from '../../classes/layers/create_tile_map_layer_descriptor'; +export { createRegionMapLayerDescriptor } from '../../classes/layers/create_region_map_layer_descriptor'; diff --git a/x-pack/plugins/maps/public/plugin.ts b/x-pack/plugins/maps/public/plugin.ts index 8f49598cf2a8d4..696964f0258d4b 100644 --- a/x-pack/plugins/maps/public/plugin.ts +++ b/x-pack/plugins/maps/public/plugin.ts @@ -32,7 +32,11 @@ import { HomePublicPluginSetup } from '../../../../src/plugins/home/public'; import { VisualizationsSetup } from '../../../../src/plugins/visualizations/public'; import { APP_ICON_SOLUTION, APP_ID, MAP_SAVED_OBJECT_TYPE } from '../common/constants'; import { VISUALIZE_GEO_FIELD_TRIGGER } from '../../../../src/plugins/ui_actions/public'; -import { createMapsUrlGenerator } from './url_generator'; +import { + createMapsUrlGenerator, + createRegionMapUrlGenerator, + createTileMapUrlGenerator, +} from './url_generator'; import { visualizeGeoFieldAction } from './trigger_actions/visualize_geo_field_action'; import { MapEmbeddableFactory } from './embeddable/map_embeddable_factory'; import { EmbeddableSetup } from '../../../../src/plugins/embeddable/public'; @@ -97,15 +101,18 @@ export class MapsPlugin setKibanaCommonConfig(plugins.mapsLegacy.config); setMapAppConfig(config); setKibanaVersion(this._initializerContext.env.packageInfo.version); - plugins.share.urlGenerators.registerUrlGenerator( - createMapsUrlGenerator(async () => { - const [coreStart] = await core.getStartServices(); - return { - appBasePath: coreStart.application.getUrlForApp('maps'), - useHashedUrl: coreStart.uiSettings.get('state:storeInSessionStorage'), - }; - }) - ); + + // register url generators + const getStartServices = async () => { + const [coreStart] = await core.getStartServices(); + return { + appBasePath: coreStart.application.getUrlForApp('maps'), + useHashedUrl: coreStart.uiSettings.get('state:storeInSessionStorage'), + }; + }; + plugins.share.urlGenerators.registerUrlGenerator(createMapsUrlGenerator(getStartServices)); + plugins.share.urlGenerators.registerUrlGenerator(createTileMapUrlGenerator(getStartServices)); + plugins.share.urlGenerators.registerUrlGenerator(createRegionMapUrlGenerator(getStartServices)); plugins.inspector.registerView(MapView); if (plugins.home) { diff --git a/x-pack/plugins/maps/public/url_generator.test.ts b/x-pack/plugins/maps/public/url_generator.test.ts index a44f8d952fde19..880d5a5e03b431 100644 --- a/x-pack/plugins/maps/public/url_generator.test.ts +++ b/x-pack/plugins/maps/public/url_generator.test.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import rison from 'rison-node'; + import { createMapsUrlGenerator } from './url_generator'; import { LAYER_TYPE, SOURCE_TYPES, SCALING_TYPES } from '../common/constants'; import { esFilters } from '../../../../src/plugins/data/public'; @@ -63,12 +63,11 @@ describe('visualize url generator', () => { }, }, ]; - const encodedLayers = rison.encode_array(initialLayers); const url = await generator.createUrl!({ initialLayers, }); expect(url).toMatchInlineSnapshot( - `"test/app/maps/map#/?_g=()&_a=()&initialLayers=${encodedLayers}"` + `"test/app/maps/map#/?_g=()&_a=()&initialLayers=(id%3A'13823000-99b9-11ea-9eb6-d9e8adceb647'%2CsourceDescriptor%3A(geoField%3Atest%2Cid%3A'13823000-99b9-11ea-9eb6-d9e8adceb647'%2CindexPatternId%3A'90943e30-9a47-11e8-b64d-95841ca0b247'%2Clabel%3A'Sample%20Data'%2CscalingType%3ALIMIT%2CtooltipProperties%3A!()%2Ctype%3AES_SEARCH)%2Ctype%3AVECTOR%2Cvisible%3A!t)"` ); }); diff --git a/x-pack/plugins/maps/public/url_generator.ts b/x-pack/plugins/maps/public/url_generator.ts index 3fbb361342c7ae..7f7f3f2c603273 100644 --- a/x-pack/plugins/maps/public/url_generator.ts +++ b/x-pack/plugins/maps/public/url_generator.ts @@ -16,11 +16,14 @@ import { setStateToKbnUrl } from '../../../../src/plugins/kibana_utils/public'; import { UrlGeneratorsDefinition } from '../../../../src/plugins/share/public'; import { LayerDescriptor } from '../common/descriptor_types'; import { INITIAL_LAYERS_KEY } from '../common/constants'; +import { lazyLoadMapModules } from './lazy_load_bundle'; const STATE_STORAGE_KEY = '_a'; const GLOBAL_STATE_STORAGE_KEY = '_g'; export const MAPS_APP_URL_GENERATOR = 'MAPS_APP_URL_GENERATOR'; +export const MAPS_APP_TILE_MAP_URL_GENERATOR = 'MAPS_APP_TILE_MAP_URL_GENERATOR'; +export const MAPS_APP_REGION_MAP_URL_GENERATOR = 'MAPS_APP_REGION_MAP_URL_GENERATOR'; export interface MapsUrlGeneratorState { /** @@ -59,51 +62,175 @@ export interface MapsUrlGeneratorState { hash?: boolean; } +type GetStartServices = () => Promise<{ + appBasePath: string; + useHashedUrl: boolean; +}>; + +async function createMapUrl({ + getStartServices, + mapId, + filters, + query, + refreshInterval, + timeRange, + initialLayers, + hash, +}: MapsUrlGeneratorState & { getStartServices: GetStartServices }): Promise { + const startServices = await getStartServices(); + const useHash = hash ?? startServices.useHashedUrl; + const appBasePath = startServices.appBasePath; + + const appState: { + query?: Query; + filters?: Filter[]; + vis?: unknown; + } = {}; + const queryState: QueryState = {}; + + if (query) appState.query = query; + if (filters && filters.length) + appState.filters = filters?.filter((f) => !esFilters.isFilterPinned(f)); + + if (timeRange) queryState.time = timeRange; + if (filters && filters.length) + queryState.filters = filters?.filter((f) => esFilters.isFilterPinned(f)); + if (refreshInterval) queryState.refreshInterval = refreshInterval; + + let url = `${appBasePath}/map#/${mapId || ''}`; + url = setStateToKbnUrl(GLOBAL_STATE_STORAGE_KEY, queryState, { useHash }, url); + url = setStateToKbnUrl(STATE_STORAGE_KEY, appState, { useHash }, url); + + if (initialLayers && initialLayers.length) { + // @ts-ignore + const risonEncodedInitialLayers = rison.encode_array(initialLayers); + url = `${url}&${INITIAL_LAYERS_KEY}=${encodeURIComponent(risonEncodedInitialLayers)}`; + } + + return url; +} + export const createMapsUrlGenerator = ( - getStartServices: () => Promise<{ - appBasePath: string; - useHashedUrl: boolean; - }> + getStartServices: GetStartServices ): UrlGeneratorsDefinition => ({ id: MAPS_APP_URL_GENERATOR, + createUrl: async (mapsUrlGeneratorState: MapsUrlGeneratorState): Promise => { + return createMapUrl({ ...mapsUrlGeneratorState, getStartServices }); + }, +}); + +export const createTileMapUrlGenerator = ( + getStartServices: GetStartServices +): UrlGeneratorsDefinition => ({ + id: MAPS_APP_TILE_MAP_URL_GENERATOR, + createUrl: async ({ + label, + mapType, + colorSchema, + indexPatternId, + geoFieldName, + metricAgg, + metricFieldName, + filters, + query, + timeRange, + hash, + }: { + label: string; + mapType: string; + colorSchema: string; + indexPatternId?: string; + geoFieldName?: string; + metricAgg: string; + metricFieldName?: string; + timeRange?: TimeRange; + filters?: Filter[]; + query?: Query; + hash?: boolean; + }): Promise => { + const mapModules = await lazyLoadMapModules(); + const initialLayers = []; + const tileMapLayerDescriptor = mapModules.createTileMapLayerDescriptor({ + label, + mapType, + colorSchema, + indexPatternId, + geoFieldName, + metricAgg, + metricFieldName, + }); + if (tileMapLayerDescriptor) { + initialLayers.push(tileMapLayerDescriptor); + } + + return createMapUrl({ + initialLayers, + filters, + query, + timeRange, + hash: true, + getStartServices, + }); + }, +}); + +export const createRegionMapUrlGenerator = ( + getStartServices: GetStartServices +): UrlGeneratorsDefinition => ({ + id: MAPS_APP_REGION_MAP_URL_GENERATOR, createUrl: async ({ - mapId, + label, + emsLayerId, + leftFieldName, + termsFieldName, + colorSchema, + indexPatternId, + indexPatternTitle, + metricAgg, + metricFieldName, filters, query, - refreshInterval, timeRange, - initialLayers, hash, - }: MapsUrlGeneratorState): Promise => { - const startServices = await getStartServices(); - const useHash = hash ?? startServices.useHashedUrl; - const appBasePath = startServices.appBasePath; - - const appState: { - query?: Query; - filters?: Filter[]; - vis?: unknown; - } = {}; - const queryState: QueryState = {}; - - if (query) appState.query = query; - if (filters && filters.length) - appState.filters = filters?.filter((f) => !esFilters.isFilterPinned(f)); - - if (timeRange) queryState.time = timeRange; - if (filters && filters.length) - queryState.filters = filters?.filter((f) => esFilters.isFilterPinned(f)); - if (refreshInterval) queryState.refreshInterval = refreshInterval; - - let url = `${appBasePath}/map#/${mapId || ''}`; - url = setStateToKbnUrl(GLOBAL_STATE_STORAGE_KEY, queryState, { useHash }, url); - url = setStateToKbnUrl(STATE_STORAGE_KEY, appState, { useHash }, url); - - if (initialLayers && initialLayers.length) { - // @ts-ignore - url = `${url}&${INITIAL_LAYERS_KEY}=${rison.encode_array(initialLayers)}`; + }: { + label: string; + emsLayerId?: string; + leftFieldName?: string; + termsFieldName?: string; + colorSchema: string; + indexPatternId?: string; + indexPatternTitle?: string; + metricAgg: string; + metricFieldName?: string; + timeRange?: TimeRange; + filters?: Filter[]; + query?: Query; + hash?: boolean; + }): Promise => { + const mapModules = await lazyLoadMapModules(); + const initialLayers = []; + const regionMapLayerDescriptor = mapModules.createRegionMapLayerDescriptor({ + label, + emsLayerId, + leftFieldName, + termsFieldName, + colorSchema, + indexPatternId, + indexPatternTitle, + metricAgg, + metricFieldName, + }); + if (regionMapLayerDescriptor) { + initialLayers.push(regionMapLayerDescriptor); } - return url; + return createMapUrl({ + initialLayers, + filters, + query, + timeRange, + hash: true, + getStartServices, + }); }, });