Fix tests

This commit is contained in:
Alexander Zobnin
2021-08-06 14:40:46 +03:00
parent 2a836b9ecd
commit 7af0d6a189
8 changed files with 121 additions and 186 deletions

View File

@@ -1,51 +0,0 @@
import _ from 'lodash';
import dataProcessor from '../dataProcessor';
describe('dataProcessor', () => {
let ctx = {};
beforeEach(() => {
ctx.datapoints = [
[[10, 1500000000000], [2, 1500000001000], [7, 1500000002000], [1, 1500000003000]],
[[9, 1500000000000], [3, 1500000001000], [4, 1500000002000], [8, 1500000003000]],
];
});
describe('When apply groupBy() functions', () => {
it('should return series average', () => {
let aggregateBy = dataProcessor.metricFunctions['groupBy'];
const avg2s = _.map(ctx.datapoints, (dp) => aggregateBy('2s', 'avg', dp));
expect(avg2s).toEqual([
[[6, 1500000000000], [4, 1500000002000]],
[[6, 1500000000000], [6, 1500000002000]],
]);
const avg10s = _.map(ctx.datapoints, (dp) => aggregateBy('10s', 'avg', dp));
expect(avg10s).toEqual([
[[5, 1500000000000]],
[[6, 1500000000000]],
]);
// not aligned
const dp = [[10, 1500000001000], [2, 1500000002000], [7, 1500000003000], [1, 1500000004000]];
expect(aggregateBy('2s', 'avg', dp)).toEqual([
[10, 1500000000000], [4.5, 1500000002000], [1, 1500000004000]
]);
});
});
describe('When apply aggregateBy() functions', () => {
it('should return series average', () => {
let aggregateBy = dataProcessor.metricFunctions['aggregateBy'];
const avg1s = aggregateBy('1s', 'avg', ctx.datapoints);
expect(avg1s).toEqual([
[9.5, 1500000000000], [2.5, 1500000001000], [5.5, 1500000002000], [4.5, 1500000003000]
]);
const avg10s = aggregateBy('10s', 'avg', ctx.datapoints);
expect(avg10s).toEqual([
[5.5, 1500000000000]
]);
});
});
});

View File

@@ -1,15 +1,17 @@
import _ from 'lodash';
import mocks from '../../test-setup/mocks';
import { ZabbixDatasource } from "../datasource";
import { zabbixTemplateFormat } from "../datasource";
import { ZabbixDatasource, zabbixTemplateFormat } from "../datasource";
import { dateMath } from '@grafana/data';
jest.mock('@grafana/runtime', () => ({
getBackendSrv: () => ({
datasourceRequest: jest.fn().mockResolvedValue({data: {result: ''}}),
datasourceRequest: jest.fn().mockResolvedValue({ data: { result: '' } }),
fetch: () => ({
toPromise: () => jest.fn().mockResolvedValue({ data: { result: '' } })
}),
}),
loadPluginCss: () => {},
}), {virtual: true});
loadPluginCss: () => {
},
}), { virtual: true });
describe('ZabbixDatasource', () => {
let ctx = {};
@@ -27,24 +29,13 @@ describe('ZabbixDatasource', () => {
}
};
ctx.templateSrv = mocks.templateSrvMock;
ctx.datasourceSrv = mocks.datasourceSrvMock;
ctx.ds = new ZabbixDatasource(ctx.instanceSettings, ctx.templateSrv);
});
describe('When querying data', () => {
beforeEach(() => {
ctx.ds.replaceTemplateVars = (str) => str;
});
ctx.options = {
targets: [
{
group: {filter: ""},
host: {filter: ""},
application: {filter: ""},
item: {filter: ""}
group: { filter: "" },
host: { filter: "" },
application: { filter: "" },
item: { filter: "" }
}
],
range: {
@@ -53,64 +44,24 @@ describe('ZabbixDatasource', () => {
}
};
it('should return an empty array when no targets are set', (done) => {
let options = {
targets: [],
range: {from: 'now-6h', to: 'now'}
};
ctx.ds.query(options).then(result => {
expect(result.data.length).toBe(0);
done();
});
});
it('should use trends if it enabled and time more than trendsFrom', (done) => {
let ranges = ['now-8d', 'now-169h', 'now-1M', 'now-1y'];
_.forEach(ranges, range => {
ctx.options.range.from = dateMath.parse(range);
ctx.ds.queryNumericData = jest.fn();
ctx.ds.query(ctx.options);
// Check that useTrends options is true
let callArgs = ctx.ds.queryNumericData.mock.calls[0];
expect(callArgs[2]).toBe(true);
ctx.ds.queryNumericData.mockClear();
});
done();
});
it('shouldnt use trends if it enabled and time less than trendsFrom', (done) => {
let ranges = ['now-7d', 'now-168h', 'now-1h', 'now-30m', 'now-30s'];
_.forEach(ranges, range => {
ctx.options.range.from = dateMath.parse(range);
ctx.ds.queryNumericData = jest.fn();
ctx.ds.query(ctx.options);
// Check that useTrends options is false
let callArgs = ctx.ds.queryNumericData.mock.calls[0];
expect(callArgs[2]).toBe(false);
ctx.ds.queryNumericData.mockClear();
});
done();
});
ctx.templateSrv = mocks.templateSrvMock;
ctx.datasourceSrv = mocks.datasourceSrvMock;
ctx.ds = new ZabbixDatasource(ctx.instanceSettings, ctx.templateSrv);
});
describe('When querying text data', () => {
beforeEach(() => {
ctx.ds.replaceTemplateVars = (str) => str;
ctx.ds.zabbix.zabbixAPI.getHistory = jest.fn().mockReturnValue(Promise.resolve([
{clock: "1500010200", itemid:"10100", ns:"900111000", value:"Linux first"},
{clock: "1500010300", itemid:"10100", ns:"900111000", value:"Linux 2nd"},
{clock: "1500010400", itemid:"10100", ns:"900111000", value:"Linux last"}
{ clock: "1500010200", itemid: "10100", ns: "900111000", value: "Linux first" },
{ clock: "1500010300", itemid: "10100", ns: "900111000", value: "Linux 2nd" },
{ clock: "1500010400", itemid: "10100", ns: "900111000", value: "Linux last" }
]));
ctx.ds.zabbix.getItemsFromTarget = jest.fn().mockReturnValue(Promise.resolve([
{
hosts: [{hostid: "10001", name: "Zabbix server"}],
hosts: [{ hostid: "10001", name: "Zabbix server" }],
itemid: "10100",
name: "System information",
key_: "system.uname",
@@ -118,10 +69,10 @@ describe('ZabbixDatasource', () => {
]));
ctx.options.targets = [{
group: {filter: ""},
host: {filter: "Zabbix server"},
application: {filter: ""},
item: {filter: "System information"},
group: { filter: "" },
host: { filter: "Zabbix server" },
application: { filter: "" },
item: { filter: "System information" },
textFilter: "",
useCaptureGroups: true,
queryType: 2,
@@ -138,7 +89,7 @@ describe('ZabbixDatasource', () => {
let tableData = result.data[0];
expect(tableData.columns).toEqual([
{text: 'Host'}, {text: 'Item'}, {text: 'Key'}, {text: 'Last value'}
{ text: 'Host' }, { text: 'Item' }, { text: 'Key' }, { text: 'Last value' }
]);
expect(tableData.rows).toEqual([
['Zabbix server', 'System information', 'system.uname', 'Linux last']
@@ -159,22 +110,22 @@ describe('ZabbixDatasource', () => {
it('should skip item when last value is empty', () => {
ctx.ds.zabbix.getItemsFromTarget = jest.fn().mockReturnValue(Promise.resolve([
{
hosts: [{hostid: "10001", name: "Zabbix server"}],
hosts: [{ hostid: "10001", name: "Zabbix server" }],
itemid: "10100", name: "System information", key_: "system.uname"
},
{
hosts: [{hostid: "10002", name: "Server02"}],
hosts: [{ hostid: "10002", name: "Server02" }],
itemid: "90109", name: "System information", key_: "system.uname"
}
]));
ctx.options.targets[0].options.skipEmptyValues = true;
ctx.ds.zabbix.getHistory = jest.fn().mockReturnValue(Promise.resolve([
{clock: "1500010200", itemid:"10100", ns:"900111000", value:"Linux first"},
{clock: "1500010300", itemid:"10100", ns:"900111000", value:"Linux 2nd"},
{clock: "1500010400", itemid:"10100", ns:"900111000", value:"Linux last"},
{clock: "1500010200", itemid:"90109", ns:"900111000", value:"Non empty value"},
{clock: "1500010500", itemid:"90109", ns:"900111000", value:""}
{ clock: "1500010200", itemid: "10100", ns: "900111000", value: "Linux first" },
{ clock: "1500010300", itemid: "10100", ns: "900111000", value: "Linux 2nd" },
{ clock: "1500010400", itemid: "10100", ns: "900111000", value: "Linux last" },
{ clock: "1500010200", itemid: "90109", ns: "900111000", value: "Non empty value" },
{ clock: "1500010500", itemid: "90109", ns: "900111000", value: "" }
]));
return ctx.ds.query(ctx.options).then(result => {
let tableData = result.data[0];
@@ -249,9 +200,9 @@ describe('ZabbixDatasource', () => {
it('should return groups', (done) => {
const tests = [
{query: '*', expect: '/.*/'},
{query: 'Backend', expect: 'Backend'},
{query: 'Back*', expect: 'Back*'},
{ query: '*', expect: '/.*/' },
{ query: 'Backend', expect: 'Backend' },
{ query: 'Back*', expect: 'Back*' },
];
for (const test of tests) {
@@ -274,10 +225,10 @@ describe('ZabbixDatasource', () => {
it('should return hosts', (done) => {
const tests = [
{query: '*.*', expect: ['/.*/', '/.*/']},
{query: '.', expect: ['', '']},
{query: 'Backend.*', expect: ['Backend', '/.*/']},
{query: 'Back*.', expect: ['Back*', '']},
{ query: '*.*', expect: ['/.*/', '/.*/'] },
{ query: '.', expect: ['', ''] },
{ query: 'Backend.*', expect: ['Backend', '/.*/'] },
{ query: 'Back*.', expect: ['Back*', ''] },
];
for (const test of tests) {
@@ -290,10 +241,10 @@ describe('ZabbixDatasource', () => {
it('should return applications', (done) => {
const tests = [
{query: '*.*.*', expect: ['/.*/', '/.*/', '/.*/']},
{query: '.*.', expect: ['', '/.*/', '']},
{query: 'Backend.backend01.*', expect: ['Backend', 'backend01', '/.*/']},
{query: 'Back*.*.', expect: ['Back*', '/.*/', '']}
{ query: '*.*.*', expect: ['/.*/', '/.*/', '/.*/'] },
{ query: '.*.', expect: ['', '/.*/', ''] },
{ query: 'Backend.backend01.*', expect: ['Backend', 'backend01', '/.*/'] },
{ query: 'Back*.*.', expect: ['Back*', '/.*/', ''] }
];
for (const test of tests) {
@@ -306,16 +257,16 @@ describe('ZabbixDatasource', () => {
it('should return items', (done) => {
const tests = [
{query: '*.*.*.*', expect: ['/.*/', '/.*/', '', '/.*/']},
{query: '.*.*.*', expect: ['', '/.*/', '', '/.*/']},
{query: 'Backend.backend01.*.*', expect: ['Backend', 'backend01', '', '/.*/']},
{query: 'Back*.*.cpu.*', expect: ['Back*', '/.*/', 'cpu', '/.*/']}
{ query: '*.*.*.*', expect: ['/.*/', '/.*/', '', '/.*/'] },
{ query: '.*.*.*', expect: ['', '/.*/', '', '/.*/'] },
{ query: 'Backend.backend01.*.*', expect: ['Backend', 'backend01', '', '/.*/'] },
{ query: 'Back*.*.cpu.*', expect: ['Back*', '/.*/', 'cpu', '/.*/'] }
];
for (const test of tests) {
ctx.ds.metricFindQuery(test.query);
expect(ctx.ds.zabbix.getItems)
.toBeCalledWith(test.expect[0], test.expect[1], test.expect[2], test.expect[3]);
.toBeCalledWith(test.expect[0], test.expect[1], test.expect[2], test.expect[3]);
ctx.ds.zabbix.getItems.mockClear();
}
done();

View File

@@ -5,8 +5,8 @@ const getAllMock = jest.fn().mockReturnValue([{ id: 42, name: 'foo', meta: {} }]
jest.mock('@grafana/runtime', () => ({
getDataSourceSrv: () => ({
loadDatasource: loadDatasourceMock,
getAll: getAllMock
get: loadDatasourceMock,
getList: getAllMock
}),
}));

View File

@@ -3,7 +3,7 @@ import { compactQuery } from '../utils';
jest.mock('@grafana/runtime', () => ({
getDataSourceSrv: jest.fn(() => ({
loadDatasource: jest.fn().mockResolvedValue(
get: jest.fn().mockResolvedValue(
{ id: 42, name: 'InfluxDB DS', meta: {} }
),
})),
@@ -29,8 +29,11 @@ describe('InfluxDBConnector', () => {
const { itemids, range, intervalSec, table, aggFunction } = ctx.defaultQueryParams;
const query = ctx.influxDBConnector.buildHistoryQuery(itemids, table, range, intervalSec, aggFunction);
const expected = compactQuery(`SELECT MAX("value")
FROM "history" WHERE ("itemid" = '123' OR "itemid" = '234') AND "time" >= 15000s AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
FROM "history"
WHERE ("itemid" = '123' OR "itemid" = '234')
AND "time" >= 15000s
AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
`);
expect(query).toBe(expected);
});
@@ -40,8 +43,11 @@ describe('InfluxDBConnector', () => {
const aggFunction = 'avg';
const query = ctx.influxDBConnector.buildHistoryQuery(itemids, table, range, intervalSec, aggFunction);
const expected = compactQuery(`SELECT MEAN("value")
FROM "history" WHERE ("itemid" = '123' OR "itemid" = '234') AND "time" >= 15000s AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
FROM "history"
WHERE ("itemid" = '123' OR "itemid" = '234')
AND "time" >= 15000s
AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
`);
expect(query).toBe(expected);
});
@@ -55,8 +61,11 @@ describe('InfluxDBConnector', () => {
{ itemid: '123', value_type: 3 }
];
const expectedQuery = compactQuery(`SELECT MEAN("value")
FROM "history_uint" WHERE ("itemid" = '123') AND "time" >= 15000s AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
FROM "history_uint"
WHERE ("itemid" = '123')
AND "time" >= 15000s
AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
`);
ctx.influxDBConnector.getHistory(items, timeFrom, timeTill, options);
expect(ctx.influxDBConnector.invokeInfluxDBQuery).toHaveBeenCalledWith(expectedQuery);
@@ -71,10 +80,12 @@ describe('InfluxDBConnector', () => {
];
const sharedQueryPart = `AND "time" >= 15000s AND "time" <= 15100s GROUP BY time(5s), "itemid" fill(none)`;
const expectedQueryFirst = compactQuery(`SELECT MEAN("value")
FROM "history" WHERE ("itemid" = '123') ${sharedQueryPart}
FROM "history"
WHERE ("itemid" = '123') ${sharedQueryPart}
`);
const expectedQuerySecond = compactQuery(`SELECT MEAN("value")
FROM "history_uint" WHERE ("itemid" = '234') ${sharedQueryPart}
FROM "history_uint"
WHERE ("itemid" = '234') ${sharedQueryPart}
`);
ctx.influxDBConnector.getHistory(items, timeFrom, timeTill, options);
expect(ctx.influxDBConnector.invokeInfluxDBQuery).toHaveBeenCalledTimes(2);
@@ -90,8 +101,11 @@ describe('InfluxDBConnector', () => {
{ itemid: '123', value_type: 3 }
];
const expectedQuery = compactQuery(`SELECT MEAN("value")
FROM "history_uint" WHERE ("itemid" = '123') AND "time" >= 15000s AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
FROM "history_uint"
WHERE ("itemid" = '123')
AND "time" >= 15000s
AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
`);
ctx.influxDBConnector.getTrends(items, timeFrom, timeTill, options);
expect(ctx.influxDBConnector.invokeInfluxDBQuery).toHaveBeenCalledWith(expectedQuery);
@@ -104,8 +118,11 @@ describe('InfluxDBConnector', () => {
{ itemid: '123', value_type: 3 }
];
const expectedQuery = compactQuery(`SELECT MEAN("value_avg")
FROM "longterm"."history_uint" WHERE ("itemid" = '123') AND "time" >= 15000s AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
FROM "longterm"."history_uint"
WHERE ("itemid" = '123')
AND "time" >= 15000s
AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
`);
ctx.influxDBConnector.getTrends(items, timeFrom, timeTill, options);
expect(ctx.influxDBConnector.invokeInfluxDBQuery).toHaveBeenCalledWith(expectedQuery);
@@ -118,8 +135,11 @@ describe('InfluxDBConnector', () => {
{ itemid: '123', value_type: 3 }
];
const expectedQuery = compactQuery(`SELECT MAX("value_max")
FROM "longterm"."history_uint" WHERE ("itemid" = '123') AND "time" >= 15000s AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
FROM "longterm"."history_uint"
WHERE ("itemid" = '123')
AND "time" >= 15000s
AND "time" <= 15100s
GROUP BY time(5s), "itemid" fill(none)
`);
ctx.influxDBConnector.getTrends(items, timeFrom, timeTill, options);
expect(ctx.influxDBConnector.invokeInfluxDBQuery).toHaveBeenCalledWith(expectedQuery);

View File

@@ -82,7 +82,7 @@ export class InfluxDBConnector extends DBConnector {
WHERE ${where_clause}
AND "time" >= ${timeFrom}s
AND "time" <= ${timeTill}s
GROUP BY time (${intervalSec}s), "itemid" fill(none)`;
GROUP BY time(${intervalSec}s), "itemid" fill(none)`;
return compactQuery(query);
}

View File

@@ -0,0 +1,13 @@
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});

View File

@@ -1,25 +1,25 @@
import _ from 'lodash';
import mocks from '../../test-setup/mocks';
import {TriggerPanelCtrl} from '../triggers_panel_ctrl';
import { DEFAULT_TARGET, DEFAULT_SEVERITY, PANEL_DEFAULTS } from '../triggers_panel_ctrl';
import './matchMedia.mock';
import { DEFAULT_SEVERITY, DEFAULT_TARGET, PANEL_DEFAULTS, TriggerPanelCtrl } from '../triggers_panel_ctrl';
import { CURRENT_SCHEMA_VERSION } from '../migrations';
jest.mock('@grafana/runtime', () => {
return {
getDataSourceSrv: () => ({
getMetricSources: () => {
return [{ meta: {id: 'alexanderzobnin-zabbix-datasource'}, value: {}, name: 'zabbix_default' }];
return [{ meta: { id: 'alexanderzobnin-zabbix-datasource' }, value: {}, name: 'zabbix_default' }];
},
get: () => Promise.resolve({})
}),
};
}, {virtual: true});
}, { virtual: true });
describe('Triggers Panel schema migration', () => {
let ctx: any = {};
let updatePanelCtrl;
const timeoutMock = () => {};
const timeoutMock = () => {
};
beforeEach(() => {
ctx = {

View File

@@ -1,6 +1,6 @@
import _ from 'lodash';
import { TriggerPanelCtrl } from '../triggers_panel_ctrl';
import { PANEL_DEFAULTS, DEFAULT_TARGET } from '../triggers_panel_ctrl';
import './matchMedia.mock';
import { DEFAULT_TARGET, PANEL_DEFAULTS, TriggerPanelCtrl } from '../triggers_panel_ctrl';
let datasourceSrvMock, zabbixDSMock;
@@ -8,19 +8,21 @@ jest.mock('@grafana/runtime', () => {
return {
getDataSourceSrv: () => datasourceSrvMock,
};
}, {virtual: true});
}, { virtual: true });
describe('TriggerPanelCtrl', () => {
let ctx: any = {};
let createPanelCtrl: () => any;
beforeEach(() => {
ctx = { scope: {
panel: {
...PANEL_DEFAULTS,
sortProblems: 'lastchange',
ctx = {
scope: {
panel: {
...PANEL_DEFAULTS,
sortProblems: 'lastchange',
}
}
}};
};
ctx.scope.panel.targets = [{
...DEFAULT_TARGET,
datasource: 'zabbix_default',
@@ -43,10 +45,10 @@ describe('TriggerPanelCtrl', () => {
ctx.panelCtrl = createPanelCtrl();
ctx.dataFramesReceived = generateDataFramesResponse([
{id: "1", timestamp: "1510000010", severity: 5},
{id: "2", timestamp: "1510000040", severity: 3},
{id: "3", timestamp: "1510000020", severity: 4},
{id: "4", timestamp: "1510000030", severity: 2},
{ id: "1", timestamp: "1510000010", severity: 5 },
{ id: "2", timestamp: "1510000040", severity: 3 },
{ id: "3", timestamp: "1510000020", severity: 4 },
{ id: "4", timestamp: "1510000030", severity: 2 },
]);
});
@@ -68,7 +70,7 @@ describe('TriggerPanelCtrl', () => {
it('should format triggers', (done) => {
ctx.panelCtrl.onDataFramesReceived(ctx.dataFramesReceived).then(() => {
const formattedTrigger: any = _.find(ctx.panelCtrl.renderData, {triggerid: "1"});
const formattedTrigger: any = _.find(ctx.panelCtrl.renderData, { triggerid: "1" });
expect(formattedTrigger.host).toBe('backend01');
expect(formattedTrigger.hostTechName).toBe('backend01_tech');
expect(formattedTrigger.datasource).toBe('zabbix_default');
@@ -167,7 +169,7 @@ const defaultProblem: any = {
"value": "1"
};
function generateDataFramesResponse(problemDescs: any[] = [{id: 1}]): any {
function generateDataFramesResponse(problemDescs: any[] = [{ id: 1 }]): any {
const problems = problemDescs.map(problem => generateProblem(problem.id, problem.timestamp, problem.severity));
return [
@@ -205,5 +207,5 @@ function generateProblem(id, timestamp?, severity?): any {
}
function getProblemById(id, ctx): any {
return _.find(ctx.panelCtrl.renderData, {triggerid: id.toString()});
return _.find(ctx.panelCtrl.renderData, { triggerid: id.toString() });
}