summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/shared/services/notification.service.spec.ts
blob: 028dd90ea39684f174fd8f6007a48697741691b0 (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
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';

import _ from 'lodash';
import { ToastrService } from 'ngx-toastr';

import { configureTestBed } from '~/testing/unit-test-helper';
import { RbdService } from '../api/rbd.service';
import { NotificationType } from '../enum/notification-type.enum';
import { CdNotificationConfig } from '../models/cd-notification';
import { FinishedTask } from '../models/finished-task';
import { CdDatePipe } from '../pipes/cd-date.pipe';
import { NotificationService } from './notification.service';
import { TaskMessageService } from './task-message.service';

describe('NotificationService', () => {
  let service: NotificationService;
  const toastFakeService = {
    error: () => true,
    info: () => true,
    success: () => true
  };

  configureTestBed({
    providers: [
      NotificationService,
      TaskMessageService,
      { provide: ToastrService, useValue: toastFakeService },
      { provide: CdDatePipe, useValue: { transform: (d: any) => d } },
      RbdService
    ],
    imports: [HttpClientTestingModule]
  });

  beforeEach(() => {
    service = TestBed.inject(NotificationService);
    service.removeAll();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should read empty notification list', () => {
    localStorage.setItem('cdNotifications', '[]');
    expect(service['dataSource'].getValue()).toEqual([]);
  });

  it('should read old notifications', fakeAsync(() => {
    localStorage.setItem(
      'cdNotifications',
      '[{"type":2,"message":"foobar","timestamp":"2018-05-24T09:41:32.726Z"}]'
    );
    service = new NotificationService(null, null, null);
    expect(service['dataSource'].getValue().length).toBe(1);
  }));

  it('should cancel a notification', fakeAsync(() => {
    const timeoutId = service.show(NotificationType.error, 'Simple test');
    service.cancel(timeoutId);
    tick(5000);
    expect(service['dataSource'].getValue().length).toBe(0);
  }));

  describe('Saved notifications', () => {
    const expectSavedNotificationToHave = (expected: object) => {
      tick(510);
      expect(service['dataSource'].getValue().length).toBe(1);
      const notification = service['dataSource'].getValue()[0];
      Object.keys(expected).forEach((key) => {
        expect(notification[key]).toBe(expected[key]);
      });
    };

    const addNotifications = (quantity: number) => {
      for (let index = 0; index < quantity; index++) {
        service.show(NotificationType.info, `${index}`);
        tick(510);
      }
    };

    beforeEach(() => {
      spyOn(service, 'show').and.callThrough();
      service.cancel((<any>service)['justShownTimeoutId']);
    });

    it('should create a success notification and save it', fakeAsync(() => {
      service.show(new CdNotificationConfig(NotificationType.success, 'Simple test'));
      expectSavedNotificationToHave({ type: NotificationType.success });
    }));

    it('should create an error notification and save it', fakeAsync(() => {
      service.show(NotificationType.error, 'Simple test');
      expectSavedNotificationToHave({ type: NotificationType.error });
    }));

    it('should create an info notification and save it', fakeAsync(() => {
      service.show(new CdNotificationConfig(NotificationType.info, 'Simple test'));
      expectSavedNotificationToHave({
        type: NotificationType.info,
        title: 'Simple test',
        message: undefined
      });
    }));

    it('should never have more then 10 notifications', fakeAsync(() => {
      addNotifications(15);
      expect(service['dataSource'].getValue().length).toBe(10);
    }));

    it('should show a success task notification, but not save it', fakeAsync(() => {
      const task = _.assign(new FinishedTask(), {
        success: true
      });

      service.notifyTask(task, true);
      tick(1500);

      expect(service.show).toHaveBeenCalled();
      const notifications = service['dataSource'].getValue();
      expect(notifications.length).toBe(0);
    }));

    it('should be able to stop notifyTask from notifying', fakeAsync(() => {
      const task = _.assign(new FinishedTask(), {
        success: true
      });
      const timeoutId = service.notifyTask(task, true);
      service.cancel(timeoutId);
      tick(100);
      expect(service['dataSource'].getValue().length).toBe(0);
    }));

    it('should show a error task notification', fakeAsync(() => {
      const task = _.assign(
        new FinishedTask('rbd/create', {
          pool_name: 'somePool',
          image_name: 'someImage'
        }),
        {
          success: false,
          exception: {
            code: 17
          }
        }
      );
      service.notifyTask(task);

      tick(1500);

      expect(service.show).toHaveBeenCalled();
      const notifications = service['dataSource'].getValue();
      expect(notifications.length).toBe(0);
    }));

    it('combines different notifications with the same title', fakeAsync(() => {
      service.show(NotificationType.error, '502 - Bad Gateway', 'Error occurred in path a');
      tick(60);
      service.show(NotificationType.error, '502 - Bad Gateway', 'Error occurred in path b');
      expectSavedNotificationToHave({
        type: NotificationType.error,
        title: '502 - Bad Gateway',
        message: '<ul><li>Error occurred in path a</li><li>Error occurred in path b</li></ul>'
      });
    }));

    it('should remove a single notification', fakeAsync(() => {
      addNotifications(5);
      let messages = service['dataSource'].getValue().map((notification) => notification.title);
      expect(messages).toEqual(['4', '3', '2', '1', '0']);
      service.remove(2);
      messages = service['dataSource'].getValue().map((notification) => notification.title);
      expect(messages).toEqual(['4', '3', '1', '0']);
    }));

    it('should remove all notifications', fakeAsync(() => {
      addNotifications(5);
      expect(service['dataSource'].getValue().length).toBe(5);
      service.removeAll();
      expect(service['dataSource'].getValue().length).toBe(0);
    }));
  });

  describe('notification queue', () => {
    const n1 = new CdNotificationConfig(NotificationType.success, 'Some success');
    const n2 = new CdNotificationConfig(NotificationType.info, 'Some info');

    const showArray = (arr: any[]) => arr.forEach((n) => service.show(n));

    beforeEach(() => {
      spyOn(service, 'save').and.stub();
    });

    it('filters out duplicated notifications on single call', fakeAsync(() => {
      showArray([n1, n1, n2, n2]);
      tick(510);
      expect(service.save).toHaveBeenCalledTimes(2);
    }));

    it('filters out duplicated notifications presented in different calls', fakeAsync(() => {
      showArray([n1, n2]);
      showArray([n1, n2]);
      tick(1000);
      expect(service.save).toHaveBeenCalledTimes(2);
    }));

    it('will reset the timeout on every call', fakeAsync(() => {
      showArray([n1, n2]);
      tick(490);
      showArray([n1, n2]);
      tick(450);
      expect(service.save).toHaveBeenCalledTimes(0);
      tick(60);
      expect(service.save).toHaveBeenCalledTimes(2);
    }));

    it('wont filter out duplicated notifications if timeout was reached before', fakeAsync(() => {
      showArray([n1, n2]);
      tick(510);
      showArray([n1, n2]);
      tick(510);
      expect(service.save).toHaveBeenCalledTimes(4);
    }));
  });

  describe('showToasty', () => {
    let toastr: ToastrService;
    const time = '2022-02-22T00:00:00.000Z';

    beforeEach(() => {
      const baseTime = new Date(time);
      spyOn(global, 'Date').and.returnValue(baseTime);
      spyOn(window, 'setTimeout').and.callFake((fn) => fn());

      toastr = TestBed.inject(ToastrService);
      // spyOn needs to know the methods before spying and can't read the array for clarification
      ['error', 'info', 'success'].forEach((method: 'error' | 'info' | 'success') =>
        spyOn(toastr, method).and.stub()
      );
    });

    it('should show with only title defined', () => {
      service.show(NotificationType.info, 'Some info');
      expect(toastr.info).toHaveBeenCalledWith(
        `<small class="date">${time}</small>` +
          '<i class="float-right custom-icon ceph-icon" title="Ceph"></i>',
        'Some info',
        undefined
      );
    });

    it('should show with title and message defined', () => {
      service.show(
        () =>
          new CdNotificationConfig(NotificationType.error, 'Some error', 'Some operation failed')
      );
      expect(toastr.error).toHaveBeenCalledWith(
        'Some operation failed<br>' +
          `<small class="date">${time}</small>` +
          '<i class="float-right custom-icon ceph-icon" title="Ceph"></i>',
        'Some error',
        undefined
      );
    });

    it('should show with title, message and application defined', () => {
      service.show(
        new CdNotificationConfig(
          NotificationType.success,
          'Alert resolved',
          'Some alert resolved',
          undefined,
          'Prometheus'
        )
      );
      expect(toastr.success).toHaveBeenCalledWith(
        'Some alert resolved<br>' +
          `<small class="date">${time}</small>` +
          '<i class="float-right custom-icon prometheus-icon" title="Prometheus"></i>',
        'Alert resolved',
        undefined
      );
    });
  });
});