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

add more rule_registry unit tests #120323

Merged
merged 8 commits into from
Dec 7, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
@@ -0,0 +1,24 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import type { PublicMethodsOf } from '@kbn/utility-types';
import { ResourceInstaller } from './resource_installer';

type Schema = PublicMethodsOf<ResourceInstaller>;
export type ResourceInstallerMock = jest.Mocked<Schema>;
const createResourceInstallerMock = () => {
return {
installCommonResources: jest.fn(() => Promise.resolve()),
installIndexLevelResources: jest.fn(),
installAndUpdateNamespaceLevelResources: jest.fn(),
};
};

export const resourceInstallerMock: {
create: () => ResourceInstallerMock;
} = {
create: createResourceInstallerMock,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { loggerMock } from '@kbn/logging/mocks';
import { RuleDataService } from './rule_data_plugin_service';
import { elasticsearchServiceMock } from 'src/core/server/mocks';
import { AlertConsumers } from '@kbn/rule-data-utils/alerts_as_data_rbac';

import { Dataset } from './index_options';
jest.mock('../rule_data_client/rule_data_client');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@weltenwort Before I open this PR for review, I would like your input regarding what's the recommended way to mock a class constructor. Later in my test I do

expect(
        jest.requireMock('../rule_data_client/rule_data_client').RuleDataClient
      ).toHaveBeenCalled();

and it works. I am just wondering if there's a better way.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like there already is a mock implementation of the rule data client in

export const createRuleDataClientMock = (
indexName: string = '.alerts-security.alerts'
): RuleDataClientMock => {
const bulk = jest.fn();
const search = jest.fn();
const getDynamicIndexPattern = jest.fn();
return {
indexName,
kibanaVersion: '7.16.0',
isWriteEnabled: jest.fn(() => true),
// @ts-ignore 4.3.5 upgrade
getReader: jest.fn((_options?: { namespace?: string }) => ({
search,
getDynamicIndexPattern,
})),
getWriter: jest.fn(() => ({
bulk,
})),
};
};
. So maybe you could use that like this:

jest.mock('../rule_data_client/rule_data_client', () => ({
  RuleDataClient: jest.fn().mockImplementation(createRuleDataClientMock),
}));

And further down I saw you're calling jest.mock again. Instead I would recommend to just import the RuleDataClient normally. The jest mocking mechanism will make sure it's replaced with the mock.

Similarly, it looks like you're calling jest.mock('./resource_installer', () => { inside of a test case. I think it's safer to only call jest.mock on the top level of the file as it needs to be evaluated before any import.


describe('ruleDataPluginService', () => {
beforeEach(() => {
jest.resetAllMocks();
});

describe('isRegistrationContextDisabled', () => {
it('should return true', async () => {
const mockClusterClient = elasticsearchServiceMock.createElasticsearchClient();
const getClusterClient = jest.fn(() => Promise.resolve(mockClusterClient));

const ruleDataService = new RuleDataService({
logger: loggerMock.create(),
getClusterClient,
kibanaVersion: '8.1.0',
isWriteEnabled: true,
disabledRegistrationContexts: ['observability.logs'],
isWriterCacheEnabled: true,
});
expect(ruleDataService.isRegistrationContextDisabled('observability.logs')).toBe(true);
});

it('should return false', async () => {
const mockClusterClient = elasticsearchServiceMock.createElasticsearchClient();
const getClusterClient = jest.fn(() => Promise.resolve(mockClusterClient));

const ruleDataService = new RuleDataService({
logger: loggerMock.create(),
getClusterClient,
kibanaVersion: '8.1.0',
isWriteEnabled: true,
disabledRegistrationContexts: ['observability.logs'],
isWriterCacheEnabled: true,
});
expect(ruleDataService.isRegistrationContextDisabled('observability.apm')).toBe(false);
});
});

describe('isWriteEnabled', () => {
it('should return true', async () => {
const mockClusterClient = elasticsearchServiceMock.createElasticsearchClient();
const getClusterClient = jest.fn(() => Promise.resolve(mockClusterClient));

const ruleDataService = new RuleDataService({
logger: loggerMock.create(),
getClusterClient,
kibanaVersion: '8.1.0',
isWriteEnabled: true,
disabledRegistrationContexts: ['observability.logs'],
isWriterCacheEnabled: true,
});

expect(ruleDataService.isWriteEnabled('observability.logs')).toBe(false);
});
});
describe('initializeService', () => {
it('calls ResourceInstaller', async () => {
const mockClusterClient = elasticsearchServiceMock.createElasticsearchClient();
const getClusterClient = jest.fn(() => Promise.resolve(mockClusterClient));

new RuleDataService({
logger: loggerMock.create(),
getClusterClient,
kibanaVersion: '8.1.0',
isWriteEnabled: true,
disabledRegistrationContexts: ['observability.logs'],
isWriterCacheEnabled: true,
});

expect(jest.requireMock('./resource_installer').ResourceInstaller).toHaveBeenCalled();
});
});

describe('initializeIndex', () => {
it('calls RuleDataClient', async () => {
const mockClusterClient = elasticsearchServiceMock.createElasticsearchClient();
const getClusterClient = jest.fn(() => Promise.resolve(mockClusterClient));
jest.mock('./resource_installer', () => {
return function () {
return { installCommonResources: () => {} };
};
});

const ruleDataService = new RuleDataService({
logger: loggerMock.create(),
getClusterClient,
kibanaVersion: '8.1.0',
isWriteEnabled: true,
disabledRegistrationContexts: ['observability.logs'],
isWriterCacheEnabled: true,
});
const indexOptions = {
feature: AlertConsumers.LOGS,
registrationContext: 'observability.logs',
dataset: Dataset.alerts,
componentTemplateRefs: [],
componentTemplates: [
{
name: 'mappings',
},
],
};
await ruleDataService.initializeService();
await ruleDataService.initializeIndex(indexOptions);
expect(
jest.requireMock('../rule_data_client/rule_data_client').RuleDataClient
).toHaveBeenCalled();
});
});
});