Skip to content

Commit

Permalink
add createMockConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
tsullivan committed Aug 19, 2020
1 parent 6ecd79f commit 0472d45
Show file tree
Hide file tree
Showing 19 changed files with 200 additions and 166 deletions.
4 changes: 0 additions & 4 deletions x-pack/plugins/reporting/server/config/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,6 @@ describe('Reporting Config Schema', () => {
"waitForElements": "PT30S",
}
`);

expect(
ConfigSchema.validate({ csv: { scroll: { duration: '1m' } } }).csv.scroll.duration
).toMatchInlineSnapshot(`"1m"`);
});

it('allows ByteSizeValue values for certain keys', () => {
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/reporting/server/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const KibanaServerSchema = schema.object({
}); // default values are all dynamic in createConfig$

const QueueSchema = schema.object({
indexInterval: schema.string({ defaultValue: 'week' }), // no schema.duration: used to create weekly indices
indexInterval: schema.string({ defaultValue: 'week' }),
pollEnabled: schema.boolean({ defaultValue: true }),
pollInterval: schema.number({ defaultValue: 3000 }),
pollIntervalErrorMultiplier: schema.number({ defaultValue: 10 }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,24 @@
* you may not use this file except in compliance with the Elastic License.
*/

import sinon from 'sinon';
import { ReportingConfig } from '../../';
import { ReportingCore } from '../../core';
import { createMockReportingCore } from '../../test_helpers';
import {
createMockConfig,
createMockConfigSchema,
createMockReportingCore,
} from '../../test_helpers';
import { ScheduledTaskParams } from '../../types';
import { ScheduledTaskParamsPDF } from '../printable_pdf/types';
import { getConditionalHeaders, getCustomLogo } from './';

let mockConfig: ReportingConfig;
let mockReportingPlugin: ReportingCore;

const getMockConfig = (mockConfigGet: sinon.SinonStub) => ({
get: mockConfigGet,
kbnConfig: { get: mockConfigGet },
});

beforeEach(async () => {
const mockConfigGet = sinon
.stub()
.withArgs('kibanaServer', 'hostname')
.returns('custom-hostname');
mockConfig = getMockConfig(mockConfigGet);
const reportingConfig = { kibanaServer: { hostname: 'custom-hostname' } };
const mockSchema = createMockConfigSchema(reportingConfig);
mockConfig = createMockConfig(mockSchema);
mockReportingPlugin = await createMockReportingCore(mockConfig);
});

Expand All @@ -36,7 +32,7 @@ describe('conditions', () => {
baz: 'quix',
};

const conditionalHeaders = await getConditionalHeaders({
const conditionalHeaders = getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: permittedHeaders,
config: mockConfig,
Expand All @@ -63,7 +59,7 @@ test('uses basePath from job when creating saved object service', async () => {
foo: 'bar',
baz: 'quix',
};
const conditionalHeaders = await getConditionalHeaders({
const conditionalHeaders = getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: permittedHeaders,
config: mockConfig,
Expand All @@ -84,16 +80,15 @@ test(`uses basePath from server if job doesn't have a basePath when creating sav
const mockGetSavedObjectsClient = jest.fn();
mockReportingPlugin.getSavedObjectsClient = mockGetSavedObjectsClient;

const mockConfigGet = sinon.stub();
mockConfigGet.withArgs('kibanaServer', 'hostname').returns('localhost');
mockConfigGet.withArgs('server', 'basePath').returns('/sbp');
mockConfig = getMockConfig(mockConfigGet);
const reportingConfig = { kibanaServer: { hostname: 'localhost' }, server: { basePath: '/sbp' } };
const mockSchema = createMockConfigSchema(reportingConfig);
mockConfig = createMockConfig(mockSchema);

const permittedHeaders = {
foo: 'bar',
baz: 'quix',
};
const conditionalHeaders = await getConditionalHeaders({
const conditionalHeaders = getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: permittedHeaders,
config: mockConfig,
Expand Down Expand Up @@ -134,25 +129,12 @@ test(`uses basePath from server if job doesn't have a basePath when creating sav
});

describe('config formatting', () => {
test(`lowercases server.host`, async () => {
const mockConfigGet = sinon.stub().withArgs('server', 'host').returns('COOL-HOSTNAME');
mockConfig = getMockConfig(mockConfigGet);

const conditionalHeaders = await getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: {},
config: mockConfig,
});
expect(conditionalHeaders.conditions.hostname).toEqual('cool-hostname');
});

test(`lowercases kibanaServer.hostname`, async () => {
const mockConfigGet = sinon
.stub()
.withArgs('kibanaServer', 'hostname')
.returns('GREAT-HOSTNAME');
mockConfig = getMockConfig(mockConfigGet);
const conditionalHeaders = await getConditionalHeaders({
const reportingConfig = { kibanaServer: { hostname: 'GREAT-HOSTNAME' } };
const mockSchema = createMockConfigSchema(reportingConfig);
mockConfig = createMockConfig(mockSchema);

const conditionalHeaders = getConditionalHeaders({
job: {
title: 'cool-job-bro',
type: 'csv',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { ReportingCore } from '../../core';
import { createMockReportingCore } from '../../test_helpers';
import { ReportingConfig, ReportingCore } from '../../';
import {
createMockConfig,
createMockConfigSchema,
createMockReportingCore,
} from '../../test_helpers';
import { ScheduledTaskParamsPDF } from '../printable_pdf/types';
import { getConditionalHeaders, getCustomLogo } from './';

const mockConfigGet = jest.fn().mockImplementation((key: string) => {
return 'localhost';
});
const mockConfig = { get: mockConfigGet, kbnConfig: { get: mockConfigGet } };

let mockConfig: ReportingConfig;
let mockReportingPlugin: ReportingCore;

beforeEach(async () => {
mockConfig = createMockConfig(createMockConfigSchema());
mockReportingPlugin = await createMockReportingCore(mockConfig);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
* you may not use this file except in compliance with the Elastic License.
*/

import _ from 'lodash';
import { ReportingConfig } from '../../';
import { createMockConfig } from '../../test_helpers';
import { ScheduledTaskParamsPNG } from '../png/types';
import { ScheduledTaskParamsPDF } from '../printable_pdf/types';
import { getFullUrls } from './get_full_urls';
Expand All @@ -15,12 +17,6 @@ interface FullUrlsOpts {
}

let mockConfig: ReportingConfig;
const getMockConfig = (mockConfigGet: jest.Mock<any, any>) => {
return {
get: mockConfigGet,
kbnConfig: { get: mockConfigGet },
};
};

beforeEach(() => {
const reportingConfig: Record<string, any> = {
Expand All @@ -29,10 +25,7 @@ beforeEach(() => {
'kibanaServer.protocol': 'http',
'server.basePath': '/sbp',
};
const mockConfigGet = jest.fn().mockImplementation((...keys: string[]) => {
return reportingConfig[keys.join('.') as string];
});
mockConfig = getMockConfig(mockConfigGet);
mockConfig = createMockConfig(reportingConfig);
});

const getMockJob = (base: object) => base as ScheduledTaskParamsPNG & ScheduledTaskParamsPDF;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { setFieldFormats } from '../../services';
import { createMockReportingCore } from '../../test_helpers';
import { runTaskFnFactory } from './execute_job';
import { ScheduledTaskParamsCSV } from './types';
import moment from 'moment';

const delay = (ms: number) => new Promise((resolve) => setTimeout(() => resolve(), ms));

Expand Down Expand Up @@ -73,6 +74,7 @@ describe('CSV Execute Job', function () {

beforeEach(async function () {
configGetStub = sinon.stub();
configGetStub.withArgs('queue', 'timeout').returns(moment.duration('2m'));
configGetStub.withArgs('index').returns('.reporting-foo-test');
configGetStub.withArgs('encryptionKey').returns(encryptionKey);
configGetStub.withArgs('csv', 'maxSizeBytes').returns(1024 * 1000); // 1mB
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import * as Rx from 'rxjs';
import { ReportingCore } from '../../../';
import { CancellationToken } from '../../../../common';
import { cryptoFactory, LevelLogger } from '../../../lib';
import { createMockReportingCore } from '../../../test_helpers';
import {
createMockConfig,
createMockConfigSchema,
createMockReportingCore,
} from '../../../test_helpers';
import { generatePdfObservableFactory } from '../lib/generate_pdf';
import { ScheduledTaskParamsPDF } from '../types';
import { runTaskFnFactory } from './';
Expand Down Expand Up @@ -39,20 +43,16 @@ const encryptHeaders = async (headers: Record<string, string>) => {
const getScheduledTaskParams = (baseObj: any) => baseObj as ScheduledTaskParamsPDF;

beforeEach(async () => {
const kbnConfig = {
'server.basePath': '/sbp',
};
const reportingConfig = {
'server.basePath': '/sbp',
index: '.reports-test',
encryptionKey: mockEncryptionKey,
'kibanaServer.hostname': 'localhost',
'kibanaServer.port': 5601,
'kibanaServer.protocol': 'http',
};
const mockReportingConfig = {
get: (...keys: string[]) => (reportingConfig as any)[keys.join('.')],
kbnConfig: { get: (...keys: string[]) => (kbnConfig as any)[keys.join('.')] },
};
const mockSchema = createMockConfigSchema(reportingConfig);
const mockReportingConfig = createMockConfig(mockSchema);

mockReporting = await createMockReportingCore(mockReportingConfig);

Expand All @@ -79,7 +79,7 @@ test(`passes browserTimezone to generatePdf`, async () => {
const generatePdfObservable = (await generatePdfObservableFactory(mockReporting)) as jest.Mock;
generatePdfObservable.mockReturnValue(Rx.of(Buffer.from('')));

const runTask = await runTaskFnFactory(mockReporting, getMockLogger());
const runTask = runTaskFnFactory(mockReporting, getMockLogger());
const browserTimezone = 'UTC';
await runTask(
'pdfJobId',
Expand All @@ -98,7 +98,7 @@ test(`passes browserTimezone to generatePdf`, async () => {

test(`returns content_type of application/pdf`, async () => {
const logger = getMockLogger();
const runTask = await runTaskFnFactory(mockReporting, logger);
const runTask = runTaskFnFactory(mockReporting, logger);
const encryptedHeaders = await encryptHeaders({});

const generatePdfObservable = await generatePdfObservableFactory(mockReporting);
Expand All @@ -117,7 +117,7 @@ test(`returns content of generatePdf getBuffer base64 encoded`, async () => {
const generatePdfObservable = await generatePdfObservableFactory(mockReporting);
(generatePdfObservable as jest.Mock).mockReturnValue(Rx.of({ buffer: Buffer.from(testContent) }));

const runTask = await runTaskFnFactory(mockReporting, getMockLogger());
const runTask = runTaskFnFactory(mockReporting, getMockLogger());
const encryptedHeaders = await encryptHeaders({});
const { content } = await runTask(
'pdfJobId',
Expand Down
30 changes: 16 additions & 14 deletions x-pack/plugins/reporting/server/lib/create_worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,26 @@

import * as sinon from 'sinon';
import { ReportingConfig, ReportingCore } from '../../server';
import { createMockReportingCore } from '../test_helpers';
import {
createMockConfig,
createMockConfigSchema,
createMockLevelLogger,
createMockReportingCore,
} from '../test_helpers';
import { createWorkerFactory } from './create_worker';
// @ts-ignore
import { Esqueue } from './esqueue';
// @ts-ignore
import { ClientMock } from './esqueue/__tests__/fixtures/legacy_elasticsearch';
import { ExportTypesRegistry } from './export_types_registry';

const configGetStub = sinon.stub();
configGetStub.withArgs('queue').returns({
pollInterval: 3300,
pollIntervalErrorMultiplier: 10,
});
configGetStub.withArgs('server', 'name').returns('test-server-123');
configGetStub.withArgs('server', 'uuid').returns('g9ymiujthvy6v8yrh7567g6fwzgzftzfr');
const logger = createMockLevelLogger();
const reportingConfig = {
queue: { pollInterval: 3300, pollIntervalErrorMultiplier: 10 },
server: { name: 'test-server-123', uuid: 'g9ymiujthvy6v8yrh7567g6fwzgzftzfr' },
};

const executeJobFactoryStub = sinon.stub();
const getMockLogger = sinon.stub();

const getMockExportTypesRegistry = (
exportTypes: any[] = [{ runTaskFnFactory: executeJobFactoryStub }]
Expand All @@ -39,18 +41,18 @@ describe('Create Worker', () => {
let client: ClientMock;

beforeEach(async () => {
mockConfig = { get: configGetStub, kbnConfig: { get: configGetStub } };
const mockSchema = createMockConfigSchema(reportingConfig);
mockConfig = createMockConfig(mockSchema);
mockReporting = await createMockReportingCore(mockConfig);
mockReporting.getExportTypesRegistry = () => getMockExportTypesRegistry();
// @ts-ignore over-riding config manually
mockReporting.config = mockConfig;

client = new ClientMock();
queue = new Esqueue('reporting-queue', { client });
executeJobFactoryStub.reset();
});

test('Creates a single Esqueue worker for Reporting', async () => {
const createWorker = createWorkerFactory(mockReporting, getMockLogger());
const createWorker = createWorkerFactory(mockReporting, logger);
const registerWorkerSpy = sinon.spy(queue, 'registerWorker');

await createWorker(queue);
Expand Down Expand Up @@ -82,7 +84,7 @@ Object {
{ runTaskFnFactory: executeJobFactoryStub },
]);
mockReporting.getExportTypesRegistry = () => exportTypesRegistry;
const createWorker = createWorkerFactory(mockReporting, getMockLogger());
const createWorker = createWorkerFactory(mockReporting, logger);
const registerWorkerSpy = sinon.spy(queue, 'registerWorker');

await createWorker(queue);
Expand Down
Loading

0 comments on commit 0472d45

Please sign in to comment.