template_srv.mock.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { ScopedVars, TimeRange, VariableModel } from '@grafana/data';
  2. import { TemplateSrv } from '@grafana/runtime';
  3. import { variableRegex } from '../variables/utils';
  4. /**
  5. * Mock for TemplateSrv where you can just supply map of key and values and it will do the interpolation based on that.
  6. * For simple tests whether you your data source for example calls correct replacing code.
  7. *
  8. * This is implementing TemplateSrv interface but that is not enough in most cases. Datasources require some additional
  9. * methods and usually require TemplateSrv class directly instead of just the interface which probably should be fixed
  10. * later on.
  11. */
  12. export class TemplateSrvMock implements TemplateSrv {
  13. private regex = variableRegex;
  14. constructor(private variables: Record<string, string>) {}
  15. getVariables(): VariableModel[] {
  16. return Object.keys(this.variables).map((key) => {
  17. return {
  18. type: 'custom',
  19. name: key,
  20. label: key,
  21. };
  22. });
  23. }
  24. replace(target?: string, scopedVars?: ScopedVars, format?: string | Function): string {
  25. if (!target) {
  26. return target ?? '';
  27. }
  28. this.regex.lastIndex = 0;
  29. return target.replace(this.regex, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
  30. const variableName = var1 || var2 || var3;
  31. return this.variables[variableName];
  32. });
  33. }
  34. getVariableName(expression: string) {
  35. this.regex.lastIndex = 0;
  36. const match = this.regex.exec(expression);
  37. if (!match) {
  38. return null;
  39. }
  40. return match.slice(1).find((match) => match !== undefined);
  41. }
  42. containsTemplate(target: string | undefined): boolean {
  43. if (!target) {
  44. return false;
  45. }
  46. this.regex.lastIndex = 0;
  47. const match = this.regex.exec(target);
  48. return match !== null;
  49. }
  50. updateTimeRange(timeRange: TimeRange) {}
  51. }