datasource.test.ts 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. import _ from 'lodash';
  2. import q from 'q';
  3. import {
  4. alignRange,
  5. extractRuleMappingFromGroups,
  6. PrometheusDatasource,
  7. prometheusRegularEscape,
  8. prometheusSpecialRegexEscape,
  9. } from '../datasource';
  10. import { dateTime } from '@grafana/ui/src/utils/moment_wrapper';
  11. import { DataSourceInstanceSettings } from '@grafana/ui';
  12. import { PromOptions } from '../types';
  13. import { TemplateSrv } from 'app/features/templating/template_srv';
  14. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  15. jest.mock('../metric_find_query');
  16. const DEFAULT_TEMPLATE_SRV_MOCK = {
  17. getAdhocFilters: () => [],
  18. replace: a => a,
  19. };
  20. describe('PrometheusDatasource', () => {
  21. const ctx: any = {};
  22. const instanceSettings = ({
  23. url: 'proxied',
  24. directUrl: 'direct',
  25. user: 'test',
  26. password: 'mupp',
  27. jsonData: {} as any,
  28. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  29. ctx.backendSrvMock = {};
  30. ctx.templateSrvMock = DEFAULT_TEMPLATE_SRV_MOCK;
  31. ctx.timeSrvMock = {
  32. timeRange: () => {
  33. return {
  34. from: dateTime(1531468681),
  35. to: dateTime(1531489712),
  36. };
  37. },
  38. };
  39. beforeEach(() => {
  40. ctx.ds = new PrometheusDatasource(instanceSettings, q, ctx.backendSrvMock, ctx.templateSrvMock, ctx.timeSrvMock);
  41. });
  42. describe('Datasource metadata requests', () => {
  43. it('should perform a GET request with the default config', () => {
  44. ctx.backendSrvMock.datasourceRequest = jest.fn();
  45. ctx.ds.metadataRequest('/foo');
  46. expect(ctx.backendSrvMock.datasourceRequest.mock.calls.length).toBe(1);
  47. expect(ctx.backendSrvMock.datasourceRequest.mock.calls[0][0].method).toBe('GET');
  48. });
  49. it('should still perform a GET request with the DS HTTP method set to POST', () => {
  50. ctx.backendSrvMock.datasourceRequest = jest.fn();
  51. const postSettings = _.cloneDeep(instanceSettings);
  52. postSettings.jsonData.httpMethod = 'POST';
  53. const ds = new PrometheusDatasource(postSettings, q, ctx.backendSrvMock, ctx.templateSrvMock, ctx.timeSrvMock);
  54. ds.metadataRequest('/foo');
  55. expect(ctx.backendSrvMock.datasourceRequest.mock.calls.length).toBe(1);
  56. expect(ctx.backendSrvMock.datasourceRequest.mock.calls[0][0].method).toBe('GET');
  57. });
  58. });
  59. describe('When using adhoc filters', () => {
  60. const DEFAULT_QUERY_EXPRESSION = 'metric{job="foo"} - metric';
  61. const target = { expr: DEFAULT_QUERY_EXPRESSION };
  62. afterEach(() => {
  63. ctx.templateSrvMock.getAdhocFilters = DEFAULT_TEMPLATE_SRV_MOCK.getAdhocFilters;
  64. });
  65. it('should not modify expression with no filters', () => {
  66. const result = ctx.ds.createQuery(target, { interval: '15s' });
  67. expect(result).toMatchObject({ expr: DEFAULT_QUERY_EXPRESSION });
  68. });
  69. it('should add filters to expression', () => {
  70. ctx.templateSrvMock.getAdhocFilters = () => [
  71. {
  72. key: 'k1',
  73. operator: '=',
  74. value: 'v1',
  75. },
  76. {
  77. key: 'k2',
  78. operator: '!=',
  79. value: 'v2',
  80. },
  81. ];
  82. const result = ctx.ds.createQuery(target, { interval: '15s' });
  83. expect(result).toMatchObject({ expr: 'metric{job="foo",k1="v1",k2!="v2"} - metric{k1="v1",k2!="v2"}' });
  84. });
  85. it('should add escaping if needed to regex filter expressions', () => {
  86. ctx.templateSrvMock.getAdhocFilters = () => [
  87. {
  88. key: 'k1',
  89. operator: '=~',
  90. value: 'v.*',
  91. },
  92. {
  93. key: 'k2',
  94. operator: '=~',
  95. value: `v'.*`,
  96. },
  97. ];
  98. const result = ctx.ds.createQuery(target, { interval: '15s' });
  99. expect(result).toMatchObject({
  100. expr: `metric{job="foo",k1=~"v.*",k2=~"v\\\\'.*"} - metric{k1=~"v.*",k2=~"v\\\\'.*"}`,
  101. });
  102. });
  103. });
  104. describe('When performing performSuggestQuery', () => {
  105. it('should cache response', async () => {
  106. ctx.backendSrvMock.datasourceRequest.mockReturnValue(
  107. Promise.resolve({
  108. status: 'success',
  109. data: { data: ['value1', 'value2', 'value3'] },
  110. })
  111. );
  112. let results = await ctx.ds.performSuggestQuery('value', true);
  113. expect(results).toHaveLength(3);
  114. ctx.backendSrvMock.datasourceRequest.mockReset();
  115. results = await ctx.ds.performSuggestQuery('value', true);
  116. expect(results).toHaveLength(3);
  117. });
  118. });
  119. describe('When converting prometheus histogram to heatmap format', () => {
  120. beforeEach(() => {
  121. ctx.query = {
  122. range: { from: dateTime(1443454528000), to: dateTime(1443454528000) },
  123. targets: [{ expr: 'test{job="testjob"}', format: 'heatmap', legendFormat: '{{le}}' }],
  124. interval: '1s',
  125. };
  126. });
  127. it('should convert cumullative histogram to ordinary', () => {
  128. const resultMock = [
  129. {
  130. metric: { __name__: 'metric', job: 'testjob', le: '10' },
  131. values: [[1443454528.0, '10'], [1443454528.0, '10']],
  132. },
  133. {
  134. metric: { __name__: 'metric', job: 'testjob', le: '20' },
  135. values: [[1443454528.0, '20'], [1443454528.0, '10']],
  136. },
  137. {
  138. metric: { __name__: 'metric', job: 'testjob', le: '30' },
  139. values: [[1443454528.0, '25'], [1443454528.0, '10']],
  140. },
  141. ];
  142. const responseMock = { data: { data: { result: resultMock } } };
  143. const expected = [
  144. {
  145. target: '10',
  146. datapoints: [[10, 1443454528000], [10, 1443454528000]],
  147. },
  148. {
  149. target: '20',
  150. datapoints: [[10, 1443454528000], [0, 1443454528000]],
  151. },
  152. {
  153. target: '30',
  154. datapoints: [[5, 1443454528000], [0, 1443454528000]],
  155. },
  156. ];
  157. ctx.ds.performTimeSeriesQuery = jest.fn().mockReturnValue(responseMock);
  158. return ctx.ds.query(ctx.query).then(result => {
  159. const results = result.data;
  160. return expect(results).toMatchObject(expected);
  161. });
  162. });
  163. it('should sort series by label value', () => {
  164. const resultMock = [
  165. {
  166. metric: { __name__: 'metric', job: 'testjob', le: '2' },
  167. values: [[1443454528.0, '10'], [1443454528.0, '10']],
  168. },
  169. {
  170. metric: { __name__: 'metric', job: 'testjob', le: '4' },
  171. values: [[1443454528.0, '20'], [1443454528.0, '10']],
  172. },
  173. {
  174. metric: { __name__: 'metric', job: 'testjob', le: '+Inf' },
  175. values: [[1443454528.0, '25'], [1443454528.0, '10']],
  176. },
  177. {
  178. metric: { __name__: 'metric', job: 'testjob', le: '1' },
  179. values: [[1443454528.0, '25'], [1443454528.0, '10']],
  180. },
  181. ];
  182. const responseMock = { data: { data: { result: resultMock } } };
  183. const expected = ['1', '2', '4', '+Inf'];
  184. ctx.ds.performTimeSeriesQuery = jest.fn().mockReturnValue(responseMock);
  185. return ctx.ds.query(ctx.query).then(result => {
  186. const seriesLabels = _.map(result.data, 'target');
  187. return expect(seriesLabels).toEqual(expected);
  188. });
  189. });
  190. });
  191. describe('alignRange', () => {
  192. it('does not modify already aligned intervals with perfect step', () => {
  193. const range = alignRange(0, 3, 3);
  194. expect(range.start).toEqual(0);
  195. expect(range.end).toEqual(3);
  196. });
  197. it('does modify end-aligned intervals to reflect number of steps possible', () => {
  198. const range = alignRange(1, 6, 3);
  199. expect(range.start).toEqual(0);
  200. expect(range.end).toEqual(6);
  201. });
  202. it('does align intervals that are a multiple of steps', () => {
  203. const range = alignRange(1, 4, 3);
  204. expect(range.start).toEqual(0);
  205. expect(range.end).toEqual(3);
  206. });
  207. it('does align intervals that are not a multiple of steps', () => {
  208. const range = alignRange(1, 5, 3);
  209. expect(range.start).toEqual(0);
  210. expect(range.end).toEqual(3);
  211. });
  212. });
  213. describe('extractRuleMappingFromGroups()', () => {
  214. it('returns empty mapping for no rule groups', () => {
  215. expect(extractRuleMappingFromGroups([])).toEqual({});
  216. });
  217. it('returns a mapping for recording rules only', () => {
  218. const groups = [
  219. {
  220. rules: [
  221. {
  222. name: 'HighRequestLatency',
  223. query: 'job:request_latency_seconds:mean5m{job="myjob"} > 0.5',
  224. type: 'alerting',
  225. },
  226. {
  227. name: 'job:http_inprogress_requests:sum',
  228. query: 'sum(http_inprogress_requests) by (job)',
  229. type: 'recording',
  230. },
  231. ],
  232. file: '/rules.yaml',
  233. interval: 60,
  234. name: 'example',
  235. },
  236. ];
  237. const mapping = extractRuleMappingFromGroups(groups);
  238. expect(mapping).toEqual({ 'job:http_inprogress_requests:sum': 'sum(http_inprogress_requests) by (job)' });
  239. });
  240. });
  241. describe('Prometheus regular escaping', () => {
  242. it('should not escape non-string', () => {
  243. expect(prometheusRegularEscape(12)).toEqual(12);
  244. });
  245. it('should not escape simple string', () => {
  246. expect(prometheusRegularEscape('cryptodepression')).toEqual('cryptodepression');
  247. });
  248. it("should escape '", () => {
  249. expect(prometheusRegularEscape("looking'glass")).toEqual("looking\\\\'glass");
  250. });
  251. it('should escape multiple characters', () => {
  252. expect(prometheusRegularEscape("'looking'glass'")).toEqual("\\\\'looking\\\\'glass\\\\'");
  253. });
  254. });
  255. describe('Prometheus regexes escaping', () => {
  256. it('should not escape simple string', () => {
  257. expect(prometheusSpecialRegexEscape('cryptodepression')).toEqual('cryptodepression');
  258. });
  259. it('should escape $^*+?.()\\', () => {
  260. expect(prometheusSpecialRegexEscape("looking'glass")).toEqual("looking\\\\'glass");
  261. expect(prometheusSpecialRegexEscape('looking{glass')).toEqual('looking\\\\{glass');
  262. expect(prometheusSpecialRegexEscape('looking}glass')).toEqual('looking\\\\}glass');
  263. expect(prometheusSpecialRegexEscape('looking[glass')).toEqual('looking\\\\[glass');
  264. expect(prometheusSpecialRegexEscape('looking]glass')).toEqual('looking\\\\]glass');
  265. expect(prometheusSpecialRegexEscape('looking$glass')).toEqual('looking\\\\$glass');
  266. expect(prometheusSpecialRegexEscape('looking^glass')).toEqual('looking\\\\^glass');
  267. expect(prometheusSpecialRegexEscape('looking*glass')).toEqual('looking\\\\*glass');
  268. expect(prometheusSpecialRegexEscape('looking+glass')).toEqual('looking\\\\+glass');
  269. expect(prometheusSpecialRegexEscape('looking?glass')).toEqual('looking\\\\?glass');
  270. expect(prometheusSpecialRegexEscape('looking.glass')).toEqual('looking\\\\.glass');
  271. expect(prometheusSpecialRegexEscape('looking(glass')).toEqual('looking\\\\(glass');
  272. expect(prometheusSpecialRegexEscape('looking)glass')).toEqual('looking\\\\)glass');
  273. expect(prometheusSpecialRegexEscape('looking\\glass')).toEqual('looking\\\\\\\\glass');
  274. });
  275. it('should escape multiple special characters', () => {
  276. expect(prometheusSpecialRegexEscape('+looking$glass?')).toEqual('\\\\+looking\\\\$glass\\\\?');
  277. });
  278. });
  279. describe('metricFindQuery', () => {
  280. beforeEach(() => {
  281. const query = 'query_result(topk(5,rate(http_request_duration_microseconds_count[$__interval])))';
  282. ctx.templateSrvMock.replace = jest.fn();
  283. ctx.timeSrvMock.timeRange = () => {
  284. return {
  285. from: dateTime(1531468681),
  286. to: dateTime(1531489712),
  287. };
  288. };
  289. ctx.ds = new PrometheusDatasource(instanceSettings, q, ctx.backendSrvMock, ctx.templateSrvMock, ctx.timeSrvMock);
  290. ctx.ds.metricFindQuery(query);
  291. });
  292. it('should call templateSrv.replace with scopedVars', () => {
  293. expect(ctx.templateSrvMock.replace.mock.calls[0][1]).toBeDefined();
  294. });
  295. it('should have the correct range and range_ms', () => {
  296. const range = ctx.templateSrvMock.replace.mock.calls[0][1].__range;
  297. const rangeMs = ctx.templateSrvMock.replace.mock.calls[0][1].__range_ms;
  298. const rangeS = ctx.templateSrvMock.replace.mock.calls[0][1].__range_s;
  299. expect(range).toEqual({ text: '21s', value: '21s' });
  300. expect(rangeMs).toEqual({ text: 21031, value: 21031 });
  301. expect(rangeS).toEqual({ text: 21, value: 21 });
  302. });
  303. it('should pass the default interval value', () => {
  304. const interval = ctx.templateSrvMock.replace.mock.calls[0][1].__interval;
  305. const intervalMs = ctx.templateSrvMock.replace.mock.calls[0][1].__interval_ms;
  306. expect(interval).toEqual({ text: '15s', value: '15s' });
  307. expect(intervalMs).toEqual({ text: 15000, value: 15000 });
  308. });
  309. });
  310. });
  311. const SECOND = 1000;
  312. const MINUTE = 60 * SECOND;
  313. const HOUR = 60 * MINUTE;
  314. const time = ({ hours = 0, seconds = 0, minutes = 0 }) => dateTime(hours * HOUR + minutes * MINUTE + seconds * SECOND);
  315. const ctx = {} as any;
  316. const instanceSettings = ({
  317. url: 'proxied',
  318. directUrl: 'direct',
  319. user: 'test',
  320. password: 'mupp',
  321. jsonData: { httpMethod: 'GET' },
  322. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  323. const backendSrv = {
  324. datasourceRequest: jest.fn(),
  325. } as any;
  326. const templateSrv = ({
  327. getAdhocFilters: () => [],
  328. replace: jest.fn(str => str),
  329. } as unknown) as TemplateSrv;
  330. const timeSrv = ({
  331. timeRange: () => {
  332. return { to: { diff: () => 2000 }, from: '' };
  333. },
  334. } as unknown) as TimeSrv;
  335. describe('PrometheusDatasource', () => {
  336. describe('When querying prometheus with one target using query editor target spec', () => {
  337. let results;
  338. const query = {
  339. range: { from: time({ seconds: 63 }), to: time({ seconds: 183 }) },
  340. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  341. interval: '60s',
  342. };
  343. // Interval alignment with step
  344. const urlExpected =
  345. 'proxied/api/v1/query_range?query=' + encodeURIComponent('test{job="testjob"}') + '&start=60&end=180&step=60';
  346. beforeEach(async () => {
  347. const response = {
  348. data: {
  349. status: 'success',
  350. data: {
  351. resultType: 'matrix',
  352. result: [
  353. {
  354. metric: { __name__: 'test', job: 'testjob' },
  355. values: [[60, '3846']],
  356. },
  357. ],
  358. },
  359. },
  360. };
  361. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  362. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  363. await ctx.ds.query(query).then(data => {
  364. results = data;
  365. });
  366. });
  367. it('should generate the correct query', () => {
  368. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  369. expect(res.method).toBe('GET');
  370. expect(res.url).toBe(urlExpected);
  371. });
  372. it('should return series list', async () => {
  373. expect(results.data.length).toBe(1);
  374. expect(results.data[0].target).toBe('test{job="testjob"}');
  375. });
  376. });
  377. describe('When querying prometheus with one target which return multiple series', () => {
  378. let results;
  379. const start = 60;
  380. const end = 360;
  381. const step = 60;
  382. const query = {
  383. range: { from: time({ seconds: start }), to: time({ seconds: end }) },
  384. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  385. interval: '60s',
  386. };
  387. beforeEach(async () => {
  388. const response = {
  389. status: 'success',
  390. data: {
  391. data: {
  392. resultType: 'matrix',
  393. result: [
  394. {
  395. metric: { __name__: 'test', job: 'testjob', series: 'series 1' },
  396. values: [[start + step * 1, '3846'], [start + step * 3, '3847'], [end - step * 1, '3848']],
  397. },
  398. {
  399. metric: { __name__: 'test', job: 'testjob', series: 'series 2' },
  400. values: [[start + step * 2, '4846']],
  401. },
  402. ],
  403. },
  404. },
  405. };
  406. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  407. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  408. await ctx.ds.query(query).then(data => {
  409. results = data;
  410. });
  411. });
  412. it('should be same length', () => {
  413. expect(results.data.length).toBe(2);
  414. expect(results.data[0].datapoints.length).toBe((end - start) / step + 1);
  415. expect(results.data[1].datapoints.length).toBe((end - start) / step + 1);
  416. });
  417. it('should fill null until first datapoint in response', () => {
  418. expect(results.data[0].datapoints[0][1]).toBe(start * 1000);
  419. expect(results.data[0].datapoints[0][0]).toBe(null);
  420. expect(results.data[0].datapoints[1][1]).toBe((start + step * 1) * 1000);
  421. expect(results.data[0].datapoints[1][0]).toBe(3846);
  422. });
  423. it('should fill null after last datapoint in response', () => {
  424. const length = (end - start) / step + 1;
  425. expect(results.data[0].datapoints[length - 2][1]).toBe((end - step * 1) * 1000);
  426. expect(results.data[0].datapoints[length - 2][0]).toBe(3848);
  427. expect(results.data[0].datapoints[length - 1][1]).toBe(end * 1000);
  428. expect(results.data[0].datapoints[length - 1][0]).toBe(null);
  429. });
  430. it('should fill null at gap between series', () => {
  431. expect(results.data[0].datapoints[2][1]).toBe((start + step * 2) * 1000);
  432. expect(results.data[0].datapoints[2][0]).toBe(null);
  433. expect(results.data[1].datapoints[1][1]).toBe((start + step * 1) * 1000);
  434. expect(results.data[1].datapoints[1][0]).toBe(null);
  435. expect(results.data[1].datapoints[3][1]).toBe((start + step * 3) * 1000);
  436. expect(results.data[1].datapoints[3][0]).toBe(null);
  437. });
  438. });
  439. describe('When querying prometheus with one target and instant = true', () => {
  440. let results;
  441. const urlExpected = 'proxied/api/v1/query?query=' + encodeURIComponent('test{job="testjob"}') + '&time=123';
  442. const query = {
  443. range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) },
  444. targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }],
  445. interval: '60s',
  446. };
  447. beforeEach(async () => {
  448. const response = {
  449. status: 'success',
  450. data: {
  451. data: {
  452. resultType: 'vector',
  453. result: [
  454. {
  455. metric: { __name__: 'test', job: 'testjob' },
  456. value: [123, '3846'],
  457. },
  458. ],
  459. },
  460. },
  461. };
  462. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  463. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  464. await ctx.ds.query(query).then(data => {
  465. results = data;
  466. });
  467. });
  468. it('should generate the correct query', () => {
  469. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  470. expect(res.method).toBe('GET');
  471. expect(res.url).toBe(urlExpected);
  472. });
  473. it('should return series list', () => {
  474. expect(results.data.length).toBe(1);
  475. expect(results.data[0].target).toBe('test{job="testjob"}');
  476. });
  477. });
  478. describe('When performing annotationQuery', () => {
  479. let results;
  480. const options: any = {
  481. annotation: {
  482. expr: 'ALERTS{alertstate="firing"}',
  483. tagKeys: 'job',
  484. titleFormat: '{{alertname}}',
  485. textFormat: '{{instance}}',
  486. },
  487. range: {
  488. from: time({ seconds: 63 }),
  489. to: time({ seconds: 123 }),
  490. },
  491. };
  492. const response = {
  493. status: 'success',
  494. data: {
  495. data: {
  496. resultType: 'matrix',
  497. result: [
  498. {
  499. metric: {
  500. __name__: 'ALERTS',
  501. alertname: 'InstanceDown',
  502. alertstate: 'firing',
  503. instance: 'testinstance',
  504. job: 'testjob',
  505. },
  506. values: [[123, '1']],
  507. },
  508. ],
  509. },
  510. },
  511. };
  512. describe('not use useValueForTime', () => {
  513. beforeEach(async () => {
  514. options.annotation.useValueForTime = false;
  515. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  516. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  517. await ctx.ds.annotationQuery(options).then(data => {
  518. results = data;
  519. });
  520. });
  521. it('should return annotation list', () => {
  522. expect(results.length).toBe(1);
  523. expect(results[0].tags).toContain('testjob');
  524. expect(results[0].title).toBe('InstanceDown');
  525. expect(results[0].text).toBe('testinstance');
  526. expect(results[0].time).toBe(123 * 1000);
  527. });
  528. });
  529. describe('use useValueForTime', () => {
  530. beforeEach(async () => {
  531. options.annotation.useValueForTime = true;
  532. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  533. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  534. await ctx.ds.annotationQuery(options).then(data => {
  535. results = data;
  536. });
  537. });
  538. it('should return annotation list', () => {
  539. expect(results[0].time).toEqual(1);
  540. });
  541. });
  542. describe('step parameter', () => {
  543. beforeEach(() => {
  544. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  545. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  546. });
  547. it('should use default step for short range if no interval is given', () => {
  548. const query = {
  549. ...options,
  550. range: {
  551. from: time({ seconds: 63 }),
  552. to: time({ seconds: 123 }),
  553. },
  554. };
  555. ctx.ds.annotationQuery(query);
  556. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  557. expect(req.url).toContain('step=60');
  558. });
  559. it('should use custom step for short range', () => {
  560. const annotation = {
  561. ...options.annotation,
  562. step: '10s',
  563. };
  564. const query = {
  565. ...options,
  566. annotation,
  567. range: {
  568. from: time({ seconds: 63 }),
  569. to: time({ seconds: 123 }),
  570. },
  571. };
  572. ctx.ds.annotationQuery(query);
  573. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  574. expect(req.url).toContain('step=10');
  575. });
  576. it('should use custom step for short range', () => {
  577. const annotation = {
  578. ...options.annotation,
  579. step: '10s',
  580. };
  581. const query = {
  582. ...options,
  583. annotation,
  584. range: {
  585. from: time({ seconds: 63 }),
  586. to: time({ seconds: 123 }),
  587. },
  588. };
  589. ctx.ds.annotationQuery(query);
  590. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  591. expect(req.url).toContain('step=10');
  592. });
  593. it('should use dynamic step on long ranges if no option was given', () => {
  594. const query = {
  595. ...options,
  596. range: {
  597. from: time({ seconds: 63 }),
  598. to: time({ hours: 24 * 30, seconds: 63 }),
  599. },
  600. };
  601. ctx.ds.annotationQuery(query);
  602. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  603. // Range in seconds: (to - from) / 1000
  604. // Max_datapoints: 11000
  605. // Step: range / max_datapoints
  606. const step = 236;
  607. expect(req.url).toContain(`step=${step}`);
  608. });
  609. });
  610. });
  611. describe('When resultFormat is table and instant = true', () => {
  612. let results;
  613. const query = {
  614. range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) },
  615. targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }],
  616. interval: '60s',
  617. };
  618. beforeEach(async () => {
  619. const response = {
  620. status: 'success',
  621. data: {
  622. data: {
  623. resultType: 'vector',
  624. result: [
  625. {
  626. metric: { __name__: 'test', job: 'testjob' },
  627. value: [123, '3846'],
  628. },
  629. ],
  630. },
  631. },
  632. };
  633. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  634. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  635. await ctx.ds.query(query).then(data => {
  636. results = data;
  637. });
  638. });
  639. it('should return result', () => {
  640. expect(results).not.toBe(null);
  641. });
  642. });
  643. describe('The "step" query parameter', () => {
  644. const response = {
  645. status: 'success',
  646. data: {
  647. data: {
  648. resultType: 'matrix',
  649. result: [],
  650. },
  651. },
  652. };
  653. it('should be min interval when greater than auto interval', async () => {
  654. const query = {
  655. // 6 minute range
  656. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  657. targets: [
  658. {
  659. expr: 'test',
  660. interval: '10s',
  661. },
  662. ],
  663. interval: '5s',
  664. };
  665. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10';
  666. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  667. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  668. await ctx.ds.query(query);
  669. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  670. expect(res.method).toBe('GET');
  671. expect(res.url).toBe(urlExpected);
  672. });
  673. it('step should never go below 1', async () => {
  674. const query = {
  675. // 6 minute range
  676. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  677. targets: [{ expr: 'test' }],
  678. interval: '100ms',
  679. };
  680. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=1';
  681. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  682. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  683. await ctx.ds.query(query);
  684. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  685. expect(res.method).toBe('GET');
  686. expect(res.url).toBe(urlExpected);
  687. });
  688. it('should be auto interval when greater than min interval', async () => {
  689. const query = {
  690. // 6 minute range
  691. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  692. targets: [
  693. {
  694. expr: 'test',
  695. interval: '5s',
  696. },
  697. ],
  698. interval: '10s',
  699. };
  700. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10';
  701. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  702. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  703. await ctx.ds.query(query);
  704. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  705. expect(res.method).toBe('GET');
  706. expect(res.url).toBe(urlExpected);
  707. });
  708. it('should result in querying fewer than 11000 data points', async () => {
  709. const query = {
  710. // 6 hour range
  711. range: { from: time({ hours: 1 }), to: time({ hours: 7 }) },
  712. targets: [{ expr: 'test' }],
  713. interval: '1s',
  714. };
  715. const end = 7 * 60 * 60;
  716. const start = 60 * 60;
  717. const urlExpected = 'proxied/api/v1/query_range?query=test&start=' + start + '&end=' + end + '&step=2';
  718. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  719. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  720. await ctx.ds.query(query);
  721. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  722. expect(res.method).toBe('GET');
  723. expect(res.url).toBe(urlExpected);
  724. });
  725. it('should not apply min interval when interval * intervalFactor greater', async () => {
  726. const query = {
  727. // 6 minute range
  728. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  729. targets: [
  730. {
  731. expr: 'test',
  732. interval: '10s',
  733. intervalFactor: 10,
  734. },
  735. ],
  736. interval: '5s',
  737. };
  738. // times get rounded up to interval
  739. const urlExpected = 'proxied/api/v1/query_range?query=test&start=50&end=400&step=50';
  740. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  741. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  742. await ctx.ds.query(query);
  743. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  744. expect(res.method).toBe('GET');
  745. expect(res.url).toBe(urlExpected);
  746. });
  747. it('should apply min interval when interval * intervalFactor smaller', async () => {
  748. const query = {
  749. // 6 minute range
  750. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  751. targets: [
  752. {
  753. expr: 'test',
  754. interval: '15s',
  755. intervalFactor: 2,
  756. },
  757. ],
  758. interval: '5s',
  759. };
  760. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=60&end=420&step=15';
  761. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  762. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  763. await ctx.ds.query(query);
  764. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  765. expect(res.method).toBe('GET');
  766. expect(res.url).toBe(urlExpected);
  767. });
  768. it('should apply intervalFactor to auto interval when greater', async () => {
  769. const query = {
  770. // 6 minute range
  771. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  772. targets: [
  773. {
  774. expr: 'test',
  775. interval: '5s',
  776. intervalFactor: 10,
  777. },
  778. ],
  779. interval: '10s',
  780. };
  781. // times get aligned to interval
  782. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=0&end=400&step=100';
  783. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  784. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  785. await ctx.ds.query(query);
  786. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  787. expect(res.method).toBe('GET');
  788. expect(res.url).toBe(urlExpected);
  789. });
  790. it('should not not be affected by the 11000 data points limit when large enough', async () => {
  791. const query = {
  792. // 1 week range
  793. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  794. targets: [
  795. {
  796. expr: 'test',
  797. intervalFactor: 10,
  798. },
  799. ],
  800. interval: '10s',
  801. };
  802. const end = 7 * 24 * 60 * 60;
  803. const start = 0;
  804. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=100';
  805. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  806. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  807. await ctx.ds.query(query);
  808. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  809. expect(res.method).toBe('GET');
  810. expect(res.url).toBe(urlExpected);
  811. });
  812. it('should be determined by the 11000 data points limit when too small', async () => {
  813. const query = {
  814. // 1 week range
  815. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  816. targets: [
  817. {
  818. expr: 'test',
  819. intervalFactor: 10,
  820. },
  821. ],
  822. interval: '5s',
  823. };
  824. const end = 7 * 24 * 60 * 60;
  825. const start = 0;
  826. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=60';
  827. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  828. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  829. await ctx.ds.query(query);
  830. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  831. expect(res.method).toBe('GET');
  832. expect(res.url).toBe(urlExpected);
  833. });
  834. });
  835. describe('The __interval and __interval_ms template variables', () => {
  836. const response = {
  837. status: 'success',
  838. data: {
  839. data: {
  840. resultType: 'matrix',
  841. result: [],
  842. },
  843. },
  844. };
  845. it('should be unchanged when auto interval is greater than min interval', async () => {
  846. const query = {
  847. // 6 minute range
  848. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  849. targets: [
  850. {
  851. expr: 'rate(test[$__interval])',
  852. interval: '5s',
  853. },
  854. ],
  855. interval: '10s',
  856. scopedVars: {
  857. __interval: { text: '10s', value: '10s' },
  858. __interval_ms: { text: 10 * 1000, value: 10 * 1000 },
  859. },
  860. };
  861. const urlExpected =
  862. 'proxied/api/v1/query_range?query=' +
  863. encodeURIComponent('rate(test[$__interval])') +
  864. '&start=60&end=420&step=10';
  865. templateSrv.replace = jest.fn(str => str);
  866. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  867. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  868. await ctx.ds.query(query);
  869. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  870. expect(res.method).toBe('GET');
  871. expect(res.url).toBe(urlExpected);
  872. // @ts-ignore
  873. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  874. __interval: {
  875. text: '10s',
  876. value: '10s',
  877. },
  878. __interval_ms: {
  879. text: 10000,
  880. value: 10000,
  881. },
  882. });
  883. });
  884. it('should be min interval when it is greater than auto interval', async () => {
  885. const query = {
  886. // 6 minute range
  887. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  888. targets: [
  889. {
  890. expr: 'rate(test[$__interval])',
  891. interval: '10s',
  892. },
  893. ],
  894. interval: '5s',
  895. scopedVars: {
  896. __interval: { text: '5s', value: '5s' },
  897. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  898. },
  899. };
  900. const urlExpected =
  901. 'proxied/api/v1/query_range?query=' +
  902. encodeURIComponent('rate(test[$__interval])') +
  903. '&start=60&end=420&step=10';
  904. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  905. templateSrv.replace = jest.fn(str => str);
  906. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  907. await ctx.ds.query(query);
  908. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  909. expect(res.method).toBe('GET');
  910. expect(res.url).toBe(urlExpected);
  911. // @ts-ignore
  912. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  913. __interval: {
  914. text: '5s',
  915. value: '5s',
  916. },
  917. __interval_ms: {
  918. text: 5000,
  919. value: 5000,
  920. },
  921. });
  922. });
  923. it('should account for intervalFactor', async () => {
  924. const query = {
  925. // 6 minute range
  926. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  927. targets: [
  928. {
  929. expr: 'rate(test[$__interval])',
  930. interval: '5s',
  931. intervalFactor: 10,
  932. },
  933. ],
  934. interval: '10s',
  935. scopedVars: {
  936. __interval: { text: '10s', value: '10s' },
  937. __interval_ms: { text: 10 * 1000, value: 10 * 1000 },
  938. },
  939. };
  940. const urlExpected =
  941. 'proxied/api/v1/query_range?query=' +
  942. encodeURIComponent('rate(test[$__interval])') +
  943. '&start=0&end=400&step=100';
  944. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  945. templateSrv.replace = jest.fn(str => str);
  946. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  947. await ctx.ds.query(query);
  948. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  949. expect(res.method).toBe('GET');
  950. expect(res.url).toBe(urlExpected);
  951. // @ts-ignore
  952. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  953. __interval: {
  954. text: '10s',
  955. value: '10s',
  956. },
  957. __interval_ms: {
  958. text: 10000,
  959. value: 10000,
  960. },
  961. });
  962. expect(query.scopedVars.__interval.text).toBe('10s');
  963. expect(query.scopedVars.__interval.value).toBe('10s');
  964. expect(query.scopedVars.__interval_ms.text).toBe(10 * 1000);
  965. expect(query.scopedVars.__interval_ms.value).toBe(10 * 1000);
  966. });
  967. it('should be interval * intervalFactor when greater than min interval', async () => {
  968. const query = {
  969. // 6 minute range
  970. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  971. targets: [
  972. {
  973. expr: 'rate(test[$__interval])',
  974. interval: '10s',
  975. intervalFactor: 10,
  976. },
  977. ],
  978. interval: '5s',
  979. scopedVars: {
  980. __interval: { text: '5s', value: '5s' },
  981. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  982. },
  983. };
  984. const urlExpected =
  985. 'proxied/api/v1/query_range?query=' +
  986. encodeURIComponent('rate(test[$__interval])') +
  987. '&start=50&end=400&step=50';
  988. templateSrv.replace = jest.fn(str => str);
  989. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  990. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  991. await ctx.ds.query(query);
  992. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  993. expect(res.method).toBe('GET');
  994. expect(res.url).toBe(urlExpected);
  995. // @ts-ignore
  996. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  997. __interval: {
  998. text: '5s',
  999. value: '5s',
  1000. },
  1001. __interval_ms: {
  1002. text: 5000,
  1003. value: 5000,
  1004. },
  1005. });
  1006. });
  1007. it('should be min interval when greater than interval * intervalFactor', async () => {
  1008. const query = {
  1009. // 6 minute range
  1010. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  1011. targets: [
  1012. {
  1013. expr: 'rate(test[$__interval])',
  1014. interval: '15s',
  1015. intervalFactor: 2,
  1016. },
  1017. ],
  1018. interval: '5s',
  1019. scopedVars: {
  1020. __interval: { text: '5s', value: '5s' },
  1021. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1022. },
  1023. };
  1024. const urlExpected =
  1025. 'proxied/api/v1/query_range?query=' +
  1026. encodeURIComponent('rate(test[$__interval])') +
  1027. '&start=60&end=420&step=15';
  1028. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1029. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1030. await ctx.ds.query(query);
  1031. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1032. expect(res.method).toBe('GET');
  1033. expect(res.url).toBe(urlExpected);
  1034. // @ts-ignore
  1035. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1036. __interval: {
  1037. text: '5s',
  1038. value: '5s',
  1039. },
  1040. __interval_ms: {
  1041. text: 5000,
  1042. value: 5000,
  1043. },
  1044. });
  1045. });
  1046. it('should be determined by the 11000 data points limit, accounting for intervalFactor', async () => {
  1047. const query = {
  1048. // 1 week range
  1049. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  1050. targets: [
  1051. {
  1052. expr: 'rate(test[$__interval])',
  1053. intervalFactor: 10,
  1054. },
  1055. ],
  1056. interval: '5s',
  1057. scopedVars: {
  1058. __interval: { text: '5s', value: '5s' },
  1059. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1060. },
  1061. };
  1062. const end = 7 * 24 * 60 * 60;
  1063. const start = 0;
  1064. const urlExpected =
  1065. 'proxied/api/v1/query_range?query=' +
  1066. encodeURIComponent('rate(test[$__interval])') +
  1067. '&start=' +
  1068. start +
  1069. '&end=' +
  1070. end +
  1071. '&step=60';
  1072. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1073. templateSrv.replace = jest.fn(str => str);
  1074. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1075. await ctx.ds.query(query);
  1076. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1077. expect(res.method).toBe('GET');
  1078. expect(res.url).toBe(urlExpected);
  1079. // @ts-ignore
  1080. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1081. __interval: {
  1082. text: '5s',
  1083. value: '5s',
  1084. },
  1085. __interval_ms: {
  1086. text: 5000,
  1087. value: 5000,
  1088. },
  1089. });
  1090. });
  1091. });
  1092. });
  1093. describe('PrometheusDatasource for POST', () => {
  1094. // const ctx = new helpers.ServiceTestContext();
  1095. const instanceSettings = ({
  1096. url: 'proxied',
  1097. directUrl: 'direct',
  1098. user: 'test',
  1099. password: 'mupp',
  1100. jsonData: { httpMethod: 'POST' },
  1101. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  1102. describe('When querying prometheus with one target using query editor target spec', () => {
  1103. let results;
  1104. const urlExpected = 'proxied/api/v1/query_range';
  1105. const dataExpected = {
  1106. query: 'test{job="testjob"}',
  1107. start: 1 * 60,
  1108. end: 2 * 60,
  1109. step: 60,
  1110. };
  1111. const query = {
  1112. range: { from: time({ minutes: 1, seconds: 3 }), to: time({ minutes: 2, seconds: 3 }) },
  1113. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  1114. interval: '60s',
  1115. };
  1116. beforeEach(async () => {
  1117. const response = {
  1118. status: 'success',
  1119. data: {
  1120. data: {
  1121. resultType: 'matrix',
  1122. result: [
  1123. {
  1124. metric: { __name__: 'test', job: 'testjob' },
  1125. values: [[2 * 60, '3846']],
  1126. },
  1127. ],
  1128. },
  1129. },
  1130. };
  1131. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1132. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1133. await ctx.ds.query(query).then(data => {
  1134. results = data;
  1135. });
  1136. });
  1137. it('should generate the correct query', () => {
  1138. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1139. expect(res.method).toBe('POST');
  1140. expect(res.url).toBe(urlExpected);
  1141. expect(res.data).toEqual(dataExpected);
  1142. });
  1143. it('should return series list', () => {
  1144. expect(results.data.length).toBe(1);
  1145. expect(results.data[0].target).toBe('test{job="testjob"}');
  1146. });
  1147. });
  1148. describe('When querying prometheus via check headers X-Dashboard-Id and X-Panel-Id', () => {
  1149. const options = { dashboardId: 1, panelId: 2 };
  1150. const httpOptions = {
  1151. headers: {},
  1152. };
  1153. it('with proxy access tracing headers should be added', () => {
  1154. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1155. ctx.ds._addTracingHeaders(httpOptions, options);
  1156. expect(httpOptions.headers['X-Dashboard-Id']).toBe(1);
  1157. expect(httpOptions.headers['X-Panel-Id']).toBe(2);
  1158. });
  1159. it('with direct access tracing headers should not be added', () => {
  1160. instanceSettings.url = 'http://127.0.0.1:8000';
  1161. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1162. ctx.ds._addTracingHeaders(httpOptions, options);
  1163. expect(httpOptions.headers['X-Dashboard-Id']).toBe(undefined);
  1164. expect(httpOptions.headers['X-Panel-Id']).toBe(undefined);
  1165. });
  1166. });
  1167. });