Commit b904e0c6 by Hugo Häggmark Committed by GitHub

Chore: Removes observableTester (#29369)

parent 465735a7
......@@ -17,4 +17,3 @@ export { locationUtil } from './location';
export { urlUtil, UrlQueryMap, UrlQueryValue } from './url';
export { DataLinkBuiltInVars, mapInternalLinkToExplore } from './dataLinks';
export { DocsId } from './docs';
export { observableTester } from './tests/observableTester';
import { Observable } from 'rxjs';
interface ObservableTester<T> {
observable: Observable<T>;
done: {
(...args: any[]): any;
fail(error?: string | { message: string }): any;
};
}
interface SubscribeAndExpectOnNext<T> extends ObservableTester<T> {
expect: (value: T) => void;
}
interface SubscribeAndExpectOnNextAndComplete<T> extends ObservableTester<T> {
expectOnNext: (value: T) => void;
expectOnComplete: () => void;
}
interface SubscribeAndExpectOnComplete<T> extends ObservableTester<T> {
expect: () => void;
}
interface SubscribeAndExpectOnError<T> extends ObservableTester<T> {
expect: (err: any) => void;
}
export const observableTester = () => {
const subscribeAndExpectOnNext = <T>({ observable, expect, done }: SubscribeAndExpectOnNext<T>): void => {
observable.subscribe({
next: value => {
try {
expect(value);
} catch (err) {
done.fail(err);
}
},
error: err => done.fail(err),
complete: () => done(),
});
};
const subscribeAndExpectOnComplete = <T>({ observable, expect, done }: SubscribeAndExpectOnComplete<T>): void => {
observable.subscribe({
next: () => {},
error: err => done.fail(err),
complete: () => {
try {
expect();
done();
} catch (err) {
done.fail(err);
}
},
});
};
const subscribeAndExpectOnNextAndComplete = <T>({
observable,
expectOnComplete,
expectOnNext,
done,
}: SubscribeAndExpectOnNextAndComplete<T>): void => {
observable.subscribe({
next: (value: T) => {
try {
expectOnNext(value);
done();
} catch (err) {
done.fail(err);
}
},
error: err => done.fail(err),
complete: () => {
try {
expectOnComplete();
done();
} catch (err) {
done.fail(err);
}
},
});
};
const subscribeAndExpectOnError = <T>({ observable, expect, done }: SubscribeAndExpectOnError<T>): void => {
observable.subscribe({
next: () => {},
error: err => {
try {
expect(err);
done();
} catch (err) {
done.fail(err);
}
},
complete: () => {
done();
},
});
};
return {
subscribeAndExpectOnNext,
subscribeAndExpectOnComplete,
subscribeAndExpectOnNextAndComplete,
subscribeAndExpectOnError,
};
};
import { of } from 'rxjs';
import { queryBuilder } from '../shared/testing/builders';
import { FieldType, observableTester, toDataFrame } from '@grafana/data';
import { FieldType, toDataFrame } from '@grafana/data';
import { initialQueryVariableModelState, updateVariableOptions, updateVariableTags } from './reducer';
import { toVariablePayload } from '../state/types';
import { VariableRefresh } from '../types';
......@@ -14,24 +14,22 @@ import {
} from './operators';
describe('operators', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('validateVariableSelection', () => {
describe('when called', () => {
it('then the correct observable should be created', done => {
it('then the correct observable should be created', async () => {
const variable = queryBuilder()
.withId('query')
.build();
const dispatch = jest.fn().mockResolvedValue({});
const observable = of(undefined).pipe(
validateVariableSelection({ variable, dispatch, searchFilter: 'A search filter' })
);
const observable = of(undefined).pipe(validateVariableSelection({ variable, dispatch }));
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
},
done,
await expect(observable).toEmitValuesWith(received => {
expect(received[0]).toEqual({});
expect(dispatch).toHaveBeenCalledTimes(1);
});
});
});
......@@ -39,7 +37,7 @@ describe('operators', () => {
describe('updateTagsState', () => {
describe('when called with a variable that uses Tags', () => {
it('then the correct observable should be created', done => {
it('then the correct observable should be created', async () => {
const variable = queryBuilder()
.withId('query')
.withTags(true)
......@@ -47,22 +45,17 @@ describe('operators', () => {
const dispatch = jest.fn().mockResolvedValue({});
const observable = of([{ text: 'A text' }]).pipe(updateTagsState({ variable, dispatch }));
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual(undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(
updateVariableTags(toVariablePayload(variable, [{ text: 'A text' }]))
);
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual(undefined);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(updateVariableTags(toVariablePayload(variable, [{ text: 'A text' }])));
});
});
});
describe('when called with a variable that does not use Tags', () => {
it('then the correct observable should be created', done => {
it('then the correct observable should be created', async () => {
const variable = queryBuilder()
.withId('query')
.withTags(false)
......@@ -70,13 +63,10 @@ describe('operators', () => {
const dispatch = jest.fn().mockResolvedValue({});
const observable = of([{ text: 'A text' }]).pipe(updateTagsState({ variable, dispatch }));
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual(undefined);
expect(dispatch).not.toHaveBeenCalled();
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual(undefined);
expect(dispatch).not.toHaveBeenCalled();
});
});
});
......@@ -84,7 +74,7 @@ describe('operators', () => {
describe('runUpdateTagsRequest', () => {
describe('when called with a datasource with metricFindQuery and variable that uses Tags and refreshes on time range changes', () => {
it('then the correct observable should be created', done => {
it('then the correct observable should be created', async () => {
const variable = queryBuilder()
.withId('query')
.withTags(true)
......@@ -98,33 +88,30 @@ describe('operators', () => {
const searchFilter = 'A search filter';
const observable = of(undefined).pipe(runUpdateTagsRequest({ variable, datasource, searchFilter }, timeSrv));
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
const { index, global, ...rest } = initialQueryVariableModelState;
expect(value).toEqual([{ text: 'A text' }]);
expect(timeSrv.timeRange).toHaveBeenCalledTimes(1);
expect(datasource.metricFindQuery).toHaveBeenCalledTimes(1);
expect(datasource.metricFindQuery).toHaveBeenCalledWith('A tags query', {
range: undefined,
searchFilter: 'A search filter',
variable: {
...rest,
id: 'query',
name: 'query',
useTags: true,
tagsQuery: 'A tags query',
refresh: VariableRefresh.onTimeRangeChanged,
},
});
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
const { index, global, ...rest } = initialQueryVariableModelState;
expect(value).toEqual([{ text: 'A text' }]);
expect(timeSrv.timeRange).toHaveBeenCalledTimes(1);
expect(datasource.metricFindQuery).toHaveBeenCalledTimes(1);
expect(datasource.metricFindQuery).toHaveBeenCalledWith('A tags query', {
range: undefined,
searchFilter: 'A search filter',
variable: {
...rest,
id: 'query',
name: 'query',
useTags: true,
tagsQuery: 'A tags query',
refresh: VariableRefresh.onTimeRangeChanged,
},
});
});
});
});
describe('when called with a datasource without metricFindQuery and variable that uses Tags and refreshes on time range changes', () => {
it('then the correct observable should be created', done => {
it('then the correct observable should be created', async () => {
const variable = queryBuilder()
.withId('query')
.withTags(true)
......@@ -138,19 +125,16 @@ describe('operators', () => {
const searchFilter = 'A search filter';
const observable = of(undefined).pipe(runUpdateTagsRequest({ variable, datasource, searchFilter }, timeSrv));
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual([]);
expect(timeSrv.timeRange).not.toHaveBeenCalled();
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual([]);
expect(timeSrv.timeRange).not.toHaveBeenCalled();
});
});
});
describe('when called with a datasource with metricFindQuery and variable that does not use Tags but refreshes on time range changes', () => {
it('then the correct observable should be created', done => {
it('then the correct observable should be created', async () => {
const variable = queryBuilder()
.withId('query')
.withTags(false)
......@@ -163,14 +147,11 @@ describe('operators', () => {
const searchFilter = 'A search filter';
const observable = of(undefined).pipe(runUpdateTagsRequest({ variable, datasource, searchFilter }, timeSrv));
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual([]);
expect(timeSrv.timeRange).not.toHaveBeenCalled();
expect(datasource.metricFindQuery).not.toHaveBeenCalled();
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual([]);
expect(timeSrv.timeRange).not.toHaveBeenCalled();
expect(datasource.metricFindQuery).not.toHaveBeenCalled();
});
});
});
......@@ -178,7 +159,7 @@ describe('operators', () => {
describe('updateOptionsState', () => {
describe('when called', () => {
it('then the correct observable should be created', done => {
it('then the correct observable should be created', async () => {
const variable = queryBuilder()
.withId('query')
.build();
......@@ -187,21 +168,18 @@ describe('operators', () => {
const observable = of([{ text: 'A' }]).pipe(updateOptionsState({ variable, dispatch, getTemplatedRegexFunc }));
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual(undefined);
expect(getTemplatedRegexFunc).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(
updateVariableOptions({
id: 'query',
type: 'query',
data: { results: [{ text: 'A' }], templatedRegex: 'getTemplatedRegexFunc result' },
})
);
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual(undefined);
expect(getTemplatedRegexFunc).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(
updateVariableOptions({
id: 'query',
type: 'query',
data: { results: [{ text: 'A' }], templatedRegex: 'getTemplatedRegexFunc result' },
})
);
});
});
});
......@@ -278,23 +256,20 @@ describe('operators', () => {
],
},
].map(scenario => {
it(`when called with series:${JSON.stringify(scenario.series, null, 0)}`, done => {
it(`when called with series:${JSON.stringify(scenario.series, null, 0)}`, async () => {
const { series, expected } = scenario;
const panelData: any = { series };
const observable = of(panelData).pipe(toMetricFindValues());
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual(expected);
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual(expected);
});
});
});
describe('when called without metric find values and string fields', () => {
it('then the observable throws', done => {
it('then the observable throws', async () => {
const frameWithTimeField = toDataFrame({
fields: [{ name: 'time', type: FieldType.time, values: [1, 2, 3] }],
});
......@@ -302,12 +277,9 @@ describe('operators', () => {
const panelData: any = { series: [frameWithTimeField] };
const observable = of(panelData).pipe(toMetricFindValues());
observableTester().subscribeAndExpectOnError({
observable,
expect: value => {
expect(value).toEqual(new Error("Couldn't find any field of type string in the results."));
},
done,
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual(new Error("Couldn't find any field of type string in the results."));
});
});
});
......
import { QueryRunners } from './queryRunners';
import { DefaultTimeRange, observableTester, VariableSupportType } from '@grafana/data';
import { DefaultTimeRange, VariableSupportType } from '@grafana/data';
import { VariableRefresh } from '../types';
import { of } from 'rxjs';
......@@ -41,17 +41,14 @@ describe('QueryRunners', () => {
});
const observable = runner.runRequest(runnerArgs, request);
it('then it should return correct observable', done => {
observableTester().subscribeAndExpectOnNext({
observable,
expect: values => {
expect(values).toEqual({
series: [{ text: 'A', value: 'A' }],
state: 'Done',
timeRange: { from: {}, raw: { from: '6h', to: 'now' }, to: {} },
});
},
done,
it('then it should return correct observable', async () => {
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual({
series: [{ text: 'A', value: 'A' }],
state: 'Done',
timeRange: { from: {}, raw: { from: '6h', to: 'now' }, to: {} },
});
});
});
......@@ -86,17 +83,14 @@ describe('QueryRunners', () => {
});
const observable = runner.runRequest(runnerArgs, request);
it('then it should return correct observable', done => {
observableTester().subscribeAndExpectOnNext({
observable,
expect: values => {
expect(values).toEqual({
series: [{ text: 'A', value: 'A' }],
state: 'Done',
timeRange: { from: {}, raw: { from: '6h', to: 'now' }, to: {} },
});
},
done,
it('then it should return correct observable', async () => {
await expect(observable).toEmitValuesWith(received => {
const values = received[0];
expect(values).toEqual({
series: [{ text: 'A', value: 'A' }],
state: 'Done',
timeRange: { from: {}, raw: { from: '6h', to: 'now' }, to: {} },
});
});
});
......@@ -161,13 +155,10 @@ describe('QueryRunners', () => {
});
const observable = runner.runRequest(runnerArgs, request);
it('then it should return correct observable', done => {
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual({});
},
done,
it('then it should return correct observable', async () => {
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual({});
});
});
......@@ -183,13 +174,10 @@ describe('QueryRunners', () => {
});
const observable = runner.runRequest(runnerArgs, request);
it('then it should return correct observable', done => {
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual({});
},
done,
it('then it should return correct observable', async () => {
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual({});
});
});
......@@ -234,13 +222,10 @@ describe('QueryRunners', () => {
const { runner, request, runnerArgs, runRequest, datasource } = getCustomTestContext();
const observable = runner.runRequest(runnerArgs, request);
it('then it should return correct observable', done => {
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual({});
},
done,
it('then it should return correct observable', async () => {
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual({});
});
});
......@@ -285,13 +270,10 @@ describe('QueryRunners', () => {
const { runner, request, runnerArgs, runRequest, datasource } = getDatasourceTestContext();
const observable = runner.runRequest(runnerArgs, request);
it('then it should return correct observable', done => {
observableTester().subscribeAndExpectOnNext({
observable,
expect: value => {
expect(value).toEqual({});
},
done,
it('then it should return correct observable', async () => {
await expect(observable).toEmitValuesWith(received => {
const value = received[0];
expect(value).toEqual({});
});
});
......
import { of, throwError } from 'rxjs';
import { DataSourceInstanceSettings, observableTester, toUtc } from '@grafana/data';
import { DataSourceInstanceSettings, toUtc } from '@grafana/data';
import CloudMonitoringDataSource from '../datasource';
import { metricDescriptors } from './testData';
......@@ -84,7 +84,7 @@ describe('CloudMonitoringDataSource', () => {
describe('When performing query', () => {
describe('and no time series data is returned', () => {
it('should return a list of datapoints', done => {
it('should return a list of datapoints', async () => {
const options = {
range: {
from: toUtc('2017-08-22T20:00:00Z'),
......@@ -116,12 +116,9 @@ describe('CloudMonitoringDataSource', () => {
const { ds } = getTestcontext({ response });
observableTester().subscribeAndExpectOnNext({
expect: results => {
expect(results.data.length).toBe(0);
},
observable: ds.query(options as any),
done,
await expect(ds.query(options as any)).toEmitValuesWith(received => {
const results = received[0];
expect(results.data.length).toBe(0);
});
});
});
......
import { of } from 'rxjs';
import { setBackendSrv } from '@grafana/runtime';
import { dateTime, DefaultTimeRange, observableTester } from '@grafana/data';
import { dateTime, DefaultTimeRange } from '@grafana/data';
import { TemplateSrv } from '../../../features/templating/template_srv';
import { CloudWatchDatasource } from './datasource';
describe('datasource', () => {
describe('query', () => {
it('should return error if log query and log groups is not specified', done => {
it('should return error if log query and log groups is not specified', async () => {
const { datasource } = setup();
const observable = datasource.query({
targets: [
{
queryMode: 'Logs' as 'Logs',
},
],
} as any);
observableTester().subscribeAndExpectOnNext({
observable: datasource.query({
targets: [
{
queryMode: 'Logs' as 'Logs',
},
],
} as any),
expect: response => {
expect(response.error?.message).toBe('Log group is required');
},
done,
await expect(observable).toEmitValuesWith(received => {
const response = received[0];
expect(response.error?.message).toBe('Log group is required');
});
});
it('should return empty response if queries are hidden', done => {
it('should return empty response if queries are hidden', async () => {
const { datasource } = setup();
const observable = datasource.query({
targets: [
{
queryMode: 'Logs' as 'Logs',
hide: true,
},
],
} as any);
observableTester().subscribeAndExpectOnNext({
observable: datasource.query({
targets: [
{
queryMode: 'Logs' as 'Logs',
hide: true,
},
],
} as any),
expect: response => {
expect(response.data).toEqual([]);
},
done,
await expect(observable).toEmitValuesWith(received => {
const response = received[0];
expect(response.data).toEqual([]);
});
});
});
describe('performTimeSeriesQuery', () => {
it('should return the same length of data as result', done => {
it('should return the same length of data as result', async () => {
const { datasource } = setup({
data: {
results: {
......@@ -58,20 +54,19 @@ describe('datasource', () => {
const buildCloudwatchConsoleUrlMock = jest.spyOn(datasource, 'buildCloudwatchConsoleUrl');
buildCloudwatchConsoleUrlMock.mockImplementation(() => '');
observableTester().subscribeAndExpectOnNext({
observable: datasource.performTimeSeriesQuery(
{
queries: [
{ datasourceId: 1, refId: 'a' },
{ datasourceId: 1, refId: 'b' },
],
} as any,
{ from: dateTime(), to: dateTime() } as any
),
expect: response => {
expect(response.data.length).toEqual(2);
},
done,
const observable = datasource.performTimeSeriesQuery(
{
queries: [
{ datasourceId: 1, refId: 'a' },
{ datasourceId: 1, refId: 'b' },
],
} as any,
{ from: dateTime(), to: dateTime() } as any
);
await expect(observable).toEmitValuesWith(received => {
const response = received[0];
expect(response.data.length).toEqual(2);
});
});
});
......
......@@ -6,9 +6,7 @@ import {
DataSourceInstanceSettings,
dateMath,
getFrameDisplayName,
observableTester,
} from '@grafana/data';
import { FetchResponse } from '@grafana/runtime';
import * as redux from 'app/store/store';
import '../datasource';
......@@ -22,6 +20,7 @@ import { getTemplateSrvDependencies } from 'test/helpers/getTemplateSrvDependenc
import { CustomVariableModel, initialVariableModelState, VariableHide } from '../../../../features/variables/types';
import * as rxjsUtils from '../utils/rxjs/increasingInterval';
import { createFetchResponse } from 'test/helpers/createFetchResponse';
jest.mock('rxjs/operators', () => {
const operators = jest.requireActual('rxjs/operators');
......@@ -358,29 +357,25 @@ describe('CloudWatchDatasource', () => {
},
};
it('should generate the correct query', done => {
it('should generate the correct query', async () => {
const { ds, fetchMock } = getTestContext({ response });
observableTester().subscribeAndExpectOnComplete({
observable: ds.query(query),
expect: () => {
expect(fetchMock.mock.calls[0][0].data.queries).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
namespace: query.targets[0].namespace,
metricName: query.targets[0].metricName,
dimensions: { InstanceId: ['i-12345678'] },
statistics: query.targets[0].statistics,
period: query.targets[0].period,
}),
])
);
},
done,
await expect(ds.query(query)).toEmitValuesWith(() => {
expect(fetchMock.mock.calls[0][0].data.queries).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
namespace: query.targets[0].namespace,
metricName: query.targets[0].metricName,
dimensions: { InstanceId: ['i-12345678'] },
statistics: query.targets[0].statistics,
period: query.targets[0].period,
}),
])
);
});
});
it('should generate the correct query with interval variable', done => {
it('should generate the correct query with interval variable', async () => {
const period: CustomVariableModel = {
...initialVariableModelState,
id: 'period',
......@@ -418,12 +413,8 @@ describe('CloudWatchDatasource', () => {
const { ds, fetchMock } = getTestContext({ response, templateSrv });
observableTester().subscribeAndExpectOnComplete({
observable: ds.query(query),
expect: () => {
expect(fetchMock.mock.calls[0][0].data.queries[0].period).toEqual('600');
},
done,
await expect(ds.query(query)).toEmitValuesWith(() => {
expect(fetchMock.mock.calls[0][0].data.queries[0].period).toEqual('600');
});
});
......@@ -451,39 +442,33 @@ describe('CloudWatchDatasource', () => {
expect(ds.query.bind(ds, query)).toThrow(/Invalid extended statistics/);
});
it('should return series list', done => {
it('should return series list', async () => {
const { ds } = getTestContext({ response });
observableTester().subscribeAndExpectOnNext({
observable: ds.query(query),
expect: result => {
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].values.buffer[0]).toBe(response.results.A.series[0].points[0][0]);
},
done,
await expect(ds.query(query)).toEmitValuesWith(received => {
const result = received[0];
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].values.buffer[0]).toBe(response.results.A.series[0].points[0][0]);
});
});
describe('a correct cloudwatch url should be built for each time series in the response', () => {
it('should be built correctly if theres one search expressions returned in meta for a given query row', done => {
it('should be built correctly if theres one search expressions returned in meta for a given query row', async () => {
const { ds } = getTestContext({ response });
response.results['A'].meta.gmdMeta = [{ Expression: `REMOVE_EMPTY(SEARCH('some expression'))`, Period: '300' }];
observableTester().subscribeAndExpectOnNext({
observable: ds.query(query),
expect: result => {
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].config.links[0].title).toBe('View in CloudWatch console');
expect(decodeURIComponent(result.data[0].fields[1].config.links[0].url)).toContain(
`region=us-east-1#metricsV2:graph={"view":"timeSeries","stacked":false,"title":"A","start":"2016-12-31T15:00:00.000Z","end":"2016-12-31T16:00:00.000Z","region":"us-east-1","metrics":[{"expression":"REMOVE_EMPTY(SEARCH(\'some expression\'))"}]}`
);
},
done,
await expect(ds.query(query)).toEmitValuesWith(received => {
const result = received[0];
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].config.links[0].title).toBe('View in CloudWatch console');
expect(decodeURIComponent(result.data[0].fields[1].config.links[0].url)).toContain(
`region=us-east-1#metricsV2:graph={"view":"timeSeries","stacked":false,"title":"A","start":"2016-12-31T15:00:00.000Z","end":"2016-12-31T16:00:00.000Z","region":"us-east-1","metrics":[{"expression":"REMOVE_EMPTY(SEARCH(\'some expression\'))"}]}`
);
});
});
it('should be built correctly if theres two search expressions returned in meta for a given query row', done => {
it('should be built correctly if theres two search expressions returned in meta for a given query row', async () => {
const { ds } = getTestContext({ response });
response.results['A'].meta.gmdMeta = [
......@@ -491,49 +476,40 @@ describe('CloudWatchDatasource', () => {
{ Expression: `REMOVE_EMPTY(SEARCH('second expression'))` },
];
observableTester().subscribeAndExpectOnNext({
observable: ds.query(query),
expect: result => {
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].config.links[0].title).toBe('View in CloudWatch console');
expect(decodeURIComponent(result.data[0].fields[0].config.links[0].url)).toContain(
`region=us-east-1#metricsV2:graph={"view":"timeSeries","stacked":false,"title":"A","start":"2016-12-31T15:00:00.000Z","end":"2016-12-31T16:00:00.000Z","region":"us-east-1","metrics":[{"expression":"REMOVE_EMPTY(SEARCH(\'first expression\'))"},{"expression":"REMOVE_EMPTY(SEARCH(\'second expression\'))"}]}`
);
},
done,
await expect(ds.query(query)).toEmitValuesWith(received => {
const result = received[0];
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].config.links[0].title).toBe('View in CloudWatch console');
expect(decodeURIComponent(result.data[0].fields[0].config.links[0].url)).toContain(
`region=us-east-1#metricsV2:graph={"view":"timeSeries","stacked":false,"title":"A","start":"2016-12-31T15:00:00.000Z","end":"2016-12-31T16:00:00.000Z","region":"us-east-1","metrics":[{"expression":"REMOVE_EMPTY(SEARCH(\'first expression\'))"},{"expression":"REMOVE_EMPTY(SEARCH(\'second expression\'))"}]}`
);
});
});
it('should be built correctly if the query is a metric stat query', done => {
it('should be built correctly if the query is a metric stat query', async () => {
const { ds } = getTestContext({ response });
response.results['A'].meta.gmdMeta = [{ Period: '300' }];
observableTester().subscribeAndExpectOnNext({
observable: ds.query(query),
expect: result => {
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].config.links[0].title).toBe('View in CloudWatch console');
expect(decodeURIComponent(result.data[0].fields[0].config.links[0].url)).toContain(
`region=us-east-1#metricsV2:graph={\"view\":\"timeSeries\",\"stacked\":false,\"title\":\"A\",\"start\":\"2016-12-31T15:00:00.000Z\",\"end\":\"2016-12-31T16:00:00.000Z\",\"region\":\"us-east-1\",\"metrics\":[[\"AWS/EC2\",\"CPUUtilization\",\"InstanceId\",\"i-12345678\",{\"stat\":\"Average\",\"period\":\"300\"}]]}`
);
},
done,
await expect(ds.query(query)).toEmitValuesWith(received => {
const result = received[0];
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].config.links[0].title).toBe('View in CloudWatch console');
expect(decodeURIComponent(result.data[0].fields[0].config.links[0].url)).toContain(
`region=us-east-1#metricsV2:graph={\"view\":\"timeSeries\",\"stacked\":false,\"title\":\"A\",\"start\":\"2016-12-31T15:00:00.000Z\",\"end\":\"2016-12-31T16:00:00.000Z\",\"region\":\"us-east-1\",\"metrics\":[[\"AWS/EC2\",\"CPUUtilization\",\"InstanceId\",\"i-12345678\",{\"stat\":\"Average\",\"period\":\"300\"}]]}`
);
});
});
it('should not be added at all if query is a math expression', done => {
it('should not be added at all if query is a math expression', async () => {
const { ds } = getTestContext({ response });
query.targets[0].expression = 'a * 2';
response.results['A'].meta.searchExpressions = [];
observableTester().subscribeAndExpectOnNext({
observable: ds.query(query),
expect: result => {
expect(result.data[0].fields[1].config.links).toBeUndefined();
},
done,
await expect(ds.query(query)).toEmitValuesWith(received => {
const result = received[0];
expect(result.data[0].fields[1].config.links).toBeUndefined();
});
});
});
......@@ -602,19 +578,15 @@ describe('CloudWatchDatasource', () => {
} as any);
});
it('should display one alert error message per region+datasource combination', done => {
it('should display one alert error message per region+datasource combination', async () => {
const { ds } = getTestContext({ response: backendErrorResponse, throws: true });
const memoizedDebounceSpy = jest.spyOn(ds, 'debouncedAlert');
observableTester().subscribeAndExpectOnError({
observable: ds.query(query),
expect: err => {
expect(memoizedDebounceSpy).toHaveBeenCalledWith('TestDatasource', 'us-east-1');
expect(memoizedDebounceSpy).toHaveBeenCalledWith('TestDatasource', 'us-east-2');
expect(memoizedDebounceSpy).toHaveBeenCalledWith('TestDatasource', 'eu-north-1');
expect(memoizedDebounceSpy).toBeCalledTimes(3);
},
done,
await expect(ds.query(query)).toEmitValuesWith(received => {
expect(memoizedDebounceSpy).toHaveBeenCalledWith('TestDatasource', 'us-east-1');
expect(memoizedDebounceSpy).toHaveBeenCalledWith('TestDatasource', 'us-east-2');
expect(memoizedDebounceSpy).toHaveBeenCalledWith('TestDatasource', 'eu-north-1');
expect(memoizedDebounceSpy).toBeCalledTimes(3);
});
});
});
......@@ -666,7 +638,7 @@ describe('CloudWatchDatasource', () => {
expect(ds.getActualRegion('some-fake-region-1')).toBe('some-fake-region-1');
});
it('should query for the datasource region if empty or "default"', done => {
it('should query for the datasource region if empty or "default"', async () => {
const { ds, instanceSettings } = getTestContext();
const performTimeSeriesQueryMock = jest.spyOn(ds, 'performTimeSeriesQuery').mockReturnValue(of({}));
......@@ -689,14 +661,10 @@ describe('CloudWatchDatasource', () => {
],
};
observableTester().subscribeAndExpectOnComplete({
observable: ds.query(query),
expect: () => {
expect(performTimeSeriesQueryMock.mock.calls[0][0].queries[0].region).toBe(
instanceSettings.jsonData.defaultRegion
);
},
done,
await expect(ds.query(query)).toEmitValuesWith(() => {
expect(performTimeSeriesQueryMock.mock.calls[0][0].queries[0].region).toBe(
instanceSettings.jsonData.defaultRegion
);
});
});
});
......@@ -809,16 +777,13 @@ describe('CloudWatchDatasource', () => {
},
};
it('should return series list', done => {
it('should return series list', async () => {
const { ds } = getTestContext({ response });
observableTester().subscribeAndExpectOnNext({
observable: ds.query(query),
expect: result => {
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].values.buffer[0]).toBe(response.results.A.series[0].points[0][0]);
},
done,
await expect(ds.query(query)).toEmitValuesWith(received => {
const result = received[0];
expect(getFrameDisplayName(result.data[0])).toBe(response.results.A.series[0].name);
expect(result.data[0].fields[1].values.buffer[0]).toBe(response.results.A.series[0].points[0][0]);
});
});
});
......@@ -892,7 +857,7 @@ describe('CloudWatchDatasource', () => {
templateSrv.init(variables);
});
it('should generate the correct query for single template variable', done => {
it('should generate the correct query for single template variable', async () => {
const { ds, fetchMock } = getTestContext({ templateSrv });
const query: any = {
range: defaultTimeRange,
......@@ -913,16 +878,12 @@ describe('CloudWatchDatasource', () => {
],
};
observableTester().subscribeAndExpectOnComplete({
observable: ds.query(query),
expect: () => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim2']).toStrictEqual(['var2-foo']);
},
done,
await expect(ds.query(query)).toEmitValuesWith(() => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim2']).toStrictEqual(['var2-foo']);
});
});
it('should generate the correct query in the case of one multilple template variables', done => {
it('should generate the correct query in the case of one multilple template variables', async () => {
const { ds, fetchMock } = getTestContext({ templateSrv });
const query: any = {
range: defaultTimeRange,
......@@ -949,18 +910,14 @@ describe('CloudWatchDatasource', () => {
},
};
observableTester().subscribeAndExpectOnComplete({
observable: ds.query(query),
expect: () => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim1']).toStrictEqual(['var1-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim2']).toStrictEqual(['var2-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim3']).toStrictEqual(['var3-foo', 'var3-baz']);
},
done,
await expect(ds.query(query)).toEmitValuesWith(() => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim1']).toStrictEqual(['var1-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim2']).toStrictEqual(['var2-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim3']).toStrictEqual(['var3-foo', 'var3-baz']);
});
});
it('should generate the correct query in the case of multilple multi template variables', done => {
it('should generate the correct query in the case of multilple multi template variables', async () => {
const { ds, fetchMock } = getTestContext({ templateSrv });
const query: any = {
range: defaultTimeRange,
......@@ -983,18 +940,14 @@ describe('CloudWatchDatasource', () => {
],
};
observableTester().subscribeAndExpectOnComplete({
observable: ds.query(query),
expect: () => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim1']).toStrictEqual(['var1-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim3']).toStrictEqual(['var3-foo', 'var3-baz']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim4']).toStrictEqual(['var4-foo', 'var4-baz']);
},
done,
await expect(ds.query(query)).toEmitValuesWith(() => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim1']).toStrictEqual(['var1-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim3']).toStrictEqual(['var3-foo', 'var3-baz']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim4']).toStrictEqual(['var4-foo', 'var4-baz']);
});
});
it('should generate the correct query for multilple template variables, lack scopedVars', done => {
it('should generate the correct query for multilple template variables, lack scopedVars', async () => {
const { ds, fetchMock } = getTestContext({ templateSrv });
const query: any = {
range: defaultTimeRange,
......@@ -1020,14 +973,10 @@ describe('CloudWatchDatasource', () => {
},
};
observableTester().subscribeAndExpectOnComplete({
observable: ds.query(query),
expect: () => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim1']).toStrictEqual(['var1-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim2']).toStrictEqual(['var2-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim3']).toStrictEqual(['var3-foo', 'var3-baz']);
},
done,
await expect(ds.query(query)).toEmitValuesWith(() => {
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim1']).toStrictEqual(['var1-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim2']).toStrictEqual(['var2-foo']);
expect(fetchMock.mock.calls[0][0].data.queries[0].dimensions['dim3']).toStrictEqual(['var3-foo', 'var3-baz']);
});
});
});
......@@ -1213,17 +1162,3 @@ function genMockFrames(numResponses: number): DataFrame[] {
return mockFrames;
}
function createFetchResponse<T>(data: T): FetchResponse<T> {
return {
data,
status: 200,
url: 'http://localhost:3000/api/query',
config: { url: 'http://localhost:3000/api/query' },
type: 'basic',
statusText: 'Ok',
redirected: false,
headers: ({} as unknown) as Headers,
ok: true,
};
}
......@@ -11,6 +11,7 @@ import { backendSrv } from 'app/core/services/backend_srv';
import { CustomVariableModel } from '../../../features/variables/types';
import { initialCustomVariableModelState } from '../../../features/variables/custom/reducer';
import { makeMockLokiDatasource } from './mocks';
import { createFetchResponse } from 'test/helpers/createFetchResponse';
jest.mock('@grafana/runtime', () => ({
// @ts-ignore
......@@ -593,17 +594,3 @@ function makeMetadataAndVersionsMocks() {
}
return mocks;
}
function createFetchResponse<T>(data: T): FetchResponse<T> {
return {
data,
status: 200,
url: 'http://localhost:3000/api/query',
config: { url: 'http://localhost:3000/api/query' },
type: 'basic',
statusText: 'Ok',
redirected: false,
headers: ({} as unknown) as Headers,
ok: true,
};
}
......@@ -6,7 +6,7 @@ import { TimeSrvStub } from 'test/specs/helpers';
import { TemplateSrv } from 'app/features/templating/template_srv';
import { backendSrv } from 'app/core/services/backend_srv';
import { initialCustomVariableModelState } from '../../../../features/variables/custom/reducer';
import { FetchResponse } from '@grafana/runtime'; // will use the version in __mocks__
import { createFetchResponse } from 'test/helpers/createFetchResponse';
jest.mock('@grafana/runtime', () => ({
...((jest.requireActual('@grafana/runtime') as unknown) as object),
......@@ -334,17 +334,3 @@ describe('MSSQLDatasource', () => {
});
});
});
function createFetchResponse<T>(data: T): FetchResponse<T> {
return {
data,
status: 200,
url: 'http://localhost:3000/api/query',
config: { url: 'http://localhost:3000/api/query' },
type: 'basic',
statusText: 'Ok',
redirected: false,
headers: ({} as unknown) as Headers,
ok: true,
};
}
......@@ -4,8 +4,8 @@ export function createFetchResponse<T>(data: T): FetchResponse<T> {
return {
data,
status: 200,
url: 'http://localhost:3000/api/query',
config: { url: 'http://localhost:3000/api/query' },
url: 'http://localhost:3000/api/tsdb/query',
config: { url: 'http://localhost:3000/api/tsdb/query' },
type: 'basic',
statusText: 'Ok',
redirected: false,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment