-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathalerts.test.ts
More file actions
934 lines (809 loc) · 28.9 KB
/
alerts.test.ts
File metadata and controls
934 lines (809 loc) · 28.9 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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
import _ from 'lodash';
import { ObjectId } from 'mongodb';
import request from 'supertest';
import { getLoggedInAgent, getServer } from '../../../fixtures';
import {
AlertChangeType,
AlertConditionType,
AlertSource,
AlertThresholdType,
} from '../../../models/alert';
import Alert from '../../../models/alert';
import Dashboard from '../../../models/dashboard';
import { SavedSearch } from '../../../models/savedSearch';
import Webhook, { WebhookService } from '../../../models/webhook';
// Constants
const ALERTS_BASE_URL = '/api/v2/alerts';
describe('External API Alerts', () => {
const server = getServer();
let agent, team, user;
beforeAll(async () => {
await server.start();
});
beforeEach(async () => {
// Setup authenticated agent for each test
const result = await getLoggedInAgent(server);
agent = result.agent;
team = result.team;
user = result.user;
});
afterEach(async () => {
await server.clearDBs();
});
afterAll(async () => {
await server.stop();
});
// Helper to make authenticated requests
const authRequest = (method, url) => {
return agent[method](url).set('Authorization', `Bearer ${user?.accessKey}`);
};
// Helper to create a webhook for testing
const createTestWebhook = async (options: { teamId?: any } = {}) => {
return await Webhook.findOneAndUpdate(
{
name: 'Test Webhook',
service: WebhookService.Slack,
team: options.teamId ?? team._id,
},
{
name: 'Test Webhook',
service: WebhookService.Slack,
url: 'https://hooks.slack.com/test',
team: options.teamId ?? team._id,
},
{ upsert: true, new: true },
);
};
// Helper to create a dashboard for testing
const createTestDashboard = async (
options: { numTiles?: number; name?: string; teamId?: any } = {},
) => {
const { numTiles = 1, name = 'Test Dashboard' } = options;
const tiles = Array.from({ length: numTiles }, (_, i) => ({
id: new ObjectId().toString(),
name: `Chart ${i + 1}`,
x: i * 6,
y: Math.floor(i / 2) * 3,
w: 6,
h: 3,
seriesReturnType: 'column',
}));
return new Dashboard({
name,
tiles,
team: options.teamId ?? team._id,
}).save();
};
// Helper to create a dashboard with a raw SQL tile for testing
const createTestDashboardWithRawSqlTile = async (
options: { teamId?: any } = {},
) => {
const tileId = new ObjectId().toString();
const tiles = [
{
id: tileId,
name: 'Raw SQL Chart',
x: 0,
y: 0,
w: 6,
h: 3,
config: {
configType: 'sql',
displayType: 'line',
sqlTemplate: 'SELECT 1',
connection: 'test-connection',
},
},
];
const dashboard = await new Dashboard({
name: 'Raw SQL Dashboard',
tiles,
team: options.teamId ?? team._id,
}).save();
return { dashboard, tileId };
};
// Helper to create a saved search for testing
const createTestSavedSearch = async (options: { teamId?: any } = {}) => {
return new SavedSearch({
name: 'Test Saved Search',
where: 'error',
whereLanguage: 'lucene',
source: new ObjectId(),
team: options.teamId ?? team._id,
}).save();
};
// Helper to create a test alert via API
const createTestAlert = async (overrides = {}) => {
const dashboard = await createTestDashboard();
const webhook = await createTestWebhook();
const alertInput = {
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
name: 'Test Alert',
message: 'Test Alert Message',
...overrides,
};
const response = await authRequest('post', ALERTS_BASE_URL)
.send(alertInput)
.expect(200);
return {
alert: response.body.data,
dashboard,
webhook,
alertInput,
};
};
// Helper to create a test alert directly in the database (bypasses validation)
const createTestAlertDirectly = async (overrides = {}) => {
return Alert.create({
team: team._id,
dashboardId: new ObjectId().toString(),
tileId: new ObjectId().toString(),
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: new ObjectId().toString(),
},
name: 'Direct DB Alert',
message: 'Created directly in DB',
...overrides,
});
};
describe('Response Format', () => {
it('should return responses in the expected format', async () => {
// Create a test dashboard and webhook with known values
const testDashboard = await createTestDashboard();
const testWebhook = await createTestWebhook();
const testAlert = {
dashboardId: testDashboard._id.toString(),
tileId: testDashboard.tiles[0].id,
threshold: 123,
interval: '15m',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: testWebhook._id.toString(),
},
name: 'Format Test Alert',
message: 'This is a test alert for format verification',
};
// Create the alert
const createResponse = await authRequest('post', ALERTS_BASE_URL)
.send(testAlert)
.expect(200);
// Verify full response structure
expect(createResponse.headers['content-type']).toMatch(
/application\/json/,
);
expect(createResponse.body).toEqual({
data: {
id: expect.any(String),
name: 'Format Test Alert',
message: 'This is a test alert for format verification',
threshold: 123,
interval: '15m',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: expect.any(String),
},
teamId: expect.any(String),
tileId: expect.any(String),
dashboardId: expect.any(String),
state: expect.any(String),
createdAt: expect.any(String),
updatedAt: expect.any(String),
},
});
// Get the alert to verify consistent format
const alertId = createResponse.body.data.id;
const getResponse = await authRequest(
'get',
`${ALERTS_BASE_URL}/${alertId}`,
).expect(200);
// Verify get response has same structure
expect(getResponse.headers['content-type']).toMatch(/application\/json/);
expect(getResponse.body).toEqual({
data: createResponse.body.data,
});
// List endpoint format
const listResponse = await authRequest('get', ALERTS_BASE_URL).expect(
200,
);
expect(listResponse.headers['content-type']).toMatch(/application\/json/);
expect(listResponse.body).toHaveProperty('data');
expect(Array.isArray(listResponse.body.data)).toBe(true);
// Delete response format
const deleteResponse = await authRequest(
'delete',
`${ALERTS_BASE_URL}/${alertId}`,
).expect(200);
expect(deleteResponse.body).toEqual({});
});
});
describe('Creating alerts', () => {
it('should create an alert', async () => {
// Create a test dashboard and webhook
const dashboard = await createTestDashboard();
const webhook = await createTestWebhook();
const alertInput = {
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
name: 'Test Alert',
message: 'Test Alert Message',
};
// Create the alert and verify response
const createResponse = await authRequest('post', ALERTS_BASE_URL)
.send(alertInput)
.expect(200);
const createdAlert = createResponse.body.data;
expect(createdAlert).toBeTruthy();
expect(createdAlert.threshold).toEqual(100);
expect(createdAlert.interval).toEqual('1h');
expect(createdAlert.name).toEqual('Test Alert');
expect(createdAlert.id).toBeTruthy();
});
it('should handle validation errors when creating alerts', async () => {
// Spy on console.error to suppress error output in tests
const consoleErrorSpy = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
// Missing required fields
const invalidInput = {
name: 'Invalid Alert',
message: 'This should fail validation',
};
// API returns 400 for validation errors
const response = await authRequest('post', ALERTS_BASE_URL)
.send(invalidInput)
.expect(400);
expect(response.body).toHaveProperty('message');
// Restore console.error
consoleErrorSpy.mockRestore();
});
it('should reject scheduleOffsetMinutes when scheduleStartAt is provided', async () => {
const dashboard = await createTestDashboard();
const response = await authRequest('post', ALERTS_BASE_URL)
.send({
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: new ObjectId().toString(),
},
scheduleOffsetMinutes: 2,
scheduleStartAt: new Date().toISOString(),
})
.expect(400);
expect(response.body).toHaveProperty('message');
});
it('should reject scheduleStartAt values more than 1 year in the future', async () => {
const dashboard = await createTestDashboard();
const response = await authRequest('post', ALERTS_BASE_URL)
.send({
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: new ObjectId().toString(),
},
scheduleStartAt: new Date(
Date.now() + 366 * 24 * 60 * 60 * 1000,
).toISOString(),
})
.expect(400);
expect(response.body).toHaveProperty('message');
});
it('should create multiple alerts for different tiles', async () => {
// Create a dashboard with multiple tiles
const dashboard = await createTestDashboard({ numTiles: 3 });
const webhook = await createTestWebhook();
// Store created alert IDs for verification
const createdAlertIds: string[] = [];
// Create alerts for each tile
const alertPromises = dashboard.tiles.map((tile, index) => {
const alertInput = {
dashboardId: dashboard._id.toString(),
tileId: tile.id,
threshold: 100 * (index + 1),
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
name: `Alert for ${tile.id}`,
message: `This is an alert for ${tile.id}`,
};
return authRequest('post', ALERTS_BASE_URL)
.send(alertInput)
.expect(200)
.then(res => {
createdAlertIds.push(res.body.data.id);
return res;
});
});
// Wait for all alerts to be created
const results = await Promise.all(alertPromises);
const createdAlerts = results.map(res => res.body.data);
expect(createdAlerts.length).toBe(3);
// Verify all alerts were created by checking the alerts list
const listResponse = await authRequest('get', ALERTS_BASE_URL).expect(
200,
);
// Verify each created alert exists in the response
for (const alertId of createdAlertIds) {
const found = listResponse.body.data.some(
alert => alert.id === alertId,
);
expect(found).toBe(true);
}
// Verify we have alerts for each tile
const tileIds = dashboard.tiles.map(tile => tile.id);
for (const tileId of tileIds) {
const alertForTile = listResponse.body.data.find(
alert => alert.tileId === tileId,
);
expect(alertForTile).toBeTruthy();
}
});
});
describe('Retrieving alerts', () => {
it('should get an alert by ID', async () => {
// Create a test alert directly in the database
const alert = await createTestAlertDirectly();
// Get the alert via API
const getResponse = await authRequest(
'get',
`${ALERTS_BASE_URL}/${alert._id}`,
).expect(200);
// Verify response
expect(getResponse.body.data.id).toEqual(alert._id.toString());
expect(getResponse.body.data.name).toEqual('Direct DB Alert');
});
it('should return 404 for non-existent alert', async () => {
const nonExistentId = new ObjectId().toString();
await authRequest('get', `${ALERTS_BASE_URL}/${nonExistentId}`).expect(
404,
);
});
it('should list all alerts', async () => {
// Create multiple alerts with different properties
await createTestAlert({ name: 'First Alert', threshold: 100 });
await createTestAlert({ name: 'Second Alert', threshold: 200 });
await createTestAlert({ name: 'Third Alert', threshold: 300 });
// Get all alerts via API
const listResponse = await authRequest('get', ALERTS_BASE_URL).expect(
200,
);
// Verify response format and content
expect(listResponse.body.data).toBeTruthy();
expect(Array.isArray(listResponse.body.data)).toBe(true);
expect(listResponse.body.data.length).toBeGreaterThanOrEqual(3);
// Verify alerts exist in the response
const alertNames = listResponse.body.data.map(alert => alert.name);
expect(alertNames).toContain('First Alert');
expect(alertNames).toContain('Second Alert');
expect(alertNames).toContain('Third Alert');
// Verify alert properties
const firstAlert = listResponse.body.data.find(
a => a.name === 'First Alert',
);
expect(firstAlert.threshold).toBe(100);
const secondAlert = listResponse.body.data.find(
a => a.name === 'Second Alert',
);
expect(secondAlert.threshold).toBe(200);
});
});
describe('Updating alerts', () => {
it('should update an alert', async () => {
// Create a test alert
const { alert } = await createTestAlert({
name: 'Update Test Alert',
threshold: 100,
interval: '15m',
message: 'Original message',
});
// Get the original alert to include all required fields
const originalAlert = await authRequest(
'get',
`${ALERTS_BASE_URL}/${alert.id}`,
).expect(200);
// Build update payload with required fields
const updatePayload = {
threshold: 500,
interval: '1h',
thresholdType: AlertThresholdType.ABOVE,
source: AlertSource.TILE,
dashboardId: originalAlert.body.data.dashboardId,
tileId: originalAlert.body.data.tileId,
channel: originalAlert.body.data.channel,
// Fields we want to update
name: 'Updated Alert Name',
message: 'Updated message',
};
// Update the alert
await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`)
.send(updatePayload)
.expect(200);
// Verify the update was applied by getting the alert again
const getResponse = await authRequest(
'get',
`${ALERTS_BASE_URL}/${alert.id}`,
).expect(200);
const retrievedAlert = getResponse.body.data;
// Verify updates were applied
expect(retrievedAlert.name).toBe('Updated Alert Name');
expect(retrievedAlert.threshold).toBe(500);
expect(retrievedAlert.interval).toBe('1h');
expect(retrievedAlert.message).toBe('Updated message');
});
it('should reject scheduleOffsetMinutes when scheduleStartAt is provided', async () => {
const { alert } = await createTestAlert({
interval: '1h',
});
const originalAlert = await authRequest(
'get',
`${ALERTS_BASE_URL}/${alert.id}`,
).expect(200);
await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`)
.send({
threshold: originalAlert.body.data.threshold,
interval: originalAlert.body.data.interval,
thresholdType: originalAlert.body.data.thresholdType,
source: originalAlert.body.data.source,
dashboardId: originalAlert.body.data.dashboardId,
tileId: originalAlert.body.data.tileId,
channel: originalAlert.body.data.channel,
scheduleOffsetMinutes: 2,
scheduleStartAt: new Date().toISOString(),
})
.expect(400);
});
});
describe('Deleting alerts', () => {
it('should delete an alert', async () => {
// Create a test alert
const { alert } = await createTestAlert({ name: 'Delete Test Alert' });
// Delete the alert
await authRequest('delete', `${ALERTS_BASE_URL}/${alert.id}`).expect(200);
// Verify alert is deleted by trying to get it
await authRequest('get', `${ALERTS_BASE_URL}/${alert.id}`).expect(404);
// Also verify it's not in the alerts list
const listResponse = await authRequest('get', ALERTS_BASE_URL).expect(
200,
);
const deletedAlert = listResponse.body.data.find(a => a.id === alert.id);
expect(deletedAlert).toBeUndefined();
});
});
describe('Input validation', () => {
describe('webhook validation', () => {
it('should reject a non-existent webhook', async () => {
const dashboard = await createTestDashboard();
const alertInput = {
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: new ObjectId().toString(), // does not exist
},
};
await authRequest('post', ALERTS_BASE_URL).send(alertInput).expect(400);
});
it('should reject a webhook belonging to another team', async () => {
const dashboard = await createTestDashboard();
const otherTeamWebhook = await createTestWebhook({
teamId: new ObjectId(),
});
const alertInput = {
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: otherTeamWebhook._id.toString(),
},
};
await authRequest('post', ALERTS_BASE_URL).send(alertInput).expect(400);
});
it('should reject an update with a webhook belonging to another team', async () => {
const { alert, dashboard } = await createTestAlert();
const otherTeamWebhook = await createTestWebhook({
teamId: new ObjectId(),
});
const updatePayload = {
threshold: 200,
interval: '1h',
thresholdType: AlertThresholdType.ABOVE,
source: AlertSource.TILE,
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
channel: {
type: 'webhook',
webhookId: otherTeamWebhook._id.toString(),
},
};
await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`)
.send(updatePayload)
.expect(400);
});
});
describe('dashboard (TILE source) validation', () => {
it('should reject a non-existent dashboard', async () => {
const webhook = await createTestWebhook();
const alertInput = {
dashboardId: new ObjectId().toString(), // does not exist
tileId: new ObjectId().toString(),
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest('post', ALERTS_BASE_URL).send(alertInput).expect(400);
});
it('should reject a dashboard belonging to another team', async () => {
const webhook = await createTestWebhook();
const otherTeamDashboard = await createTestDashboard({
teamId: new ObjectId(),
});
const alertInput = {
dashboardId: otherTeamDashboard._id.toString(),
tileId: otherTeamDashboard.tiles[0].id,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest('post', ALERTS_BASE_URL).send(alertInput).expect(400);
});
it('should reject an update with a dashboard belonging to another team', async () => {
const { alert, webhook } = await createTestAlert();
const otherTeamDashboard = await createTestDashboard({
teamId: new ObjectId(),
});
const updatePayload = {
threshold: 200,
interval: '1h',
thresholdType: AlertThresholdType.ABOVE,
source: AlertSource.TILE,
dashboardId: otherTeamDashboard._id.toString(),
tileId: otherTeamDashboard.tiles[0].id,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`)
.send(updatePayload)
.expect(400);
});
it('should reject creating an alert on a raw SQL tile', async () => {
const webhook = await createTestWebhook();
const { dashboard, tileId } = await createTestDashboardWithRawSqlTile();
const alertInput = {
dashboardId: dashboard._id.toString(),
tileId,
threshold: 100,
interval: '1h',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest('post', ALERTS_BASE_URL).send(alertInput).expect(400);
});
it('should reject updating an alert to reference a raw SQL tile', async () => {
const { alert, webhook } = await createTestAlert();
const { dashboard: rawSqlDashboard, tileId: rawSqlTileId } =
await createTestDashboardWithRawSqlTile();
const updatePayload = {
threshold: 200,
interval: '1h',
thresholdType: AlertThresholdType.ABOVE,
source: AlertSource.TILE,
dashboardId: rawSqlDashboard._id.toString(),
tileId: rawSqlTileId,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`)
.send(updatePayload)
.expect(400);
});
});
describe('saved search (SAVED_SEARCH source) validation', () => {
it('should reject a non-existent saved search', async () => {
const webhook = await createTestWebhook();
const alertInput = {
savedSearchId: new ObjectId().toString(), // does not exist
threshold: 100,
interval: '1h',
source: AlertSource.SAVED_SEARCH,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest('post', ALERTS_BASE_URL).send(alertInput).expect(400);
});
it('should reject a saved search belonging to another team', async () => {
const webhook = await createTestWebhook();
const otherTeamSavedSearch = await createTestSavedSearch({
teamId: new ObjectId(),
});
const alertInput = {
savedSearchId: otherTeamSavedSearch._id.toString(),
threshold: 100,
interval: '1h',
source: AlertSource.SAVED_SEARCH,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest('post', ALERTS_BASE_URL).send(alertInput).expect(400);
});
it('should create an alert with a valid saved search belonging to the team', async () => {
const webhook = await createTestWebhook();
const savedSearch = await createTestSavedSearch();
const alertInput = {
savedSearchId: savedSearch._id.toString(),
threshold: 100,
interval: '1h',
source: AlertSource.SAVED_SEARCH,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
name: 'Saved Search Alert',
};
const response = await authRequest('post', ALERTS_BASE_URL)
.send(alertInput)
.expect(200);
expect(response.body.data.source).toBe(AlertSource.SAVED_SEARCH);
expect(response.body.data.savedSearchId).toBe(
savedSearch._id.toString(),
);
});
it('should reject an update with a saved search belonging to another team', async () => {
const savedSearch = await createTestSavedSearch();
const webhook = await createTestWebhook();
// Create a saved search alert first
const createResponse = await authRequest('post', ALERTS_BASE_URL)
.send({
savedSearchId: savedSearch._id.toString(),
threshold: 100,
interval: '1h',
source: AlertSource.SAVED_SEARCH,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
})
.expect(200);
const otherTeamSavedSearch = await createTestSavedSearch({
teamId: new ObjectId(),
});
const updatePayload = {
savedSearchId: otherTeamSavedSearch._id.toString(),
threshold: 200,
interval: '1h',
source: AlertSource.SAVED_SEARCH,
thresholdType: AlertThresholdType.ABOVE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
};
await authRequest(
'put',
`${ALERTS_BASE_URL}/${createResponse.body.data.id}`,
)
.send(updatePayload)
.expect(400);
});
});
});
describe('Authentication', () => {
it('should require authentication', async () => {
// Create an unauthenticated agent
const unauthenticatedAgent = request(server.getHttpServer());
const testId = new ObjectId().toString();
await unauthenticatedAgent
.get(`${ALERTS_BASE_URL}/${testId}`)
.expect(401);
});
});
describe('Rate of Change Alerts', () => {
it('should create and retrieve a rate-of-change alert', async () => {
const { alert } = await createTestAlert({
conditionType: AlertConditionType.RATE_OF_CHANGE,
changeType: AlertChangeType.PERCENTAGE,
});
expect(alert.conditionType).toBe(AlertConditionType.RATE_OF_CHANGE);
expect(alert.changeType).toBe(AlertChangeType.PERCENTAGE);
const getResp = await authRequest(
'get',
`${ALERTS_BASE_URL}/${alert.id}`,
).expect(200);
expect(getResp.body.data.conditionType).toBe(
AlertConditionType.RATE_OF_CHANGE,
);
expect(getResp.body.data.changeType).toBe(AlertChangeType.PERCENTAGE);
});
it('should reject rate-of-change without changeType', async () => {
const dashboard = await createTestDashboard();
const webhook = await createTestWebhook();
await authRequest('post', ALERTS_BASE_URL)
.send({
dashboardId: dashboard._id.toString(),
tileId: dashboard.tiles[0].id,
threshold: 50,
interval: '5m',
source: AlertSource.TILE,
thresholdType: AlertThresholdType.ABOVE,
conditionType: AlertConditionType.RATE_OF_CHANGE,
channel: {
type: 'webhook',
webhookId: webhook._id.toString(),
},
})
.expect(400);
});
});
});