-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatasource.test.ts
More file actions
466 lines (378 loc) · 14.4 KB
/
Copy pathdatasource.test.ts
File metadata and controls
466 lines (378 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import { DataSource } from './datasource';
import { DataSourceInstanceSettings } from '@grafana/data';
import { CubeDataSourceOptions, Operator } from './types';
import { getTemplateSrv } from '@grafana/runtime';
// Mock @grafana/runtime
jest.mock('@grafana/runtime', () => ({
...jest.requireActual('@grafana/runtime'),
getTemplateSrv: jest.fn(),
}));
const mockGetTemplateSrv = getTemplateSrv as jest.Mock;
// Mock the getResource method
const mockGetResource = jest.fn();
const createDataSource = (options: Partial<CubeDataSourceOptions> = {}) => {
const instanceSettings: DataSourceInstanceSettings<CubeDataSourceOptions> = {
id: 1,
uid: 'test-uid',
type: 'cube-datasource',
name: 'Test Cube',
meta: {} as any,
jsonData: {
cubeApiUrl: 'http://localhost:4000',
...options,
},
readOnly: false,
access: 'proxy',
};
const datasource = new DataSource(instanceSettings);
datasource.getResource = mockGetResource;
return datasource;
};
describe('DataSource', () => {
beforeEach(() => {
mockGetResource.mockClear();
});
describe('getMetadata', () => {
it('should call metadata endpoint', async () => {
const mockMetadata = {
dimensions: [
{ label: 'orders.status', value: 'orders.status' },
{ label: 'orders.customer_name', value: 'orders.customer_name' },
],
measures: [
{ label: 'orders.count', value: 'orders.count' },
{ label: 'orders.total', value: 'orders.total' },
],
};
mockGetResource.mockResolvedValue(mockMetadata);
const datasource = createDataSource();
const result = await datasource.getMetadata();
expect(mockGetResource).toHaveBeenCalledWith('metadata');
expect(result).toEqual(mockMetadata);
});
it('should handle metadata endpoint errors', async () => {
mockGetResource.mockRejectedValue(new Error('API Error'));
const datasource = createDataSource();
await expect(datasource.getMetadata()).rejects.toThrow('API Error');
expect(mockGetResource).toHaveBeenCalledWith('metadata');
});
});
describe('getTagKeys', () => {
it('should transform metadata dimensions to TagKey format', async () => {
const mockMetadata = {
dimensions: [
{ label: 'orders.status', value: 'orders.status' },
{ label: 'orders.customer_name', value: 'orders.customer_name' },
],
measures: [{ label: 'orders.count', value: 'orders.count' }],
};
mockGetResource.mockResolvedValue(mockMetadata);
const datasource = createDataSource();
const result = await datasource.getTagKeys();
expect(mockGetResource).toHaveBeenCalledWith('metadata');
expect(result).toEqual([
{ text: 'orders.status', value: 'orders.status' },
{ text: 'orders.customer_name', value: 'orders.customer_name' },
]);
});
it('should handle empty dimensions', async () => {
const mockMetadata = {
dimensions: [],
measures: [{ label: 'orders.count', value: 'orders.count' }],
};
mockGetResource.mockResolvedValue(mockMetadata);
const datasource = createDataSource();
const result = await datasource.getTagKeys();
expect(result).toEqual([]);
});
it('should propagate metadata errors', async () => {
mockGetResource.mockRejectedValue(new Error('Metadata fetch failed'));
const datasource = createDataSource();
await expect(datasource.getTagKeys()).rejects.toThrow('Metadata fetch failed');
});
});
describe('getTagValues', () => {
it('should call tag-values endpoint with key', async () => {
const mockValues = ['value1', 'value2'];
mockGetResource.mockResolvedValue(mockValues);
const datasource = createDataSource();
const result = await datasource.getTagValues({ key: 'orders.status' });
expect(mockGetResource).toHaveBeenCalledWith('tag-values', { key: 'orders.status', filters: undefined });
expect(result).toEqual(mockValues);
});
it('should pass existing filters to scope tag values', async () => {
const mockValues = ['filtered1', 'filtered2'];
mockGetResource.mockResolvedValue(mockValues);
const datasource = createDataSource();
const existingFilters = [
{ key: 'orders.status', operator: '=', value: 'completed' },
{ key: 'orders.region', operator: '=|', value: 'US', values: ['US', 'EU'] },
];
const result = await datasource.getTagValues({ key: 'orders.customer', filters: existingFilters });
expect(mockGetResource).toHaveBeenCalledWith('tag-values', {
key: 'orders.customer',
filters: JSON.stringify([
{ member: 'orders.status', operator: 'equals', values: ['completed'] },
{ member: 'orders.region', operator: 'equals', values: ['US', 'EU'] },
]),
});
expect(result).toEqual(mockValues);
});
it('should handle empty filters array', async () => {
const mockValues = ['value1'];
mockGetResource.mockResolvedValue(mockValues);
const datasource = createDataSource();
const result = await datasource.getTagValues({ key: 'orders.status', filters: [] });
expect(mockGetResource).toHaveBeenCalledWith('tag-values', { key: 'orders.status', filters: undefined });
expect(result).toEqual(mockValues);
});
});
describe('applyTemplateVariables', () => {
beforeEach(() => {
mockGetTemplateSrv.mockReturnValue({
replace: (str: string) => str,
});
});
it('should interpolate template variables in filter values', () => {
const mockReplace = jest.fn((str: string) => {
if (str === '$filterValue') {
return 'completed';
}
return str;
});
mockGetTemplateSrv.mockReturnValue({
replace: mockReplace,
});
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
filters: [
{
member: 'orders.status',
operator: Operator.Equals,
values: ['$filterValue'],
},
],
};
const result = datasource.applyTemplateVariables(query, {});
expect(result.filters).toBeDefined();
expect(result.filters![0].values).toContain('completed');
});
describe('dashboard-level time dimension', () => {
it('should inject time dimension when $cubeTimeDimension variable is set and query has no timeDimensions', () => {
const fromTimestamp = '1701388800000'; // 2023-12-01T00:00:00.000Z
const toTimestamp = '1701475200000'; // 2023-12-02T00:00:00.000Z
const mockReplace = jest.fn((str: string) => {
if (str === '$cubeTimeDimension') {
return 'orders.created_at';
}
if (str === '$__from') {
return fromTimestamp;
}
if (str === '$__to') {
return toTimestamp;
}
return str;
});
mockGetTemplateSrv.mockReturnValue({
replace: mockReplace,
});
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
};
const result = datasource.applyTemplateVariables(query, {});
expect(result.timeDimensions).toBeDefined();
expect(result.timeDimensions).toHaveLength(1);
expect(result.timeDimensions![0]).toEqual({
dimension: 'orders.created_at',
dateRange: ['2023-12-01T00:00:00.000Z', '2023-12-02T00:00:00.000Z'],
});
});
it('should not inject time dimension when query already has timeDimensions', () => {
const mockReplace = jest.fn((str: string) => {
if (str === '$cubeTimeDimension') {
return 'orders.created_at';
}
if (str === '$__from') {
return '1701388800000';
}
if (str === '$__to') {
return '1701475200000';
}
return str;
});
mockGetTemplateSrv.mockReturnValue({
replace: mockReplace,
});
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
timeDimensions: [
{
dimension: 'orders.updated_at',
granularity: 'day',
},
],
};
const result = datasource.applyTemplateVariables(query, {});
// Should preserve existing timeDimensions, not override
expect(result.timeDimensions).toHaveLength(1);
expect(result.timeDimensions![0].dimension).toBe('orders.updated_at');
});
it('should not inject time dimension when $cubeTimeDimension variable is not set', () => {
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
};
const result = datasource.applyTemplateVariables(query, {});
expect(result.timeDimensions).toBeUndefined();
});
it('should not inject time dimension when time range variables are not available', () => {
const mockReplace = jest.fn((str: string) => {
if (str === '$cubeTimeDimension') {
return 'orders.created_at';
}
// Return unchanged for time range variables (simulating they're not available)
return str;
});
mockGetTemplateSrv.mockReturnValue({
replace: mockReplace,
});
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
};
const result = datasource.applyTemplateVariables(query, {});
expect(result.timeDimensions).toBeUndefined();
});
});
describe('AdHoc filter operators', () => {
it('should map "One of" operator (=|) to Cube equals with multiple values', () => {
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
};
const result = datasource.applyTemplateVariables(query, {}, [
{
key: 'orders.status',
operator: '=|',
value: 'completed',
values: ['completed', 'shipped', 'delivered'],
},
]);
expect(result.filters).toBeDefined();
expect(result.filters).toHaveLength(1);
expect(result.filters![0]).toEqual({
member: 'orders.status',
operator: 'equals',
values: ['completed', 'shipped', 'delivered'],
});
});
it('should map "Not one of" operator (!=|) to Cube notEquals with multiple values', () => {
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
};
const result = datasource.applyTemplateVariables(query, {}, [
{
key: 'orders.status',
operator: '!=|',
value: 'cancelled',
values: ['cancelled', 'refunded'],
},
]);
expect(result.filters).toBeDefined();
expect(result.filters).toHaveLength(1);
expect(result.filters![0]).toEqual({
member: 'orders.status',
operator: 'notEquals',
values: ['cancelled', 'refunded'],
});
});
it('should fall back to single value when values array is empty', () => {
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
};
const result = datasource.applyTemplateVariables(query, {}, [
{
key: 'orders.status',
operator: '=',
value: 'completed',
values: [], // Empty values array
},
]);
expect(result.filters).toBeDefined();
expect(result.filters![0].values).toEqual(['completed']);
});
it('should handle standard single-value operators', () => {
const datasource = createDataSource();
const query = {
refId: 'A',
dimensions: ['orders.status'],
measures: ['orders.count'],
};
const result = datasource.applyTemplateVariables(query, {}, [
{ key: 'orders.status', operator: '=', value: 'completed' },
{ key: 'orders.customer', operator: '!=', value: 'test' },
]);
expect(result.filters).toHaveLength(2);
expect(result.filters![0].operator).toBe('equals');
expect(result.filters![1].operator).toBe('notEquals');
});
});
describe('filter validation', () => {
it('should strip out filters with empty values', () => {
const datasource = createDataSource();
const query = {
refId: 'A',
measures: ['orders.count'],
filters: [
{ member: 'orders.status', operator: Operator.Equals, values: ['completed'] },
{ member: 'orders.type', operator: Operator.Equals, values: [] }, // should be stripped
{ member: 'orders.customer', operator: Operator.NotEquals, values: ['test'] },
],
};
const result = datasource.applyTemplateVariables(query, {});
// Only valid filters should remain
expect(result.filters).toHaveLength(2);
expect(result.filters![0].member).toBe('orders.status');
expect(result.filters![1].member).toBe('orders.customer');
});
});
});
describe('filterQuery', () => {
it('should return false when query has no dimensions or measures', () => {
const datasource = createDataSource();
const query = { refId: 'A' };
expect(datasource.filterQuery(query)).toBe(false);
});
it('should return true when query has only dimensions (no measures)', () => {
const datasource = createDataSource();
const query = { refId: 'A', dimensions: ['orders.status'] };
expect(datasource.filterQuery(query)).toBe(true);
});
it('should return true when query has only measures (no dimensions)', () => {
const datasource = createDataSource();
const query = { refId: 'A', measures: ['orders.count'] };
expect(datasource.filterQuery(query)).toBe(true);
});
});
});