Skip to content

Commit

Permalink
Added server api tests for event log service (#63540)
Browse files Browse the repository at this point in the history
* Added server api tests for event log service

* fixed tests

* fixed type check issue

* Fixed failing tests

* fixed jest tests

* Fixed due to comments

* Removed flackiness tests

* fixed type check error

* Fixed func test
  • Loading branch information
YulNaumenko committed Apr 17, 2020
1 parent d26b213 commit 62bc699
Show file tree
Hide file tree
Showing 6 changed files with 520 additions and 54 deletions.
1 change: 1 addition & 0 deletions x-pack/plugins/event_log/server/es/context.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const createContextMock = () => {
initialize: jest.fn(),
waitTillReady: jest.fn(),
esAdapter: clusterClientAdapterMock.create(),
initialized: true,
};
return mock;
};
Expand Down
95 changes: 95 additions & 0 deletions x-pack/plugins/event_log/server/es/context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* 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 { createEsContext } from './context';
import { ClusterClient, Logger } from '../../../../../src/core/server';
import { elasticsearchServiceMock, loggingServiceMock } from '../../../../../src/core/server/mocks';
jest.mock('../lib/../../../../package.json', () => ({
version: '1.2.3',
}));
type EsClusterClient = Pick<jest.Mocked<ClusterClient>, 'callAsInternalUser' | 'asScoped'>;

let logger: Logger;
let clusterClient: EsClusterClient;

beforeEach(() => {
logger = loggingServiceMock.createLogger();
clusterClient = elasticsearchServiceMock.createClusterClient();
});

describe('createEsContext', () => {
test('should return is ready state as falsy if not initialized', () => {
const context = createEsContext({
logger,
clusterClientPromise: Promise.resolve(clusterClient),
indexNameRoot: 'test0',
});

expect(context.initialized).toBeFalsy();

context.initialize();
expect(context.initialized).toBeTruthy();
});

test('should return esNames', () => {
const context = createEsContext({
logger,
clusterClientPromise: Promise.resolve(clusterClient),
indexNameRoot: 'test-index',
});

const esNames = context.esNames;
expect(esNames).toStrictEqual({
base: 'test-index',
alias: 'test-index-event-log-1.2.3',
ilmPolicy: 'test-index-event-log-policy',
indexPattern: 'test-index-event-log-*',
indexPatternWithVersion: 'test-index-event-log-1.2.3-*',
indexTemplate: 'test-index-event-log-1.2.3-template',
initialIndex: 'test-index-event-log-1.2.3-000001',
});
});

test('should return exist false for esAdapter ilm policy, index template and alias before initialize', async () => {
const context = createEsContext({
logger,
clusterClientPromise: Promise.resolve(clusterClient),
indexNameRoot: 'test1',
});
clusterClient.callAsInternalUser.mockResolvedValue(false);

const doesAliasExist = await context.esAdapter.doesAliasExist(context.esNames.alias);
expect(doesAliasExist).toBeFalsy();

const doesIndexTemplateExist = await context.esAdapter.doesIndexTemplateExist(
context.esNames.indexTemplate
);
expect(doesIndexTemplateExist).toBeFalsy();
});

test('should return exist true for esAdapter ilm policy, index template and alias after initialize', async () => {
const context = createEsContext({
logger,
clusterClientPromise: Promise.resolve(clusterClient),
indexNameRoot: 'test2',
});
clusterClient.callAsInternalUser.mockResolvedValue(true);
context.initialize();

const doesIlmPolicyExist = await context.esAdapter.doesIlmPolicyExist(
context.esNames.ilmPolicy
);
expect(doesIlmPolicyExist).toBeTruthy();

const doesAliasExist = await context.esAdapter.doesAliasExist(context.esNames.alias);
expect(doesAliasExist).toBeTruthy();

const doesIndexTemplateExist = await context.esAdapter.doesIndexTemplateExist(
context.esNames.indexTemplate
);
expect(doesIndexTemplateExist).toBeTruthy();
});
});
3 changes: 2 additions & 1 deletion x-pack/plugins/event_log/server/es/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface EsContext {
esAdapter: IClusterClientAdapter;
initialize(): void;
waitTillReady(): Promise<boolean>;
initialized: boolean;
}

export interface EsError {
Expand All @@ -41,7 +42,7 @@ class EsContextImpl implements EsContext {
public readonly esNames: EsNames;
public esAdapter: IClusterClientAdapter;
private readonly readySignal: ReadySignal<boolean>;
private initialized: boolean;
public initialized: boolean;

constructor(params: EsContextCtorParams) {
this.logger = params.logger;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
/*
* 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 {
RequestHandlerContext,
KibanaRequest,
KibanaResponseFactory,
IKibanaResponse,
IRouter,
Logger,
RouteValidationResultFactory,
} from 'kibana/server';
import { IEventLogService, IEventLogger } from '../../../../../plugins/event_log/server';
import { IValidatedEvent } from '../../../../../plugins/event_log/server/types';

export const logEventRoute = (router: IRouter, eventLogger: IEventLogger, logger: Logger) => {
router.post(
{
path: `/api/log_event_fixture/{id}/_log`,
validate: {
// removed validation as schema is currently broken in tests
// blocked by: https://github.com/elastic/kibana/issues/61652
params: (value: any, { ok }: RouteValidationResultFactory) => ok(value),
body: (value: any, { ok }: RouteValidationResultFactory) => ok(value),
},
},
async function(
context: RequestHandlerContext,
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
const { id } = req.params as { id: string };
const event: IValidatedEvent = req.body;
logger.info(`test fixture: log event: ${id} ${JSON.stringify(event)}`);
try {
await context.core.savedObjects.client.get('event_log_test', id);
logger.info(`found existing saved object`);
} catch (ex) {
logger.info(`log event error: ${ex}`);
await context.core.savedObjects.client.create('event_log_test', {}, { id });
logger.info(`created saved object`);
}
eventLogger.logEvent(event);
logger.info(`logged`);
return res.ok({});
}
);
};

export const registerProviderActionsRoute = (
router: IRouter,
eventLogService: IEventLogService,
logger: Logger
) => {
router.post(
{
path: '/api/log_event_fixture/{provider}/_registerProviderActions',
validate: {
body: value => ({ value }),
params: (value: any, { ok }: RouteValidationResultFactory) => ok(value),
},
options: { authRequired: false },
},
(context, request, response) => {
const { provider } = request.params as { provider: string };
const actions = request.body;
try {
logger.info(
`test register provider actions: ${provider}, actions: ${JSON.stringify(actions)}`
);

eventLogService.registerProviderActions(provider, actions);
logger.info(`registered`);
} catch (e) {
return response.badRequest({ body: e });
}
return response.ok({ body: {} });
}
);
};

export const isProviderActionRegisteredRoute = (
router: IRouter,
eventLogService: IEventLogService,
logger: Logger
) => {
router.get(
{
path: `/api/log_event_fixture/{provider}/{action}/_isProviderActionRegistered`,
validate: {
params: (value: any, { ok }: RouteValidationResultFactory) => ok(value),
},
},
async function(
context: RequestHandlerContext,
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
const { provider, action } = req.params as { provider: string; action: string };
logger.info(`test provider actions is registered: ${provider} for action: ${action}`);

return res.ok({
body: {
isProviderActionRegistered: eventLogService.isProviderActionRegistered(provider, action),
},
});
}
);
};

export const getProviderActionsRoute = (
router: IRouter,
eventLogService: IEventLogService,
logger: Logger
) => {
router.get(
{
path: `/api/log_event_fixture/{provider}/getProviderActions`,
validate: {
params: (value: any, { ok }: RouteValidationResultFactory) => ok(value),
},
},
async function(
context: RequestHandlerContext,
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
const { provider } = req.params as { provider: string };

logger.info(`test if get all provider actions is registered`);
return res.ok({
body: { actions: [...(eventLogService.getProviderActions().get(provider) ?? [])] },
});
}
);
};

export const getLoggerRoute = (
router: IRouter,
eventLogService: IEventLogService,
logger: Logger
) => {
router.get(
{
path: `/api/log_event_fixture/getEventLogger/{event}`,
validate: {
params: (value: any, { ok }: RouteValidationResultFactory) => ok(value),
},
},
async function(
context: RequestHandlerContext,
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
const { event } = req.params as { event: string };
logger.info(`test get event logger for event: ${event}`);

return res.ok({
body: { eventLogger: eventLogService.getLogger({ event: { provider: event } }) },
});
}
);
};

export const isIndexingEntriesRoute = (
router: IRouter,
eventLogService: IEventLogService,
logger: Logger
) => {
router.get(
{
path: `/api/log_event_fixture/isIndexingEntries`,
validate: {},
},
async function(
context: RequestHandlerContext,
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
logger.info(`test if event logger is indexing entries`);
return res.ok({ body: { isIndexingEntries: eventLogService.isIndexingEntries() } });
}
);
};

export const isEventLogServiceEnabledRoute = (
router: IRouter,
eventLogService: IEventLogService,
logger: Logger
) => {
router.get(
{
path: `/api/log_event_fixture/isEventLogServiceEnabled`,
validate: {},
},
async function(
context: RequestHandlerContext,
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
logger.info(`test if event logger is enabled`);
return res.ok({ body: { isEnabled: eventLogService.isEnabled() } });
}
);
};

export const isEventLogServiceLoggingEntriesRoute = (
router: IRouter,
eventLogService: IEventLogService,
logger: Logger
) => {
router.get(
{
path: `/api/log_event_fixture/isEventLogServiceLoggingEntries`,
validate: {},
},
async function(
context: RequestHandlerContext,
req: KibanaRequest<any, any, any, any>,
res: KibanaResponseFactory
): Promise<IKibanaResponse<any>> {
logger.info(`test if event logger is logging entries`);
return res.ok({ body: { isLoggingEntries: eventLogService.isLoggingEntries() } });
}
);
};
Loading

0 comments on commit 62bc699

Please sign in to comment.