Skip to content

Commit

Permalink
fix export response
Browse files Browse the repository at this point in the history
  • Loading branch information
angorayc committed Jul 1, 2020
1 parent f4e7f14 commit a7b9cc7
Show file tree
Hide file tree
Showing 6 changed files with 170 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,15 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { shallow } from 'enzyme';
import { shallow, mount } from 'enzyme';
import React from 'react';
import { GenericDownloaderComponent } from './index';
import { GenericDownloaderComponent, ExportSelectedData } from './index';
import { errorToToaster } from '../toasters';

jest.mock('../toasters', () => ({
useStateToaster: jest.fn(() => [jest.fn(), jest.fn()]),
errorToToaster: jest.fn(),
}));

describe('GenericDownloader', () => {
test('renders correctly against snapshot', () => {
Expand All @@ -19,4 +25,16 @@ describe('GenericDownloader', () => {
);
expect(wrapper).toMatchSnapshot();
});

test('show toaster with correct error message if error occurrs', () => {
mount(
<GenericDownloaderComponent
filename={'export_rules.ndjson'}
onExportSuccess={jest.fn()}
exportSelectedData={('some error' as unknown) as ExportSelectedData}
ids={['123']}
/>
);
expect((errorToToaster as jest.Mock).mock.calls[0][0].title).toEqual('Failed to export data…');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import { i18n } from '@kbn/i18n';

export const EXPORT_FAILURE = i18n.translate(
'xpack.securitySolution.detectionEngine.rules.components.ruleDownloader.exportFailureTitle',
'xpack.securitySolution.detectionEngine.rules.components.genericDownloader.exportFailureTitle',
{
defaultMessage: 'Failed to export rules…',
defaultMessage: 'Failed to export data…',
}
);
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import * as api from './api';
import { KibanaServices } from '../../common/lib/kibana';
import { TimelineType, TimelineStatus } from '../../../common/types/timeline';
import { TIMELINE_DRAFT_URL, TIMELINE_URL } from '../../../common/constants';
import { ImportDataProps } from '../../alerts/containers/detection_engine/rules/types';

jest.mock('../../common/lib/kibana', () => {
return {
KibanaServices: { get: jest.fn() },
KibanaServices: { get: jest.fn(() => ({ http: { fetch: jest.fn() } })) },
};
});

Expand Down Expand Up @@ -190,6 +191,7 @@ describe('persistTimeline', () => {

afterAll(() => {
jest.resetAllMocks();
jest.resetModules();
});

test('it should create a draft timeline if given status is draft and timelineId is null', () => {
Expand Down Expand Up @@ -506,3 +508,143 @@ describe('persistTimeline', () => {
});
});
});

describe('importTimelines', () => {
const fileToImport = { fileToImport: {} } as ImportDataProps;
const fetchMock = jest.fn();

beforeAll(() => {
jest.resetAllMocks();

(KibanaServices.get as jest.Mock).mockReturnValue({
http: {
fetch: fetchMock,
},
});
api.importTimelines(fileToImport);
});

afterAll(() => {
jest.resetAllMocks();
jest.resetModules();
});

test('should pass correct args to KibanaServices - url', () => {
expect(fetchMock.mock.calls[0][0]).toEqual('/api/timeline/_import');
});

test('should pass correct args to KibanaServices - args', () => {
expect(JSON.stringify(fetchMock.mock.calls[0][1])).toEqual(
JSON.stringify({
method: 'POST',
headers: { 'Content-Type': undefined },
body: new FormData(),
signal: undefined,
})
);
});
});

describe('exportSelectedTimeline', () => {
const ids = ['123', 'abc'];
const fetchMock = jest.fn();

beforeAll(() => {
jest.resetAllMocks();

(KibanaServices.get as jest.Mock).mockReturnValue({
http: {
fetch: fetchMock,
},
});
api.exportSelectedTimeline({
filename: 'timelines_export.ndjson',
ids,
signal: {} as AbortSignal,
});
});

afterAll(() => {
jest.resetAllMocks();
jest.resetModules();
});

test('should pass correct args to KibanaServices', () => {
expect(fetchMock).toBeCalledWith('/api/timeline/_export', {
body: JSON.stringify({ ids }),
method: 'POST',
query: { file_name: 'timelines_export.ndjson' },
signal: {},
});
});
});

describe('getDraftTimeline', () => {
const timelineType = { timelineType: TimelineType.default };
const getMock = jest.fn();

beforeAll(() => {
jest.resetAllMocks();

(KibanaServices.get as jest.Mock).mockReturnValue({
http: {
get: getMock,
},
});
api.getDraftTimeline(timelineType);
});

afterAll(() => {
jest.resetAllMocks();
jest.resetModules();
});

test('should pass correct args to KibanaServices', () => {
expect(getMock).toBeCalledWith('/api/timeline/_draft', {
query: timelineType,
});
});
});

describe('cleanDraftTimeline', () => {
const postMock = jest.fn();

beforeEach(() => {
jest.resetAllMocks();

(KibanaServices.get as jest.Mock).mockReturnValue({
http: {
post: postMock,
},
});
});

afterEach(() => {
jest.resetAllMocks();
jest.resetModules();
});

test('should pass correct args to KibanaServices - timeline', () => {
const args = { timelineType: TimelineType.default };

api.cleanDraftTimeline(args);

expect(postMock).toBeCalledWith('/api/timeline/_draft', {
body: JSON.stringify(args),
});
});

test('should pass correct args to KibanaServices - timeline template', () => {
const args = {
timelineType: TimelineType.template,
templateTimelineId: 'test-123',
templateTimelineVersion: 1,
};

api.cleanDraftTimeline(args);

expect(postMock).toBeCalledWith('/api/timeline/_draft', {
body: JSON.stringify(args),
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ export const persistTimeline = async ({

export const importTimelines = async ({
fileToImport,
signal,
}: ImportDataProps): Promise<ImportDataResponse> => {
const formData = new FormData();
formData.append('file', fileToImport);
Expand All @@ -140,24 +141,24 @@ export const importTimelines = async ({
method: 'POST',
headers: { 'Content-Type': undefined },
body: formData,
signal,
});
};

export const exportSelectedTimeline: ExportSelectedData = async ({
export const exportSelectedTimeline: ExportSelectedData = ({
filename = `timelines_export.ndjson`,
ids = [],
signal,
}): Promise<Blob> => {
const body = ids.length > 0 ? JSON.stringify({ ids }) : undefined;
const response = await KibanaServices.get().http.fetch<{ body: Blob }>(`${TIMELINE_EXPORT_URL}`, {
return KibanaServices.get().http.fetch<Blob>(`${TIMELINE_EXPORT_URL}`, {
method: 'POST',
body,
query: {
file_name: filename,
},
signal,
});

return response.body;
};

export const getDraftTimeline = async ({
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/ja-JP.json
Original file line number Diff line number Diff line change
Expand Up @@ -14200,7 +14200,6 @@
"xpack.securitySolution.detectionEngine.rules.allRules.tabs.rules": "ルール",
"xpack.securitySolution.detectionEngine.rules.backOptionsHeader": "検出に戻る",
"xpack.securitySolution.detectionEngine.rules.components.ruleActionsOverflow.allActionsTitle": "すべてのアクション",
"xpack.securitySolution.detectionEngine.rules.components.ruleDownloader.exportFailureTitle": "ルールをエクスポートできませんでした...",
"xpack.securitySolution.detectionEngine.rules.continueButtonTitle": "続行",
"xpack.securitySolution.detectionEngine.rules.create.successfullyCreatedRuleTitle": "{ruleName}が作成されました",
"xpack.securitySolution.detectionEngine.rules.defineRuleTitle": "ルールの定義",
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -14205,7 +14205,6 @@
"xpack.securitySolution.detectionEngine.rules.allRules.tabs.rules": "规则",
"xpack.securitySolution.detectionEngine.rules.backOptionsHeader": "返回到检测",
"xpack.securitySolution.detectionEngine.rules.components.ruleActionsOverflow.allActionsTitle": "所有操作",
"xpack.securitySolution.detectionEngine.rules.components.ruleDownloader.exportFailureTitle": "无法导出规则……",
"xpack.securitySolution.detectionEngine.rules.continueButtonTitle": "继续",
"xpack.securitySolution.detectionEngine.rules.create.successfullyCreatedRuleTitle": "{ruleName} 已创建",
"xpack.securitySolution.detectionEngine.rules.defineRuleTitle": "定义规则",
Expand Down

0 comments on commit a7b9cc7

Please sign in to comment.