Skip to content

Commit

Permalink
Merge branch 'master' into np-licensing-functional-tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mshustov committed Dec 19, 2019
2 parents cc4943c + ba7589d commit d06e46d
Show file tree
Hide file tree
Showing 23 changed files with 205 additions and 227 deletions.
4 changes: 3 additions & 1 deletion packages/kbn-analytics/scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ run(
'--extensions',
'.ts,.js,.tsx',
...(flags.watch ? ['--watch'] : ['--quiet']),
...(flags['source-maps'] ? ['--source-maps', 'inline'] : []),
...(!flags['source-maps'] || !!process.env.CODE_COVERAGE
? []
: ['--source-maps', 'inline']),
],
wait: true,
env: {
Expand Down
4 changes: 3 additions & 1 deletion packages/kbn-i18n/scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ run(
'--extensions',
'.ts,.js,.tsx',
...(flags.watch ? ['--watch'] : ['--quiet']),
...(flags['source-maps'] ? ['--source-maps', 'inline'] : []),
...(!flags['source-maps'] || !!process.env.CODE_COVERAGE
? []
: ['--source-maps', 'inline']),
],
wait: true,
env: {
Expand Down
8 changes: 1 addition & 7 deletions test/functional/services/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,7 @@ import { Browsers } from './remote/browsers';

export async function BrowserProvider({ getService }: FtrProviderContext) {
const log = getService('log');
const { driver, browserType, consoleLog$ } = await getService('__webdriver__').init();

consoleLog$.subscribe(({ message, level }) => {
log[level === 'SEVERE' || level === 'error' ? 'error' : 'debug'](
`browser[${level}] ${message}`
);
});
const { driver, browserType } = await getService('__webdriver__').init();

const isW3CEnabled = (driver as any).executor_.w3c === true;

Expand Down
91 changes: 46 additions & 45 deletions test/functional/services/remote/remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,11 @@
import Fs from 'fs';
import { resolve } from 'path';

import * as Rx from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { logging } from 'selenium-webdriver';

import { FtrProviderContext } from '../../ftr_provider_context';
import { initWebDriver } from './webdriver';
import { Browsers } from './browsers';
import { pollForLogEntry$ } from './poll_for_log_entry';

export async function RemoteProvider({ getService }: FtrProviderContext) {
const lifecycle = getService('lifecycle');
Expand All @@ -37,7 +34,7 @@ export async function RemoteProvider({ getService }: FtrProviderContext) {
const collectCoverage: boolean = !!process.env.CODE_COVERAGE;
const coveragePrefix = 'coveragejson:';
const coverageDir = resolve(__dirname, '../../../../target/kibana-coverage/functional');
let logSubscription: undefined | Rx.Subscription;
let coverageCounter = 1;
type BrowserStorage = 'sessionStorage' | 'localStorage';

const clearBrowserStorage = async (storageType: BrowserStorage) => {
Expand All @@ -50,6 +47,14 @@ export async function RemoteProvider({ getService }: FtrProviderContext) {
}
};

const writeCoverage = (coverageJson: string) => {
const id = coverageCounter++;
const timestamp = Date.now();
const path = resolve(coverageDir, `${id}.${timestamp}.coverage.json`);
log.info('writing coverage to', path);
Fs.writeFileSync(path, JSON.stringify(JSON.parse(coverageJson), null, 2));
};

const { driver, By, until, consoleLog$ } = await initWebDriver(
log,
browserType,
Expand All @@ -69,46 +74,35 @@ export async function RemoteProvider({ getService }: FtrProviderContext) {
caps.get('chrome').chromedriverVersion
}, w3c=${isW3CEnabled}, codeCoverage=${collectCoverage}`
);

if (collectCoverage) {
let coverageCounter = 1;
// We are running xpack tests with different configs and cleanup will delete collected coverage
// del.sync(coverageDir);
Fs.mkdirSync(coverageDir, { recursive: true });

logSubscription = pollForLogEntry$(
driver,
logging.Type.BROWSER,
config.get('browser.logPollingMs'),
lifecycle.cleanup.after$
)
.pipe(
mergeMap(logEntry => {
if (logEntry.message.includes(coveragePrefix)) {
const id = coverageCounter++;
const timestamp = Date.now();
const path = resolve(coverageDir, `${id}.${timestamp}.coverage.json`);
const [, coverageJsonBase64] = logEntry.message.split(coveragePrefix);
const coverageJson = Buffer.from(coverageJsonBase64, 'base64').toString('utf8');

log.info('writing coverage to', path);
Fs.writeFileSync(path, JSON.stringify(JSON.parse(coverageJson), null, 2));

// filter out this message
return [];
}

return [logEntry];
})
)
.subscribe({
next({ message, level: { name: level } }) {
const msg = message.replace(/\\n/g, '\n');
log[level === 'SEVERE' ? 'error' : 'debug'](`browser[${level}] ${msg}`);
},
});
}
}
// code coverage is supported only in Chrome browser
if (collectCoverage) {
// We are running xpack tests with different configs and cleanup will delete collected coverage
// del.sync(coverageDir);
Fs.mkdirSync(coverageDir, { recursive: true });
}

consoleLog$
.pipe(
mergeMap(logEntry => {
if (collectCoverage && logEntry.message.includes(coveragePrefix)) {
const [, coverageJsonBase64] = logEntry.message.split(coveragePrefix);
const coverageJson = Buffer.from(coverageJsonBase64, 'base64').toString('utf8');
writeCoverage(coverageJson);

// filter out this message
return [];
}

return [logEntry];
})
)
.subscribe({
next({ message, level }) {
const msg = message.replace(/\\n/g, '\n');
log[level === 'SEVERE' ? 'error' : 'debug'](`browser[${level}] ${msg}`);
},
});

lifecycle.beforeTests.add(async () => {
// hard coded default, can be overridden per suite using `browser.setWindowSize()`
Expand Down Expand Up @@ -144,8 +138,15 @@ export async function RemoteProvider({ getService }: FtrProviderContext) {
});

lifecycle.cleanup.add(async () => {
if (logSubscription) {
await new Promise(r => logSubscription!.add(r));
// Getting the last piece of code coverage before closing browser
if (collectCoverage) {
const coverageJson = await driver
.executeScript('return window.__coverage__')
.catch(() => undefined)
.then(coverage => coverage && JSON.stringify(coverage));
if (coverageJson) {
writeCoverage(coverageJson);
}
}

await driver.quit();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ export const SignalsTableComponent = React.memo<SignalsTableComponentProps>(

const [showClearSelectionAction, setShowClearSelectionAction] = useState(false);
const [filterGroup, setFilterGroup] = useState<SignalFilterOption>(FILTER_OPEN);
const [{ browserFields, indexPatterns }] = useFetchIndexPatterns([DEFAULT_SIGNALS_INDEX]); // TODO Get from new FrankInspired XavierHook
const [{ browserFields, indexPatterns }] = useFetchIndexPatterns([
`${DEFAULT_SIGNALS_INDEX}-default`,
]); // TODO Get from new FrankInspired XavierHook
const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION);
const core = useKibanaCore();

Expand Down Expand Up @@ -265,7 +267,9 @@ export const SignalsTableComponent = React.memo<SignalsTableComponentProps>(
[createTimelineCallback, filterGroup, kbnVersion]
);

const defaultIndices = useMemo(() => [`${DEFAULT_SIGNALS_INDEX}`], [DEFAULT_SIGNALS_INDEX]);
const defaultIndices = useMemo(() => [`${DEFAULT_SIGNALS_INDEX}-default`], [
`${DEFAULT_SIGNALS_INDEX}-default`,
]);
const defaultFiltersMemo = useMemo(
() => [
...defaultFilters,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,31 @@ import { ILicense } from '../../../../../../../plugins/licensing/server';
import { licenseCheck } from '../license';

describe('license check', () => {
let mockLicense: Pick<ILicense, 'isActive' | 'isOneOf'>;
let mockLicense: Pick<ILicense, 'isActive' | 'hasAtLeast'>;

it('throws for null license', () => {
expect(licenseCheck(undefined)).toMatchSnapshot();
});

it('throws for unsupported license type', () => {
mockLicense = {
isOneOf: jest.fn().mockReturnValue(false),
hasAtLeast: jest.fn().mockReturnValue(false),
isActive: false,
};
expect(licenseCheck(mockLicense)).toMatchSnapshot();
});

it('throws for inactive license', () => {
mockLicense = {
isOneOf: jest.fn().mockReturnValue(true),
hasAtLeast: jest.fn().mockReturnValue(true),
isActive: false,
};
expect(licenseCheck(mockLicense)).toMatchSnapshot();
});

it('returns result for a valid license', () => {
mockLicense = {
isOneOf: jest.fn().mockReturnValue(true),
hasAtLeast: jest.fn().mockReturnValue(true),
isActive: true,
};
expect(licenseCheck(mockLicense)).toMatchSnapshot();
Expand Down
4 changes: 2 additions & 2 deletions x-pack/legacy/plugins/uptime/server/lib/domains/license.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export interface UMLicenseStatusResponse {
message: string;
}
export type UMLicenseCheck = (
license?: Pick<ILicense, 'isActive' | 'isOneOf'>
license?: Pick<ILicense, 'isActive' | 'hasAtLeast'>
) => UMLicenseStatusResponse;

export const licenseCheck: UMLicenseCheck = license => {
Expand All @@ -21,7 +21,7 @@ export const licenseCheck: UMLicenseCheck = license => {
statusCode: 400,
};
}
if (!license.isOneOf(['basic', 'standard', 'gold', 'platinum', 'enterprise', 'trial'])) {
if (!license.hasAtLeast('basic')) {
return {
message: 'License not supported',
statusCode: 401,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { licensingMock } from '../../../../../plugins/licensing/server/licensing.mock';
import { licensingMock } from '../../../../../plugins/licensing/server/mocks';
import { XPackInfoLicense } from './xpack_info_license';

function getXPackInfoLicense(getRawLicense) {
Expand Down
5 changes: 3 additions & 2 deletions x-pack/plugins/licensing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ chrome.navLinks.update('myPlugin', {
"requiredPlugins": ["licensing"],

// my_plugin/server/plugin.ts
import { LicensingPluginSetup, LICENSE_CHECK_STATE } from '../licensing'
import { LicensingPluginSetup, LICENSE_CHECK_STATE } from '../licensing/server'

interface SetupDeps {
licensing: LicensingPluginSetup;
Expand All @@ -77,7 +77,8 @@ class MyPlugin {
}
}

// my_plugin/client/plugin.ts
// my_plugin/public/plugin.ts
import { LicensingPluginSetup, LICENSE_CHECK_STATE } from '../licensing/public'
class MyPlugin {
setup(core: CoreSetup, deps: SetupDeps) {
deps.licensing.license$.subscribe(license => {
Expand Down
55 changes: 24 additions & 31 deletions x-pack/plugins/licensing/common/license.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import { LICENSE_CHECK_STATE } from './types';
import { licenseMock } from './licensing.mock';

describe('License', () => {
const basicLicense = licenseMock.create();
const basicExpiredLicense = licenseMock.create({ license: { status: 'expired' } });
const goldLicense = licenseMock.create({ license: { type: 'gold' } });
const enterpriseLicense = licenseMock.create({ license: { type: 'enterprise' } });
const basicLicense = licenseMock.createLicense();
const basicExpiredLicense = licenseMock.createLicense({ license: { status: 'expired' } });
const goldLicense = licenseMock.createLicense({ license: { type: 'gold' } });
const enterpriseLicense = licenseMock.createLicense({ license: { type: 'enterprise' } });

const errorMessage = 'unavailable';
const errorLicense = new License({ error: errorMessage, signature: '' });
Expand Down Expand Up @@ -50,34 +50,23 @@ describe('License', () => {
expect(unavailableLicense.isActive).toBe(false);
});

it('isBasic', () => {
expect(basicLicense.isBasic).toBe(true);
expect(goldLicense.isBasic).toBe(false);
expect(enterpriseLicense.isBasic).toBe(false);
expect(errorLicense.isBasic).toBe(false);
expect(unavailableLicense.isBasic).toBe(false);
});
it('hasAtLeast', () => {
expect(basicLicense.hasAtLeast('platinum')).toBe(false);
expect(basicLicense.hasAtLeast('gold')).toBe(false);
expect(basicLicense.hasAtLeast('basic')).toBe(true);

it('isNotBasic', () => {
expect(basicLicense.isNotBasic).toBe(false);
expect(goldLicense.isNotBasic).toBe(true);
expect(enterpriseLicense.isNotBasic).toBe(true);
expect(errorLicense.isNotBasic).toBe(false);
expect(unavailableLicense.isNotBasic).toBe(false);
});
expect(errorLicense.hasAtLeast('basic')).toBe(false);

it('isOneOf', () => {
expect(basicLicense.isOneOf('platinum')).toBe(false);
expect(basicLicense.isOneOf(['platinum'])).toBe(false);
expect(basicLicense.isOneOf(['gold', 'platinum'])).toBe(false);
expect(basicLicense.isOneOf(['platinum', 'gold'])).toBe(false);
expect(basicLicense.isOneOf(['basic', 'gold'])).toBe(true);
expect(basicLicense.isOneOf(['basic'])).toBe(true);
expect(basicLicense.isOneOf('basic')).toBe(true);
expect(unavailableLicense.hasAtLeast('basic')).toBe(false);

expect(errorLicense.isOneOf(['basic', 'gold', 'platinum'])).toBe(false);
expect(goldLicense.hasAtLeast('basic')).toBe(true);
expect(goldLicense.hasAtLeast('gold')).toBe(true);
expect(goldLicense.hasAtLeast('platinum')).toBe(false);

expect(unavailableLicense.isOneOf(['basic', 'gold', 'platinum'])).toBe(false);
expect(enterpriseLicense.hasAtLeast('basic')).toBe(true);
expect(enterpriseLicense.hasAtLeast('platinum')).toBe(true);
expect(enterpriseLicense.hasAtLeast('enterprise')).toBe(true);
expect(enterpriseLicense.hasAtLeast('trial')).toBe(false);
});

it('getUnavailableReason', () => {
Expand Down Expand Up @@ -115,9 +104,13 @@ describe('License', () => {
});

it('throws in case of unknown license type', () => {
expect(
() => basicLicense.check('ccr', 'any' as any).state
).toThrowErrorMatchingInlineSnapshot(`"\\"any\\" is not a valid license type"`);
expect(() => basicLicense.check('ccr', 'any' as any)).toThrowErrorMatchingInlineSnapshot(
`"\\"any\\" is not a valid license type"`
);

expect(() => basicLicense.hasAtLeast('any' as any)).toThrowErrorMatchingInlineSnapshot(
`"\\"any\\" is not a valid license type"`
);
});
});
});
Loading

0 comments on commit d06e46d

Please sign in to comment.