Resolve credential type id and retrieve scm_type choices from OPTIONS

This commit is contained in:
Marliana Lara
2019-10-29 14:56:03 -04:00
parent 31fdd5e85c
commit ae349addfe
4 changed files with 285 additions and 92 deletions

View File

@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { bool, func, number, string } from 'prop-types'; import { bool, func, number, string, oneOfType } from 'prop-types';
import { CredentialsAPI } from '@api'; import { CredentialsAPI } from '@api';
import { Credential } from '@types'; import { Credential } from '@types';
import { mergeParams } from '@util/qs'; import { mergeParams } from '@util/qs';
@@ -46,7 +46,7 @@ function CredentialLookup({
} }
CredentialLookup.propTypes = { CredentialLookup.propTypes = {
credentialTypeId: number.isRequired, credentialTypeId: oneOfType([number, string]).isRequired,
helperTextInvalid: string, helperTextInvalid: string,
isValid: bool, isValid: bool,
label: string.isRequired, label: string.isRequired,

View File

@@ -3,11 +3,12 @@ import { act } from 'react-dom/test-utils';
import { createMemoryHistory } from 'history'; import { createMemoryHistory } from 'history';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers'; import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import ProjectAdd from './ProjectAdd'; import ProjectAdd from './ProjectAdd';
import { ProjectsAPI } from '@api'; import { ProjectsAPI, CredentialTypesAPI } from '@api';
jest.mock('@api'); jest.mock('@api');
describe('<ProjectAdd />', () => { describe('<ProjectAdd />', () => {
let wrapper;
const projectData = { const projectData = {
name: 'foo', name: 'foo',
description: 'bar', description: 'bar',
@@ -22,12 +23,68 @@ describe('<ProjectAdd />', () => {
custom_virtualenv: '/venv/custom-env', custom_virtualenv: '/venv/custom-env',
}; };
const projectOptionsResolve = {
data: {
actions: {
GET: {
scm_type: {
choices: [
['', 'Manual'],
['git', 'Git'],
['hg', 'Mercurial'],
['svn', 'Subversion'],
['insights', 'Red Hat Insights'],
],
},
},
},
},
};
const scmCredentialResolve = {
data: {
results: [
{
id: 4,
name: 'Source Control',
kind: 'scm',
},
],
},
};
const insightsCredentialResolve = {
data: {
results: [
{
id: 5,
name: 'Insights',
kind: 'insights',
},
],
},
};
beforeEach(async () => {
await ProjectsAPI.readOptions.mockImplementation(
() => projectOptionsResolve
);
await CredentialTypesAPI.read.mockImplementationOnce(
() => scmCredentialResolve
);
await CredentialTypesAPI.read.mockImplementationOnce(
() => insightsCredentialResolve
);
});
afterEach(() => { afterEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
test('initially renders successfully', () => { test('initially renders successfully', async () => {
const wrapper = mountWithContexts(<ProjectAdd />); await act(async () => {
wrapper = mountWithContexts(<ProjectAdd />);
});
expect(wrapper.length).toBe(1); expect(wrapper.length).toBe(1);
}); });
@@ -35,11 +92,10 @@ describe('<ProjectAdd />', () => {
ProjectsAPI.create.mockResolvedValueOnce({ ProjectsAPI.create.mockResolvedValueOnce({
data: { ...projectData }, data: { ...projectData },
}); });
let wrapper;
await act(async () => { await act(async () => {
wrapper = mountWithContexts(<ProjectAdd />); wrapper = mountWithContexts(<ProjectAdd />);
}); });
await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0); await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
const formik = wrapper.find('Formik').instance(); const formik = wrapper.find('Formik').instance();
const changeState = new Promise(resolve => { const changeState = new Promise(resolve => {
formik.setState( formik.setState(
@@ -57,11 +113,10 @@ describe('<ProjectAdd />', () => {
test('handleSubmit should throw an error', async () => { test('handleSubmit should throw an error', async () => {
ProjectsAPI.create.mockImplementation(() => Promise.reject(new Error())); ProjectsAPI.create.mockImplementation(() => Promise.reject(new Error()));
let wrapper;
await act(async () => { await act(async () => {
wrapper = mountWithContexts(<ProjectAdd />); wrapper = mountWithContexts(<ProjectAdd />);
}); });
await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0); await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
const formik = wrapper.find('Formik').instance(); const formik = wrapper.find('Formik').instance();
const changeState = new Promise(resolve => { const changeState = new Promise(resolve => {
formik.setState( formik.setState(
@@ -81,21 +136,26 @@ describe('<ProjectAdd />', () => {
expect(wrapper.find('ProjectAdd .formSubmitError').length).toBe(1); expect(wrapper.find('ProjectAdd .formSubmitError').length).toBe(1);
}); });
test('CardHeader close button should navigate to projects list', () => { test('CardHeader close button should navigate to projects list', async () => {
const history = createMemoryHistory(); const history = createMemoryHistory();
const wrapper = mountWithContexts(<ProjectAdd />, { await act(async () => {
context: { router: { history } }, wrapper = mountWithContexts(<ProjectAdd />, {
}).find('ProjectAdd CardHeader'); context: { router: { history } },
}).find('ProjectAdd CardHeader');
});
wrapper.find('CardCloseButton').simulate('click'); wrapper.find('CardCloseButton').simulate('click');
expect(history.location.pathname).toEqual('/projects'); expect(history.location.pathname).toEqual('/projects');
}); });
test('CardBody cancel button should navigate to projects list', () => { test('CardBody cancel button should navigate to projects list', async () => {
const history = createMemoryHistory(); const history = createMemoryHistory();
const wrapper = mountWithContexts(<ProjectAdd />, { await act(async () => {
context: { router: { history } }, wrapper = mountWithContexts(<ProjectAdd />, {
}).find('ProjectAdd CardBody'); context: { router: { history } },
wrapper.find('button[aria-label="Cancel"]').simulate('click'); });
});
await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0);
wrapper.find('ProjectAdd button[aria-label="Cancel"]').simulate('click');
expect(history.location.pathname).toEqual('/projects'); expect(history.location.pathname).toEqual('/projects');
}); });
}); });

View File

@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { withRouter, Link } from 'react-router-dom'; import { withRouter, Link } from 'react-router-dom';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
@@ -11,11 +11,14 @@ import {
Title as _Title, Title as _Title,
} from '@patternfly/react-core'; } from '@patternfly/react-core';
import AnsibleSelect from '@components/AnsibleSelect'; import AnsibleSelect from '@components/AnsibleSelect';
import ContentError from '@components/ContentError';
import ContentLoading from '@components/ContentLoading';
import FormActionGroup from '@components/FormActionGroup/FormActionGroup'; import FormActionGroup from '@components/FormActionGroup/FormActionGroup';
import FormField, { CheckboxField, FieldTooltip } from '@components/FormField'; import FormField, { CheckboxField, FieldTooltip } from '@components/FormField';
import FormRow from '@components/FormRow'; import FormRow from '@components/FormRow';
import OrganizationLookup from '@components/Lookup/OrganizationLookup'; import OrganizationLookup from '@components/Lookup/OrganizationLookup';
import CredentialLookup from '@components/Lookup/CredentialLookup'; import CredentialLookup from '@components/Lookup/CredentialLookup';
import { CredentialTypesAPI, ProjectsAPI } from '@api';
import { required } from '@util/validators'; import { required } from '@util/validators';
import styled from 'styled-components'; import styled from 'styled-components';
@@ -41,9 +44,54 @@ const Title = styled(_Title)`
function ProjectForm(props) { function ProjectForm(props) {
const { values, handleCancel, handleSubmit, i18n } = props; const { values, handleCancel, handleSubmit, i18n } = props;
const [contentError, setContentError] = useState(null);
const [hasContentLoading, setHasContentLoading] = useState(true);
const [organization, setOrganization] = useState(null); const [organization, setOrganization] = useState(null);
const [scmCredential, setScmCredential] = useState(null); const [scmTypeOptions, setScmTypeOptions] = useState(null);
const [insightsCredential, setInsightsCredential] = useState(null); const [scmCredential, setScmCredential] = useState({
typeId: null,
value: null,
});
const [insightsCredential, setInsightsCredential] = useState({
typeId: null,
value: null,
});
useEffect(() => {
async function fetchCredTypeId(params) {
try {
const {
data: {
results: [credential],
},
} = await CredentialTypesAPI.read(params);
return credential.id;
} catch (error) {
setContentError(error);
return null;
}
}
async function fetchData() {
const insightsTypeId = await fetchCredTypeId({ name: 'Insights' });
const scmTypeId = await fetchCredTypeId({ kind: 'scm' });
const {
data: {
actions: {
GET: {
scm_type: { choices },
},
},
},
} = await ProjectsAPI.readOptions();
setInsightsCredential({ typeId: insightsTypeId });
setScmCredential({ typeId: scmTypeId });
setScmTypeOptions(choices);
setHasContentLoading(false);
}
fetchData();
}, []);
const resetScmTypeFields = (value, form) => { const resetScmTypeFields = (value, form) => {
if (form.initialValues.scm_type === value) { if (form.initialValues.scm_type === value) {
@@ -67,36 +115,6 @@ function ProjectForm(props) {
}); });
}; };
const scmTypeOptions = [
{
value: '',
key: '',
label: i18n._(t`Choose a SCM Type`),
isDisabled: true,
},
{ value: 'manual', key: 'manual', label: i18n._(t`Manual`) },
{
value: 'git',
key: 'git',
label: i18n._(t`Git`),
},
{
value: 'hg',
key: 'hg',
label: i18n._(t`Mercurial`),
},
{
value: 'svn',
key: 'svn',
label: i18n._(t`Subversion`),
},
{
value: 'insights',
key: 'insights',
label: i18n._(t`Red Hat Insights`),
},
];
const gitScmTooltip = ( const gitScmTooltip = (
<span> <span>
{i18n._(t`Example URLs for GIT SCM include:`)} {i18n._(t`Example URLs for GIT SCM include:`)}
@@ -153,6 +171,14 @@ function ProjectForm(props) {
svn: i18n._(t`Revision #`), svn: i18n._(t`Revision #`),
}; };
if (hasContentLoading) {
return <ContentLoading />;
}
if (contentError) {
return <ContentError error={contentError} />;
}
return ( return (
<Form autoComplete="off" onSubmit={handleSubmit}> <Form autoComplete="off" onSubmit={handleSubmit}>
<FormRow> <FormRow>
@@ -173,23 +199,19 @@ function ProjectForm(props) {
<Field <Field
name="organization" name="organization"
validate={required(i18n._(t`Select a value for this field`), i18n)} validate={required(i18n._(t`Select a value for this field`), i18n)}
render={({ form }) => { render={({ form }) => (
return ( <OrganizationLookup
<OrganizationLookup helperTextInvalid={form.errors.organization}
helperTextInvalid={form.errors.organization} isValid={!form.touched.organization || !form.errors.organization}
isValid={ onBlur={() => form.setFieldTouched('organization')}
!form.touched.organization || !form.errors.organization onChange={value => {
} form.setFieldValue('organization', value.id);
onBlur={() => form.setFieldTouched('organization')} setOrganization(value);
onChange={value => { }}
form.setFieldValue('organization', value.id); value={organization}
setOrganization(value); required
}} />
value={organization} )}
required
/>
);
}}
/> />
<Field <Field
name="scm_type" name="scm_type"
@@ -205,7 +227,24 @@ function ProjectForm(props) {
<AnsibleSelect <AnsibleSelect
{...field} {...field}
id="scm_type" id="scm_type"
data={scmTypeOptions} data={[
{
value: '',
key: '',
label: i18n._(t`Choose an SCM Type`),
isDisabled: true,
},
...scmTypeOptions.map(option => {
if (option[1] === 'Manual') {
option[0] = 'manual';
}
return {
label: option[1],
value: option[0],
key: option[0],
};
}),
]}
onChange={(event, value) => { onChange={(event, value) => {
form.setFieldValue('scm_type', value); form.setFieldValue('scm_type', value);
resetScmTypeFields(value, form); resetScmTypeFields(value, form);
@@ -291,12 +330,15 @@ function ProjectForm(props) {
name="credential" name="credential"
render={({ form }) => ( render={({ form }) => (
<CredentialLookup <CredentialLookup
credentialTypeId={2} credentialTypeId={scmCredential.typeId}
label={i18n._(t`SCM Credential`)} label={i18n._(t`SCM Credential`)}
value={scmCredential} value={scmCredential.value}
onChange={value => { onChange={credential => {
form.setFieldValue('credential', value.id); form.setFieldValue('credential', credential.id);
setScmCredential(value); setScmCredential({
...scmCredential,
value: credential,
});
}} }}
/> />
)} )}
@@ -311,18 +353,21 @@ function ProjectForm(props) {
)} )}
render={({ form }) => ( render={({ form }) => (
<CredentialLookup <CredentialLookup
credentialTypeId={14} credentialTypeId={insightsCredential.typeId}
label={i18n._(t`Insights Credential`)} label={i18n._(t`Insights Credential`)}
helperTextInvalid={form.errors.credential} helperTextInvalid={form.errors.credential}
isValid={ isValid={
!form.touched.credential || !form.errors.credential !form.touched.credential || !form.errors.credential
} }
onBlur={() => form.setFieldTouched('credential')} onBlur={() => form.setFieldTouched('credential')}
onChange={value => { onChange={credential => {
form.setFieldValue('credential', value.id); form.setFieldValue('credential', credential.id);
setInsightsCredential(value); setInsightsCredential({
...insightsCredential,
value: credential,
});
}} }}
value={insightsCredential} value={insightsCredential.value}
required required
/> />
)} )}

View File

@@ -3,6 +3,7 @@ import { act } from 'react-dom/test-utils';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers'; import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import { sleep } from '@testUtils/testUtils'; import { sleep } from '@testUtils/testUtils';
import ProjectForm from './ProjectForm'; import ProjectForm from './ProjectForm';
import { CredentialTypesAPI, ProjectsAPI } from '@api';
jest.mock('@api'); jest.mock('@api');
@@ -22,27 +23,88 @@ describe('<ProjectAdd />', () => {
custom_virtualenv: '/venv/custom-env', custom_virtualenv: '/venv/custom-env',
}; };
beforeEach(() => { const projectOptionsResolve = {
const config = { data: {
custom_virtualenvs: ['venv/foo', 'venv/bar'], actions: {
}; GET: {
wrapper = mountWithContexts( scm_type: {
<ProjectForm handleSubmit={jest.fn()} handleCancel={jest.fn()} />, choices: [
{ ['', 'Manual'],
context: { config }, ['git', 'Git'],
} ['hg', 'Mercurial'],
['svn', 'Subversion'],
['insights', 'Red Hat Insights'],
],
},
},
},
},
};
const scmCredentialResolve = {
data: {
results: [
{
id: 4,
name: 'Source Control',
kind: 'scm',
},
],
},
};
const insightsCredentialResolve = {
data: {
results: [
{
id: 5,
name: 'Insights',
kind: 'insights',
},
],
},
};
beforeEach(async () => {
await ProjectsAPI.readOptions.mockImplementation(
() => projectOptionsResolve
);
await CredentialTypesAPI.read.mockImplementationOnce(
() => scmCredentialResolve
);
await CredentialTypesAPI.read.mockImplementationOnce(
() => insightsCredentialResolve
); );
}); });
afterEach(() => { afterEach(() => {
wrapper.unmount();
jest.clearAllMocks(); jest.clearAllMocks();
}); });
test('initially renders successfully', () => { test('initially renders successfully', async () => {
await act(async () => {
wrapper = mountWithContexts(
<ProjectForm handleSubmit={jest.fn()} handleCancel={jest.fn()} />
);
});
expect(wrapper.find('ProjectForm').length).toBe(1); expect(wrapper.find('ProjectForm').length).toBe(1);
}); });
test('new form displays primary form fields', () => { test('new form displays primary form fields', async () => {
const config = {
custom_virtualenvs: ['venv/foo', 'venv/bar'],
};
await act(async () => {
wrapper = mountWithContexts(
<ProjectForm handleSubmit={jest.fn()} handleCancel={jest.fn()} />,
{
context: { config },
}
);
});
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
expect(wrapper.find('FormGroup[label="Name"]').length).toBe(1); expect(wrapper.find('FormGroup[label="Name"]').length).toBe(1);
expect(wrapper.find('FormGroup[label="Description"]').length).toBe(1); expect(wrapper.find('FormGroup[label="Description"]').length).toBe(1);
expect(wrapper.find('FormGroup[label="Organization"]').length).toBe(1); expect(wrapper.find('FormGroup[label="Organization"]').length).toBe(1);
@@ -54,6 +116,12 @@ describe('<ProjectAdd />', () => {
}); });
test('should display scm subform when scm type select has a value', async () => { test('should display scm subform when scm type select has a value', async () => {
await act(async () => {
wrapper = mountWithContexts(
<ProjectForm handleSubmit={jest.fn()} handleCancel={jest.fn()} />
);
});
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
const formik = wrapper.find('Formik').instance(); const formik = wrapper.find('Formik').instance();
const changeState = new Promise(resolve => { const changeState = new Promise(resolve => {
formik.setState( formik.setState(
@@ -87,6 +155,7 @@ describe('<ProjectAdd />', () => {
/> />
); );
}); });
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
const form = wrapper.find('Formik'); const form = wrapper.find('Formik');
act(() => { act(() => {
wrapper.find('OrganizationLookup').invoke('onBlur')(); wrapper.find('OrganizationLookup').invoke('onBlur')();
@@ -107,6 +176,12 @@ describe('<ProjectAdd />', () => {
}); });
test('should display insights credential lookup when scm type is "Insights"', async () => { test('should display insights credential lookup when scm type is "Insights"', async () => {
await act(async () => {
wrapper = mountWithContexts(
<ProjectForm handleSubmit={jest.fn()} handleCancel={jest.fn()} />
);
});
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
const formik = wrapper.find('Formik').instance(); const formik = wrapper.find('Formik').instance();
const changeState = new Promise(resolve => { const changeState = new Promise(resolve => {
formik.setState( formik.setState(
@@ -144,6 +219,8 @@ describe('<ProjectAdd />', () => {
/> />
); );
}); });
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
const scmTypeSelect = wrapper.find( const scmTypeSelect = wrapper.find(
'FormGroup[label="SCM Type"] FormSelect' 'FormGroup[label="SCM Type"] FormSelect'
); );
@@ -183,7 +260,7 @@ describe('<ProjectAdd />', () => {
/> />
); );
}); });
await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0); await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
expect(handleSubmit).not.toHaveBeenCalled(); expect(handleSubmit).not.toHaveBeenCalled();
wrapper.find('button[aria-label="Save"]').simulate('click'); wrapper.find('button[aria-label="Save"]').simulate('click');
await sleep(1); await sleep(1);
@@ -201,9 +278,20 @@ describe('<ProjectAdd />', () => {
/> />
); );
}); });
await waitForElement(wrapper, 'EmptyStateBody', el => el.length === 0); await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
expect(handleCancel).not.toHaveBeenCalled(); expect(handleCancel).not.toHaveBeenCalled();
wrapper.find('button[aria-label="Cancel"]').invoke('onClick')(); wrapper.find('button[aria-label="Cancel"]').invoke('onClick')();
expect(handleCancel).toBeCalled(); expect(handleCancel).toBeCalled();
}); });
test('should display ContentError on throw', async () => {
CredentialTypesAPI.read = () => Promise.reject(new Error());
await act(async () => {
wrapper = mountWithContexts(
<ProjectForm handleSubmit={jest.fn()} handleCancel={jest.fn()} />
);
});
await waitForElement(wrapper, 'ContentLoading', el => el.length === 0);
expect(wrapper.find('ContentError').length).toBe(1);
});
}); });