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,14 +1,16 @@
import _ from 'lodash';
import mocks from '../../test-setup/mocks'; import mocks from '../../test-setup/mocks';
import { ZabbixDatasource } from "../datasource"; import { ZabbixDatasource, zabbixTemplateFormat } from "../datasource";
import { zabbixTemplateFormat } from "../datasource";
import { dateMath } from '@grafana/data'; import { dateMath } from '@grafana/data';
jest.mock('@grafana/runtime', () => ({ jest.mock('@grafana/runtime', () => ({
getBackendSrv: () => ({ getBackendSrv: () => ({
datasourceRequest: jest.fn().mockResolvedValue({ data: { result: '' } }), datasourceRequest: jest.fn().mockResolvedValue({ data: { result: '' } }),
fetch: () => ({
toPromise: () => jest.fn().mockResolvedValue({ data: { result: '' } })
}), }),
loadPluginCss: () => {}, }),
loadPluginCss: () => {
},
}), { virtual: true }); }), { virtual: true });
describe('ZabbixDatasource', () => { describe('ZabbixDatasource', () => {
@@ -27,17 +29,6 @@ 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 = { ctx.options = {
targets: [ targets: [
{ {
@@ -53,50 +44,10 @@ describe('ZabbixDatasource', () => {
} }
}; };
it('should return an empty array when no targets are set', (done) => { ctx.templateSrv = mocks.templateSrvMock;
let options = { ctx.datasourceSrv = mocks.datasourceSrvMock;
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.ds = new ZabbixDatasource(ctx.instanceSettings, ctx.templateSrv);
}); });
describe('When querying text data', () => { describe('When querying text data', () => {

View File

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

View File

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

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,7 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import mocks from '../../test-setup/mocks'; import './matchMedia.mock';
import {TriggerPanelCtrl} from '../triggers_panel_ctrl'; import { DEFAULT_SEVERITY, DEFAULT_TARGET, PANEL_DEFAULTS, TriggerPanelCtrl } from '../triggers_panel_ctrl';
import { DEFAULT_TARGET, DEFAULT_SEVERITY, PANEL_DEFAULTS } from '../triggers_panel_ctrl';
import { CURRENT_SCHEMA_VERSION } from '../migrations'; import { CURRENT_SCHEMA_VERSION } from '../migrations';
jest.mock('@grafana/runtime', () => { jest.mock('@grafana/runtime', () => {
@@ -19,7 +18,8 @@ describe('Triggers Panel schema migration', () => {
let ctx: any = {}; let ctx: any = {};
let updatePanelCtrl; let updatePanelCtrl;
const timeoutMock = () => {}; const timeoutMock = () => {
};
beforeEach(() => { beforeEach(() => {
ctx = { ctx = {

View File

@@ -1,6 +1,6 @@
import _ from 'lodash'; import _ from 'lodash';
import { TriggerPanelCtrl } from '../triggers_panel_ctrl'; import './matchMedia.mock';
import { PANEL_DEFAULTS, DEFAULT_TARGET } from '../triggers_panel_ctrl'; import { DEFAULT_TARGET, PANEL_DEFAULTS, TriggerPanelCtrl } from '../triggers_panel_ctrl';
let datasourceSrvMock, zabbixDSMock; let datasourceSrvMock, zabbixDSMock;
@@ -15,12 +15,14 @@ describe('TriggerPanelCtrl', () => {
let createPanelCtrl: () => any; let createPanelCtrl: () => any;
beforeEach(() => { beforeEach(() => {
ctx = { scope: { ctx = {
scope: {
panel: { panel: {
...PANEL_DEFAULTS, ...PANEL_DEFAULTS,
sortProblems: 'lastchange', sortProblems: 'lastchange',
} }
}}; }
};
ctx.scope.panel.targets = [{ ctx.scope.panel.targets = [{
...DEFAULT_TARGET, ...DEFAULT_TARGET,
datasource: 'zabbix_default', datasource: 'zabbix_default',