Merge pull request #6950 from AlexSCorey/6903-InventorySourceSyncAll

Adds Inventory Source Sync Button

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot]
2020-05-18 14:18:27 +00:00
committed by GitHub
6 changed files with 233 additions and 95 deletions

View File

@@ -88,6 +88,12 @@ class Inventories extends InstanceGroupsMixin(Base) {
`How did you get here? Source not found for Inventory ID: ${inventoryId}` `How did you get here? Source not found for Inventory ID: ${inventoryId}`
); );
} }
syncAllSources(inventoryId) {
return this.http.post(
`${this.baseUrl}${inventoryId}/update_inventory_sources/`
);
}
} }
export default Inventories; export default Inventories;

View File

@@ -2,7 +2,12 @@ import React, { useCallback, useEffect } from 'react';
import { useParams, useLocation } from 'react-router-dom'; import { useParams, useLocation } from 'react-router-dom';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import useRequest, { useDeleteItems } from '../../../util/useRequest'; import { Button, Tooltip } from '@patternfly/react-core';
import useRequest, {
useDeleteItems,
useDismissableError,
} from '../../../util/useRequest';
import { getQSConfig, parseQueryString } from '../../../util/qs'; import { getQSConfig, parseQueryString } from '../../../util/qs';
import { InventoriesAPI, InventorySourcesAPI } from '../../../api'; import { InventoriesAPI, InventorySourcesAPI } from '../../../api';
import PaginatedDataList, { import PaginatedDataList, {
@@ -28,7 +33,7 @@ function InventorySourceList({ i18n }) {
const { const {
isLoading, isLoading,
error, error: fetchError,
result: { sources, sourceCount, sourceChoices, sourceChoicesOptions }, result: { sources, sourceCount, sourceChoices, sourceChoicesOptions },
request: fetchSources, request: fetchSources,
} = useRequest( } = useRequest(
@@ -38,7 +43,6 @@ function InventorySourceList({ i18n }) {
InventoriesAPI.readSources(id, params), InventoriesAPI.readSources(id, params),
InventorySourcesAPI.readOptions(), InventorySourcesAPI.readOptions(),
]); ]);
return { return {
sources: results[0].data.results, sources: results[0].data.results,
sourceCount: results[0].data.count, sourceCount: results[0].data.count,
@@ -49,8 +53,23 @@ function InventorySourceList({ i18n }) {
{ {
sources: [], sources: [],
sourceCount: 0, sourceCount: 0,
sourceChoices: [],
} }
); );
const canSyncSources =
sources.length > 0 &&
sources.every(source => source.summary_fields.user_capabilities.start);
const {
isLoading: isSyncAllLoading,
error: syncAllError,
request: syncAll,
} = useRequest(
useCallback(async () => {
if (canSyncSources) {
await InventoriesAPI.syncAllSources(id);
}
}, [id, canSyncSources])
);
useEffect(() => { useEffect(() => {
fetchSources(); fetchSources();
@@ -80,6 +99,7 @@ function InventorySourceList({ i18n }) {
qsConfig: QS_CONFIG, qsConfig: QS_CONFIG,
} }
); );
const { error: syncError, dismissError } = useDismissableError(syncAllError);
const handleDelete = async () => { const handleDelete = async () => {
await handleDeleteSources(); await handleDeleteSources();
@@ -92,8 +112,8 @@ function InventorySourceList({ i18n }) {
return ( return (
<> <>
<PaginatedDataList <PaginatedDataList
contentError={error || deletionError} contentError={fetchError}
hasContentLoading={isLoading || isDeleteLoading} hasContentLoading={isLoading || isDeleteLoading || isSyncAllLoading}
items={sources} items={sources}
itemCount={sourceCount} itemCount={sourceCount}
pluralizedItemName={i18n._(t`Inventory Sources`)} pluralizedItemName={i18n._(t`Inventory Sources`)}
@@ -117,6 +137,23 @@ function InventorySourceList({ i18n }) {
itemsToDelete={selected} itemsToDelete={selected}
pluralizedItemName={i18n._(t`Inventory Sources`)} pluralizedItemName={i18n._(t`Inventory Sources`)}
/>, />,
...(canSyncSources
? [
<Tooltip
key="update"
content={i18n._(t`Sync all sources`)}
position="top"
>
<Button
onClick={syncAll}
aria-label={i18n._(t`Sync all`)}
variant="secondary"
>
{i18n._(t`Sync all`)}
</Button>
</Tooltip>,
]
: []),
]} ]}
/> />
)} )}
@@ -139,15 +176,28 @@ function InventorySourceList({ i18n }) {
); );
}} }}
/> />
{syncError && (
<AlertModal
aria-label={i18n._(t`Sync error`)}
isOpen={syncError}
variant="error"
title={i18n._(t`Error!`)}
onClose={dismissError}
>
{i18n._(t`Failed to sync some or all inventory sources.`)}
<ErrorDetail error={syncError} />
</AlertModal>
)}
{deletionError && ( {deletionError && (
<AlertModal <AlertModal
aria-label={i18n._(t`Delete Error`)} aria-label={i18n._(t`Delete error`)}
isOpen={deletionError} isOpen={deletionError}
variant="error" variant="error"
title={i18n._(t`Error!`)} title={i18n._(t`Error!`)}
onClose={clearDeletionError} onClose={clearDeletionError}
> >
{i18n._(t`Failed to delete one or more Inventory Sources.`)} {i18n._(t`Failed to delete one or more inventory sources.`)}
<ErrorDetail error={deletionError} /> <ErrorDetail error={deletionError} />
</AlertModal> </AlertModal>
)} )}

View File

@@ -7,39 +7,57 @@ import {
mountWithContexts, mountWithContexts,
waitForElement, waitForElement,
} from '../../../../testUtils/enzymeHelpers'; } from '../../../../testUtils/enzymeHelpers';
import InventorySourceList from './InventorySourceList'; import InventorySourceList from './InventorySourceList';
jest.mock('../../../api/models/InventorySources'); jest.mock('../../../api/models/InventorySources');
jest.mock('../../../api/models/Inventories'); jest.mock('../../../api/models/Inventories');
jest.mock('../../../api/models/InventoryUpdates'); jest.mock('../../../api/models/InventoryUpdates');
const sources = {
data: {
results: [
{
id: 1,
name: 'Source Foo',
status: '',
source: 'ec2',
url: '/api/v2/inventory_sources/56/',
summary_fields: {
user_capabilities: {
edit: true,
delete: true,
start: true,
schedule: true,
},
},
},
{
id: 2,
name: 'Source Bar',
status: '',
source: 'scm',
url: '/api/v2/inventory_sources/57/',
summary_fields: {
user_capabilities: {
edit: true,
delete: true,
start: true,
schedule: true,
},
},
},
],
count: 1,
},
};
describe('<InventorySourceList />', () => { describe('<InventorySourceList />', () => {
let wrapper; let wrapper;
let history; let history;
beforeEach(async () => { beforeEach(async () => {
InventoriesAPI.readSources.mockResolvedValue({ InventoriesAPI.readSources.mockResolvedValue(sources);
data: {
results: [
{
id: 1,
name: 'Source Foo',
status: '',
source: 'ec2',
url: '/api/v2/inventory_sources/56/',
summary_fields: {
user_capabilities: {
edit: true,
delete: true,
start: true,
schedule: true,
},
},
},
],
count: 1,
},
});
InventorySourcesAPI.readOptions.mockResolvedValue({ InventorySourcesAPI.readOptions.mockResolvedValue({
data: { data: {
actions: { actions: {
@@ -81,9 +99,11 @@ describe('<InventorySourceList />', () => {
wrapper.unmount(); wrapper.unmount();
jest.clearAllMocks(); jest.clearAllMocks();
}); });
test('should mount properly', async () => { test('should mount properly', async () => {
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0); await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
}); });
test('api calls should be made on mount', async () => { test('api calls should be made on mount', async () => {
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0); await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
expect(InventoriesAPI.readSources).toHaveBeenCalledWith('1', { expect(InventoriesAPI.readSources).toHaveBeenCalledWith('1', {
@@ -94,15 +114,23 @@ describe('<InventorySourceList />', () => {
}); });
expect(InventorySourcesAPI.readOptions).toHaveBeenCalled(); expect(InventorySourcesAPI.readOptions).toHaveBeenCalled();
}); });
test('source data should render properly', async () => { test('source data should render properly', async () => {
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0); await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
expect(wrapper.find('PFDataListCell[aria-label="name"]').text()).toBe( expect(
'Source Foo' wrapper
); .find("DataListItem[aria-labelledby='check-action-1']")
expect(wrapper.find('PFDataListCell[aria-label="type"]').text()).toBe( .find('PFDataListCell[aria-label="name"]')
'EC2' .text()
); ).toBe('Source Foo');
expect(
wrapper
.find("DataListItem[aria-labelledby='check-action-1']")
.find('PFDataListCell[aria-label="type"]')
.text()
).toBe('EC2');
}); });
test('add button is not disabled and delete button is disabled', async () => { test('add button is not disabled and delete button is disabled', async () => {
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0); await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
const addButton = wrapper.find('ToolbarAddButton').find('Link'); const addButton = wrapper.find('ToolbarAddButton').find('Link');
@@ -118,7 +146,7 @@ describe('<InventorySourceList />', () => {
expect(deleteButton.prop('isDisabled')).toBe(true); expect(deleteButton.prop('isDisabled')).toBe(true);
await act(async () => await act(async () =>
wrapper.find('DataListCheck').prop('onChange')({ id: 1 }) wrapper.find('DataListCheck#select-source-1').prop('onChange')({ id: 1 })
); );
wrapper.update(); wrapper.update();
expect(wrapper.find('input#select-source-1').prop('checked')).toBe(true); expect(wrapper.find('input#select-source-1').prop('checked')).toBe(true);
@@ -134,6 +162,7 @@ describe('<InventorySourceList />', () => {
); );
expect(InventorySourcesAPI.destroy).toHaveBeenCalledWith(1); expect(InventorySourcesAPI.destroy).toHaveBeenCalledWith(1);
}); });
test('should throw error after deletion failure', async () => { test('should throw error after deletion failure', async () => {
InventorySourcesAPI.destroy.mockRejectedValue( InventorySourcesAPI.destroy.mockRejectedValue(
new Error({ new Error({
@@ -151,7 +180,7 @@ describe('<InventorySourceList />', () => {
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0); await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
await act(async () => await act(async () =>
wrapper.find('DataListCheck').prop('onChange')({ id: 1 }) wrapper.find('DataListCheck#select-source-1').prop('onChange')({ id: 1 })
); );
wrapper.update(); wrapper.update();
@@ -164,10 +193,11 @@ describe('<InventorySourceList />', () => {
wrapper.find('Button[aria-label="confirm delete"]').prop('onClick')() wrapper.find('Button[aria-label="confirm delete"]').prop('onClick')()
); );
wrapper.update(); wrapper.update();
expect(wrapper.find("AlertModal[aria-label='Delete Error']").length).toBe( expect(wrapper.find("AlertModal[aria-label='Delete error']").length).toBe(
1 1
); );
}); });
test('displays error after unsuccessful read sources fetch', async () => { test('displays error after unsuccessful read sources fetch', async () => {
InventorySourcesAPI.readOptions.mockRejectedValue( InventorySourcesAPI.readOptions.mockRejectedValue(
new Error({ new Error({
@@ -225,32 +255,52 @@ describe('<InventorySourceList />', () => {
expect(wrapper.find('ContentError').length).toBe(1); expect(wrapper.find('ContentError').length).toBe(1);
}); });
test('displays error after unsuccessful sync all button', async () => {
InventoriesAPI.syncAllSources.mockRejectedValue(
new Error({
response: {
config: {
method: 'post',
url: '/api/v2/inventories/',
},
data: 'An error occurred',
status: 403,
},
})
);
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
await act(async () =>
wrapper.find('Button[aria-label="Sync all"]').prop('onClick')()
);
expect(InventoriesAPI.syncAllSources).toBeCalled();
wrapper.update();
expect(wrapper.find("AlertModal[aria-label='Sync error']").length).toBe(1);
});
test('should render sync all button and make api call to start sync for all', async () => {
await waitForElement(
wrapper,
'InventorySourceListItem',
el => el.length > 0
);
const syncAllButton = wrapper.find('Button[aria-label="Sync all"]');
expect(syncAllButton.length).toBe(1);
await act(async () => syncAllButton.prop('onClick')());
expect(InventoriesAPI.syncAllSources).toBeCalled();
expect(InventoriesAPI.readSources).toBeCalled();
});
}); });
describe('<InventorySourceList /> RBAC testing', () => { describe('<InventorySourceList /> RBAC testing', () => {
test('should not render add button', async () => { test('should not render add button', async () => {
InventoriesAPI.readSources.mockResolvedValue({ sources.data.results[0].summary_fields.user_capabilities = {
data: { edit: true,
results: [ delete: true,
{ start: true,
id: 1, schedule: true,
name: 'Source Foo', };
status: '', InventoriesAPI.readSources.mockResolvedValue(sources);
source: 'ec2',
url: '/api/v2/inventory_sources/56/',
summary_fields: {
user_capabilities: {
edit: true,
delete: true,
start: true,
schedule: true,
},
},
},
],
count: 1,
},
});
InventorySourcesAPI.readOptions.mockResolvedValue({ InventorySourcesAPI.readOptions.mockResolvedValue({
data: { data: {
actions: { actions: {
@@ -296,4 +346,44 @@ describe('<InventorySourceList /> RBAC testing', () => {
newWrapper.unmount(); newWrapper.unmount();
jest.clearAllMocks(); jest.clearAllMocks();
}); });
test('should not render Sync All button', async () => {
sources.data.results[0].summary_fields.user_capabilities = {
edit: true,
delete: true,
start: false,
schedule: true,
};
InventoriesAPI.readSources.mockResolvedValue(sources);
let newWrapper;
const history = createMemoryHistory({
initialEntries: ['/inventories/inventory/2/sources'],
});
await act(async () => {
newWrapper = mountWithContexts(
<Route path="/inventories/:inventoryType/:id/sources">
<InventorySourceList />
</Route>,
{
context: {
router: {
history,
route: {
location: { search: '' },
match: { params: { id: 2 } },
},
},
},
}
);
});
await waitForElement(
newWrapper,
'InventorySourceList',
el => el.length > 0
);
expect(newWrapper.find('Button[aria-label="Sync All"]').length).toBe(0);
newWrapper.unmount();
jest.clearAllMocks();
});
}); });

View File

@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React from 'react';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
@@ -25,8 +25,6 @@ function InventorySourceListItem({
detailUrl, detailUrl,
label, label,
}) { }) {
const [isSyncLoading, setIsSyncLoading] = useState(false);
const generateLastJobTooltip = job => { const generateLastJobTooltip = job => {
return ( return (
<> <>
@@ -50,7 +48,6 @@ function InventorySourceListItem({
<DataListItem aria-labelledby={`check-action-${source.id}`}> <DataListItem aria-labelledby={`check-action-${source.id}`}>
<DataListItemRow> <DataListItemRow>
<DataListCheck <DataListCheck
isDisabled={isSyncLoading}
id={`select-source-${source.id}`} id={`select-source-${source.id}`}
checked={isSelected} checked={isSelected}
onChange={onSelect} onChange={onSelect}
@@ -95,19 +92,13 @@ function InventorySourceListItem({
aria-label="actions" aria-label="actions"
> >
{source.summary_fields.user_capabilities.start && ( {source.summary_fields.user_capabilities.start && (
<InventorySourceSyncButton <InventorySourceSyncButton source={source} />
onSyncLoading={isLoading => {
setIsSyncLoading(isLoading);
}}
source={source}
/>
)} )}
{source.summary_fields.user_capabilities.edit && ( {source.summary_fields.user_capabilities.edit && (
<Button <Button
aria-label={i18n._(t`Edit Source`)} aria-label={i18n._(t`Edit Source`)}
variant="plain" variant="plain"
component={Link} component={Link}
isDisabled={isSyncLoading}
to={`${detailUrl}/edit`} to={`${detailUrl}/edit`}
> >
<PencilAltIcon /> <PencilAltIcon />

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useState, useEffect } from 'react'; import React, { useCallback } from 'react';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
@@ -9,9 +9,7 @@ import AlertModal from '../../../components/AlertModal/AlertModal';
import ErrorDetail from '../../../components/ErrorDetail/ErrorDetail'; import ErrorDetail from '../../../components/ErrorDetail/ErrorDetail';
import { InventoryUpdatesAPI, InventorySourcesAPI } from '../../../api'; import { InventoryUpdatesAPI, InventorySourcesAPI } from '../../../api';
function InventorySourceSyncButton({ onSyncLoading, source, i18n }) { function InventorySourceSyncButton({ source, i18n }) {
const [updateStatus, setUpdateStatus] = useState(source.status);
const { const {
isLoading: startSyncLoading, isLoading: startSyncLoading,
error: startSyncError, error: startSyncError,
@@ -22,8 +20,6 @@ function InventorySourceSyncButton({ onSyncLoading, source, i18n }) {
data: { status }, data: { status },
} = await InventorySourcesAPI.createSyncStart(source.id); } = await InventorySourcesAPI.createSyncStart(source.id);
setUpdateStatus(status);
return status; return status;
}, [source.id]), }, [source.id]),
{} {}
@@ -44,23 +40,16 @@ function InventorySourceSyncButton({ onSyncLoading, source, i18n }) {
} = await InventorySourcesAPI.readDetail(source.id); } = await InventorySourcesAPI.readDetail(source.id);
await InventoryUpdatesAPI.createSyncCancel(id); await InventoryUpdatesAPI.createSyncCancel(id);
setUpdateStatus(null);
}, [source.id]) }, [source.id])
); );
useEffect(() => onSyncLoading(startSyncLoading || cancelSyncLoading), [
onSyncLoading,
startSyncLoading,
cancelSyncLoading,
]);
const { error, dismissError } = useDismissableError( const { error, dismissError } = useDismissableError(
cancelSyncError || startSyncError cancelSyncError || startSyncError
); );
return ( return (
<> <>
{updateStatus === 'pending' ? ( {source.status === 'pending' ? (
<Tooltip content={i18n._(t`Cancel sync process`)} position="top"> <Tooltip content={i18n._(t`Cancel sync process`)} position="top">
<Button <Button
isDisabled={cancelSyncLoading || startSyncLoading} isDisabled={cancelSyncLoading || startSyncLoading}
@@ -105,7 +94,6 @@ InventorySourceSyncButton.defaultProps = {
}; };
InventorySourceSyncButton.propTypes = { InventorySourceSyncButton.propTypes = {
onSyncLoading: PropTypes.func.isRequired,
source: PropTypes.shape({}), source: PropTypes.shape({}),
}; };

View File

@@ -17,6 +17,7 @@ describe('<InventorySourceSyncButton />', () => {
<InventorySourceSyncButton <InventorySourceSyncButton
source={source} source={source}
onSyncLoading={onSyncLoading} onSyncLoading={onSyncLoading}
onFetchSources={() => {}}
/> />
); );
}); });
@@ -40,6 +41,7 @@ describe('<InventorySourceSyncButton />', () => {
<InventorySourceSyncButton <InventorySourceSyncButton
source={{ status: 'pending', ...source }} source={{ status: 'pending', ...source }}
onSyncLoading={onSyncLoading} onSyncLoading={onSyncLoading}
onFetchSources={() => {}}
/> />
); );
expect(wrapper.find('MinusCircleIcon').length).toBe(1); expect(wrapper.find('MinusCircleIcon').length).toBe(1);
@@ -54,10 +56,6 @@ describe('<InventorySourceSyncButton />', () => {
wrapper.find('Button[aria-label="Start sync source"]').simulate('click') wrapper.find('Button[aria-label="Start sync source"]').simulate('click')
); );
expect(InventorySourcesAPI.createSyncStart).toBeCalledWith(1); expect(InventorySourcesAPI.createSyncStart).toBeCalledWith(1);
wrapper.update();
expect(wrapper.find('Button[aria-label="Cancel sync source"]').length).toBe(
1
);
}); });
test('should cancel sync properly', async () => { test('should cancel sync properly', async () => {
InventorySourcesAPI.readDetail.mockResolvedValue({ InventorySourcesAPI.readDetail.mockResolvedValue({
@@ -71,6 +69,7 @@ describe('<InventorySourceSyncButton />', () => {
<InventorySourceSyncButton <InventorySourceSyncButton
source={{ status: 'pending', ...source }} source={{ status: 'pending', ...source }}
onSyncLoading={onSyncLoading} onSyncLoading={onSyncLoading}
onFetchSources={() => {}}
/> />
); );
expect(wrapper.find('Button[aria-label="Cancel sync source"]').length).toBe( expect(wrapper.find('Button[aria-label="Cancel sync source"]').length).toBe(
@@ -83,11 +82,25 @@ describe('<InventorySourceSyncButton />', () => {
expect(InventorySourcesAPI.readDetail).toBeCalledWith(1); expect(InventorySourcesAPI.readDetail).toBeCalledWith(1);
expect(InventoryUpdatesAPI.createSyncCancel).toBeCalledWith(120); expect(InventoryUpdatesAPI.createSyncCancel).toBeCalledWith(120);
});
wrapper.update(); test('should throw error on sync start properly', async () => {
InventorySourcesAPI.createSyncStart.mockRejectedValueOnce(
expect(wrapper.find('Button[aria-label="Start sync source"]').length).toBe( new Error({
1 response: {
config: {
method: 'post',
url: '/api/v2/inventory_sources/update',
},
data: 'An error occurred',
status: 403,
},
})
); );
await act(async () =>
wrapper.find('Button[aria-label="Start sync source"]').simulate('click')
);
wrapper.update();
expect(wrapper.find('AlertModal').length).toBe(1);
}); });
}); });