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

test(system): add unit tests #34

Merged
merged 1 commit into from
Sep 22, 2023
Merged
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
168 changes: 168 additions & 0 deletions src/datasources/system/SystemDataSource.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import { MockProxy } from 'jest-mock-extended';
import { SystemDataSource } from './SystemDataSource';
import { BackendSrv, TemplateSrv } from '@grafana/runtime';
import { createFetchResponse, getQueryBuilder, requestMatching, setupDataSource } from 'test/fixtures';
import { SystemMetadata, SystemQuery, SystemQueryType } from './types';

let ds: SystemDataSource, backendSrv: MockProxy<BackendSrv>, templateSrv: MockProxy<TemplateSrv>;

beforeEach(() => {
[ds, backendSrv, templateSrv] = setupDataSource(SystemDataSource);
});

const buildQuery = getQueryBuilder<SystemQuery>()({ systemName: '' });

test('query for summary counts', async () => {
backendSrv.fetch
.calledWith(requestMatching({ url: '/nisysmgmt/v1/get-systems-summary' }))
.mockReturnValue(createFetchResponse({ connectedCount: 1, disconnectedCount: 2 }));

const result = await ds.query(buildQuery({ queryKind: SystemQueryType.Summary }));

expect(result.data).toEqual([
{
fields: [
{ name: 'Connected', values: [1] },
{ name: 'Disconnected', values: [2] },
],
refId: 'A',
},
]);
});

test('query metadata for all systems', async () => {
backendSrv.fetch
.calledWith(requestMatching({ url: '/nisysmgmt/v1/query-systems', data: { filter: '' } }))
.mockReturnValue(createFetchResponse({ data: fakeSystems }));

const result = await ds.query(buildQuery({ queryKind: SystemQueryType.Metadata }));

expect(result.data).toEqual([
{
fields: [
{ name: 'id', values: ['system-1', 'system-2'] },
{ name: 'alias', values: ['my system', 'Cool system 😎'] },
{ name: 'connection status', values: ['CONNECTED', 'DISCONNECTED'] },
{ name: 'locked status', values: [false, true] },
{ name: 'system start time', values: ['2023-07-18T10:19:46Z', '2023-03-02T18:48:09Z'] },
{ name: 'model', values: ['NI cRIO-9033', '20LCS0X700'] },
{ name: 'vendor', values: ['National Instruments', 'LENOVO'] },
{ name: 'operating system', values: ['nilrt', 'Microsoft Windows 10 Enterprise'] },
{ name: 'ip address', values: ['172.17.0.1', 'fe80::280:2fff:fe24:fcfa'] },
{ name: 'workspace', values: ['Default workspace', 'Other workspace'] },
],
refId: 'A',
},
]);
});

test('query metadata for one system', async () => {
backendSrv.fetch
.calledWith(
requestMatching({ url: '/nisysmgmt/v1/query-systems', data: { filter: 'id = "system-1" || alias = "system-1"' } })
)
.mockReturnValue(createFetchResponse({ data: [fakeSystems[0]] }));

const result = await ds.query(buildQuery({ queryKind: SystemQueryType.Metadata, systemName: 'system-1' }));

expect(result.data).toEqual([
{
fields: [
{ name: 'id', values: ['system-1'] },
{ name: 'alias', values: ['my system'] },
{ name: 'connection status', values: ['CONNECTED'] },
{ name: 'locked status', values: [false] },
{ name: 'system start time', values: ['2023-07-18T10:19:46Z'] },
{ name: 'model', values: ['NI cRIO-9033'] },
{ name: 'vendor', values: ['National Instruments'] },
{ name: 'operating system', values: ['nilrt'] },
{ name: 'ip address', values: ['172.17.0.1'] },
{ name: 'workspace', values: ['Default workspace'] },
],
refId: 'A',
},
]);
});

test('query metadata with templated system name', async () => {
templateSrv.replace.calledWith('$system_id').mockReturnValue('system-1');
backendSrv.fetch
.calledWith(
requestMatching({ url: '/nisysmgmt/v1/query-systems', data: { filter: 'id = "system-1" || alias = "system-1"' } })
)
.mockReturnValue(createFetchResponse({ data: [fakeSystems[0]] }));

await ds.query(buildQuery({ queryKind: SystemQueryType.Metadata, systemName: '$system_id' }));
});

test('queries for system variable values', async () => {
backendSrv.fetch
.calledWith(
requestMatching({ url: '/nisysmgmt/v1/query-systems', data: { projection: 'new(id,alias)' } })
)
.mockReturnValue(createFetchResponse({ data: fakeSystems.map(({id, alias}) => ({id, alias})) }));

const result = await ds.metricFindQuery();

expect(result).toEqual([
{ text: 'my system', value: 'system-1' },
{ text: 'Cool system 😎', value: 'system-2' },
]);
})

const fakeSystems: SystemMetadata[] = [
{
id: 'system-1',
alias: 'my system',
state: 'CONNECTED',
locked: false,
systemStartTime: '2023-07-18T10:19:46Z',
model: 'NI cRIO-9033',
vendor: 'National Instruments',
osFullName: 'nilrt',
ip4Interfaces: {
cali816305ba9ce: [],
calie2bed856fa8: [],
docker0: ['172.17.0.1'],
enp0s31f6: [],
enp5s0: [],
lo: ['127.0.0.1'],
'ni-bridge': ['10.164.64.144'],
'vxlan.calico': ['10.1.157.0'],
},
ip6Interfaces: {
cali816305ba9ce: ['fe80::ecee:eeff:feee:eeee'],
calie2bed856fa8: ['fe80::ecee:eeff:feee:eeee'],
docker0: ['fe80::42:42ff:fe0f:811a'],
enp0s31f6: [],
enp5s0: [],
lo: ['::1'],
'ni-bridge': ['fe80::38b3:39ff:fe28:69bf'],
'vxlan.calico': ['fe80::6486:2cff:fe02:5f49'],
},
workspace: '1',
},
{
id: 'system-2',
alias: 'Cool system 😎',
state: 'DISCONNECTED',
locked: true,
systemStartTime: '2023-03-02T18:48:09Z',
model: '20LCS0X700',
vendor: 'LENOVO',
osFullName: 'Microsoft Windows 10 Enterprise',
ip4Interfaces: {
usb0: [],
eth1: [],
eth0: [],
lo: ['127.0.0.1'],
},
ip6Interfaces: {
usb0: [],
eth1: ['fe80::280:2fff:fe24:fcfa'],
eth0: ['fe80::280:2fff:fe24:fcf9'],
lo: ['::1'],
},
workspace: '2',
},
];
6 changes: 3 additions & 3 deletions src/datasources/system/SystemDataSource.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DataFrameDTO, DataQueryRequest, DataSourceInstanceSettings, FieldType, MetricFindValue } from '@grafana/data';
import { DataFrameDTO, DataQueryRequest, DataSourceInstanceSettings, MetricFindValue } from '@grafana/data';
import { BackendSrv, TemplateSrv, TestingStatus, getBackendSrv, getTemplateSrv } from '@grafana/runtime';
import { DataSourceBase } from 'core/DataSourceBase';
import { defaultOrderBy, defaultProjection } from './constants';
Expand Down Expand Up @@ -28,8 +28,8 @@ export class SystemDataSource extends DataSourceBase<SystemQuery> {
return {
refId: query.refId,
fields: [
{ name: 'Connected', values: [summary.connectedCount], type: FieldType.number },
{ name: 'Disconnected', values: [summary.disconnectedCount], type: FieldType.number },
{ name: 'Connected', values: [summary.connectedCount] },
{ name: 'Disconnected', values: [summary.disconnectedCount] },
mure marked this conversation as resolved.
Show resolved Hide resolved
],
};
} else {
Expand Down
35 changes: 35 additions & 0 deletions src/datasources/system/components/SystemQueryEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { screen } from '@testing-library/react';
import { setupRenderer } from "test/fixtures";
import { SystemDataSource } from "../SystemDataSource";
import { SystemQueryEditor } from "./SystemQueryEditor";
import { SystemQuery, SystemQueryType } from "../types";
import userEvent from '@testing-library/user-event';

const render = setupRenderer(SystemQueryEditor, SystemDataSource);

it('renders with query defaults', () => {
render({} as SystemQuery);

expect(screen.getByRole('radio', { name: 'Summary' })).toBeChecked();
expect(screen.queryByLabelText('System')).not.toBeInTheDocument();
});

it('renders with saved metadata query', async () => {
render({ queryKind: SystemQueryType.Metadata, systemName: 'my-system'});

expect(screen.getByRole('radio', { name: 'Metadata' })).toBeChecked();
expect(screen.queryByLabelText('System')).toHaveValue('my-system');
});

it('updates when user interacts with fields', async () => {
const [onChange] = render({ queryKind: SystemQueryType.Summary, systemName: '' });

// User changes query type
await userEvent.click(screen.getByRole('radio', { name: 'Metadata' }));
expect(onChange).toBeCalledWith(expect.objectContaining({ queryKind: SystemQueryType.Metadata }));
expect(screen.getByPlaceholderText('All systems')).toBeInTheDocument();

// User types system name
await userEvent.type(screen.getByLabelText('System'), 'my-system{enter}');
expect(onChange).toBeCalledWith(expect.objectContaining({ systemName: 'my-system' }));
});
3 changes: 2 additions & 1 deletion src/datasources/system/components/SystemQueryEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React, { FormEvent } from 'react';
import { AutoSizeInput, InlineField, RadioButtonGroup } from '@grafana/ui';
import { AutoSizeInput, RadioButtonGroup } from '@grafana/ui';
import { QueryEditorProps } from '@grafana/data';
import { SystemDataSource } from '../SystemDataSource';
import { SystemQueryType, SystemQuery } from '../types';
import { enumToOptions } from 'core/utils';
import { InlineField } from 'core/components/InlineField';

type Props = QueryEditorProps<SystemDataSource, SystemQuery>;

Expand Down
2 changes: 1 addition & 1 deletion src/datasources/system/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface SystemMetadata {
id: string,
alias: string,
state: string,
locked: string,
locked: boolean,
systemStartTime: string,
model: string,
vendor: string,
Expand Down
20 changes: 10 additions & 10 deletions src/test/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,19 @@ export function setupRenderer<DSType extends DataSourceApi<TQuery>, TQuery exten
ds: new (instanceSettings: DataSourceInstanceSettings, backendSrv: BackendSrv) => DSType
) {
return (initialQuery: Omit<TQuery, 'refId'>) => {
const onChange = jest.fn(),
const onChange = jest.fn<void, [TQuery]>(),
onRunQuery = jest.fn();

const [datasource] = setupDataSource(ds);

render(
React.createElement(component, {
datasource,
query: { ...initialQuery, refId: 'A' } as TQuery,
onRunQuery,
onChange,
})
);
const createElement = (query: TQuery) =>
React.createElement(component, { datasource, query, onRunQuery, onChange });

const { rerender } = render(createElement({ ...initialQuery, refId: 'A' } as TQuery));

// Mimicks Grafana's query editor by rerendering when onChange is called
onChange.mockImplementation(newQuery => rerender(createElement(newQuery)));

return [onChange, onRunQuery, ds] as const;
};
}
Expand All @@ -59,7 +59,7 @@ export const requestMatching: MatcherCreator<BackendSrvRequest, Partial<BackendS
new Matcher(request => _.isMatch(request, expected!), 'requestMatcher()');

export function mockTimers() {
jest.spyOn(window, "setTimeout").mockImplementation((fn) => {
jest.spyOn(window, 'setTimeout').mockImplementation(fn => {
fn();
return setTimeout(() => 1, 0);
});
Expand Down