Chore: Fix strict errors, down to 340 (#32109)

* Chore: reduces misc reducerTester strict issues

* Chore: fixes various strict errors in reducer tests for ElasticSearch

* Chore: lowers errors in AzureMonitor DataSource tests
This commit is contained in:
Hugo Häggmark
2021-03-19 13:10:03 +01:00
committed by GitHub
parent d3544d6df1
commit c8b59b79c3
12 changed files with 129 additions and 147 deletions

View File

@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { render, screen } from '@testing-library/react'; import { render, screen } from '@testing-library/react';
import { SoloPanelPage, Props } from './SoloPanelPage'; import { Props, SoloPanelPage } from './SoloPanelPage';
import { Props as DashboardPanelProps } from '../dashgrid/DashboardPanel'; import { Props as DashboardPanelProps } from '../dashgrid/DashboardPanel';
import { DashboardModel } from '../state'; import { DashboardModel } from '../state';
import { DashboardRoutes } from 'app/types'; import { DashboardRoutes } from 'app/types';
@@ -82,7 +82,7 @@ function soloPanelPageScenario(description: string, scenarioFn: (ctx: ScenarioCo
ctx.dashboard = props.dashboard; ctx.dashboard = props.dashboard;
let { rerender } = render(<SoloPanelPage {...props} />); let { rerender } = render(<SoloPanelPage {...props} />);
// prop updates will be submitted by rerendering the same component with different props // prop updates will be submitted by rerendering the same component with different props
ctx.rerender = (newProps: Partial<Props>) => { ctx.rerender = (newProps?: Partial<Props>) => {
Object.assign(props, newProps); Object.assign(props, newProps);
rerender(<SoloPanelPage {...props} />); rerender(<SoloPanelPage {...props} />);
}; };

View File

@@ -114,7 +114,7 @@ describe('running queries', () => {
describe('reducer', () => { describe('reducer', () => {
describe('scanning', () => { describe('scanning', () => {
it('should start scanning', () => { it('should start scanning', () => {
const initialState = { const initialState: ExploreItemState = {
...makeExplorePaneState(), ...makeExplorePaneState(),
scanning: false, scanning: false,
}; };

View File

@@ -1,12 +1,12 @@
import { reducerTester } from '../../../../test/core/redux/reducerTester'; import { reducerTester } from '../../../../test/core/redux/reducerTester';
import { initialVariableInspectState, initInspect, variableInspectReducer } from './reducer'; import { initialVariableInspectState, initInspect, variableInspectReducer, VariableInspectState } from './reducer';
import { textboxBuilder } from '../shared/testing/builders'; import { textboxBuilder } from '../shared/testing/builders';
describe('variableInspectReducer', () => { describe('variableInspectReducer', () => {
describe('when initInspect is dispatched', () => { describe('when initInspect is dispatched', () => {
it('then state should be correct', () => { it('then state should be correct', () => {
const variable = textboxBuilder().withId('text').withName('text').build(); const variable = textboxBuilder().withId('text').withName('text').build();
reducerTester() reducerTester<VariableInspectState>()
.givenReducer(variableInspectReducer, { ...initialVariableInspectState }) .givenReducer(variableInspectReducer, { ...initialVariableInspectState })
.whenActionIsDispatched( .whenActionIsDispatched(
initInspect({ initInspect({

View File

@@ -2,6 +2,7 @@ import { interval, of, throwError } from 'rxjs';
import { import {
DataFrame, DataFrame,
DataQueryErrorType, DataQueryErrorType,
DataQueryRequest,
DataQueryResponse, DataQueryResponse,
DataSourceInstanceSettings, DataSourceInstanceSettings,
dateMath, dateMath,
@@ -16,6 +17,7 @@ import {
CloudWatchLogsQuery, CloudWatchLogsQuery,
CloudWatchLogsQueryStatus, CloudWatchLogsQueryStatus,
CloudWatchMetricsQuery, CloudWatchMetricsQuery,
CloudWatchQuery,
LogAction, LogAction,
} from '../types'; } from '../types';
import { backendSrv } from 'app/core/services/backend_srv'; // will use the version in __mocks__ import { backendSrv } from 'app/core/services/backend_srv'; // will use the version in __mocks__
@@ -301,7 +303,7 @@ describe('CloudWatchDatasource', () => {
it('should call the replace method on provided log groups', () => { it('should call the replace method on provided log groups', () => {
const { ds } = getTestContext(); const { ds } = getTestContext();
const replaceSpy = jest.spyOn(ds, 'replace').mockImplementation((target: string) => target); const replaceSpy = jest.spyOn(ds, 'replace').mockImplementation((target?: string) => target ?? '');
ds.makeLogActionRequest('StartQuery', [ ds.makeLogActionRequest('StartQuery', [
{ {
queryString: 'test query string', queryString: 'test query string',
@@ -425,7 +427,7 @@ describe('CloudWatchDatasource', () => {
it.each(['pNN.NN', 'p9', 'p99.', 'p99.999'])('should cancel query for invalid extended statistics (%s)', (stat) => { it.each(['pNN.NN', 'p9', 'p99.', 'p99.999'])('should cancel query for invalid extended statistics (%s)', (stat) => {
const { ds } = getTestContext({ response }); const { ds } = getTestContext({ response });
const query = { const query: DataQueryRequest<CloudWatchQuery> = ({
range: defaultTimeRange, range: defaultTimeRange,
rangeRaw: { from: 1483228800, to: 1483232400 }, rangeRaw: { from: 1483228800, to: 1483232400 },
targets: [ targets: [
@@ -442,7 +444,7 @@ describe('CloudWatchDatasource', () => {
period: '60s', period: '60s',
}, },
], ],
}; } as unknown) as DataQueryRequest<CloudWatchQuery>;
expect(ds.query.bind(ds, query)).toThrow(/Invalid extended statistics/); expect(ds.query.bind(ds, query)).toThrow(/Invalid extended statistics/);
}); });

View File

@@ -5,7 +5,7 @@ import { reducer } from './reducer';
describe('Filters Bucket Aggregation Settings Reducer', () => { describe('Filters Bucket Aggregation Settings Reducer', () => {
it('Should correctly add new filter', () => { it('Should correctly add new filter', () => {
reducerTester() reducerTester<Filter[]>()
.givenReducer(reducer, []) .givenReducer(reducer, [])
.whenActionIsDispatched(addFilter()) .whenActionIsDispatched(addFilter())
.thenStatePredicateShouldEqual((state: Filter[]) => state.length === 1); .thenStatePredicateShouldEqual((state: Filter[]) => state.length === 1);
@@ -22,7 +22,7 @@ describe('Filters Bucket Aggregation Settings Reducer', () => {
query: '*', query: '*',
}; };
reducerTester() reducerTester<Filter[]>()
.givenReducer(reducer, [firstFilter, secondFilter]) .givenReducer(reducer, [firstFilter, secondFilter])
.whenActionIsDispatched(removeFilter(0)) .whenActionIsDispatched(removeFilter(0))
.thenStateShouldEqual([secondFilter]); .thenStateShouldEqual([secondFilter]);
@@ -44,7 +44,7 @@ describe('Filters Bucket Aggregation Settings Reducer', () => {
query: 'Changed query', query: 'Changed query',
}; };
reducerTester() reducerTester<Filter[]>()
.givenReducer(reducer, [firstFilter, secondFilter]) .givenReducer(reducer, [firstFilter, secondFilter])
.whenActionIsDispatched(changeFilter(1, expectedSecondFilter)) .whenActionIsDispatched(changeFilter(1, expectedSecondFilter))
.thenStateShouldEqual([firstFilter, expectedSecondFilter]); .thenStateShouldEqual([firstFilter, expectedSecondFilter]);

View File

@@ -12,6 +12,7 @@ import {
} from './actions'; } from './actions';
import { reducer } from './reducer'; import { reducer } from './reducer';
import { initQuery } from '../../state'; import { initQuery } from '../../state';
import { ElasticsearchQuery } from 'app/plugins/datasource/elasticsearch/types';
describe('Bucket Aggregations Reducer', () => { describe('Bucket Aggregations Reducer', () => {
it('Should correctly add new aggregations', () => { it('Should correctly add new aggregations', () => {
@@ -27,7 +28,7 @@ describe('Bucket Aggregations Reducer', () => {
settings: bucketAggregationConfig['terms'].defaultSettings, settings: bucketAggregationConfig['terms'].defaultSettings,
}; };
reducerTester() reducerTester<ElasticsearchQuery['bucketAggs']>()
.givenReducer(reducer, []) .givenReducer(reducer, [])
.whenActionIsDispatched(addBucketAggregation(firstAggregation.id)) .whenActionIsDispatched(addBucketAggregation(firstAggregation.id))
.thenStateShouldEqual([firstAggregation]) .thenStateShouldEqual([firstAggregation])
@@ -46,7 +47,7 @@ describe('Bucket Aggregations Reducer', () => {
type: 'date_histogram', type: 'date_histogram',
}; };
reducerTester() reducerTester<ElasticsearchQuery['bucketAggs']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(removeBucketAggregation(firstAggregation.id)) .whenActionIsDispatched(removeBucketAggregation(firstAggregation.id))
.thenStateShouldEqual([secondAggregation]); .thenStateShouldEqual([secondAggregation]);
@@ -68,7 +69,7 @@ describe('Bucket Aggregations Reducer', () => {
settings: bucketAggregationConfig['histogram'].defaultSettings, settings: bucketAggregationConfig['histogram'].defaultSettings,
}; };
reducerTester() reducerTester<ElasticsearchQuery['bucketAggs']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(changeBucketAggregationType(secondAggregation.id, expectedSecondAggregation.type)) .whenActionIsDispatched(changeBucketAggregationType(secondAggregation.id, expectedSecondAggregation.type))
.thenStateShouldEqual([firstAggregation, expectedSecondAggregation]); .thenStateShouldEqual([firstAggregation, expectedSecondAggregation]);
@@ -89,7 +90,7 @@ describe('Bucket Aggregations Reducer', () => {
field: 'new field', field: 'new field',
}; };
reducerTester() reducerTester<ElasticsearchQuery['bucketAggs']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(changeBucketAggregationField(secondAggregation.id, expectedSecondAggregation.field)) .whenActionIsDispatched(changeBucketAggregationField(secondAggregation.id, expectedSecondAggregation.field))
.thenStateShouldEqual([firstAggregation, expectedSecondAggregation]); .thenStateShouldEqual([firstAggregation, expectedSecondAggregation]);
@@ -104,17 +105,17 @@ describe('Bucket Aggregations Reducer', () => {
}, },
]; ];
reducerTester() reducerTester<ElasticsearchQuery['bucketAggs']>()
.givenReducer(reducer, initialState) .givenReducer(reducer, initialState)
// If the new metric aggregation is `isSingleMetric` we should remove all bucket aggregations. // If the new metric aggregation is `isSingleMetric` we should remove all bucket aggregations.
.whenActionIsDispatched(changeMetricType('Some id', 'raw_data')) .whenActionIsDispatched(changeMetricType('Some id', 'raw_data'))
.thenStatePredicateShouldEqual((newState: BucketAggregation[]) => newState.length === 0) .thenStatePredicateShouldEqual((newState) => newState?.length === 0)
// Switching back to another aggregation that is NOT `isSingleMetric` should bring back a bucket aggregation // Switching back to another aggregation that is NOT `isSingleMetric` should bring back a bucket aggregation
.whenActionIsDispatched(changeMetricType('Some id', 'max')) .whenActionIsDispatched(changeMetricType('Some id', 'max'))
.thenStatePredicateShouldEqual((newState: BucketAggregation[]) => newState.length === 1) .thenStatePredicateShouldEqual((newState) => newState?.length === 1)
// When none of the above is true state shouldn't change. // When none of the above is true state shouldn't change.
.whenActionIsDispatched(changeMetricType('Some id', 'min')) .whenActionIsDispatched(changeMetricType('Some id', 'min'))
.thenStatePredicateShouldEqual((newState: BucketAggregation[]) => newState.length === 1); .thenStatePredicateShouldEqual((newState) => newState?.length === 1);
}); });
}); });
@@ -135,7 +136,7 @@ describe('Bucket Aggregations Reducer', () => {
min_doc_count: '1', min_doc_count: '1',
}; };
reducerTester() reducerTester<ElasticsearchQuery['bucketAggs']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched( .whenActionIsDispatched(
changeBucketAggregationSetting(firstAggregation, 'min_doc_count', expectedSettings.min_doc_count!) changeBucketAggregationSetting(firstAggregation, 'min_doc_count', expectedSettings.min_doc_count!)
@@ -144,7 +145,7 @@ describe('Bucket Aggregations Reducer', () => {
}); });
it('Should correctly initialize first Bucket Aggregation', () => { it('Should correctly initialize first Bucket Aggregation', () => {
reducerTester() reducerTester<ElasticsearchQuery['bucketAggs']>()
.givenReducer(reducer, []) .givenReducer(reducer, [])
.whenActionIsDispatched(initQuery()) .whenActionIsDispatched(initQuery())
.thenStateShouldEqual([defaultBucketAgg('2')]); .thenStateShouldEqual([defaultBucketAgg('2')]);

View File

@@ -15,7 +15,7 @@ describe('BucketScript Settings Reducer', () => {
pipelineAgg: '', pipelineAgg: '',
}; };
reducerTester() reducerTester<PipelineVariable[]>()
.givenReducer(reducer, []) .givenReducer(reducer, [])
.whenActionIsDispatched(addPipelineVariable()) .whenActionIsDispatched(addPipelineVariable())
.thenStateShouldEqual([expectedPipelineVar]); .thenStateShouldEqual([expectedPipelineVar]);
@@ -32,7 +32,7 @@ describe('BucketScript Settings Reducer', () => {
pipelineAgg: '', pipelineAgg: '',
}; };
reducerTester() reducerTester<PipelineVariable[]>()
.givenReducer(reducer, [firstVar, secondVar]) .givenReducer(reducer, [firstVar, secondVar])
.whenActionIsDispatched(removePipelineVariable(0)) .whenActionIsDispatched(removePipelineVariable(0))
.thenStateShouldEqual([secondVar]); .thenStateShouldEqual([secondVar]);
@@ -54,7 +54,7 @@ describe('BucketScript Settings Reducer', () => {
name: 'new name', name: 'new name',
}; };
reducerTester() reducerTester<PipelineVariable[]>()
.givenReducer(reducer, [firstVar, secondVar]) .givenReducer(reducer, [firstVar, secondVar])
.whenActionIsDispatched(renamePipelineVariable(expectedSecondVar.name, 1)) .whenActionIsDispatched(renamePipelineVariable(expectedSecondVar.name, 1))
.thenStateShouldEqual([firstVar, expectedSecondVar]); .thenStateShouldEqual([firstVar, expectedSecondVar]);
@@ -76,7 +76,7 @@ describe('BucketScript Settings Reducer', () => {
pipelineAgg: 'some new agg', pipelineAgg: 'some new agg',
}; };
reducerTester() reducerTester<PipelineVariable[]>()
.givenReducer(reducer, [firstVar, secondVar]) .givenReducer(reducer, [firstVar, secondVar])
.whenActionIsDispatched(changePipelineVariableMetric(expectedSecondVar.pipelineAgg, 1)) .whenActionIsDispatched(changePipelineVariableMetric(expectedSecondVar.pipelineAgg, 1))
.thenStateShouldEqual([firstVar, expectedSecondVar]); .thenStateShouldEqual([firstVar, expectedSecondVar]);
@@ -94,7 +94,7 @@ describe('BucketScript Settings Reducer', () => {
}, },
]; ];
reducerTester() reducerTester<PipelineVariable[]>()
.givenReducer(reducer, initialState) .givenReducer(reducer, initialState)
.whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' }) .whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' })
.thenStateShouldEqual(initialState); .thenStateShouldEqual(initialState);

View File

@@ -14,6 +14,7 @@ import { Derivative, ExtendedStats, MetricAggregation } from '../aggregations';
import { defaultMetricAgg } from '../../../../query_def'; import { defaultMetricAgg } from '../../../../query_def';
import { metricAggregationConfig } from '../utils'; import { metricAggregationConfig } from '../utils';
import { initQuery } from '../../state'; import { initQuery } from '../../state';
import { ElasticsearchQuery } from 'app/plugins/datasource/elasticsearch/types';
describe('Metric Aggregations Reducer', () => { describe('Metric Aggregations Reducer', () => {
it('should correctly add new aggregations', () => { it('should correctly add new aggregations', () => {
@@ -26,7 +27,7 @@ describe('Metric Aggregations Reducer', () => {
type: 'count', type: 'count',
}; };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, []) .givenReducer(reducer, [])
.whenActionIsDispatched(addMetric(firstAggregation.id)) .whenActionIsDispatched(addMetric(firstAggregation.id))
.thenStateShouldEqual([firstAggregation]) .thenStateShouldEqual([firstAggregation])
@@ -45,7 +46,7 @@ describe('Metric Aggregations Reducer', () => {
type: 'count', type: 'count',
}; };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(removeMetric(firstAggregation.id)) .whenActionIsDispatched(removeMetric(firstAggregation.id))
.thenStateShouldEqual([secondAggregation]); .thenStateShouldEqual([secondAggregation]);
@@ -54,7 +55,7 @@ describe('Metric Aggregations Reducer', () => {
it('Should insert a default aggregation when the last one is removed', () => { it('Should insert a default aggregation when the last one is removed', () => {
const initialState: MetricAggregation[] = [{ id: '2', type: 'avg' }]; const initialState: MetricAggregation[] = [{ id: '2', type: 'avg' }];
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, initialState) .givenReducer(reducer, initialState)
.whenActionIsDispatched(removeMetric(initialState[0].id)) .whenActionIsDispatched(removeMetric(initialState[0].id))
.thenStateShouldEqual([defaultMetricAgg()]); .thenStateShouldEqual([defaultMetricAgg()]);
@@ -74,7 +75,7 @@ describe('Metric Aggregations Reducer', () => {
const expectedSecondAggregation: MetricAggregation = { ...secondAggregation, type: 'avg' }; const expectedSecondAggregation: MetricAggregation = { ...secondAggregation, type: 'avg' };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(changeMetricType(secondAggregation.id, expectedSecondAggregation.type)) .whenActionIsDispatched(changeMetricType(secondAggregation.id, expectedSecondAggregation.type))
.thenStateShouldEqual([firstAggregation, { ...secondAggregation, type: expectedSecondAggregation.type }]); .thenStateShouldEqual([firstAggregation, { ...secondAggregation, type: expectedSecondAggregation.type }]);
@@ -96,7 +97,7 @@ describe('Metric Aggregations Reducer', () => {
...metricAggregationConfig['raw_data'].defaults, ...metricAggregationConfig['raw_data'].defaults,
}; };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(changeMetricType(secondAggregation.id, expectedAggregation.type)) .whenActionIsDispatched(changeMetricType(secondAggregation.id, expectedAggregation.type))
.thenStateShouldEqual([expectedAggregation]); .thenStateShouldEqual([expectedAggregation]);
@@ -124,7 +125,7 @@ describe('Metric Aggregations Reducer', () => {
field: 'new field', field: 'new field',
}; };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
// When changing a a pipelineAggregation field we set both pipelineAgg and field // When changing a a pipelineAggregation field we set both pipelineAgg and field
.whenActionIsDispatched(changeMetricField(secondAggregation.id, expectedSecondAggregation.field)) .whenActionIsDispatched(changeMetricField(secondAggregation.id, expectedSecondAggregation.field))
@@ -145,7 +146,7 @@ describe('Metric Aggregations Reducer', () => {
type: 'count', type: 'count',
}; };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(toggleMetricVisibility(firstAggregation.id)) .whenActionIsDispatched(toggleMetricVisibility(firstAggregation.id))
.thenStateShouldEqual([{ ...firstAggregation, hide: true }, secondAggregation]) .thenStateShouldEqual([{ ...firstAggregation, hide: true }, secondAggregation])
@@ -170,7 +171,7 @@ describe('Metric Aggregations Reducer', () => {
unit: 'Changed unit', unit: 'Changed unit',
}; };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(changeMetricSetting(firstAggregation, 'unit', expectedSettings.unit!)) .whenActionIsDispatched(changeMetricSetting(firstAggregation, 'unit', expectedSettings.unit!))
.thenStateShouldEqual([{ ...firstAggregation, settings: expectedSettings }, secondAggregation]); .thenStateShouldEqual([{ ...firstAggregation, settings: expectedSettings }, secondAggregation]);
@@ -193,7 +194,7 @@ describe('Metric Aggregations Reducer', () => {
avg: false, avg: false,
}; };
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(changeMetricMeta(firstAggregation, 'avg', expectedMeta.avg!)) .whenActionIsDispatched(changeMetricMeta(firstAggregation, 'avg', expectedMeta.avg!))
.thenStateShouldEqual([{ ...firstAggregation, meta: expectedMeta }, secondAggregation]); .thenStateShouldEqual([{ ...firstAggregation, meta: expectedMeta }, secondAggregation]);
@@ -211,7 +212,7 @@ describe('Metric Aggregations Reducer', () => {
const expectedHide: typeof firstAggregation['hide'] = false; const expectedHide: typeof firstAggregation['hide'] = false;
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, [firstAggregation, secondAggregation]) .givenReducer(reducer, [firstAggregation, secondAggregation])
.whenActionIsDispatched(changeMetricAttribute(firstAggregation, 'hide', expectedHide)) .whenActionIsDispatched(changeMetricAttribute(firstAggregation, 'hide', expectedHide))
.thenStateShouldEqual([{ ...firstAggregation, hide: expectedHide }, secondAggregation]); .thenStateShouldEqual([{ ...firstAggregation, hide: expectedHide }, secondAggregation]);
@@ -225,14 +226,14 @@ describe('Metric Aggregations Reducer', () => {
}, },
]; ];
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, initialState) .givenReducer(reducer, initialState)
.whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' }) .whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' })
.thenStateShouldEqual(initialState); .thenStateShouldEqual(initialState);
}); });
it('Should correctly initialize first Metric Aggregation', () => { it('Should correctly initialize first Metric Aggregation', () => {
reducerTester() reducerTester<ElasticsearchQuery['metrics']>()
.givenReducer(reducer, []) .givenReducer(reducer, [])
.whenActionIsDispatched(initQuery()) .whenActionIsDispatched(initQuery())
.thenStateShouldEqual([defaultMetricAgg('1')]); .thenStateShouldEqual([defaultMetricAgg('1')]);

View File

@@ -7,7 +7,7 @@ describe('Query Reducer', () => {
it('Should maintain the previous `query` if present', () => { it('Should maintain the previous `query` if present', () => {
const initialQuery: ElasticsearchQuery['query'] = 'Some lucene query'; const initialQuery: ElasticsearchQuery['query'] = 'Some lucene query';
reducerTester() reducerTester<ElasticsearchQuery['query']>()
.givenReducer(queryReducer, initialQuery) .givenReducer(queryReducer, initialQuery)
.whenActionIsDispatched(initQuery()) .whenActionIsDispatched(initQuery())
.thenStateShouldEqual(initialQuery); .thenStateShouldEqual(initialQuery);
@@ -17,7 +17,7 @@ describe('Query Reducer', () => {
const initialQuery: ElasticsearchQuery['query'] = undefined; const initialQuery: ElasticsearchQuery['query'] = undefined;
const expectedQuery = ''; const expectedQuery = '';
reducerTester() reducerTester<ElasticsearchQuery['query']>()
.givenReducer(queryReducer, initialQuery) .givenReducer(queryReducer, initialQuery)
.whenActionIsDispatched(initQuery()) .whenActionIsDispatched(initQuery())
.thenStateShouldEqual(expectedQuery); .thenStateShouldEqual(expectedQuery);
@@ -27,7 +27,7 @@ describe('Query Reducer', () => {
it('Should correctly set `query`', () => { it('Should correctly set `query`', () => {
const expectedQuery: ElasticsearchQuery['query'] = 'Some lucene query'; const expectedQuery: ElasticsearchQuery['query'] = 'Some lucene query';
reducerTester() reducerTester<ElasticsearchQuery['query']>()
.givenReducer(queryReducer, '') .givenReducer(queryReducer, '')
.whenActionIsDispatched(changeQuery(expectedQuery)) .whenActionIsDispatched(changeQuery(expectedQuery))
.thenStateShouldEqual(expectedQuery); .thenStateShouldEqual(expectedQuery);
@@ -36,7 +36,7 @@ describe('Query Reducer', () => {
it('Should not change state with other action types', () => { it('Should not change state with other action types', () => {
const initialState: ElasticsearchQuery['query'] = 'Some lucene query'; const initialState: ElasticsearchQuery['query'] = 'Some lucene query';
reducerTester() reducerTester<ElasticsearchQuery['query']>()
.givenReducer(queryReducer, initialState) .givenReducer(queryReducer, initialState)
.whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' }) .whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' })
.thenStateShouldEqual(initialState); .thenStateShouldEqual(initialState);
@@ -47,7 +47,7 @@ describe('Alias Pattern Reducer', () => {
it('Should correctly set `alias`', () => { it('Should correctly set `alias`', () => {
const expectedAlias: ElasticsearchQuery['alias'] = 'Some alias pattern'; const expectedAlias: ElasticsearchQuery['alias'] = 'Some alias pattern';
reducerTester() reducerTester<ElasticsearchQuery['query']>()
.givenReducer(aliasPatternReducer, '') .givenReducer(aliasPatternReducer, '')
.whenActionIsDispatched(changeAliasPattern(expectedAlias)) .whenActionIsDispatched(changeAliasPattern(expectedAlias))
.thenStateShouldEqual(expectedAlias); .thenStateShouldEqual(expectedAlias);
@@ -56,7 +56,7 @@ describe('Alias Pattern Reducer', () => {
it('Should not change state with other action types', () => { it('Should not change state with other action types', () => {
const initialState: ElasticsearchQuery['alias'] = 'Some alias pattern'; const initialState: ElasticsearchQuery['alias'] = 'Some alias pattern';
reducerTester() reducerTester<ElasticsearchQuery['query']>()
.givenReducer(aliasPatternReducer, initialState) .givenReducer(aliasPatternReducer, initialState)
.whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' }) .whenActionIsDispatched({ type: 'THIS ACTION SHOULD NOT HAVE ANY EFFECT IN THIS REDUCER' })
.thenStateShouldEqual(initialState); .thenStateShouldEqual(initialState);

View File

@@ -102,14 +102,13 @@ describe('AzureMonitorDatasource', () => {
datasourceRequestMock.mockImplementation(() => Promise.resolve(response)); datasourceRequestMock.mockImplementation(() => Promise.resolve(response));
}); });
it('should return a list of subscriptions', () => { it('should return a list of subscriptions', async () => {
return ctx.ds.metricFindQuery('subscriptions()').then((results: Array<{ text: string; value: string }>) => { const results = await ctx.ds.metricFindQuery('subscriptions()');
expect(results.length).toBe(2); expect(results.length).toBe(2);
expect(results[0].text).toBe('Primary'); expect(results[0].text).toBe('Primary');
expect(results[0].value).toBe('sub1'); expect(results[0].value).toBe('sub1');
expect(results[1].text).toBe('Secondary'); expect(results[1].text).toBe('Secondary');
expect(results[1].value).toBe('sub2'); expect(results[1].value).toBe('sub2');
});
}); });
}); });
@@ -126,14 +125,13 @@ describe('AzureMonitorDatasource', () => {
datasourceRequestMock.mockImplementation(() => Promise.resolve(response)); datasourceRequestMock.mockImplementation(() => Promise.resolve(response));
}); });
it('should return a list of resource groups', () => { it('should return a list of resource groups', async () => {
return ctx.ds.metricFindQuery('ResourceGroups()').then((results: Array<{ text: string; value: string }>) => { const results = await ctx.ds.metricFindQuery('ResourceGroups()');
expect(results.length).toBe(2); expect(results.length).toBe(2);
expect(results[0].text).toBe('grp1'); expect(results[0].text).toBe('grp1');
expect(results[0].value).toBe('grp1'); expect(results[0].value).toBe('grp1');
expect(results[1].text).toBe('grp2'); expect(results[1].text).toBe('grp2');
expect(results[1].value).toBe('grp2'); expect(results[1].value).toBe('grp2');
});
}); });
}); });
@@ -153,16 +151,13 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of resource groups', () => { it('should return a list of resource groups', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery('ResourceGroups(11112222-eeee-4949-9b2d-9106972f9123)');
.metricFindQuery('ResourceGroups(11112222-eeee-4949-9b2d-9106972f9123)') expect(results.length).toBe(2);
.then((results: Array<{ text: string; value: string }>) => { expect(results[0].text).toBe('grp1');
expect(results.length).toBe(2); expect(results[0].value).toBe('grp1');
expect(results[0].text).toBe('grp1'); expect(results[1].text).toBe('grp2');
expect(results[0].value).toBe('grp1'); expect(results[1].value).toBe('grp2');
expect(results[1].text).toBe('grp2');
expect(results[1].value).toBe('grp2');
});
}); });
}); });
@@ -189,14 +184,11 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of namespaces', () => { it('should return a list of namespaces', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery('Namespaces(nodesapp)');
.metricFindQuery('Namespaces(nodesapp)') expect(results.length).toEqual(1);
.then((results: Array<{ text: string; value: string }>) => { expect(results[0].text).toEqual('Microsoft.Network/networkInterfaces');
expect(results.length).toEqual(1); expect(results[0].value).toEqual('Microsoft.Network/networkInterfaces');
expect(results[0].text).toEqual('Microsoft.Network/networkInterfaces');
expect(results[0].value).toEqual('Microsoft.Network/networkInterfaces');
});
}); });
}); });
@@ -223,14 +215,11 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of namespaces', () => { it('should return a list of namespaces', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery('namespaces(11112222-eeee-4949-9b2d-9106972f9123, nodesapp)');
.metricFindQuery('namespaces(11112222-eeee-4949-9b2d-9106972f9123, nodesapp)') expect(results.length).toEqual(1);
.then((results: Array<{ text: string; value: string }>) => { expect(results[0].text).toEqual('Microsoft.Network/networkInterfaces');
expect(results.length).toEqual(1); expect(results[0].value).toEqual('Microsoft.Network/networkInterfaces');
expect(results[0].text).toEqual('Microsoft.Network/networkInterfaces');
expect(results[0].value).toEqual('Microsoft.Network/networkInterfaces');
});
}); });
}); });
@@ -261,14 +250,11 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of resource names', () => { it('should return a list of resource names', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery('resourceNames(nodeapp, microsoft.insights/components )');
.metricFindQuery('resourceNames(nodeapp, microsoft.insights/components )') expect(results.length).toEqual(1);
.then((results: Array<{ text: string; value: string }>) => { expect(results[0].text).toEqual('nodeapp');
expect(results.length).toEqual(1); expect(results[0].value).toEqual('nodeapp');
expect(results[0].text).toEqual('nodeapp');
expect(results[0].value).toEqual('nodeapp');
});
}); });
}); });
@@ -347,17 +333,16 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of metric names', () => { it('should return a list of metric names', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery(
.metricFindQuery('Metricnames(nodeapp, microsoft.insights/components, rn, default)') 'Metricnames(nodeapp, microsoft.insights/components, rn, default)'
.then((results: Array<{ text: string; value: string }>) => { );
expect(results.length).toEqual(2); expect(results.length).toEqual(2);
expect(results[0].text).toEqual('Percentage CPU'); expect(results[0].text).toEqual('Percentage CPU');
expect(results[0].value).toEqual('Percentage CPU'); expect(results[0].value).toEqual('Percentage CPU');
expect(results[1].text).toEqual('Used capacity'); expect(results[1].text).toEqual('Used capacity');
expect(results[1].value).toEqual('UsedCapacity'); expect(results[1].value).toEqual('UsedCapacity');
});
}); });
}); });
@@ -396,19 +381,16 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of metric names', () => { it('should return a list of metric names', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery(
.metricFindQuery( 'Metricnames(11112222-eeee-4949-9b2d-9106972f9123, nodeapp, microsoft.insights/components, rn, default)'
'Metricnames(11112222-eeee-4949-9b2d-9106972f9123, nodeapp, microsoft.insights/components, rn, default)' );
) expect(results.length).toEqual(2);
.then((results: Array<{ text: string; value: string }>) => { expect(results[0].text).toEqual('Percentage CPU');
expect(results.length).toEqual(2); expect(results[0].value).toEqual('Percentage CPU');
expect(results[0].text).toEqual('Percentage CPU');
expect(results[0].value).toEqual('Percentage CPU');
expect(results[1].text).toEqual('Used capacity'); expect(results[1].text).toEqual('Used capacity');
expect(results[1].value).toEqual('UsedCapacity'); expect(results[1].value).toEqual('UsedCapacity');
});
}); });
}); });
@@ -446,17 +428,14 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of metric names', () => { it('should return a list of metric names', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery('Metricnamespace(nodeapp, Microsoft.Compute/virtualMachines, rn)');
.metricFindQuery('Metricnamespace(nodeapp, Microsoft.Compute/virtualMachines, rn)') expect(results.length).toEqual(2);
.then((results: Array<{ text: string; value: string }>) => { expect(results[0].text).toEqual('Microsoft.Compute-virtualMachines');
expect(results.length).toEqual(2); expect(results[0].value).toEqual('Microsoft.Compute/virtualMachines');
expect(results[0].text).toEqual('Microsoft.Compute-virtualMachines');
expect(results[0].value).toEqual('Microsoft.Compute/virtualMachines');
expect(results[1].text).toEqual('Telegraf-mem'); expect(results[1].text).toEqual('Telegraf-mem');
expect(results[1].value).toEqual('Telegraf/mem'); expect(results[1].value).toEqual('Telegraf/mem');
});
}); });
}); });
@@ -494,19 +473,16 @@ describe('AzureMonitorDatasource', () => {
}); });
}); });
it('should return a list of metric namespaces', () => { it('should return a list of metric namespaces', async () => {
return ctx.ds const results = await ctx.ds.metricFindQuery(
.metricFindQuery( 'Metricnamespace(11112222-eeee-4949-9b2d-9106972f9123, nodeapp, Microsoft.Compute/virtualMachines, rn)'
'Metricnamespace(11112222-eeee-4949-9b2d-9106972f9123, nodeapp, Microsoft.Compute/virtualMachines, rn)' );
) expect(results.length).toEqual(2);
.then((results: Array<{ text: string; value: string }>) => { expect(results[0].text).toEqual('Microsoft.Compute-virtualMachines');
expect(results.length).toEqual(2); expect(results[0].value).toEqual('Microsoft.Compute/virtualMachines');
expect(results[0].text).toEqual('Microsoft.Compute-virtualMachines');
expect(results[0].value).toEqual('Microsoft.Compute/virtualMachines');
expect(results[1].text).toEqual('Telegraf-mem'); expect(results[1].text).toEqual('Telegraf-mem');
expect(results[1].value).toEqual('Telegraf/mem'); expect(results[1].value).toEqual('Telegraf/mem');
});
}); });
}); });
}); });

View File

@@ -1,10 +1,12 @@
import { Reducer } from 'redux'; import { Action } from 'redux';
import { PayloadAction, Action } from '@reduxjs/toolkit'; import { AnyAction } from '@reduxjs/toolkit';
import { cloneDeep } from 'lodash'; import { cloneDeep } from 'lodash';
type GrafanaReducer<S = any, A extends Action = AnyAction> = (state: S, action: A) => S;
export interface Given<State> { export interface Given<State> {
givenReducer: ( givenReducer: (
reducer: Reducer<State, PayloadAction<any> | Action<any>>, reducer: GrafanaReducer<State, AnyAction>,
state: State, state: State,
showDebugOutput?: boolean, showDebugOutput?: boolean,
disableDeepFreeze?: boolean disableDeepFreeze?: boolean
@@ -12,13 +14,13 @@ export interface Given<State> {
} }
export interface When<State> { export interface When<State> {
whenActionIsDispatched: (action: PayloadAction<any> | Action<any>) => Then<State>; whenActionIsDispatched: (action: AnyAction) => Then<State>;
} }
export interface Then<State> { export interface Then<State> {
thenStateShouldEqual: (state: State) => When<State>; thenStateShouldEqual: (state: State) => When<State>;
thenStatePredicateShouldEqual: (predicate: (resultingState: State) => boolean) => When<State>; thenStatePredicateShouldEqual: (predicate: (resultingState: State) => boolean) => When<State>;
whenActionIsDispatched: (action: PayloadAction<any> | Action<any>) => Then<State>; whenActionIsDispatched: (action: AnyAction) => Then<State>;
} }
interface ObjectType extends Object { interface ObjectType extends Object {
@@ -56,13 +58,13 @@ export const deepFreeze = <T>(obj: T): T => {
interface ReducerTester<State> extends Given<State>, When<State>, Then<State> {} interface ReducerTester<State> extends Given<State>, When<State>, Then<State> {}
export const reducerTester = <State>(): Given<State> => { export const reducerTester = <State>(): Given<State> => {
let reducerUnderTest: Reducer<State, PayloadAction<any>>; let reducerUnderTest: GrafanaReducer<State, AnyAction>;
let resultingState: State; let resultingState: State;
let initialState: State; let initialState: State;
let showDebugOutput = false; let showDebugOutput = false;
const givenReducer = ( const givenReducer = (
reducer: Reducer<State, PayloadAction<any>>, reducer: GrafanaReducer<State, AnyAction>,
state: State, state: State,
debug = false, debug = false,
disableDeepFreeze = false disableDeepFreeze = false
@@ -77,7 +79,7 @@ export const reducerTester = <State>(): Given<State> => {
return instance; return instance;
}; };
const whenActionIsDispatched = (action: PayloadAction<any>): Then<State> => { const whenActionIsDispatched = (action: AnyAction): Then<State> => {
resultingState = reducerUnderTest(resultingState || initialState, action); resultingState = reducerUnderTest(resultingState || initialState, action);
return instance; return instance;

View File

@@ -3,7 +3,7 @@ set -e
echo -e "Collecting code stats (typescript errors & more)" echo -e "Collecting code stats (typescript errors & more)"
ERROR_COUNT_LIMIT=416 ERROR_COUNT_LIMIT=340
ERROR_COUNT="$(./node_modules/.bin/tsc --project tsconfig.json --noEmit --strict true | grep -oP 'Found \K(\d+)')" ERROR_COUNT="$(./node_modules/.bin/tsc --project tsconfig.json --noEmit --strict true | grep -oP 'Found \K(\d+)')"
if [ "$ERROR_COUNT" -gt $ERROR_COUNT_LIMIT ]; then if [ "$ERROR_COUNT" -gt $ERROR_COUNT_LIMIT ]; then