Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(Policies): Remove GraphQL implementation #2316

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 13 additions & 27 deletions src/PresentationalComponents/ComplianceTable/ComplianceTable.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import React from 'react';
import { Spinner, Bullseye } from '@patternfly/react-core';

import propTypes from 'prop-types';
import AsyncTableToolsTable from '@/Frameworks/AsyncTableTools/components/AsyncTableToolsTable';
import { TableToolsTable } from 'Utilities/hooks/useTableTools';
import useAPIV2FeatureFlag from '@/Utilities/hooks/useAPIV2FeatureFlag';
import {
paginationSerialiser,
filtersSerialiser,
Expand All @@ -22,29 +18,19 @@ import {
* @category Compliance
*
*/
const ComplianceTable = (props) => {
const apiV2Enabled = useAPIV2FeatureFlag();

return apiV2Enabled === undefined ? (
<Bullseye>
<Spinner />
</Bullseye>
) : apiV2Enabled ? (
<AsyncTableToolsTable
{...props}
options={{
serialisers: {
pagination: paginationSerialiser,
filters: filtersSerialiser,
sort: sortSerialiser,
},
...props.options,
}}
/>
) : (
<TableToolsTable {...props} />
);
};
const ComplianceTable = (props) => (
<AsyncTableToolsTable
{...props}
options={{
serialisers: {
pagination: paginationSerialiser,
filters: filtersSerialiser,
sort: sortSerialiser,
},
...props.options,
}}
/>
);

ComplianceTable.propTypes = {
options: propTypes.object,
Expand Down
1 change: 1 addition & 0 deletions src/PresentationalComponents/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,4 @@ export { default as InlineEdit } from './InlineEdit/InlineEdit';
export { default as ComplianceRoute } from './ComplianceRoute/ComplianceRoute';
export { default as ComplianceTable } from './ComplianceTable/ComplianceTable';
export { default as Tailorings } from './Tailorings/Tailorings';
export { default as ComplianceEmptyState } from './ComplianceEmptyState/ComplianceEmptyState';
55 changes: 6 additions & 49 deletions src/SmartComponents/CompliancePolicies/CompliancePolicies.cy.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
import CompliancePolicies from './CompliancePolicies';
import { init } from 'Store';
import { featureFlagsInterceptors } from '../../../cypress/utils/interceptors';
import { buildPolicies, buildPoliciesV2 } from '../../__factories__/policies';
import { buildPoliciesV2 } from '../../__factories__/policies';

const mountComponent = () => {
cy.mountWithContext(CompliancePolicies, { store: init().getStore() });
};

const fixtures = buildPolicies(13);
const fixturesV2 = buildPoliciesV2(13);

const policies = Object.assign([], fixtures['profiles']['edges']);
const policies_v2 = Object.assign([], fixturesV2);
const policies = buildPoliciesV2(13);

describe('Policies table tests', () => {
beforeEach(() => {
cy.intercept('*', {
cy.intercept('**/policies*', {
statusCode: 201,
body: {
data: fixtures,
data: policies,
},
});
featureFlagsInterceptors.apiV2Disabled();
mountComponent();
});

describe('defaults', () => {
it('The table renders', () => {
cy.get('table').should('have.length', 1);
Expand All @@ -35,6 +31,7 @@ describe('Policies table tests', () => {
cy.ouiaType('PF5/Pagination', 'div').first().click();
cy.get('[role="menuitem"]').contains('20 per page').click();
});

it('Sort by Name', () => {
let policyNames = [];
policies.forEach((item) => {
Expand Down Expand Up @@ -404,43 +401,3 @@ describe('Policies table tests', () => {
});
});
});

describe('Policies table tests API V2', () => {
beforeEach(() => {
featureFlagsInterceptors.apiV2Enabled();
cy.intercept('**/graphql', {
statusCode: 200,
body: {
data: fixtures,
},
});
cy.intercept('**/policies*', {
statusCode: 200,
body: {
data: fixturesV2,
},
});
mountComponent();
});
describe('defaults', () => {
it.skip('The table renders with data', () => {
cy.get('table').should('have.length', 1);

let policyNames = [];
policies_v2.forEach((item) => {
policyNames.push(item['title']);
});

// Check Name sorting
const ascendingSorted = [...policyNames].sort((a, b) => {
return a.localeCompare(b, undefined, { sensitivity: 'base' });
});
cy.get('th[data-label="Name"]')
.invoke('attr', 'aria-sort')
.should('eq', 'ascending');
cy.get('td[data-label="Name"] > div > div > a').each((item, index) => {
expect(Cypress.$(item).text()).to.eq(ascendingSorted[index]);
});
});
});
});
116 changes: 108 additions & 8 deletions src/SmartComponents/CompliancePolicies/CompliancePolicies.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,115 @@
import React from 'react';
import GatedComponents from '@/PresentationalComponents/GatedComponents';
import React, { useCallback } from 'react';
import TableStateProvider from '@/Frameworks/AsyncTableTools/components/TableStateProvider';
import CompliancePoliciesRest from 'SmartComponents/CompliancePolicies/CompliancePoliciesRest';
import CompliancePoliciesGraphQL from 'SmartComponents/CompliancePolicies/CompliancePoliciesGraphQL';
import { Grid } from '@patternfly/react-core';
import PageHeader, {
PageHeaderTitle,
} from '@redhat-cloud-services/frontend-components/PageHeader';
import {
ComplianceEmptyState,
ErrorPage,
LoadingPoliciesTable,
PoliciesTable,
StateView,
StateViewPart,
} from 'PresentationalComponents';
import usePolicies from 'Utilities/hooks/api/usePolicies';
import dataSerialiser from 'Utilities/dataSerialiser';
import usePoliciesCount from 'Utilities/hooks/usePoliciesCount';
import useExporter from '@/Frameworks/AsyncTableTools/hooks/useExporter';
import CreateLink from './components/CreateLink';

import { dataMap } from './constants';

const CompliancePolicies = () => {
// Async table needs info about total policy count before mounting
// Also required for correctly showing empty state
const totalPolicies = usePoliciesCount();
let totalPoliciesLoading = totalPolicies == null;

const options = {
useTableState: true,
};

let {
data: { data, meta: { total: currentTotalPolicies } = {} } = {},
error,
loading,
fetch: fetchPolicies,
} = usePolicies(options);

const fetchForExport = useCallback(
async (offset, limit) => await fetchPolicies({ offset, limit }, false),
[fetchPolicies]
);

const policiesExporter = useExporter(fetchForExport);

let showTable = data || !totalPoliciesLoading;

if (showTable) {
if (data) {
data = dataSerialiser(data, dataMap);
error = undefined;
}
totalPoliciesLoading = undefined;
}
// Async table always needs one total value
const calculatedTotal = currentTotalPolicies ?? totalPolicies;

if (error) {
totalPoliciesLoading = undefined;
showTable = undefined;
}

return (
<>
<PageHeader className="page-header">
<PageHeaderTitle title="SCAP policies" />
</PageHeader>
<section className="pf-v5-c-page__main-section">
<StateView
stateValues={{
error,
loading: totalPoliciesLoading,
showTable: showTable,
}}
>
<StateViewPart stateKey="error">
<ErrorPage error={error} />
</StateViewPart>
<StateViewPart stateKey="loading">
<LoadingPoliciesTable />
</StateViewPart>
<StateViewPart stateKey="showTable">
{totalPolicies === 0 ? (
<Grid hasGutter>
<ComplianceEmptyState
title="No policies"
mainButton={<CreateLink />}
/>
</Grid>
) : (
<PoliciesTable
policies={data}
total={calculatedTotal}
loading={loading}
DedicatedAction={CreateLink}
options={{
exporter: async () =>
dataSerialiser(await policiesExporter(), dataMap),
}}
/>
)}
</StateViewPart>
</StateView>
</section>
</>
);
};

const CompliancePoliciesWrapper = () => (
<TableStateProvider>
<GatedComponents
RestComponent={CompliancePoliciesRest}
GraphQLComponent={CompliancePoliciesGraphQL}
/>
<CompliancePolicies />
</TableStateProvider>
);

Expand Down
42 changes: 23 additions & 19 deletions src/SmartComponents/CompliancePolicies/CompliancePolicies.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ import '@testing-library/jest-dom';

import propTypes from 'prop-types';
import { MemoryRouter } from 'react-router-dom';
import { useQuery } from '@apollo/client';

import { profiles } from '@/__fixtures__/profiles.js';
import { buildPoliciesV2 } from '../../__factories__/policies';

import CompliancePolicies from './CompliancePolicies.js';
import useAPIV2FeatureFlag from '../../Utilities/hooks/useAPIV2FeatureFlag';
import usePolicies from 'Utilities/hooks/api/usePolicies';
import usePoliciesCount from 'Utilities/hooks/usePoliciesCount';

jest.mock('Utilities/hooks/api/usePolicies');
jest.mock('Utilities/hooks/usePoliciesCount');

jest.mock('@apollo/client');
jest.mock('../../Utilities/hooks/useAPIV2FeatureFlag');
const policies = buildPoliciesV2(13);

const TestWrapper = ({ children }) => <MemoryRouter>{children}</MemoryRouter>;
TestWrapper.propTypes = { children: propTypes.node };
Expand All @@ -25,33 +28,34 @@ describe('CompliancePolicies', () => {
};

beforeEach(() => {
useAPIV2FeatureFlag.mockImplementation(() => false);
});

it('expect to render without error', () => {
useQuery.mockImplementation(() => ({
usePolicies.mockImplementation(() => ({
...queryDefaults,
data: profiles,
data: policies,
meta: {
total: policies.length,
},
}));
usePoliciesCount.mockImplementation(() => policies.length);
});

it.only('expect to render without error', () => {
render(
<TestWrapper>
<CompliancePolicies />
</TestWrapper>
);

screen.logTestingPlaygroundURL();
expect(
within(screen.getByLabelText('Policies')).queryAllByRole('row').length
).toEqual(11);
});

it('expect to render emptystate', () => {
useQuery.mockImplementation(() => ({
usePolicies.mockImplementation(() => ({
...queryDefaults,
data: {
profiles: {
edges: [],
},
data: [],
meta: {
total: 0,
},
}));

Expand All @@ -69,7 +73,7 @@ describe('CompliancePolicies', () => {
networkError: { statusCode: 500 },
error: 'Test Error loading',
};
useQuery.mockImplementation(() => ({
usePolicies.mockImplementation(() => ({
...queryDefaults,
error,
}));
Expand All @@ -84,7 +88,7 @@ describe('CompliancePolicies', () => {
});

it('expect to render loading', () => {
useQuery.mockImplementation(() => ({
usePolicies.mockImplementation(() => ({
...queryDefaults,
loading: true,
}));
Expand Down
Loading