Files
grafana/public/app/features/dashboard/components/DashExportModal/DashboardExporter.test.ts

514 lines
15 KiB
TypeScript
Raw Normal View History

import { find } from 'lodash';
import { DataSourceInstanceSettings, DataSourceRef, PanelPluginMeta } from '@grafana/data';
import { Dashboard, ThresholdsMode } from '@grafana/schema';
import config from 'app/core/config';
import { LibraryElementKind } from '../../../library-panels/types';
import { variableAdapters } from '../../../variables/adapters';
import { createConstantVariableAdapter } from '../../../variables/constant/adapter';
import { createDataSourceVariableAdapter } from '../../../variables/datasource/adapter';
import { createQueryVariableAdapter } from '../../../variables/query/adapter';
import { DashboardModel } from '../../state/DashboardModel';
import { DashboardExporter, LibraryElementExport } from './DashboardExporter';
2018-06-13 15:15:36 +02:00
jest.mock('app/core/store', () => {
return {
getBool: jest.fn(),
Templating: Migrates some variable types from Angular to React/Redux (#22434) * Refactor: Adds variables in state to TemplateSrv * Refactor: Introduces some typings and structures * Refactor: Introduces picker to adapter * Refactor: Removes useState and introduces contains instead * Refactor: Introduces Variable Editor * Refactor: Adds uuid and simplifies state * Refactor: Consolidates to VariableRenderer * Refactor: Adds name change capability * Refactor: Adds variableMiddleware * Refactor: Adds ability to change Angular type to type in State * Fix: Fixes so we check for duplicate names * Refactor: Adds ability to change State type to type in Angular * Refactor: Updates name in dashboard templating list * Refactor: Adds label change to VariableEditor * Refactor: Adds hide change to VariableEditor * Refactor: Adds update ability * Refactor: Adds tooltip * Refactor: Adds SelectionOptionsEditor * Refactor: Adds query editor and validation * Refactor: Adds regex and sort to editor * Refactor: Adds Selection options * Refactor: Adds Varible Values Previewer * Refactor: Changes from array in state to Record * Refactor: Removes getVariableAtIndex from templateSrv * Tests: Fixs broken tests * Chore: Fixes duplicate merge import * Refactor: Removes strict null errors * Refactor: Adds duplicate variable * Refactor: Adds remove variable * Refactor: Adds change order of variables * Refactor: Adds add new variable * Chore: Fixes Prettier formatting * Refactor: Adds VariablePicker * Fixed so sub menu is displayed when we only have redux template variables. * removed unused variable. * tags will be visibile in the new react picker. * added some nice colors to the tags. * Added thunk for selecting a tag. * Refactor: Cleans up templating state when dashboard unloads * Refactor: Adds save capabilities for variables in state * added possibility to select tag. * Added so you can deselect a tag. * Fixed issue with coloring on top. * minor refactoring to make the code more slim. * Refactor: Fixes dispatch return and copy of variable * selecting options when tag i selected * small refactoring. * fixed so we use options. * Refactor: Adds getValueForUrl capabilities * first implementation of keyboard navigation on picker. * removed comment. * fixed so you can toggle all options. * Refactor: Simplified state handling using Redux Toolkit and flat reducer structure * Refactor: Adds sharedTemplatingReducer and queryVariableReducer * Tests: Fixs broken tests * Chore: Removes some strict null errors * Tests: Fix broken tests * Refactor: Splitted QueryVariablePicker into smaller components * Refactor: Moves linktext and selected tags to component instead * Fix: Fixes the ability to have multiple dropdowns opened at same time * Fix: Fixes onKeyDown from prev refactor * Refactor: Adds searchfilter searching * Tests: Fixes after running e2e tests * Refactor: Adds an attempt to solve dependencies at startup * Refactor: Adds feature toggle * Refactor: Resets all angular files to master * Refactor: Move stuff to query folder * Refactor: Initial commit for SubMenu component * Refactor: Updated DashboardModel with new list * Refactor: Adds feature toggle to dashboard model and friends * Refactor: Adds picker to SubMenu * Refactor: Fixes styling on SubMenu * Refactor: Fixes processvariables * Refactor: Initial EditorList skeleton * Refactor: Refactors out VariableEditorList and VariableEditorContainer * Refactor: Adds New variable functionality * Refactor: Adds registred types * Refactor: Adds edit existing variable functionality * Refactor: Changes params to thunks * Refactor: Small fix for cleaning up state when clicking update/add * Refactor: Better typings for outer containers * Refactor: Adds change order functionality * Refactor: Removed notify angular args * Change so the url is in sync with the redux template variables. * Adding support for saving proper values and checking changes. * Refactor: Adds duplicate variable functionality * Feature: Adds remove variable functionality * Refactor: Small refactor so e2e tests work as before * Refactor: Returns null if no visible variables * Refactor: Adds annotations to SubMenu * Refactor: Fixes toggling of annotations in SubMenu * added dashboard links to new submehu. * Refactor: Small refactor breaking up into smaller components * Fix: Fixes infinite recursive loop when changing varible name * Templating: Do not mutate location query state * Refactor: Fixes minor timing issue when adding new variable * Refactor: removes initialization in variable_srv constructor * Refactor: Suggestion on how to handle templating.list in DashboardExporter * Refactor: Adds getVariables typings and changes ChangeTracker and ShareSnapshotCtrl * Refactor: Adds getVariable on DashboardModel and changes DashboardMigrator * Fix: Fixes repeated panels * wip: starting to add custom variable type. * Refactor: Merging two different toVariablePayload functions * Tests: Fixes broken tests * Fix: Reduces strict null errors * Tests: Initial commit and fixes strange dependency order * Tests: Covers sharedTemplatingReducer with tests * Refactor: Rename state/index.ts => state/reducers.ts as every where else * Refactor: Renames and moves adapters.ts * Tests: Adds tests for templatingReducer * Tests: Adds intitial tests for queryVariableReducer * starting to ad custom variable. * Tests: Adds more queryVariableReducer tests * Added support for custom variable. Next up applying some DRY principles and refactoring. * fixed compile issue. * added todo. * Tests: Fixes broken test * Tests: Covers queryVariableReducer with tests and fixed a couple of bugs * Fix: Fixes broken test * Fix: Reduces strict null errors * change so custom won't be depending on anything elese. * fixed descriptions. * removed unused dependency. * Fixed issue when adding a new variable and editor is being unmount twice. * fixed issue with select option loop. * changed so we update query on typing in editor and removed it from component state. * Moved runQuery up one level in the component tree. * renamed action and moved it to custom actions. * moved applyStateChanges to shared code. * removed todo comment. * first stab on moving picker to more general. * Refactor: Changes so we always show variables type * removed duplicate code regarding picker. * Did some renamings. * Feature: Adds text box variable type * moved tests from query reducer to picker reducer. * Removed picker from VariableState. * removed reference to picker. * Some more refactorings of the picker reducer + actions. * Chore: Refactors away editor state to its own state slice (#22515) * Refactor: Inital move, tests not working * Tests: Adds editorReducer tests * Refactor: Cleaning up * Refactor: Moves logic to thunk instead * Refactor: Initial commit * Refactor: Combines reducers to one state * Refactor: Adds combine reducers * moved navigation logic flow to a thunk instead of in the component. * fixed issue with rendering picker link. * Refactor: Removes variable prop from templating.variables * refactored and removed some more code. * Feature: adds Constant variable type * fixed so tags can be selected. * Fix: fixes default hide for constant and enum order * fixed so tags works again. * Fix: fixes so we use Angular editor when newVariables is not defined * Fix: fixes wrong hide default for Constant variable * Fix: fixes bug when using duplicate button * Fix: changes action id * Tests: prepares for newVariables * Chore: reduces strict null errors * Refactor: removes uuidInEditorReducer for simplification * Chore: changes after PR comments * Chore: uses getConfig instead of config * Tests: fixes so e2e tests check for feature toggle and fixed initLock bug * Refactor: changes so sharedReducer uses createSlice instead * Refactor: changes textBoxVariableReducer to use creactSlice instead * Refactor: changes queryBoxVariableReducer to use creactSlice instead * Refactor: changes customVariableReducer to use creactSlice instead * Refactor: changes constantVariableReducer to use creactSlice instead * Refactor: moves types to specific types.ts files instead * changed so we use queryValue stored on the variable to populate options input when opening picker. * Feature: adds the ability to test templating thunks using real store and middleware * Chore: cleans up unused import * excluded queryValue from the getSaveModel * Refactor: adds whenAsyncActionIsDispatched to reduxTester * Tests: adds initial tests for processVariables * Added reducer tests for constant variable. * added tests for custom reducer. * added tets for texbox reducer. * Tests: adds more tests for ProcessVariable * Refactor: fixes processVariable flow so we do notrun updateOptions twice * Tests: finishes tests for processVariables and removed skip test * added actions tests for custom and constant. * Tests: adds tests for setOptionFromUrl * Tests: adds a naive variable mock builder * Tests: adds tests for validateVariableSelectionState * added tests for query variable actions. * added last test for query actions. * added more tests. * some more tests. * fixed typing errors. * Fixed issues with variable tags. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-10 08:53:41 +01:00
getObject: jest.fn(),
2018-06-13 15:15:36 +02:00
};
});
jest.mock('@grafana/runtime', () => ({
...jest.requireActual('@grafana/runtime'),
getDataSourceSrv: () => {
return {
get: (v: any) => {
const s = getStubInstanceSettings(v);
// console.log('GET', v, s);
return Promise.resolve(s);
},
getInstanceSettings: getStubInstanceSettings,
};
},
config: {
buildInfo: {},
panels: {},
Templating: Migrates some variable types from Angular to React/Redux (#22434) * Refactor: Adds variables in state to TemplateSrv * Refactor: Introduces some typings and structures * Refactor: Introduces picker to adapter * Refactor: Removes useState and introduces contains instead * Refactor: Introduces Variable Editor * Refactor: Adds uuid and simplifies state * Refactor: Consolidates to VariableRenderer * Refactor: Adds name change capability * Refactor: Adds variableMiddleware * Refactor: Adds ability to change Angular type to type in State * Fix: Fixes so we check for duplicate names * Refactor: Adds ability to change State type to type in Angular * Refactor: Updates name in dashboard templating list * Refactor: Adds label change to VariableEditor * Refactor: Adds hide change to VariableEditor * Refactor: Adds update ability * Refactor: Adds tooltip * Refactor: Adds SelectionOptionsEditor * Refactor: Adds query editor and validation * Refactor: Adds regex and sort to editor * Refactor: Adds Selection options * Refactor: Adds Varible Values Previewer * Refactor: Changes from array in state to Record * Refactor: Removes getVariableAtIndex from templateSrv * Tests: Fixs broken tests * Chore: Fixes duplicate merge import * Refactor: Removes strict null errors * Refactor: Adds duplicate variable * Refactor: Adds remove variable * Refactor: Adds change order of variables * Refactor: Adds add new variable * Chore: Fixes Prettier formatting * Refactor: Adds VariablePicker * Fixed so sub menu is displayed when we only have redux template variables. * removed unused variable. * tags will be visibile in the new react picker. * added some nice colors to the tags. * Added thunk for selecting a tag. * Refactor: Cleans up templating state when dashboard unloads * Refactor: Adds save capabilities for variables in state * added possibility to select tag. * Added so you can deselect a tag. * Fixed issue with coloring on top. * minor refactoring to make the code more slim. * Refactor: Fixes dispatch return and copy of variable * selecting options when tag i selected * small refactoring. * fixed so we use options. * Refactor: Adds getValueForUrl capabilities * first implementation of keyboard navigation on picker. * removed comment. * fixed so you can toggle all options. * Refactor: Simplified state handling using Redux Toolkit and flat reducer structure * Refactor: Adds sharedTemplatingReducer and queryVariableReducer * Tests: Fixs broken tests * Chore: Removes some strict null errors * Tests: Fix broken tests * Refactor: Splitted QueryVariablePicker into smaller components * Refactor: Moves linktext and selected tags to component instead * Fix: Fixes the ability to have multiple dropdowns opened at same time * Fix: Fixes onKeyDown from prev refactor * Refactor: Adds searchfilter searching * Tests: Fixes after running e2e tests * Refactor: Adds an attempt to solve dependencies at startup * Refactor: Adds feature toggle * Refactor: Resets all angular files to master * Refactor: Move stuff to query folder * Refactor: Initial commit for SubMenu component * Refactor: Updated DashboardModel with new list * Refactor: Adds feature toggle to dashboard model and friends * Refactor: Adds picker to SubMenu * Refactor: Fixes styling on SubMenu * Refactor: Fixes processvariables * Refactor: Initial EditorList skeleton * Refactor: Refactors out VariableEditorList and VariableEditorContainer * Refactor: Adds New variable functionality * Refactor: Adds registred types * Refactor: Adds edit existing variable functionality * Refactor: Changes params to thunks * Refactor: Small fix for cleaning up state when clicking update/add * Refactor: Better typings for outer containers * Refactor: Adds change order functionality * Refactor: Removed notify angular args * Change so the url is in sync with the redux template variables. * Adding support for saving proper values and checking changes. * Refactor: Adds duplicate variable functionality * Feature: Adds remove variable functionality * Refactor: Small refactor so e2e tests work as before * Refactor: Returns null if no visible variables * Refactor: Adds annotations to SubMenu * Refactor: Fixes toggling of annotations in SubMenu * added dashboard links to new submehu. * Refactor: Small refactor breaking up into smaller components * Fix: Fixes infinite recursive loop when changing varible name * Templating: Do not mutate location query state * Refactor: Fixes minor timing issue when adding new variable * Refactor: removes initialization in variable_srv constructor * Refactor: Suggestion on how to handle templating.list in DashboardExporter * Refactor: Adds getVariables typings and changes ChangeTracker and ShareSnapshotCtrl * Refactor: Adds getVariable on DashboardModel and changes DashboardMigrator * Fix: Fixes repeated panels * wip: starting to add custom variable type. * Refactor: Merging two different toVariablePayload functions * Tests: Fixes broken tests * Fix: Reduces strict null errors * Tests: Initial commit and fixes strange dependency order * Tests: Covers sharedTemplatingReducer with tests * Refactor: Rename state/index.ts => state/reducers.ts as every where else * Refactor: Renames and moves adapters.ts * Tests: Adds tests for templatingReducer * Tests: Adds intitial tests for queryVariableReducer * starting to ad custom variable. * Tests: Adds more queryVariableReducer tests * Added support for custom variable. Next up applying some DRY principles and refactoring. * fixed compile issue. * added todo. * Tests: Fixes broken test * Tests: Covers queryVariableReducer with tests and fixed a couple of bugs * Fix: Fixes broken test * Fix: Reduces strict null errors * change so custom won't be depending on anything elese. * fixed descriptions. * removed unused dependency. * Fixed issue when adding a new variable and editor is being unmount twice. * fixed issue with select option loop. * changed so we update query on typing in editor and removed it from component state. * Moved runQuery up one level in the component tree. * renamed action and moved it to custom actions. * moved applyStateChanges to shared code. * removed todo comment. * first stab on moving picker to more general. * Refactor: Changes so we always show variables type * removed duplicate code regarding picker. * Did some renamings. * Feature: Adds text box variable type * moved tests from query reducer to picker reducer. * Removed picker from VariableState. * removed reference to picker. * Some more refactorings of the picker reducer + actions. * Chore: Refactors away editor state to its own state slice (#22515) * Refactor: Inital move, tests not working * Tests: Adds editorReducer tests * Refactor: Cleaning up * Refactor: Moves logic to thunk instead * Refactor: Initial commit * Refactor: Combines reducers to one state * Refactor: Adds combine reducers * moved navigation logic flow to a thunk instead of in the component. * fixed issue with rendering picker link. * Refactor: Removes variable prop from templating.variables * refactored and removed some more code. * Feature: adds Constant variable type * fixed so tags can be selected. * Fix: fixes default hide for constant and enum order * fixed so tags works again. * Fix: fixes so we use Angular editor when newVariables is not defined * Fix: fixes wrong hide default for Constant variable * Fix: fixes bug when using duplicate button * Fix: changes action id * Tests: prepares for newVariables * Chore: reduces strict null errors * Refactor: removes uuidInEditorReducer for simplification * Chore: changes after PR comments * Chore: uses getConfig instead of config * Tests: fixes so e2e tests check for feature toggle and fixed initLock bug * Refactor: changes so sharedReducer uses createSlice instead * Refactor: changes textBoxVariableReducer to use creactSlice instead * Refactor: changes queryBoxVariableReducer to use creactSlice instead * Refactor: changes customVariableReducer to use creactSlice instead * Refactor: changes constantVariableReducer to use creactSlice instead * Refactor: moves types to specific types.ts files instead * changed so we use queryValue stored on the variable to populate options input when opening picker. * Feature: adds the ability to test templating thunks using real store and middleware * Chore: cleans up unused import * excluded queryValue from the getSaveModel * Refactor: adds whenAsyncActionIsDispatched to reduxTester * Tests: adds initial tests for processVariables * Added reducer tests for constant variable. * added tests for custom reducer. * added tets for texbox reducer. * Tests: adds more tests for ProcessVariable * Refactor: fixes processVariable flow so we do notrun updateOptions twice * Tests: finishes tests for processVariables and removed skip test * added actions tests for custom and constant. * Tests: adds tests for setOptionFromUrl * Tests: adds a naive variable mock builder * Tests: adds tests for validateVariableSelectionState * added tests for query variable actions. * added last test for query actions. * added more tests. * some more tests. * fixed typing errors. * Fixed issues with variable tags. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-10 08:53:41 +01:00
featureToggles: {
newVariables: false,
},
angularSupportEnabled: true,
},
}));
2018-06-13 15:15:36 +02:00
jest.mock('app/features/library-panels/state/api', () => ({
getLibraryPanel: jest.fn().mockReturnValue(
Promise.resolve({
model: {
type: 'graph',
datasource: {
type: 'testdb',
uid: '${DS_GFDB}',
},
},
})
),
}));
variableAdapters.register(createQueryVariableAdapter());
variableAdapters.register(createConstantVariableAdapter());
variableAdapters.register(createDataSourceVariableAdapter());
it('handles a default datasource in a template variable', async () => {
const dashboard: any = {
templating: {
list: [
{
current: {},
definition: 'test',
error: {},
hide: 0,
includeAll: false,
multi: false,
name: 'query0',
options: [],
query: {
query: 'test',
refId: 'StandardVariableQuery',
},
refresh: 1,
regex: '',
skipUrlSync: false,
sort: 0,
type: 'query',
},
],
},
};
const dashboardModel = new DashboardModel(dashboard, undefined, {
getVariablesFromState: () => dashboard.templating.list,
});
const exporter = new DashboardExporter();
const exported: any = await exporter.makeExportable(dashboardModel);
expect(exported.templating.list[0].datasource.uid).toBe('${DS_GFDB}');
});
it('replaces datasource ref in library panel', async () => {
const dashboard: Dashboard = {
style: 'dark',
editable: true,
graphTooltip: 1,
schemaVersion: 38,
panels: [
{
id: 1,
title: 'Panel title',
type: 'timeseries',
options: {
cellHeight: 'sm',
footer: {
countRows: false,
fields: '',
reducer: ['sum'],
show: false,
},
showHeader: true,
},
transformations: [],
transparent: false,
fieldConfig: {
defaults: {
custom: {
align: 'auto',
cellOptions: {
type: 'auto',
},
inspect: false,
},
mappings: [],
thresholds: {
mode: ThresholdsMode.Absolute,
steps: [
{
color: 'green',
value: 10,
},
{
color: 'red',
value: 80,
},
],
},
},
overrides: [],
},
gridPos: {
h: 8,
w: 12,
x: 0,
y: 0,
},
libraryPanel: {
name: 'Testing lib panel',
uid: 'c46a6b49-de40-43b3-982c-1b5e1ec084a4',
},
},
],
};
const dashboardModel = new DashboardModel(dashboard, {});
const exporter = new DashboardExporter();
const exported = await exporter.makeExportable(dashboardModel);
if ('error' in exported) {
throw new Error('error should not be returned when making exportable json');
}
expect(exported.__elements!['c46a6b49-de40-43b3-982c-1b5e1ec084a4'].model.datasource.uid).toBe('${DS_GFDB}');
expect(exported.__inputs![0].name).toBe('DS_GFDB');
});
it('If a panel queries has no datasource prop ignore it', async () => {
const dashboard: any = {
panels: [
{
id: 1,
type: 'graph',
datasource: {
uid: 'other',
type: 'other',
},
targets: [{ refId: 'A', a: 'A' }],
},
],
};
const dashboardModel = new DashboardModel(dashboard, undefined, {
getVariablesFromState: () => [],
});
const exporter = new DashboardExporter();
const exported: any = await exporter.makeExportable(dashboardModel);
expect(exported.panels[0].datasource).toEqual({ uid: '${DS_OTHER}', type: 'other' });
expect(exported.panels[0].targets[0].datasource).toEqual({ uid: '${DS_OTHER}', type: 'other' });
});
2018-06-13 15:15:36 +02:00
describe('given dashboard with repeated panels', () => {
let dash: any, exported: any;
2018-06-13 15:15:36 +02:00
beforeEach((done) => {
2018-06-13 15:15:36 +02:00
dash = {
2018-06-14 14:37:48 +02:00
templating: {
list: [
{
name: 'apps',
type: 'query',
datasource: { uid: 'gfdb', type: 'testdb' },
2018-06-14 14:37:48 +02:00
current: { value: 'Asd', text: 'Asd' },
options: [{ value: 'Asd', text: 'Asd' }],
},
{
name: 'prefix',
type: 'constant',
current: { value: 'collectd', text: 'collectd' },
options: [],
query: 'collectd',
2018-06-14 14:37:48 +02:00
},
{
name: 'ds',
type: 'datasource',
query: 'other2',
current: { value: 'other2', text: 'other2' },
2018-06-14 14:37:48 +02:00
options: [],
},
],
},
annotations: {
list: [
{
name: 'logs',
datasource: 'gfdb',
2018-06-14 14:37:48 +02:00
},
],
},
panels: [
{ id: 6, datasource: { uid: 'gfdb', type: 'testdb' }, type: 'graph' },
2018-06-14 14:37:48 +02:00
{ id: 7 },
{
id: 8,
datasource: { uid: '-- Mixed --', type: 'mixed' },
targets: [{ datasource: { uid: 'other', type: 'other' } }],
2018-06-14 14:37:48 +02:00
},
{ id: 9, datasource: { uid: '$ds', type: 'other2' } },
{
id: 17,
libraryPanel: {
name: 'Library Panel 2',
uid: 'ah8NqyDPs',
},
},
2018-06-14 14:37:48 +02:00
{
id: 2,
repeat: 'apps',
datasource: { uid: 'gfdb', type: 'testdb' },
2018-06-14 14:37:48 +02:00
type: 'graph',
},
{ id: 3, repeat: null, repeatPanelId: 2 },
{
id: 4,
collapsed: true,
panels: [
{ id: 10, datasource: { uid: 'gfdb', type: 'testdb' }, type: 'table' },
{ id: 11 },
{
id: 12,
datasource: { uid: '-- Mixed --', type: 'mixed' },
targets: [{ datasource: { uid: 'other', type: 'other' } }],
},
{ id: 13, datasource: { uid: '$uid', type: 'other' } },
{
id: 14,
repeat: 'apps',
datasource: { uid: 'gfdb', type: 'testdb' },
type: 'heatmap',
},
{ id: 15, repeat: null, repeatPanelId: 14 },
{
id: 16,
// datasource: { uid: 'gfdb', type: 'testdb' },
// type: 'graph',
libraryPanel: {
name: 'Library Panel',
uid: 'jL6MrxCMz',
},
},
],
},
{
id: 5,
targets: [{ scenarioId: 'random_walk', refId: 'A' }],
},
2018-06-14 14:37:48 +02:00
],
2018-06-13 15:15:36 +02:00
};
config.buildInfo.version = '3.0.2';
2018-06-13 15:15:36 +02:00
config.panels['graph'] = {
id: 'graph',
name: 'Graph',
info: { version: '1.1.0' },
} as PanelPluginMeta;
2018-06-13 15:15:36 +02:00
config.panels['table'] = {
id: 'table',
name: 'Table',
info: { version: '1.1.1' },
} as PanelPluginMeta;
config.panels['heatmap'] = {
id: 'heatmap',
name: 'Heatmap',
info: { version: '1.1.2' },
} as PanelPluginMeta;
dash = new DashboardModel(
dash,
{},
{
getVariablesFromState: () => dash.templating.list,
}
);
// init library panels
dash.getPanelById(17).initLibraryPanel({
uid: 'ah8NqyDPs',
name: 'Library Panel 2',
model: {
datasource: { type: 'other2', uid: '$ds' },
targets: [{ refId: 'A', datasource: { type: 'other2', uid: '$ds' } }],
type: 'graph',
},
});
const exporter = new DashboardExporter();
exporter.makeExportable(dash).then((clean) => {
2018-06-13 15:15:36 +02:00
exported = clean;
done();
});
});
it('should replace datasource refs', () => {
const panel = exported.panels[0];
expect(panel.datasource.uid).toBe('${DS_GFDB}');
2018-06-13 15:15:36 +02:00
});
it('should explicitly specify default datasources', () => {
const panel = exported.panels[7];
expect(exported.__inputs.some((ds: Record<string, string>) => ds.name === 'DS_GFDB')).toBeTruthy();
expect(panel.datasource.uid).toBe('${DS_GFDB}');
expect(panel.targets[0].datasource).toEqual({ type: 'testdb', uid: '${DS_GFDB}' });
});
it('should not include default datasource in __inputs unnecessarily', async () => {
const testJson: any = {
panels: [{ id: 1, datasource: { uid: 'other', type: 'other' }, type: 'graph' }],
};
const testDash = new DashboardModel(testJson);
const exporter = new DashboardExporter();
const exportedJson: any = await exporter.makeExportable(testDash);
expect(exportedJson.__inputs.some((ds: Record<string, string>) => ds.name === 'DS_GFDB')).toBeFalsy();
});
it('should replace datasource refs in collapsed row', () => {
const panel = exported.panels[6].panels[0];
expect(panel.datasource.uid).toBe('${DS_GFDB}');
});
2018-06-13 15:15:36 +02:00
it('should replace datasource in variable query', () => {
expect(exported.templating.list[0].datasource.uid).toBe('${DS_GFDB}');
2018-06-13 15:15:36 +02:00
expect(exported.templating.list[0].options.length).toBe(0);
expect(exported.templating.list[0].current.value).toBe(undefined);
expect(exported.templating.list[0].current.text).toBe(undefined);
});
it('should replace datasource in annotation query', () => {
expect(exported.annotations.list[1].datasource.uid).toBe('${DS_GFDB}');
2018-06-13 15:15:36 +02:00
});
it('should add datasource as input', () => {
expect(exported.__inputs[0].name).toBe('DS_GFDB');
expect(exported.__inputs[0].pluginId).toBe('testdb');
expect(exported.__inputs[0].type).toBe('datasource');
});
it('should add datasource to required', () => {
const require: any = find(exported.__requires, { name: 'TestDB' });
2018-06-13 15:15:36 +02:00
expect(require.name).toBe('TestDB');
expect(require.id).toBe('testdb');
expect(require.type).toBe('datasource');
expect(require.version).toBe('1.2.1');
});
it('should not add built in datasources to required', () => {
const require: any = find(exported.__requires, { name: 'Mixed' });
2018-06-13 15:15:36 +02:00
expect(require).toBe(undefined);
});
it('should add datasources used in mixed mode', () => {
const require: any = find(exported.__requires, { name: 'OtherDB' });
2018-06-13 15:15:36 +02:00
expect(require).not.toBe(undefined);
});
it('should add graph panel to required', () => {
const require: any = find(exported.__requires, { name: 'Graph' });
2018-06-13 15:15:36 +02:00
expect(require.name).toBe('Graph');
expect(require.id).toBe('graph');
expect(require.version).toBe('1.1.0');
});
it('should add table panel to required', () => {
const require: any = find(exported.__requires, { name: 'Table' });
expect(require.name).toBe('Table');
expect(require.id).toBe('table');
expect(require.version).toBe('1.1.1');
});
it('should add heatmap panel to required', () => {
const require: any = find(exported.__requires, { name: 'Heatmap' });
expect(require.name).toBe('Heatmap');
expect(require.id).toBe('heatmap');
expect(require.version).toBe('1.1.2');
});
2018-06-13 15:15:36 +02:00
it('should add grafana version', () => {
const require: any = find(exported.__requires, { name: 'Grafana' });
2018-06-13 15:15:36 +02:00
expect(require.type).toBe('grafana');
expect(require.id).toBe('grafana');
expect(require.version).toBe('3.0.2');
});
it('should add constant template variables as inputs', () => {
const input: any = find(exported.__inputs, { name: 'VAR_PREFIX' });
2018-06-13 15:15:36 +02:00
expect(input.type).toBe('constant');
expect(input.label).toBe('prefix');
expect(input.value).toBe('collectd');
});
it('should templatize constant variables', () => {
const variable: any = find(exported.templating.list, { name: 'prefix' });
2018-06-13 15:15:36 +02:00
expect(variable.query).toBe('${VAR_PREFIX}');
expect(variable.current.text).toBe('${VAR_PREFIX}');
expect(variable.current.value).toBe('${VAR_PREFIX}');
expect(variable.options[0].text).toBe('${VAR_PREFIX}');
expect(variable.options[0].value).toBe('${VAR_PREFIX}');
});
it('should add datasources only use via datasource variable to requires', () => {
const require: any = find(exported.__requires, { name: 'OtherDB_2' });
expect(require.id).toBe('other2');
});
it('should add library panels as elements', () => {
const element: LibraryElementExport = exported.__elements['ah8NqyDPs'];
expect(element.name).toBe('Library Panel 2');
expect(element.kind).toBe(LibraryElementKind.Panel);
expect(element.model).toEqual({
datasource: { type: 'testdb', uid: '${DS_GFDB}' },
type: 'graph',
});
});
it('should add library panels in collapsed rows as elements', () => {
const element: LibraryElementExport = exported.__elements['jL6MrxCMz'];
expect(element.name).toBe('Library Panel');
expect(element.kind).toBe(LibraryElementKind.Panel);
expect(element.model).toEqual({
type: 'graph',
datasource: {
type: 'testdb',
uid: '${DS_GFDB}',
},
});
});
2018-06-13 15:15:36 +02:00
});
2018-06-14 09:46:36 +02:00
function getStubInstanceSettings(v: string | DataSourceRef): DataSourceInstanceSettings {
let key = (v as DataSourceRef)?.type ?? v;
return (stubs[(key as any) ?? 'gfdb'] ?? stubs['gfdb']) as any;
}
2018-06-14 14:37:48 +02:00
// Stub responses
const stubs: { [key: string]: {} } = {};
2018-06-14 14:37:48 +02:00
stubs['gfdb'] = {
name: 'gfdb',
meta: { id: 'testdb', info: { version: '1.2.1' }, name: 'TestDB' },
};
stubs['other'] = {
name: 'other',
meta: { id: 'other', info: { version: '1.2.1' }, name: 'OtherDB' },
};
stubs['other2'] = {
name: 'other2',
meta: { id: 'other2', info: { version: '1.2.1' }, name: 'OtherDB_2' },
};
stubs['mixed'] = {
2018-06-14 14:37:48 +02:00
name: 'mixed',
meta: {
id: 'mixed',
info: { version: '1.2.1' },
name: 'Mixed',
builtIn: true,
},
};
stubs['grafana'] = {
2018-06-14 14:37:48 +02:00
name: '-- Grafana --',
meta: {
id: 'grafana',
info: { version: '1.2.1' },
name: 'grafana',
builtIn: true,
},
};