summaryrefslogtreecommitdiff
path: root/spec/frontend/monitoring/alert_widget_spec.js
blob: d004b1da0b64dafbe1b103d8a9585ee3771258d2 (plain)
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
import { shallowMount } from '@vue/test-utils';
import { GlLoadingIcon, GlTooltip, GlSprintf, GlBadge } from '@gitlab/ui';
import waitForPromises from 'helpers/wait_for_promises';
import AlertWidget from '~/monitoring/components/alert_widget.vue';
import { deprecatedCreateFlash as createFlash } from '~/flash';

const mockReadAlert = jest.fn();
const mockCreateAlert = jest.fn();
const mockUpdateAlert = jest.fn();
const mockDeleteAlert = jest.fn();

jest.mock('~/flash');
jest.mock(
  '~/monitoring/services/alerts_service',
  () =>
    function AlertsServiceMock() {
      return {
        readAlert: mockReadAlert,
        createAlert: mockCreateAlert,
        updateAlert: mockUpdateAlert,
        deleteAlert: mockDeleteAlert,
      };
    },
);

describe('AlertWidget', () => {
  let wrapper;

  const nonFiringAlertResult = [
    {
      values: [[0, 1], [1, 42], [2, 41]],
    },
  ];
  const firingAlertResult = [
    {
      values: [[0, 42], [1, 43], [2, 44]],
    },
  ];
  const metricId = '5';
  const alertPath = 'my/alert.json';

  const relevantQueries = [
    {
      metricId,
      label: 'alert-label',
      alert_path: alertPath,
      result: nonFiringAlertResult,
    },
  ];

  const firingRelevantQueries = [
    {
      metricId,
      label: 'alert-label',
      alert_path: alertPath,
      result: firingAlertResult,
    },
  ];

  const defaultProps = {
    alertsEndpoint: '',
    relevantQueries,
    alertsToManage: {},
    modalId: 'alert-modal-1',
  };

  const propsWithAlert = {
    relevantQueries,
  };

  const propsWithAlertData = {
    relevantQueries,
    alertsToManage: {
      [alertPath]: { operator: '>', threshold: 42, alert_path: alertPath, metricId },
    },
  };

  const createComponent = propsData => {
    wrapper = shallowMount(AlertWidget, {
      stubs: { GlTooltip, GlSprintf },
      propsData: {
        ...defaultProps,
        ...propsData,
      },
    });
  };
  const hasLoadingIcon = () => wrapper.find(GlLoadingIcon).exists();
  const findWidgetForm = () => wrapper.find({ ref: 'widgetForm' });
  const findAlertErrorMessage = () => wrapper.find({ ref: 'alertErrorMessage' });
  const findCurrentSettingsText = () =>
    wrapper
      .find({ ref: 'alertCurrentSetting' })
      .text()
      .replace(/\s\s+/g, ' ');
  const findBadge = () => wrapper.find(GlBadge);
  const findTooltip = () => wrapper.find(GlTooltip);

  afterEach(() => {
    wrapper.destroy();
    wrapper = null;
  });

  it('displays a loading spinner and disables form when fetching alerts', () => {
    let resolveReadAlert;
    mockReadAlert.mockReturnValue(
      new Promise(resolve => {
        resolveReadAlert = resolve;
      }),
    );
    createComponent(defaultProps);
    return wrapper.vm
      .$nextTick()
      .then(() => {
        expect(hasLoadingIcon()).toBe(true);
        expect(findWidgetForm().props('disabled')).toBe(true);

        resolveReadAlert({ operator: '==', threshold: 42 });
      })
      .then(() => waitForPromises())
      .then(() => {
        expect(hasLoadingIcon()).toBe(false);
        expect(findWidgetForm().props('disabled')).toBe(false);
      });
  });

  it('does not render loading spinner if showLoadingState is false', () => {
    let resolveReadAlert;
    mockReadAlert.mockReturnValue(
      new Promise(resolve => {
        resolveReadAlert = resolve;
      }),
    );
    createComponent({
      ...defaultProps,
      showLoadingState: false,
    });
    return wrapper.vm
      .$nextTick()
      .then(() => {
        expect(wrapper.find(GlLoadingIcon).exists()).toBe(false);

        resolveReadAlert({ operator: '==', threshold: 42 });
      })
      .then(() => waitForPromises())
      .then(() => {
        expect(wrapper.find(GlLoadingIcon).exists()).toBe(false);
      });
  });

  it('displays an error message when fetch fails', () => {
    mockReadAlert.mockRejectedValue();
    createComponent(propsWithAlert);
    expect(hasLoadingIcon()).toBe(true);

    return waitForPromises().then(() => {
      expect(createFlash).toHaveBeenCalled();
      expect(hasLoadingIcon()).toBe(false);
    });
  });

  describe('Alert not firing', () => {
    it('displays a warning icon and matches snapshot', () => {
      mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
      createComponent(propsWithAlertData);

      return waitForPromises().then(() => {
        expect(findBadge().element).toMatchSnapshot();
      });
    });

    it('displays an alert summary when there is a single alert', () => {
      mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
      createComponent(propsWithAlertData);
      return waitForPromises().then(() => {
        expect(findCurrentSettingsText()).toEqual('alert-label > 42');
      });
    });

    it('displays a combined alert summary when there are multiple alerts', () => {
      mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
      const propsWithManyAlerts = {
        relevantQueries: [
          ...relevantQueries,
          ...[
            {
              metricId: '6',
              alert_path: 'my/alert2.json',
              label: 'alert-label2',
              result: [{ values: [] }],
            },
          ],
        ],
        alertsToManage: {
          'my/alert.json': {
            operator: '>',
            threshold: 42,
            alert_path: alertPath,
            metricId,
          },
          'my/alert2.json': {
            operator: '==',
            threshold: 900,
            alert_path: 'my/alert2.json',
            metricId: '6',
          },
        },
      };
      createComponent(propsWithManyAlerts);
      return waitForPromises().then(() => {
        expect(findCurrentSettingsText()).toContain('2 alerts applied');
      });
    });
  });

  describe('Alert firing', () => {
    it('displays a warning icon and matches snapshot', () => {
      mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
      propsWithAlertData.relevantQueries = firingRelevantQueries;
      createComponent(propsWithAlertData);

      return waitForPromises().then(() => {
        expect(findBadge().element).toMatchSnapshot();
      });
    });

    it('displays an alert summary when there is a single alert', () => {
      mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
      propsWithAlertData.relevantQueries = firingRelevantQueries;
      createComponent(propsWithAlertData);
      return waitForPromises().then(() => {
        expect(findCurrentSettingsText()).toEqual('Firing: alert-label > 42');
      });
    });

    it('displays a combined alert summary when there are multiple alerts', () => {
      mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
      const propsWithManyAlerts = {
        relevantQueries: [
          ...firingRelevantQueries,
          ...[
            {
              metricId: '6',
              alert_path: 'my/alert2.json',
              label: 'alert-label2',
              result: [{ values: [] }],
            },
          ],
        ],
        alertsToManage: {
          'my/alert.json': {
            operator: '>',
            threshold: 42,
            alert_path: alertPath,
            metricId,
          },
          'my/alert2.json': {
            operator: '==',
            threshold: 900,
            alert_path: 'my/alert2.json',
            metricId: '6',
          },
        },
      };
      createComponent(propsWithManyAlerts);

      return waitForPromises().then(() => {
        expect(findCurrentSettingsText()).toContain('2 alerts applied, 1 firing');
      });
    });

    it('should display tooltip with thresholds summary', () => {
      mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
      const propsWithManyAlerts = {
        relevantQueries: [
          ...firingRelevantQueries,
          ...[
            {
              metricId: '6',
              alert_path: 'my/alert2.json',
              label: 'alert-label2',
              result: [{ values: [] }],
            },
          ],
        ],
        alertsToManage: {
          'my/alert.json': {
            operator: '>',
            threshold: 42,
            alert_path: alertPath,
            metricId,
          },
          'my/alert2.json': {
            operator: '==',
            threshold: 900,
            alert_path: 'my/alert2.json',
            metricId: '6',
          },
        },
      };
      createComponent(propsWithManyAlerts);

      return waitForPromises().then(() => {
        expect(
          findTooltip()
            .text()
            .replace(/\s\s+/g, ' '),
        ).toEqual('Firing: alert-label > 42');
      });
    });
  });

  it('creates an alert with an appropriate handler', () => {
    const alertParams = {
      operator: '<',
      threshold: 4,
      prometheus_metric_id: '5',
    };
    mockReadAlert.mockResolvedValue({ operator: '>', threshold: 42 });
    const fakeAlertPath = 'foo/bar';
    mockCreateAlert.mockResolvedValue({ alert_path: fakeAlertPath, ...alertParams });
    createComponent({
      alertsToManage: {
        [fakeAlertPath]: {
          alert_path: fakeAlertPath,
          operator: '<',
          threshold: 4,
          prometheus_metric_id: '5',
          metricId: '5',
        },
      },
    });

    findWidgetForm().vm.$emit('create', alertParams);

    expect(mockCreateAlert).toHaveBeenCalledWith(alertParams);
  });

  it('updates an alert with an appropriate handler', () => {
    const alertParams = { operator: '<', threshold: 4, alert_path: alertPath };
    const newAlertParams = { operator: '==', threshold: 12 };
    mockReadAlert.mockResolvedValue(alertParams);
    mockUpdateAlert.mockResolvedValue({ ...alertParams, ...newAlertParams });
    createComponent({
      ...propsWithAlertData,
      alertsToManage: {
        [alertPath]: {
          alert_path: alertPath,
          operator: '==',
          threshold: 12,
          metricId: '5',
        },
      },
    });

    findWidgetForm().vm.$emit('update', {
      alert: alertPath,
      ...newAlertParams,
      prometheus_metric_id: '5',
    });

    expect(mockUpdateAlert).toHaveBeenCalledWith(alertPath, newAlertParams);
  });

  it('deletes an alert with an appropriate handler', () => {
    const alertParams = { alert_path: alertPath, operator: '>', threshold: 42 };
    mockReadAlert.mockResolvedValue(alertParams);
    mockDeleteAlert.mockResolvedValue({});
    createComponent({
      ...propsWithAlert,
      alertsToManage: {
        [alertPath]: {
          alert_path: alertPath,
          operator: '>',
          threshold: 42,
          metricId: '5',
        },
      },
    });

    findWidgetForm().vm.$emit('delete', { alert: alertPath });

    return wrapper.vm.$nextTick().then(() => {
      expect(mockDeleteAlert).toHaveBeenCalledWith(alertPath);
      expect(findAlertErrorMessage().exists()).toBe(false);
    });
  });

  describe('when delete fails', () => {
    beforeEach(() => {
      const alertParams = { alert_path: alertPath, operator: '>', threshold: 42 };
      mockReadAlert.mockResolvedValue(alertParams);
      mockDeleteAlert.mockRejectedValue();

      createComponent({
        ...propsWithAlert,
        alertsToManage: {
          [alertPath]: {
            alert_path: alertPath,
            operator: '>',
            threshold: 42,
            metricId: '5',
          },
        },
      });

      findWidgetForm().vm.$emit('delete', { alert: alertPath });
      return wrapper.vm.$nextTick();
    });

    it('shows error message', () => {
      expect(findAlertErrorMessage().text()).toEqual('Error deleting alert');
    });

    it('dismisses error message on cancel', () => {
      findWidgetForm().vm.$emit('cancel');

      return wrapper.vm.$nextTick().then(() => {
        expect(findAlertErrorMessage().exists()).toBe(false);
      });
    });
  });
});