Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
alisonelizabeth committed Sep 21, 2020
1 parent a32e5c1 commit d1b6fd2
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ const appServices = {
api: apiService,
notifications: notificationServiceMock.createSetupContract(),
history,
urlGenerators: {
getUrlGenerator: jest.fn().mockReturnValue({
createUrl: jest.fn(),
}),
},
};

export const setupEnvironment = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,20 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
]);
};

const setFetchDocumentsResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);

server.respondWith('GET', '/api/ingest_pipelines/documents/:index/:id', [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};

return {
setSimulatePipelineResponse,
setFetchDocumentsResponse,
};
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,20 @@ const createActions = (testBed: TestBed<TestSubject>) => {
});
component.update();
},

async toggleDocumentsAccordion() {
await act(async () => {
find('importDocumentsAccordion').simulate('click');
});
component.update();
},

async clickImportButton() {
await act(async () => {
find('importDocumentButton').simulate('click');
});
component.update();
},
};
};

Expand Down Expand Up @@ -234,4 +248,7 @@ type TestSubject =
| 'configurationTab'
| 'outputTab'
| 'processorOutputTabContent'
| 'importDocumentsAccordion'
| 'importDocumentButton'
| 'importDocumentError'
| string;
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,67 @@ describe('Test pipeline', () => {
expect(exists('pipelineExecutionError')).toBe(true);
expect(find('pipelineExecutionError').text()).toContain(error.message);
});

describe('Import indexed documents', () => {
test('should successfully import an index document', async () => {
const { actions, form } = testBed;

const { _index: index, _id: documentId } = DOCUMENTS[0];

httpRequestsMockHelpers.setFetchDocumentsResponse(DOCUMENTS[0]);

// Open flyout
actions.clickAddDocumentsButton();

// Open documents accordion, click run without required fields, and verify error messages
await actions.toggleDocumentsAccordion();
await actions.clickImportButton();
expect(form.getErrorsMessages()).toEqual([
'An index name is required.',
'A document ID is required.',
]);

// Add required fields, and click run
form.setInputValue('indexField.input', index);
form.setInputValue('idField.input', documentId);
await actions.clickImportButton();

// Verify request
const latestRequest = server.requests[server.requests.length - 1];
expect(latestRequest.status).toEqual(200);
expect(latestRequest.url).toEqual(`/api/ingest_pipelines/documents/${index}/${documentId}`);
});

test('should surface API errors from the request', async () => {
const { actions, form, exists, find } = testBed;

const nonExistentDoc = {
index: 'foo',
id: '1',
};

const error = {
status: 404,
error: 'Not found',
message: '[index_not_found_exception] no such index',
};

httpRequestsMockHelpers.setFetchDocumentsResponse(undefined, { body: error });

// Open flyout
actions.clickAddDocumentsButton();

// Open documents accordion, add required fields, and click run
await actions.toggleDocumentsAccordion();
form.setInputValue('indexField.input', nonExistentDoc.index);
form.setInputValue('idField.input', nonExistentDoc.id);
await actions.clickImportButton();

// Verify error rendered
expect(exists('importDocumentError')).toBe(true);
expect(find('importDocumentError').text()).toContain(error.message);
});
});
});

describe('Processors', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export const ImportDocumentForm: FunctionComponent<Props> = ({ onAddDocuments })

if (isValid) {
setIsLoadingDocument(true);
setLoadingDocumentError(undefined);

const { error, data: document } = await services.api.loadDocument(index, id);

Expand All @@ -135,7 +136,7 @@ export const ImportDocumentForm: FunctionComponent<Props> = ({ onAddDocuments })
title={i18nTexts.importDocumentErrorMessage}
color="danger"
iconType="alert"
data-test-subj="pipelineExecutionError"
data-test-subj="importDocumentError"
>
<p>{loadingDocumentError.message}</p>
</EuiCallOut>
Expand All @@ -147,18 +148,32 @@ export const ImportDocumentForm: FunctionComponent<Props> = ({ onAddDocuments })
<EuiPanel paddingSize="m">
<EuiFlexGroup>
<EuiFlexItem>
<UseField path="index" component={TextField} config={fieldsConfig.index} />
<UseField
path="index"
component={TextField}
config={fieldsConfig.index}
componentProps={{
['data-test-subj']: 'indexField',
}}
/>
</EuiFlexItem>

<EuiFlexItem>
<UseField path="id" component={TextField} config={fieldsConfig.id} />
<UseField
path="id"
component={TextField}
config={fieldsConfig.id}
componentProps={{
['data-test-subj']: 'idField',
}}
/>
</EuiFlexItem>

<EuiFlexItem grow={false}>
<EuiFormRow hasEmptyLabelSpace>
<EuiButton
onClick={submitForm}
data-test-subj="addDocumentButton"
data-test-subj="importDocumentButton"
isLoading={isLoadingDocument}
>
{i18nTexts.importDocumentButton}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const ImportDocumentsAccordion: FunctionComponent<Props> = ({ onAddDocume

return (
<EuiAccordion
id="addDocumentsAccordion"
id="importDocumentsAccordion"
buttonContent={i18nTexts.addDocumentsButton}
paddingSize="s"
data-test-subj="importDocumentsAccordion"
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 React, { useRef, FunctionComponent, useCallback } from 'react';
import React, { FunctionComponent, useCallback } from 'react';
import { FormattedMessage } from '@kbn/i18n/react';
import { i18n } from '@kbn/i18n';

Expand Down Expand Up @@ -37,18 +37,13 @@ export const DocumentsTab: FunctionComponent<Props> = ({
}) => {
const { services } = useKibana();

const documentsStateRef = useRef<any[]>([]);

const [, formatData] = useFormData({ form });

const onAddDocumentHandler = useCallback(
(document) => {
const existingDocuments = [...documentsStateRef.current, document];
documentsStateRef.current = existingDocuments;

const { documents } = formatData();
const { documents: existingDocuments } = formatData();

form.reset({ defaultValue: { documents: [...existingDocuments, ...documents] } });
form.reset({ defaultValue: { documents: [...existingDocuments, document] } });
},
[form, formatData]
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ const API_BASE_PATH = '/api/ingest_pipelines';
export default function ({ getService }: FtrProviderContext) {
const supertest = getService('supertest');

const { createPipeline, deletePipeline, cleanupPipelines } = registerEsHelpers(getService);
const {
createPipeline,
deletePipeline,
cleanupPipelines,
createIndex,
deleteIndex,
} = registerEsHelpers(getService);

describe('Pipelines', function () {
after(async () => {
Expand Down Expand Up @@ -445,5 +451,59 @@ export default function ({ getService }: FtrProviderContext) {
expect(body.docs?.length).to.eql(2);
});
});

describe('Fetch documents', () => {
const INDEX = 'test_index';
const DOCUMENT_ID = '1';
const DOCUMENT = {
name: 'John Doe',
};

before(async () => {
// Create an index with a document that can be used to test GET request
try {
await createIndex({ id: DOCUMENT_ID, index: INDEX, body: DOCUMENT });
} catch (err) {
// eslint-disable-next-line no-console
console.log('[Setup error] Error creating index');
throw err;
}
});

after(async () => {
// Clean up index created
try {
await deleteIndex(INDEX);
} catch (err) {
// eslint-disable-next-line no-console
console.log('[Cleanup error] Error deleting index');
throw err;
}
});

it('should return a document', async () => {
const uri = `${API_BASE_PATH}/documents/${INDEX}/${DOCUMENT_ID}`;

const { body } = await supertest.get(uri).set('kbn-xsrf', 'xxx').expect(200);

expect(body).to.eql({
_index: INDEX,
_id: DOCUMENT_ID,
_source: DOCUMENT,
});
});

it('should return an error if the document does not exist', async () => {
const uri = `${API_BASE_PATH}/documents/${INDEX}/2`; // Document 2 does not exist

const { body } = await supertest.get(uri).set('kbn-xsrf', 'xxx').expect(404);

expect(body).to.eql({
error: 'Not Found',
message: 'Not Found',
statusCode: 404,
});
});
});
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,19 @@ export const registerEsHelpers = (getService: FtrProviderContext['getService'])
console.log(`[Cleanup error] Error deleting ES resources: ${err.message}`);
});

const createIndex = (index: { index: string; id: string; body: object }) => {
return es.index(index);
};

const deleteIndex = (indexName: string) => {
return es.indices.delete({ index: indexName });
};

return {
createPipeline,
deletePipeline,
cleanupPipelines,
createIndex,
deleteIndex,
};
};

0 comments on commit d1b6fd2

Please sign in to comment.