Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[alerting] Adds an alertServices mock and uses it in siem, monitoring and uptime #63489

Merged
merged 6 commits into from
Apr 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,27 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { savedObjectsClientMock } from 'src/core/server/mocks';
import { loggerMock } from 'src/core/server/logging/logger.mock';
import { getResult } from '../routes/__mocks__/request_responses';
import { rulesNotificationAlertType } from './rules_notification_alert_type';
import { buildSignalsSearchQuery } from './build_signals_query';
import { AlertInstance } from '../../../../../../../plugins/alerting/server';
import { alertsMock, AlertServicesMock } from '../../../../../../../plugins/alerting/server/mocks';
import { NotificationExecutorOptions } from './types';
jest.mock('./build_signals_query');

describe('rules_notification_alert_type', () => {
let payload: NotificationExecutorOptions;
let alert: ReturnType<typeof rulesNotificationAlertType>;
let alertInstanceMock: Record<string, jest.Mock>;
let alertInstanceFactoryMock: () => AlertInstance;
let savedObjectsClient: ReturnType<typeof savedObjectsClientMock.create>;
let logger: ReturnType<typeof loggerMock.create>;
let callClusterMock: jest.Mock;
let alertServices: AlertServicesMock;

beforeEach(() => {
alertInstanceMock = {
scheduleActions: jest.fn(),
replaceState: jest.fn(),
};
alertInstanceMock.replaceState.mockReturnValue(alertInstanceMock);
alertInstanceFactoryMock = jest.fn().mockReturnValue(alertInstanceMock);
callClusterMock = jest.fn();
savedObjectsClient = savedObjectsClientMock.create();
alertServices = alertsMock.createAlertServices();
logger = loggerMock.create();

payload = {
alertId: '1111',
services: {
savedObjectsClient,
alertInstanceFactory: alertInstanceFactoryMock,
callCluster: callClusterMock,
},
services: alertServices,
params: { ruleAlertId: '2222' },
state: {},
spaceId: '',
Expand All @@ -58,7 +43,7 @@ describe('rules_notification_alert_type', () => {

describe('executor', () => {
it('throws an error if rule alert was not found', async () => {
savedObjectsClient.get.mockResolvedValue({
alertServices.savedObjectsClient.get.mockResolvedValue({
id: 'id',
attributes: {},
type: 'type',
Expand All @@ -72,13 +57,13 @@ describe('rules_notification_alert_type', () => {

it('should call buildSignalsSearchQuery with proper params', async () => {
const ruleAlert = getResult();
savedObjectsClient.get.mockResolvedValue({
alertServices.savedObjectsClient.get.mockResolvedValue({
id: 'id',
type: 'type',
references: [],
attributes: ruleAlert,
});
callClusterMock.mockResolvedValue({
alertServices.callCluster.mockResolvedValue({
count: 0,
});

Expand All @@ -96,36 +81,38 @@ describe('rules_notification_alert_type', () => {

it('should not call alertInstanceFactory if signalsCount was 0', async () => {
const ruleAlert = getResult();
savedObjectsClient.get.mockResolvedValue({
alertServices.savedObjectsClient.get.mockResolvedValue({
id: 'id',
type: 'type',
references: [],
attributes: ruleAlert,
});
callClusterMock.mockResolvedValue({
alertServices.callCluster.mockResolvedValue({
count: 0,
});

await alert.executor(payload);

expect(alertInstanceFactoryMock).not.toHaveBeenCalled();
expect(alertServices.alertInstanceFactory).not.toHaveBeenCalled();
});

it('should call scheduleActions if signalsCount was greater than 0', async () => {
const ruleAlert = getResult();
savedObjectsClient.get.mockResolvedValue({
alertServices.savedObjectsClient.get.mockResolvedValue({
id: 'id',
type: 'type',
references: [],
attributes: ruleAlert,
});
callClusterMock.mockResolvedValue({
alertServices.callCluster.mockResolvedValue({
count: 10,
});

await alert.executor(payload);

expect(alertInstanceFactoryMock).toHaveBeenCalled();
expect(alertServices.alertInstanceFactory).toHaveBeenCalled();

const [{ value: alertInstanceMock }] = alertServices.alertInstanceFactory.mock.results;
expect(alertInstanceMock.replaceState).toHaveBeenCalledWith(
expect.objectContaining({ signals_count: 10 })
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,28 @@
*/

import { getQueryFilter, getFilter } from './get_filter';
import { savedObjectsClientMock } from 'src/core/server/mocks';
import { PartialFilter } from '../types';
import { AlertServices } from '../../../../../../../plugins/alerting/server';
import { alertsMock, AlertServicesMock } from '../../../../../../../plugins/alerting/server/mocks';

describe('get_filter', () => {
let savedObjectsClient = savedObjectsClientMock.create();
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
attributes: {
query: { query: 'host.name: linux', language: 'kuery' },
filters: [],
},
}));
let servicesMock: AlertServices = {
savedObjectsClient,
callCluster: jest.fn(),
alertInstanceFactory: jest.fn(),
};
let servicesMock: AlertServicesMock;

beforeAll(() => {
jest.resetAllMocks();
});

beforeEach(() => {
savedObjectsClient = savedObjectsClientMock.create();
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
servicesMock = alertsMock.createAlertServices();
servicesMock.savedObjectsClient.get.mockImplementation(async (type: string, id: string) => ({
id,
type,
references: [],
attributes: {
query: { query: 'host.name: linux', language: 'kuery' },
language: 'kuery',
filters: [],
},
}));
servicesMock = {
savedObjectsClient,
callCluster: jest.fn(),
alertInstanceFactory: jest.fn(),
};
});

afterEach(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,13 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { savedObjectsClientMock } from 'src/core/server/mocks';
import { DEFAULT_INDEX_KEY } from '../../../../common/constants';
import { getInputIndex } from './get_input_output_index';
import { defaultIndexPattern } from '../../../../default_index_pattern';
import { AlertServices } from '../../../../../../../plugins/alerting/server';
import { alertsMock, AlertServicesMock } from '../../../../../../../plugins/alerting/server/mocks';

describe('get_input_output_index', () => {
let savedObjectsClient = savedObjectsClientMock.create();
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
attributes: {},
}));
let servicesMock: AlertServices = {
savedObjectsClient,
callCluster: jest.fn(),
alertInstanceFactory: jest.fn(),
};
let servicesMock: AlertServicesMock;

beforeAll(() => {
jest.resetAllMocks();
Expand All @@ -30,28 +21,32 @@ describe('get_input_output_index', () => {
});

beforeEach(() => {
savedObjectsClient = savedObjectsClientMock.create();
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
servicesMock = alertsMock.createAlertServices();
servicesMock.savedObjectsClient.get.mockImplementation(async (type: string, id: string) => ({
id,
type,
references: [],
attributes: {},
}));
servicesMock = {
savedObjectsClient,
callCluster: jest.fn(),
alertInstanceFactory: jest.fn(),
};
});

describe('getInputOutputIndex', () => {
test('Returns inputIndex if inputIndex is passed in', async () => {
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
servicesMock.savedObjectsClient.get.mockImplementation(async (type: string, id: string) => ({
id,
type,
references: [],
attributes: {},
}));
const inputIndex = await getInputIndex(servicesMock, '8.0.0', ['test-input-index-1']);
expect(inputIndex).toEqual(['test-input-index-1']);
});

test('Returns a saved object inputIndex if passed in inputIndex is undefined', async () => {
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
servicesMock.savedObjectsClient.get.mockImplementation(async (type: string, id: string) => ({
id,
type,
references: [],
attributes: {
[DEFAULT_INDEX_KEY]: ['configured-index-1', 'configured-index-2'],
},
Expand All @@ -61,7 +56,10 @@ describe('get_input_output_index', () => {
});

test('Returns a saved object inputIndex if passed in inputIndex is null', async () => {
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
servicesMock.savedObjectsClient.get.mockImplementation(async (type: string, id: string) => ({
id,
type,
references: [],
attributes: {
[DEFAULT_INDEX_KEY]: ['configured-index-1', 'configured-index-2'],
},
Expand All @@ -71,7 +69,10 @@ describe('get_input_output_index', () => {
});

test('Returns a saved object inputIndex default from constants if inputIndex passed in is null and the key is also null', async () => {
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
servicesMock.savedObjectsClient.get.mockImplementation(async (type: string, id: string) => ({
id,
type,
references: [],
attributes: {
[DEFAULT_INDEX_KEY]: null,
},
Expand All @@ -81,7 +82,10 @@ describe('get_input_output_index', () => {
});

test('Returns a saved object inputIndex default from constants if inputIndex passed in is undefined and the key is also null', async () => {
savedObjectsClient.get = jest.fn().mockImplementation(() => ({
servicesMock.savedObjectsClient.get.mockImplementation(async (type: string, id: string) => ({
id,
type,
references: [],
attributes: {
[DEFAULT_INDEX_KEY]: null,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,16 @@ import {
} from './__mocks__/es_results';
import { searchAfterAndBulkCreate } from './search_after_bulk_create';
import { DEFAULT_SIGNALS_INDEX } from '../../../../common/constants';
import { savedObjectsClientMock } from 'src/core/server/mocks';
import { alertsMock, AlertServicesMock } from '../../../../../../../plugins/alerting/server/mocks';
import uuid from 'uuid';

export const mockService = {
callCluster: jest.fn(),
alertInstanceFactory: jest.fn(),
savedObjectsClient: savedObjectsClientMock.create(),
};

describe('searchAfterAndBulkCreate', () => {
let mockService: AlertServicesMock;
let inputIndexPattern: string[] = [];
beforeEach(() => {
jest.clearAllMocks();
inputIndexPattern = ['auditbeat-*'];
mockService = alertsMock.createAlertServices();
});

test('if successful with empty search results', async () => {
Expand Down Expand Up @@ -65,7 +61,7 @@ describe('searchAfterAndBulkCreate', () => {
const sampleParams = sampleRuleAlertParams(30);
const someGuids = Array.from({ length: 13 }).map(x => uuid.v4());
mockService.callCluster
.mockReturnValueOnce({
.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand All @@ -79,8 +75,8 @@ describe('searchAfterAndBulkCreate', () => {
},
],
})
.mockReturnValueOnce(repeatedSearchResultsWithSortId(3, 1, someGuids.slice(0, 3)))
.mockReturnValueOnce({
.mockResolvedValueOnce(repeatedSearchResultsWithSortId(3, 1, someGuids.slice(0, 3)))
.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand All @@ -94,8 +90,8 @@ describe('searchAfterAndBulkCreate', () => {
},
],
})
.mockReturnValueOnce(repeatedSearchResultsWithSortId(3, 1, someGuids.slice(3, 6)))
.mockReturnValueOnce({
.mockResolvedValueOnce(repeatedSearchResultsWithSortId(3, 1, someGuids.slice(3, 6)))
.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand Down Expand Up @@ -139,7 +135,7 @@ describe('searchAfterAndBulkCreate', () => {
test('if unsuccessful first bulk create', async () => {
const someGuids = Array.from({ length: 4 }).map(x => uuid.v4());
const sampleParams = sampleRuleAlertParams(10);
mockService.callCluster.mockReturnValue(sampleBulkCreateDuplicateResult);
mockService.callCluster.mockResolvedValue(sampleBulkCreateDuplicateResult);
const { success, createdSignalsCount } = await searchAfterAndBulkCreate({
someResult: repeatedSearchResultsWithSortId(4, 1, someGuids),
ruleParams: sampleParams,
Expand Down Expand Up @@ -169,7 +165,7 @@ describe('searchAfterAndBulkCreate', () => {

test('if unsuccessful iteration of searchAfterAndBulkCreate due to empty sort ids', async () => {
const sampleParams = sampleRuleAlertParams();
mockService.callCluster.mockReturnValueOnce({
mockService.callCluster.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand Down Expand Up @@ -212,7 +208,7 @@ describe('searchAfterAndBulkCreate', () => {

test('if unsuccessful iteration of searchAfterAndBulkCreate due to empty sort ids and 0 total hits', async () => {
const sampleParams = sampleRuleAlertParams();
mockService.callCluster.mockReturnValueOnce({
mockService.callCluster.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand Down Expand Up @@ -256,7 +252,7 @@ describe('searchAfterAndBulkCreate', () => {
const sampleParams = sampleRuleAlertParams(10);
const someGuids = Array.from({ length: 4 }).map(x => uuid.v4());
mockService.callCluster
.mockReturnValueOnce({
.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand All @@ -270,7 +266,7 @@ describe('searchAfterAndBulkCreate', () => {
},
],
})
.mockReturnValueOnce(sampleDocSearchResultsNoSortId());
.mockResolvedValueOnce(sampleDocSearchResultsNoSortId());
const { success, createdSignalsCount } = await searchAfterAndBulkCreate({
someResult: repeatedSearchResultsWithSortId(4, 1, someGuids),
ruleParams: sampleParams,
Expand Down Expand Up @@ -301,7 +297,7 @@ describe('searchAfterAndBulkCreate', () => {
const sampleParams = sampleRuleAlertParams(10);
const someGuids = Array.from({ length: 4 }).map(x => uuid.v4());
mockService.callCluster
.mockReturnValueOnce({
.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand All @@ -315,7 +311,7 @@ describe('searchAfterAndBulkCreate', () => {
},
],
})
.mockReturnValueOnce(sampleEmptyDocSearchResults());
.mockResolvedValueOnce(sampleEmptyDocSearchResults());
const { success, createdSignalsCount } = await searchAfterAndBulkCreate({
someResult: repeatedSearchResultsWithSortId(4, 1, someGuids),
ruleParams: sampleParams,
Expand Down Expand Up @@ -346,7 +342,7 @@ describe('searchAfterAndBulkCreate', () => {
const sampleParams = sampleRuleAlertParams(10);
const someGuids = Array.from({ length: 4 }).map(x => uuid.v4());
mockService.callCluster
.mockReturnValueOnce({
.mockResolvedValueOnce({
took: 100,
errors: false,
items: [
Expand Down
Loading