Skip to content

Commit

Permalink
add mocks and test example
Browse files Browse the repository at this point in the history
  • Loading branch information
pgayvallet committed May 10, 2023
1 parent eec0fc1 commit 2464efd
Show file tree
Hide file tree
Showing 12 changed files with 293 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* Side Public License, v 1.
*/

import type { PublicMethodsOf } from '@kbn/utility-types';
import type {
ISavedObjectTypeRegistry,
ISavedObjectsSpacesExtension,
Expand All @@ -17,6 +18,8 @@ import { SavedObjectsErrorHelpers } from '@kbn/core-saved-objects-server';
import { normalizeNamespace } from '../utils';
import type { CreatePointInTimeFinderFn } from '../../point_in_time_finder';

export type ICommonHelper = PublicMethodsOf<CommonHelper>;

export class CommonHelper {
private registry: ISavedObjectTypeRegistry;
private spaceExtension?: ISavedObjectsSpacesExtension;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
* Side Public License, v 1.
*/

import type { PublicMethodsOf } from '@kbn/utility-types';
import { SavedObject } from '@kbn/core-saved-objects-common/src/server_types';
import type {
AuthorizationTypeMap,
ISavedObjectsSecurityExtension,
ISavedObjectsEncryptionExtension,
} from '@kbn/core-saved-objects-server';

export type IEncryptionHelper = PublicMethodsOf<EncryptionHelper>;

export class EncryptionHelper {
private securityExtension?: ISavedObjectsSecurityExtension;
private encryptionExtension?: ISavedObjectsEncryptionExtension;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
* Side Public License, v 1.
*/

import type { CommonHelper } from './common';
import type { EncryptionHelper } from './encryption';
import type { ValidationHelper } from './validation';
import type { PreflightCheckHelper } from './preflight_check';
import type { SerializerHelper } from './serializer';
import type { ICommonHelper } from './common';
import type { IEncryptionHelper } from './encryption';
import type { IValidationHelper } from './validation';
import type { IPreflightCheckHelper } from './preflight_check';
import type { ISerializerHelper } from './serializer';

export { CommonHelper } from './common';
export { EncryptionHelper } from './encryption';
Expand All @@ -23,9 +23,9 @@ export {
} from './preflight_check';

export interface RepositoryHelpers {
common: CommonHelper;
encryption: EncryptionHelper;
validation: ValidationHelper;
preflight: PreflightCheckHelper;
serializer: SerializerHelper;
common: ICommonHelper;
encryption: IEncryptionHelper;
validation: IValidationHelper;
preflight: IPreflightCheckHelper;
serializer: ISerializerHelper;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* Side Public License, v 1.
*/

import type { PublicMethodsOf } from '@kbn/utility-types';
import { isNotFoundFromUnsupportedServer } from '@kbn/core-elasticsearch-server-internal';
import type {
ISavedObjectTypeRegistry,
Expand All @@ -28,6 +29,8 @@ import {
PreflightCheckForCreateObject,
} from '../internals/preflight_check_for_create';

export type IPreflightCheckHelper = PublicMethodsOf<PreflightCheckHelper>;

export class PreflightCheckHelper {
private registry: ISavedObjectTypeRegistry;
private serializer: ISavedObjectsSerializer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import { omit } from 'lodash';
import type { PublicMethodsOf } from '@kbn/utility-types';
import type {
ISavedObjectTypeRegistry,
ISavedObjectsSerializer,
Expand All @@ -18,6 +19,8 @@ import {
SavedObjectsRawDocParseOptions,
} from '@kbn/core-saved-objects-server';

export type ISerializerHelper = PublicMethodsOf<SerializerHelper>;

export class SerializerHelper {
private registry: ISavedObjectTypeRegistry;
private serializer: ISavedObjectsSerializer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* Side Public License, v 1.
*/

import type { PublicMethodsOf } from '@kbn/utility-types';
import type { Logger } from '@kbn/logging';
import type { ISavedObjectTypeRegistry } from '@kbn/core-saved-objects-server';
import { SavedObjectsTypeValidator } from '@kbn/core-saved-objects-base-server-internal';
Expand All @@ -15,6 +16,8 @@ import {
} from '@kbn/core-saved-objects-server';
import { ALL_NAMESPACES_STRING } from '@kbn/core-saved-objects-utils-server';

export type IValidationHelper = PublicMethodsOf<ValidationHelper>;

export class ValidationHelper {
private registry: ISavedObjectTypeRegistry;
private logger: Logger;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { apiContextMock, ApiExecutionContextMock } from '../../mocks';
import { createType } from '../../test_helpers/repository.test.common';
import { performRemoveReferencesTo } from './remove_references_to';

const fooType = createType('foo', {});
const barType = createType('bar', {});

describe('performRemoveReferencesTo', () => {
const namespace = 'some_ns';
const indices = ['.kib_1', '.kib_2'];
let apiExecutionContext: ApiExecutionContextMock;

beforeEach(() => {
apiExecutionContext = apiContextMock.create();
apiExecutionContext.registry.registerType(fooType);
apiExecutionContext.registry.registerType(barType);

apiExecutionContext.helpers.common.getCurrentNamespace.mockImplementation(
(space) => space ?? 'default'
);
apiExecutionContext.helpers.common.getIndicesForTypes.mockReturnValue(indices);
});

describe('with all extensions enabled', () => {
it('calls getCurrentNamespace with the correct parameters', async () => {
await performRemoveReferencesTo(
{ type: 'foo', id: 'id', options: { namespace } },
apiExecutionContext
);

const commonHelper = apiExecutionContext.helpers.common;
expect(commonHelper.getCurrentNamespace).toHaveBeenCalledTimes(1);
expect(commonHelper.getCurrentNamespace).toHaveBeenLastCalledWith(namespace);
});

it('calls authorizeRemoveReferences with the correct parameters', async () => {
await performRemoveReferencesTo(
{ type: 'foo', id: 'id', options: { namespace } },
apiExecutionContext
);

const securityExt = apiExecutionContext.extensions.securityExtension!;
expect(securityExt.authorizeRemoveReferences).toHaveBeenCalledTimes(1);
expect(securityExt.authorizeRemoveReferences).toHaveBeenLastCalledWith({
namespace,
object: { type: 'foo', id: 'id' },
});
});

it('calls client.updateByQuery with the correct parameters', async () => {
await performRemoveReferencesTo(
{ type: 'foo', id: 'id', options: { namespace, refresh: false } },
apiExecutionContext
);

const client = apiExecutionContext.client;
expect(client.updateByQuery).toHaveBeenCalledTimes(1);
expect(client.updateByQuery).toHaveBeenLastCalledWith(
{
refresh: false,
index: indices,
body: expect.any(Object),
},
{ ignore: [404], meta: true }
);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { loggerMock, MockedLogger } from '@kbn/logging-mocks';
import {
elasticsearchClientMock,
ElasticsearchClientMock,
} from '@kbn/core-elasticsearch-client-server-mocks';
import { SavedObjectTypeRegistry } from '@kbn/core-saved-objects-base-server-internal';
import { serializerMock } from '@kbn/core-saved-objects-base-server-mocks';
import type { ApiExecutionContext } from '../lib/apis/types';
import { apiHelperMocks, RepositoryHelpersMock } from './api_helpers.mocks';
import { savedObjectsExtensionsMock } from './saved_objects_extensions.mock';
import { createMigratorMock, KibanaMigratorMock } from './migrator.mock';

export type ApiExecutionContextMock = Pick<ApiExecutionContext, 'allowedTypes' | 'mappings'> & {
registry: SavedObjectTypeRegistry;
helpers: RepositoryHelpersMock;
extensions: ReturnType<typeof savedObjectsExtensionsMock.create>;
client: ElasticsearchClientMock;
serializer: ReturnType<typeof serializerMock.create>;
migrator: KibanaMigratorMock;
logger: MockedLogger;
};

const createApiExecutionContextMock = (): ApiExecutionContextMock => {
return {
registry: new SavedObjectTypeRegistry(),
helpers: apiHelperMocks.create(),
extensions: savedObjectsExtensionsMock.create(),
client: elasticsearchClientMock.createElasticsearchClient(),
serializer: serializerMock.create(),
migrator: createMigratorMock(),
logger: loggerMock.create(),
allowedTypes: ['foo', 'bar'],
mappings: { properties: { mockMappings: { type: 'text' } } },
};
};

export const apiContextMock = {
create: createApiExecutionContextMock,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import type { PublicMethodsOf } from '@kbn/utility-types';
import type {
CommonHelper,
EncryptionHelper,
ValidationHelper,
PreflightCheckHelper,
SerializerHelper,
} from '../lib/apis/helpers';

export type CommonHelperMock = jest.Mocked<PublicMethodsOf<CommonHelper>>;

const createCommonHelperMock = (): CommonHelperMock => {
const mock: CommonHelperMock = {
createPointInTimeFinder: jest.fn(),
getIndexForType: jest.fn(),
getIndicesForTypes: jest.fn(),
getCurrentNamespace: jest.fn(),
getValidId: jest.fn(),
};

mock.getIndexForType.mockReturnValue('.kibana_mock');
mock.getIndicesForTypes.mockReturnValue(['.kibana_mock']);
mock.getCurrentNamespace.mockImplementation((space) => space ?? 'default');
mock.getValidId.mockReturnValue('valid-id');

return mock;
};

export type EncryptionHelperMock = jest.Mocked<PublicMethodsOf<EncryptionHelper>>;

const createEncryptionHelperMock = (): EncryptionHelperMock => {
const mock: EncryptionHelperMock = {
optionallyEncryptAttributes: jest.fn(),
optionallyDecryptAndRedactSingleResult: jest.fn(),
optionallyDecryptAndRedactBulkResult: jest.fn(),
};

return mock;
};

export type ValidationHelperMock = jest.Mocked<PublicMethodsOf<ValidationHelper>>;

const createValidationHelperMock = (): ValidationHelperMock => {
const mock: ValidationHelperMock = {
validateInitialNamespaces: jest.fn(),
validateObjectNamespaces: jest.fn(),
validateObjectForCreate: jest.fn(),
validateOriginId: jest.fn(),
};

return mock;
};

export type SerializerHelperMock = jest.Mocked<PublicMethodsOf<SerializerHelper>>;

const createSerializerHelperMock = (): SerializerHelperMock => {
const mock: SerializerHelperMock = {
rawToSavedObject: jest.fn(),
};

return mock;
};

export type PreflightCheckHelperMock = jest.Mocked<PublicMethodsOf<PreflightCheckHelper>>;

const createPreflightCheckHelperMock = (): PreflightCheckHelperMock => {
const mock: PreflightCheckHelperMock = {
preflightCheckForCreate: jest.fn(),
preflightCheckForBulkDelete: jest.fn(),
preflightCheckNamespaces: jest.fn(),
preflightCheckForUpsertAliasConflict: jest.fn(),
};

return mock;
};

export interface RepositoryHelpersMock {
common: CommonHelperMock;
encryption: EncryptionHelperMock;
validation: ValidationHelperMock;
preflight: PreflightCheckHelperMock;
serializer: SerializerHelperMock;
}

const createRepositoryHelpersMock = (): RepositoryHelpersMock => {
return {
common: createCommonHelperMock(),
encryption: createEncryptionHelperMock(),
validation: createValidationHelperMock(),
preflight: createPreflightCheckHelperMock(),
serializer: createSerializerHelperMock(),
};
};

export const apiHelperMocks = {
create: createRepositoryHelpersMock,
createCommonHelper: createCommonHelperMock,
createEncryptionHelper: createEncryptionHelperMock,
createValidationHelper: createValidationHelperMock,
createSerializerHelper: createSerializerHelperMock,
createPreflightCheckHelper: createPreflightCheckHelperMock,
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,13 @@
export { savedObjectsPointInTimeFinderMock } from './point_in_time_finder.mock';
export { kibanaMigratorMock } from './kibana_migrator.mock';
export { repositoryMock } from './repository.mock';
export {
apiHelperMocks,
type SerializerHelperMock,
type CommonHelperMock,
type ValidationHelperMock,
type EncryptionHelperMock,
type RepositoryHelpersMock,
type PreflightCheckHelperMock,
} from './api_helpers.mocks';
export { apiContextMock, type ApiExecutionContextMock } from './api_context.mock';
Original file line number Diff line number Diff line change
@@ -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
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import type { IKibanaMigrator } from '@kbn/core-saved-objects-base-server-internal';

export type KibanaMigratorMock = jest.Mocked<IKibanaMigrator>;

export const createMigratorMock = (kibanaVersion: string = '8.0.0'): KibanaMigratorMock => {
return {
kibanaVersion,
runMigrations: jest.fn(),
prepareMigrations: jest.fn(),
getStatus$: jest.fn(),
getActiveMappings: jest.fn(),
migrateDocument: jest.fn(),
};
};
Loading

0 comments on commit 2464efd

Please sign in to comment.