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

HDDS-9791. Add tests for Datanodes page #7626

Merged
merged 6 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"devDependencies": {
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^12.1.5",
"@testing-library/user-event": "^14.5.2",
"@types/react": "16.8.15",
"@types/react-dom": "16.8.4",
"@types/react-router-dom": "^5.3.3",
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import {
render,
screen,
waitFor
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { rest } from "msw";
import { vi } from 'vitest';

import Datanodes from '@/v2/pages/datanodes/datanodes';
import * as commonUtils from '@/utils/common';
import { datanodeServer } from '@/__tests__/mocks/datanodeMocks/datanodeServer';
import { datanodeLocators } from '@/__tests__/locators/locators';

// Mock utility functions
vi.spyOn(commonUtils, 'showDataFetchError');

vi.mock('@/components/autoReloadPanel/autoReloadPanel', () => ({
default: () => <div data-testid="auto-reload-panel" />,
}));
vi.mock('@/v2/components/select/multiSelect.tsx', () => ({
default: ({ onChange }: { onChange: Function }) => (
<select data-testid="multi-select" onChange={(e) => onChange(e.target.value)}>
<option value="hostname">Hostname</option>
<option value="uuid">UUID</option>
</select>
),
}));

describe('Datanodes Component', () => {
// Start and stop MSW server before and after all tests
beforeAll(() => datanodeServer.listen());
afterEach(() => datanodeServer.resetHandlers());
afterAll(() => datanodeServer.close());

test('renders component correctly', () => {
render(<Datanodes />);

expect(screen.getByText(/Datanodes/)).toBeInTheDocument();
expect(screen.getByTestId('auto-reload-panel')).toBeInTheDocument();
expect(screen.getByTestId('multi-select')).toBeInTheDocument();
expect(screen.getByTestId('search-input')).toBeInTheDocument();
});

test('renders table with correct number of rows', async () => {
render(<Datanodes />);

// Wait for the data to load
const rows = await waitFor(() => screen.getAllByTestId(/dntable-/));
devabhishekpal marked this conversation as resolved.
Show resolved Hide resolved
expect(rows).toHaveLength(5); // Based on the mocked DatanodeResponse
});

test('loads data on mount', async () => {
render(<Datanodes />);
// Wait for the data to be loaded into the table
const dnTable = await waitFor(() => screen.getByTestId('dn-table'));

// Ensure the correct data is displayed in the table
expect(dnTable).toHaveTextContent('ozone-datanode-1.ozone_default');
expect(dnTable).toHaveTextContent('HEALTHY');
});

test('displays no data message if the datanodes API returns an empty array', async () => {
datanodeServer.use(
rest.get('api/v1/datanodes', (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ totalCount: 0, datanodes: [] }));
})
);

render(<Datanodes />);

// Wait for the no data message
await waitFor(() => expect(screen.getByText('No Data')).toBeInTheDocument());
});

test('handles search input change', async () => {
render(<Datanodes />);
await waitFor(() => screen.getByTestId('dn-table'));

const searchInput = screen.getByTestId('search-input');
userEvent.type(searchInput, 'ozone-datanode-1');
await waitFor(() => expect(searchInput).toHaveValue('ozone-datanode-1'));
});

test('displays a message when no results match the search term', async () => {
render(<Datanodes />);
const searchInput = screen.getByTestId('search-input');

// Type a term that doesn't match any datanode
userEvent.type(searchInput, 'nonexistent-datanode');

// Verify that no results message is displayed
await waitFor(() => expect(screen.getByText('No Data')).toBeInTheDocument());
});

// Since this is a static response, even if we remove we will not get the truncated response from backend
// i.e response with the removed DN. So the table will always have the value even if we remove it
// causing this test to fail
test.skip('shows modal on row selection and confirms removal', async () => {
render(<Datanodes />);

// Wait for the data to be loaded into the table
await waitFor(() => screen.getByTestId('dn-table'));

// Simulate selecting a row
// The first checkbox is for the table header "Select All" checkbox -> idx 0
// Second checkbox is for the healthy DN -> idx 1
// Third checkbox is the active one for Dead DN -> idx 2
const checkbox = document.querySelectorAll('input.ant-checkbox-input');
userEvent.click(checkbox[0]);
// Click the "Remove" button to open the modal
await waitFor(() => {
// Wait for the button to appear in screen
screen.getByTestId(datanodeLocators.datanodeRemoveButton);
}).then(() => {
userEvent.click(screen.getByText(/Remove/));
})

// Confirm removal in the modal
await waitFor(() => {
// Wait for the button to appear in screen
screen.getByTestId(datanodeLocators.datanodeRemoveModal);
}).then(() => {
userEvent.click(screen.getByText(/OK/));
})

// Wait for the removal operation to complete
await waitFor(() =>
expect(screen.queryByText('ozone-datanode-3.ozone_default')).not.toBeInTheDocument()
);
});

test('handles API errors gracefully', async () => {
// Set up MSW to return an error for the datanode API
datanodeServer.use(
rest.get('api/v1/datanodes', (req, res, ctx) => {
return res(ctx.status(500), ctx.json({ error: 'Internal Server Error' }));
})
);

render(<Datanodes />);

// Wait for the error to be handled
await waitFor(() =>
expect(commonUtils.showDataFetchError).toHaveBeenCalledWith('AxiosError: Request failed with status code 500')
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import React from 'react';
devabhishekpal marked this conversation as resolved.
Show resolved Hide resolved
import { vi } from 'vitest';
import {
fireEvent,
render,
screen,
waitFor
} from '@testing-library/react';

import { DatanodeTableProps } from '@/v2/types/datanode.types';
import DatanodesTable from '@/v2/components/tables/datanodesTable';
import { datanodeServer } from '@/__tests__/mocks/datanodeMocks/datanodeServer';

const defaultProps: DatanodeTableProps = {
loading: false,
selectedRows: [],
data: [],
decommissionUuids: [],
searchColumn: 'hostname',
searchTerm: '',
selectedColumns: [
{ label: 'Hostname', value: 'hostname' },
{ label: 'State', value: 'state' },
],
handleSelectionChange: vi.fn(),
};

function getDataWith(name: string, state: "HEALTHY" | "STALE" | "DEAD", uuid: number) {
return {
hostname: name,
uuid: uuid,
state: state,
opState: 'IN_SERVICE',
lastHeartbeat: 1728280581608,
storageUsed: 4096,
storageTotal: 125645656770,
storageCommitted: 0,
storageRemaining: 114225606656,
pipelines: [
{
"pipelineID": "0f9f7bc0-505e-4428-b148-dd7eac2e8ac2",
"replicationType": "RATIS",
"replicationFactor": "THREE",
"leaderNode": "ozone-datanode-3.ozone_default"
},
{
"pipelineID": "2c23e76e-3f18-4b86-9541-e48bdc152fda",
"replicationType": "RATIS",
"replicationFactor": "ONE",
"leaderNode": "ozone-datanode-1.ozone_default"
}
],
containers: 8192,
openContainers: 8182,
leaderCount: 2,
version: '0.6.0-SNAPSHOT',
setupTime: 1728280539733,
revision: '3f9953c0fbbd2175ee83e8f0b4927e45e9c10ac1',
buildDate: '2024-10-06T16:41Z',
networkLocation: '/default-rack'
}
}

describe('DatanodesTable Component', () => {
// Start and stop MSW server before and after all tests
beforeAll(() => datanodeServer.listen());
afterEach(() => datanodeServer.resetHandlers());
afterAll(() => datanodeServer.close());

test('renders table with data', async () => {
render(<DatanodesTable {...defaultProps} data={[]} />);

// Wait for the table to render
await waitFor(() => screen.getByTestId('dn-table'));

expect(screen.getByTestId('dn-table')).toBeInTheDocument();
});

test('filters data based on search term', async () => {
render(
<DatanodesTable
{...defaultProps}
searchTerm="ozone-datanode-1"
data={[
getDataWith('ozone-datanode-1', 'HEALTHY', 1),
getDataWith('ozone-datanode-2', 'STALE', 2)
]}
/>
);

// Only the matching datanode should be visible
expect(screen.getByText('ozone-datanode-1')).toBeInTheDocument();
expect(screen.queryByText('ozone-datanode-2')).not.toBeInTheDocument();
});

test('handles row selection', async () => {
render(
<DatanodesTable
{...defaultProps}
data={[
getDataWith('ozone-datanode-1', 'HEALTHY', 1),
getDataWith('ozone-datanode-2', 'DEAD', 2)
]}
/>
);

// The first checkbox is for the table header "Select All" checkbox -> idx 0
// Second checkbox is for the healthy DN -> idx 1
// Third checkbox is the active one for Dead DN -> idx 2
const checkbox = document.querySelectorAll('input.ant-checkbox-input')[2];
fireEvent.click(checkbox);

expect(defaultProps.handleSelectionChange).toHaveBeenCalledWith([2]);
});

test('disables selection for non-DEAD nodes', async () => {
render(
<DatanodesTable
{...defaultProps}
data={[
getDataWith('ozone-datanode-1', 'HEALTHY', 1),
getDataWith('ozone-datanode-2', 'DEAD', 2)
]}
/>
);

// Check disabled and enabled rows
const checkboxes = document.querySelectorAll('input.ant-checkbox-input');
expect(checkboxes[1]).toBeDisabled(); // HEALTHY node
expect(checkboxes[2]).not.toBeDisabled(); // DEAD node
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,14 @@ export const overviewLocators = {
}

export const datanodeLocators = {
'datanodeContainer': 'datanodes-container',
'datanodeMultiSelect': 'datanodes-multiselect'
'datanodeMultiSelect': 'dn-multi-select',
'datanodeSearchcDropdown': 'search-dropdown',
'datanodeSearchInput': 'search-input',
'datanodeRemoveButton': 'dn-remove-btn',
'datanodeRemoveModal': 'dn-remove-modal',
'datanodeTable': 'dn-table',
datanodeSearchOption: (label: string) => `search-opt-${label}`,
datanodeTableRow: (uuid: string) => `dntable-${uuid}`
}

export const autoReloadPanelLocators = {
Expand Down
Loading
Loading