]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
c8f6c22a14b9a093ae846e1de101d99732cbf883
[ceph.git] /
1 import { HttpClientTestingModule } from '@angular/common/http/testing';
2 import { Type } from '@angular/core';
3 import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
4 import { Validators } from '@angular/forms';
5 import { RouterTestingModule } from '@angular/router/testing';
6
7 import { TreeComponent, TreeModule, TREE_ACTIONS } from '@circlon/angular-tree-component';
8 import { NgbActiveModal, NgbModalModule, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
9 import { ToastrModule } from 'ngx-toastr';
10 import { Observable, of } from 'rxjs';
11
12 import { CephfsService } from '~/app/shared/api/cephfs.service';
13 import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component';
14 import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component';
15 import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component';
16 import { NotificationType } from '~/app/shared/enum/notification-type.enum';
17 import { CdValidators } from '~/app/shared/forms/cd-validators';
18 import { CdTableAction } from '~/app/shared/models/cd-table-action';
19 import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
20 import {
21   CephfsDir,
22   CephfsQuotas,
23   CephfsSnapshot
24 } from '~/app/shared/models/cephfs-directory-models';
25 import { ModalService } from '~/app/shared/services/modal.service';
26 import { NotificationService } from '~/app/shared/services/notification.service';
27 import { SharedModule } from '~/app/shared/shared.module';
28 import { configureTestBed, modalServiceShow, PermissionHelper } from '~/testing/unit-test-helper';
29 import { CephfsDirectoriesComponent } from './cephfs-directories.component';
30
31 describe('CephfsDirectoriesComponent', () => {
32   let component: CephfsDirectoriesComponent;
33   let fixture: ComponentFixture<CephfsDirectoriesComponent>;
34   let cephfsService: CephfsService;
35   let noAsyncUpdate: boolean;
36   let lsDirSpy: jasmine.Spy;
37   let modalShowSpy: jasmine.Spy;
38   let notificationShowSpy: jasmine.Spy;
39   let minValidator: jasmine.Spy;
40   let maxValidator: jasmine.Spy;
41   let minBinaryValidator: jasmine.Spy;
42   let maxBinaryValidator: jasmine.Spy;
43   let modal: NgbModalRef;
44
45   // Get's private attributes or functions
46   const get = {
47     nodeIds: (): { [path: string]: CephfsDir } => component['nodeIds'],
48     dirs: (): CephfsDir[] => component['dirs'],
49     requestedPaths: (): string[] => component['requestedPaths']
50   };
51
52   // Object contains mock data that will be reset before each test.
53   let mockData: {
54     nodes: any;
55     parent: any;
56     createdSnaps: CephfsSnapshot[] | any[];
57     deletedSnaps: CephfsSnapshot[] | any[];
58     updatedQuotas: { [path: string]: CephfsQuotas };
59     createdDirs: CephfsDir[];
60   };
61
62   // Object contains mock functions
63   const mockLib = {
64     quotas: (max_bytes: number, max_files: number): CephfsQuotas => ({ max_bytes, max_files }),
65     snapshots: (dirPath: string, howMany: number): CephfsSnapshot[] => {
66       const name = 'someSnapshot';
67       const snapshots = [];
68       const oneDay = 3600 * 24 * 1000;
69       for (let i = 0; i < howMany; i++) {
70         const snapName = `${name}${i + 1}`;
71         const path = `${dirPath}/.snap/${snapName}`;
72         const created = new Date(+new Date() - oneDay * i).toString();
73         snapshots.push({ name: snapName, path, created });
74       }
75       return snapshots;
76     },
77     dir: (parentPath: string, name: string, modifier: number): CephfsDir => {
78       const dirPath = `${parentPath === '/' ? '' : parentPath}/${name}`;
79       let snapshots = mockLib.snapshots(parentPath, modifier);
80       const extraSnapshots = mockData.createdSnaps.filter((s) => s.path === dirPath);
81       if (extraSnapshots.length > 0) {
82         snapshots = snapshots.concat(extraSnapshots);
83       }
84       const deletedSnapshots = mockData.deletedSnaps
85         .filter((s) => s.path === dirPath)
86         .map((s) => s.name);
87       if (deletedSnapshots.length > 0) {
88         snapshots = snapshots.filter((s) => !deletedSnapshots.includes(s.name));
89       }
90       return {
91         name,
92         path: dirPath,
93         parent: parentPath,
94         quotas: Object.assign(
95           mockLib.quotas(1024 * modifier, 10 * modifier),
96           mockData.updatedQuotas[dirPath] || {}
97         ),
98         snapshots: snapshots
99       };
100     },
101     // Only used inside other mocks
102     lsSingleDir: (path = ''): CephfsDir[] => {
103       const customDirs = mockData.createdDirs.filter((d) => d.parent === path);
104       const isCustomDir = mockData.createdDirs.some((d) => d.path === path);
105       if (isCustomDir || path.includes('b')) {
106         // 'b' has no sub directories
107         return customDirs;
108       }
109       return customDirs.concat([
110         // Directories are not sorted!
111         mockLib.dir(path, 'c', 3),
112         mockLib.dir(path, 'a', 1),
113         mockLib.dir(path, 'b', 2)
114       ]);
115     },
116     lsDir: (_id: number, path = ''): Observable<CephfsDir[]> => {
117       // will return 2 levels deep
118       let data = mockLib.lsSingleDir(path);
119       const paths = data.map((dir) => dir.path);
120       paths.forEach((pathL2) => {
121         data = data.concat(mockLib.lsSingleDir(pathL2));
122       });
123       if (path === '' || path === '/') {
124         // Adds root directory on ls of '/' to the directories list.
125         const root = mockLib.dir(path, '/', 1);
126         root.path = '/';
127         root.parent = undefined;
128         root.quotas = undefined;
129         data = [root].concat(data);
130       }
131       return of(data);
132     },
133     mkSnapshot: (_id: any, path: string, name: string): Observable<string> => {
134       mockData.createdSnaps.push({
135         name,
136         path,
137         created: new Date().toString()
138       });
139       return of(name);
140     },
141     rmSnapshot: (_id: any, path: string, name: string): Observable<string> => {
142       mockData.deletedSnaps.push({
143         name,
144         path,
145         created: new Date().toString()
146       });
147       return of(name);
148     },
149     updateQuota: (_id: any, path: string, updated: CephfsQuotas): Observable<string> => {
150       mockData.updatedQuotas[path] = Object.assign(mockData.updatedQuotas[path] || {}, updated);
151       return of('Response');
152     },
153     modalShow: (comp: Type<any>, init: any): any => {
154       modal = modalServiceShow(comp, init);
155       return modal;
156     },
157     getNodeById: (path: string) => {
158       return mockLib.useNode(path);
159     },
160     updateNodes: (path: string) => {
161       const p: Promise<any[]> = component.treeOptions.getChildren({ id: path });
162       return noAsyncUpdate ? () => p : mockLib.asyncNodeUpdate(p);
163     },
164     asyncNodeUpdate: fakeAsync((p: Promise<any[]>) => {
165       p.then((nodes) => {
166         mockData.nodes = mockData.nodes.concat(nodes);
167       });
168       tick();
169     }),
170     changeId: (id: number) => {
171       // For some reason this spy has to be renewed after usage
172       spyOn(global, 'setTimeout').and.callFake((fn) => fn());
173       component.id = id;
174       component.ngOnChanges();
175       mockData.nodes = component.nodes.concat(mockData.nodes);
176     },
177     selectNode: (path: string) => {
178       component.treeOptions.actionMapping.mouse.click(undefined, mockLib.useNode(path), undefined);
179     },
180     // Creates TreeNode with parents until root
181     useNode: (path: string): { id: string; parent: any; data: any; loadNodeChildren: Function } => {
182       const parentPath = path.split('/');
183       parentPath.pop();
184       const parentIsRoot = parentPath.length === 1;
185       const parent = parentIsRoot ? { id: '/' } : mockLib.useNode(parentPath.join('/'));
186       return {
187         id: path,
188         parent,
189         data: {},
190         loadNodeChildren: () => mockLib.updateNodes(path)
191       };
192     },
193     treeActions: {
194       toggleActive: (_a: any, node: any, _b: any) => {
195         return mockLib.updateNodes(node.id);
196       }
197     },
198     mkDir: (path: string, name: string, maxFiles: number, maxBytes: number) => {
199       const dir = mockLib.dir(path, name, 3);
200       dir.quotas.max_bytes = maxBytes * 1024;
201       dir.quotas.max_files = maxFiles;
202       mockData.createdDirs.push(dir);
203       // Below is needed for quota tests only where 4 dirs are mocked
204       get.nodeIds()[dir.path] = dir;
205       mockData.nodes.push({ id: dir.path });
206     },
207     createSnapshotThroughModal: (name: string) => {
208       component.createSnapshot();
209       modal.componentInstance.onSubmitForm({ name });
210     },
211     deleteSnapshotsThroughModal: (snapshots: CephfsSnapshot[]) => {
212       component.snapshot.selection.selected = snapshots;
213       component.deleteSnapshotModal();
214       modal.componentInstance.callSubmitAction();
215     },
216     updateQuotaThroughModal: (attribute: string, value: number) => {
217       component.quota.selection.selected = component.settings.filter(
218         (q) => q.quotaKey === attribute
219       );
220       component.updateQuotaModal();
221       modal.componentInstance.onSubmitForm({ [attribute]: value });
222     },
223     unsetQuotaThroughModal: (attribute: string) => {
224       component.quota.selection.selected = component.settings.filter(
225         (q) => q.quotaKey === attribute
226       );
227       component.unsetQuotaModal();
228       modal.componentInstance.onSubmit();
229     },
230     setFourQuotaDirs: (quotas: number[][]) => {
231       expect(quotas.length).toBe(4); // Make sure this function is used correctly
232       let path = '';
233       quotas.forEach((quota, index) => {
234         index += 1;
235         mockLib.mkDir(path === '' ? '/' : path, index.toString(), quota[0], quota[1]);
236         path += '/' + index;
237       });
238       mockData.parent = {
239         value: '3',
240         id: '/1/2/3',
241         parent: {
242           value: '2',
243           id: '/1/2',
244           parent: {
245             value: '1',
246             id: '/1',
247             parent: { value: '/', id: '/' }
248           }
249         }
250       };
251       mockLib.selectNode('/1/2/3/4');
252     }
253   };
254
255   // Expects that are used frequently
256   const assert = {
257     dirLength: (n: number) => expect(get.dirs().length).toBe(n),
258     nodeLength: (n: number) => expect(mockData.nodes.length).toBe(n),
259     lsDirCalledTimes: (n: number) => expect(lsDirSpy).toHaveBeenCalledTimes(n),
260     lsDirHasBeenCalledWith: (id: number, paths: string[]) => {
261       paths.forEach((path) => expect(lsDirSpy).toHaveBeenCalledWith(id, path));
262       assert.lsDirCalledTimes(paths.length);
263     },
264     requestedPaths: (expected: string[]) => expect(get.requestedPaths()).toEqual(expected),
265     snapshotsByName: (snaps: string[]) =>
266       expect(component.selectedDir.snapshots.map((s) => s.name)).toEqual(snaps),
267     dirQuotas: (bytes: number, files: number) => {
268       expect(component.selectedDir.quotas).toEqual({ max_bytes: bytes, max_files: files });
269     },
270     noQuota: (key: 'bytes' | 'files') => {
271       assert.quotaRow(key, '', 0, '');
272     },
273     quotaIsNotInherited: (key: 'bytes' | 'files', shownValue: any, nextMaximum: number) => {
274       const dir = component.selectedDir;
275       const path = dir.path;
276       assert.quotaRow(key, shownValue, nextMaximum, path);
277     },
278     quotaIsInherited: (key: 'bytes' | 'files', shownValue: any, path: string) => {
279       const isBytes = key === 'bytes';
280       const nextMaximum = get.nodeIds()[path].quotas[isBytes ? 'max_bytes' : 'max_files'];
281       assert.quotaRow(key, shownValue, nextMaximum, path);
282     },
283     quotaRow: (
284       key: 'bytes' | 'files',
285       shownValue: number | string,
286       nextTreeMaximum: number,
287       originPath: string
288     ) => {
289       const isBytes = key === 'bytes';
290       expect(component.settings[isBytes ? 1 : 0]).toEqual({
291         row: {
292           name: `Max ${isBytes ? 'size' : key}`,
293           value: shownValue,
294           originPath
295         },
296         quotaKey: `max_${key}`,
297         dirValue: expect.any(Number),
298         nextTreeMaximum: {
299           value: nextTreeMaximum,
300           path: expect.any(String)
301         }
302       });
303     },
304     quotaUnsetModalTexts: (titleText: string, message: string, notificationMsg: string) => {
305       expect(modalShowSpy).toHaveBeenCalledWith(
306         ConfirmationModalComponent,
307         expect.objectContaining({
308           titleText,
309           description: message,
310           buttonText: 'Unset'
311         })
312       );
313       expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg);
314     },
315     quotaUpdateModalTexts: (titleText: string, message: string, notificationMsg: string) => {
316       expect(modalShowSpy).toHaveBeenCalledWith(
317         FormModalComponent,
318         expect.objectContaining({
319           titleText,
320           message,
321           submitButtonText: 'Save'
322         })
323       );
324       expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg);
325     },
326     quotaUpdateModalField: (
327       type: string,
328       label: string,
329       key: string,
330       value: number,
331       max: number,
332       errors?: { [key: string]: string }
333     ) => {
334       expect(modalShowSpy).toHaveBeenCalledWith(
335         FormModalComponent,
336         expect.objectContaining({
337           fields: [
338             {
339               type,
340               label,
341               errors,
342               name: key,
343               value,
344               validators: expect.anything(),
345               required: true
346             }
347           ]
348         })
349       );
350       if (type === 'binary') {
351         expect(minBinaryValidator).toHaveBeenCalledWith(0);
352         expect(maxBinaryValidator).toHaveBeenCalledWith(max);
353       } else {
354         expect(minValidator).toHaveBeenCalledWith(0);
355         expect(maxValidator).toHaveBeenCalledWith(max);
356       }
357     }
358   };
359
360   configureTestBed(
361     {
362       imports: [
363         HttpClientTestingModule,
364         SharedModule,
365         RouterTestingModule,
366         TreeModule,
367         ToastrModule.forRoot(),
368         NgbModalModule
369       ],
370       declarations: [CephfsDirectoriesComponent],
371       providers: [NgbActiveModal]
372     },
373     [CriticalConfirmationModalComponent, FormModalComponent, ConfirmationModalComponent]
374   );
375
376   beforeEach(() => {
377     noAsyncUpdate = false;
378     mockData = {
379       nodes: [],
380       parent: undefined,
381       createdSnaps: [],
382       deletedSnaps: [],
383       createdDirs: [],
384       updatedQuotas: {}
385     };
386
387     cephfsService = TestBed.inject(CephfsService);
388     lsDirSpy = spyOn(cephfsService, 'lsDir').and.callFake(mockLib.lsDir);
389     spyOn(cephfsService, 'mkSnapshot').and.callFake(mockLib.mkSnapshot);
390     spyOn(cephfsService, 'rmSnapshot').and.callFake(mockLib.rmSnapshot);
391     spyOn(cephfsService, 'quota').and.callFake(mockLib.updateQuota);
392
393     modalShowSpy = spyOn(TestBed.inject(ModalService), 'show').and.callFake(mockLib.modalShow);
394     notificationShowSpy = spyOn(TestBed.inject(NotificationService), 'show').and.stub();
395
396     fixture = TestBed.createComponent(CephfsDirectoriesComponent);
397     component = fixture.componentInstance;
398     fixture.detectChanges();
399
400     spyOn(TREE_ACTIONS, 'TOGGLE_ACTIVE').and.callFake(mockLib.treeActions.toggleActive);
401
402     component.treeComponent = {
403       sizeChanged: () => null,
404       treeModel: { getNodeById: mockLib.getNodeById, update: () => null }
405     } as TreeComponent;
406   });
407
408   it('should create', () => {
409     expect(component).toBeTruthy();
410   });
411
412   describe('mock self test', () => {
413     it('tests snapshots mock', () => {
414       expect(mockLib.snapshots('/a', 1).map((s) => ({ name: s.name, path: s.path }))).toEqual([
415         {
416           name: 'someSnapshot1',
417           path: '/a/.snap/someSnapshot1'
418         }
419       ]);
420       expect(mockLib.snapshots('/a/b', 3).map((s) => ({ name: s.name, path: s.path }))).toEqual([
421         {
422           name: 'someSnapshot1',
423           path: '/a/b/.snap/someSnapshot1'
424         },
425         {
426           name: 'someSnapshot2',
427           path: '/a/b/.snap/someSnapshot2'
428         },
429         {
430           name: 'someSnapshot3',
431           path: '/a/b/.snap/someSnapshot3'
432         }
433       ]);
434     });
435
436     it('tests dir mock', () => {
437       const path = '/a/b/c';
438       mockData.createdSnaps = [
439         { path, name: 's1' },
440         { path, name: 's2' }
441       ];
442       mockData.deletedSnaps = [
443         { path, name: 'someSnapshot2' },
444         { path, name: 's2' }
445       ];
446       const dir = mockLib.dir('/a/b', 'c', 2);
447       expect(dir.path).toBe('/a/b/c');
448       expect(dir.parent).toBe('/a/b');
449       expect(dir.quotas).toEqual({ max_bytes: 2048, max_files: 20 });
450       expect(dir.snapshots.map((s) => s.name)).toEqual(['someSnapshot1', 's1']);
451     });
452
453     it('tests lsdir mock', () => {
454       let dirs: CephfsDir[] = [];
455       mockLib.lsDir(2, '/a').subscribe((x) => (dirs = x));
456       expect(dirs.map((d) => d.path)).toEqual([
457         '/a/c',
458         '/a/a',
459         '/a/b',
460         '/a/c/c',
461         '/a/c/a',
462         '/a/c/b',
463         '/a/a/c',
464         '/a/a/a',
465         '/a/a/b'
466       ]);
467     });
468
469     describe('test quota update mock', () => {
470       const PATH = '/a';
471       const ID = 2;
472
473       const updateQuota = (quotas: CephfsQuotas) => mockLib.updateQuota(ID, PATH, quotas);
474
475       const expectMockUpdate = (max_bytes?: number, max_files?: number) =>
476         expect(mockData.updatedQuotas[PATH]).toEqual({
477           max_bytes,
478           max_files
479         });
480
481       const expectLsUpdate = (max_bytes?: number, max_files?: number) => {
482         let dir: CephfsDir;
483         mockLib.lsDir(ID, '/').subscribe((dirs) => (dir = dirs.find((d) => d.path === PATH)));
484         expect(dir.quotas).toEqual({
485           max_bytes,
486           max_files
487         });
488       };
489
490       it('tests to set quotas', () => {
491         expectLsUpdate(1024, 10);
492
493         updateQuota({ max_bytes: 512 });
494         expectMockUpdate(512);
495         expectLsUpdate(512, 10);
496
497         updateQuota({ max_files: 100 });
498         expectMockUpdate(512, 100);
499         expectLsUpdate(512, 100);
500       });
501
502       it('tests to unset quotas', () => {
503         updateQuota({ max_files: 0 });
504         expectMockUpdate(undefined, 0);
505         expectLsUpdate(1024, 0);
506
507         updateQuota({ max_bytes: 0 });
508         expectMockUpdate(0, 0);
509         expectLsUpdate(0, 0);
510       });
511     });
512   });
513
514   it('calls lsDir only if an id exits', () => {
515     assert.lsDirCalledTimes(0);
516
517     mockLib.changeId(1);
518     assert.lsDirCalledTimes(1);
519     expect(lsDirSpy).toHaveBeenCalledWith(1, '/');
520
521     mockLib.changeId(2);
522     assert.lsDirCalledTimes(2);
523     expect(lsDirSpy).toHaveBeenCalledWith(2, '/');
524   });
525
526   describe('listing sub directories', () => {
527     beforeEach(() => {
528       mockLib.changeId(1);
529       /**
530        * Tree looks like this:
531        * v /
532        *   > a
533        *   * b
534        *   > c
535        * */
536     });
537
538     it('expands first level', () => {
539       // Tree will only show '*' if nor 'loadChildren' or 'children' are defined
540       expect(
541         mockData.nodes.map((node: any) => ({
542           [node.id]: node.hasChildren || node.isExpanded || Boolean(node.children)
543         }))
544       ).toEqual([{ '/': true }, { '/a': true }, { '/b': false }, { '/c': true }]);
545     });
546
547     it('resets all dynamic content on id change', () => {
548       mockLib.selectNode('/a');
549       /**
550        * Tree looks like this:
551        * v /
552        *   v a <- Selected
553        *     > a
554        *     * b
555        *     > c
556        *   * b
557        *   > c
558        * */
559       assert.requestedPaths(['/', '/a']);
560       assert.nodeLength(7);
561       assert.dirLength(16);
562       expect(component.selectedDir).toBeDefined();
563
564       mockLib.changeId(undefined);
565       assert.dirLength(0);
566       assert.requestedPaths([]);
567       expect(component.selectedDir).not.toBeDefined();
568     });
569
570     it('should select a node and show the directory contents', () => {
571       mockLib.selectNode('/a');
572       const dir = get.dirs().find((d) => d.path === '/a');
573       expect(component.selectedDir).toEqual(dir);
574       assert.quotaIsNotInherited('files', 10, 0);
575       assert.quotaIsNotInherited('bytes', '1 KiB', 0);
576     });
577
578     it('should extend the list by subdirectories when expanding', () => {
579       mockLib.selectNode('/a');
580       mockLib.selectNode('/a/c');
581       /**
582        * Tree looks like this:
583        * v /
584        *   v a
585        *     > a
586        *     * b
587        *     v c <- Selected
588        *       > a
589        *       * b
590        *       > c
591        *   * b
592        *   > c
593        * */
594       assert.lsDirCalledTimes(3);
595       assert.requestedPaths(['/', '/a', '/a/c']);
596       assert.dirLength(22);
597       assert.nodeLength(10);
598     });
599
600     it('should update the tree after each selection', () => {
601       const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough();
602       expect(spy).toHaveBeenCalledTimes(0);
603       mockLib.selectNode('/a');
604       expect(spy).toHaveBeenCalledTimes(1);
605       mockLib.selectNode('/a/c');
606       expect(spy).toHaveBeenCalledTimes(2);
607     });
608
609     it('should select parent by path', () => {
610       mockLib.selectNode('/a');
611       mockLib.selectNode('/a/c');
612       mockLib.selectNode('/a/c/a');
613       component.selectOrigin('/a');
614       expect(component.selectedDir.path).toBe('/a');
615     });
616
617     it('should refresh directories with no sub directories as they could have some now', () => {
618       mockLib.selectNode('/b');
619       /**
620        * Tree looks like this:
621        * v /
622        *   > a
623        *   * b <- Selected
624        *   > c
625        * */
626       assert.lsDirCalledTimes(2);
627       assert.requestedPaths(['/', '/b']);
628       assert.nodeLength(4);
629     });
630
631     describe('used quotas', () => {
632       it('should use no quota if none is set', () => {
633         mockLib.setFourQuotaDirs([
634           [0, 0],
635           [0, 0],
636           [0, 0],
637           [0, 0]
638         ]);
639         assert.noQuota('files');
640         assert.noQuota('bytes');
641         assert.dirQuotas(0, 0);
642       });
643
644       it('should use quota from upper parents', () => {
645         mockLib.setFourQuotaDirs([
646           [100, 0],
647           [0, 8],
648           [0, 0],
649           [0, 0]
650         ]);
651         assert.quotaIsInherited('files', 100, '/1');
652         assert.quotaIsInherited('bytes', '8 KiB', '/1/2');
653         assert.dirQuotas(0, 0);
654       });
655
656       it('should use quota from the parent with the lowest value (deep inheritance)', () => {
657         mockLib.setFourQuotaDirs([
658           [200, 1],
659           [100, 4],
660           [400, 3],
661           [300, 2]
662         ]);
663         assert.quotaIsInherited('files', 100, '/1/2');
664         assert.quotaIsInherited('bytes', '1 KiB', '/1');
665         assert.dirQuotas(2048, 300);
666       });
667
668       it('should use current value', () => {
669         mockLib.setFourQuotaDirs([
670           [200, 2],
671           [300, 4],
672           [400, 3],
673           [100, 1]
674         ]);
675         assert.quotaIsNotInherited('files', 100, 200);
676         assert.quotaIsNotInherited('bytes', '1 KiB', 2048);
677         assert.dirQuotas(1024, 100);
678       });
679     });
680   });
681
682   describe('snapshots', () => {
683     beforeEach(() => {
684       mockLib.changeId(1);
685       mockLib.selectNode('/a');
686     });
687
688     it('should create a snapshot', () => {
689       mockLib.createSnapshotThroughModal('newSnap');
690       expect(cephfsService.mkSnapshot).toHaveBeenCalledWith(1, '/a', 'newSnap');
691       assert.snapshotsByName(['someSnapshot1', 'newSnap']);
692     });
693
694     it('should delete a snapshot', () => {
695       mockLib.createSnapshotThroughModal('deleteMe');
696       mockLib.deleteSnapshotsThroughModal([component.selectedDir.snapshots[1]]);
697       assert.snapshotsByName(['someSnapshot1']);
698     });
699
700     it('should delete all snapshots', () => {
701       mockLib.createSnapshotThroughModal('deleteAll');
702       mockLib.deleteSnapshotsThroughModal(component.selectedDir.snapshots);
703       assert.snapshotsByName([]);
704     });
705   });
706
707   it('should test all snapshot table actions combinations', () => {
708     const permissionHelper: PermissionHelper = new PermissionHelper(component.permission);
709     const tableActions = permissionHelper.setPermissionsAndGetActions(
710       component.snapshot.tableActions
711     );
712
713     expect(tableActions).toEqual({
714       'create,update,delete': {
715         actions: ['Create', 'Delete'],
716         primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
717       },
718       'create,update': {
719         actions: ['Create'],
720         primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
721       },
722       'create,delete': {
723         actions: ['Create', 'Delete'],
724         primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
725       },
726       create: {
727         actions: ['Create'],
728         primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
729       },
730       'update,delete': {
731         actions: ['Delete'],
732         primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
733       },
734       update: {
735         actions: [],
736         primary: { multiple: '', executing: '', single: '', no: '' }
737       },
738       delete: {
739         actions: ['Delete'],
740         primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
741       },
742       'no-permissions': {
743         actions: [],
744         primary: { multiple: '', executing: '', single: '', no: '' }
745       }
746     });
747   });
748
749   describe('quotas', () => {
750     beforeEach(() => {
751       // Spies
752       minValidator = spyOn(Validators, 'min').and.callThrough();
753       maxValidator = spyOn(Validators, 'max').and.callThrough();
754       minBinaryValidator = spyOn(CdValidators, 'binaryMin').and.callThrough();
755       maxBinaryValidator = spyOn(CdValidators, 'binaryMax').and.callThrough();
756       // Select /a/c/b
757       mockLib.changeId(1);
758       mockLib.selectNode('/a');
759       mockLib.selectNode('/a/c');
760       mockLib.selectNode('/a/c/b');
761       // Quotas after selection
762       assert.quotaIsInherited('files', 10, '/a');
763       assert.quotaIsInherited('bytes', '1 KiB', '/a');
764       assert.dirQuotas(2048, 20);
765     });
766
767     describe('update modal', () => {
768       describe('max_files', () => {
769         beforeEach(() => {
770           mockLib.updateQuotaThroughModal('max_files', 5);
771         });
772
773         it('should update max_files correctly', () => {
774           expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 5 });
775           assert.quotaIsNotInherited('files', 5, 10);
776         });
777
778         it('uses the correct form field', () => {
779           assert.quotaUpdateModalField('number', 'Max files', 'max_files', 20, 10, {
780             min: 'Value has to be at least 0 or more',
781             max: 'Value has to be at most 10 or less'
782           });
783         });
784
785         it('shows the right texts', () => {
786           assert.quotaUpdateModalTexts(
787             `Update CephFS files quota for '/a/c/b'`,
788             `The inherited files quota 10 from '/a' is the maximum value to be used.`,
789             `Updated CephFS files quota for '/a/c/b'`
790           );
791         });
792       });
793
794       describe('max_bytes', () => {
795         beforeEach(() => {
796           mockLib.updateQuotaThroughModal('max_bytes', 512);
797         });
798
799         it('should update max_files correctly', () => {
800           expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 512 });
801           assert.quotaIsNotInherited('bytes', '512 B', 1024);
802         });
803
804         it('uses the correct form field', () => {
805           mockLib.updateQuotaThroughModal('max_bytes', 512);
806           assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 2048, 1024);
807         });
808
809         it('shows the right texts', () => {
810           assert.quotaUpdateModalTexts(
811             `Update CephFS size quota for '/a/c/b'`,
812             `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`,
813             `Updated CephFS size quota for '/a/c/b'`
814           );
815         });
816       });
817
818       describe('action behaviour', () => {
819         it('opens with next maximum as maximum if directory holds the current maximum', () => {
820           mockLib.updateQuotaThroughModal('max_bytes', 512);
821           mockLib.updateQuotaThroughModal('max_bytes', 888);
822           assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 512, 1024);
823         });
824
825         it(`uses 'Set' action instead of 'Update' if the quota is not set (0)`, () => {
826           mockLib.updateQuotaThroughModal('max_bytes', 0);
827           mockLib.updateQuotaThroughModal('max_bytes', 200);
828           assert.quotaUpdateModalTexts(
829             `Set CephFS size quota for '/a/c/b'`,
830             `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`,
831             `Set CephFS size quota for '/a/c/b'`
832           );
833         });
834       });
835     });
836
837     describe('unset modal', () => {
838       describe('max_files', () => {
839         beforeEach(() => {
840           mockLib.updateQuotaThroughModal('max_files', 5); // Sets usable quota
841           mockLib.unsetQuotaThroughModal('max_files');
842         });
843
844         it('should unset max_files correctly', () => {
845           expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 0 });
846           assert.dirQuotas(2048, 0);
847         });
848
849         it('shows the right texts', () => {
850           assert.quotaUnsetModalTexts(
851             `Unset CephFS files quota for '/a/c/b'`,
852             `Unset files quota 5 from '/a/c/b' in order to inherit files quota 10 from '/a'.`,
853             `Unset CephFS files quota for '/a/c/b'`
854           );
855         });
856       });
857
858       describe('max_bytes', () => {
859         beforeEach(() => {
860           mockLib.updateQuotaThroughModal('max_bytes', 512); // Sets usable quota
861           mockLib.unsetQuotaThroughModal('max_bytes');
862         });
863
864         it('should unset max_files correctly', () => {
865           expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 0 });
866           assert.dirQuotas(0, 20);
867         });
868
869         it('shows the right texts', () => {
870           assert.quotaUnsetModalTexts(
871             `Unset CephFS size quota for '/a/c/b'`,
872             `Unset size quota 512 B from '/a/c/b' in order to inherit size quota 1 KiB from '/a'.`,
873             `Unset CephFS size quota for '/a/c/b'`
874           );
875         });
876       });
877
878       describe('action behaviour', () => {
879         it('uses different Text if no quota is inherited', () => {
880           mockLib.selectNode('/a');
881           mockLib.unsetQuotaThroughModal('max_bytes');
882           assert.quotaUnsetModalTexts(
883             `Unset CephFS size quota for '/a'`,
884             `Unset size quota 1 KiB from '/a' in order to have no quota on the directory.`,
885             `Unset CephFS size quota for '/a'`
886           );
887         });
888
889         it('uses different Text if quota is already inherited', () => {
890           mockLib.unsetQuotaThroughModal('max_bytes');
891           assert.quotaUnsetModalTexts(
892             `Unset CephFS size quota for '/a/c/b'`,
893             `Unset size quota 2 KiB from '/a/c/b' which isn't used because of the inheritance ` +
894               `of size quota 1 KiB from '/a'.`,
895             `Unset CephFS size quota for '/a/c/b'`
896           );
897         });
898       });
899     });
900   });
901
902   describe('table actions', () => {
903     let actions: CdTableAction[];
904
905     const empty = (): CdTableSelection => new CdTableSelection();
906
907     const select = (value: number): CdTableSelection => {
908       const selection = new CdTableSelection();
909       selection.selected = [{ dirValue: value }];
910       return selection;
911     };
912
913     beforeEach(() => {
914       actions = component.quota.tableActions;
915     });
916
917     it(`shows 'Set' for empty and not set quotas`, () => {
918       const isSetVisible = actions[0].visible;
919       expect(isSetVisible(empty())).toBe(true);
920       expect(isSetVisible(select(0))).toBe(true);
921       expect(isSetVisible(select(1))).toBe(false);
922     });
923
924     it(`shows 'Update' for set quotas only`, () => {
925       const isUpdateVisible = actions[1].visible;
926       expect(isUpdateVisible(empty())).toBeFalsy();
927       expect(isUpdateVisible(select(0))).toBe(false);
928       expect(isUpdateVisible(select(1))).toBe(true);
929     });
930
931     it(`only enables 'Unset' for set quotas only`, () => {
932       const isUnsetDisabled = actions[2].disable;
933       expect(isUnsetDisabled(empty())).toBe(true);
934       expect(isUnsetDisabled(select(0))).toBe(true);
935       expect(isUnsetDisabled(select(1))).toBe(false);
936     });
937
938     it('should test all quota table actions permission combinations', () => {
939       const permissionHelper: PermissionHelper = new PermissionHelper(component.permission, {
940         single: { dirValue: 0 },
941         multiple: [{ dirValue: 0 }, {}]
942       });
943       const tableActions = permissionHelper.setPermissionsAndGetActions(
944         component.quota.tableActions
945       );
946
947       expect(tableActions).toEqual({
948         'create,update,delete': {
949           actions: ['Set', 'Update', 'Unset'],
950           primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
951         },
952         'create,update': {
953           actions: ['Set', 'Update', 'Unset'],
954           primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
955         },
956         'create,delete': {
957           actions: [],
958           primary: { multiple: '', executing: '', single: '', no: '' }
959         },
960         create: {
961           actions: [],
962           primary: { multiple: '', executing: '', single: '', no: '' }
963         },
964         'update,delete': {
965           actions: ['Set', 'Update', 'Unset'],
966           primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
967         },
968         update: {
969           actions: ['Set', 'Update', 'Unset'],
970           primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
971         },
972         delete: {
973           actions: [],
974           primary: { multiple: '', executing: '', single: '', no: '' }
975         },
976         'no-permissions': {
977           actions: [],
978           primary: { multiple: '', executing: '', single: '', no: '' }
979         }
980       });
981     });
982   });
983
984   describe('reload all', () => {
985     const calledPaths = ['/', '/a', '/a/c', '/a/c/a', '/a/c/a/b'];
986
987     const dirsByPath = (): string[] => get.dirs().map((d) => d.path);
988
989     beforeEach(() => {
990       mockLib.changeId(1);
991       mockLib.selectNode('/a');
992       mockLib.selectNode('/a/c');
993       mockLib.selectNode('/a/c/a');
994       mockLib.selectNode('/a/c/a/b');
995     });
996
997     it('should reload all requested paths', () => {
998       assert.lsDirHasBeenCalledWith(1, calledPaths);
999       lsDirSpy.calls.reset();
1000       assert.lsDirHasBeenCalledWith(1, []);
1001       component.refreshAllDirectories();
1002       assert.lsDirHasBeenCalledWith(1, calledPaths);
1003     });
1004
1005     it('should reload all requested paths if not selected anything', () => {
1006       lsDirSpy.calls.reset();
1007       mockLib.changeId(2);
1008       assert.lsDirHasBeenCalledWith(2, ['/']);
1009       lsDirSpy.calls.reset();
1010       component.refreshAllDirectories();
1011       assert.lsDirHasBeenCalledWith(2, ['/']);
1012     });
1013
1014     it('should add new directories', () => {
1015       // Create two new directories in preparation
1016       const dirsBeforeRefresh = dirsByPath();
1017       expect(dirsBeforeRefresh.includes('/a/c/has_dir_now')).toBe(false);
1018       mockLib.mkDir('/a/c', 'has_dir_now', 0, 0);
1019       mockLib.mkDir('/a/c/a/b', 'has_dir_now_too', 0, 0);
1020       // Now the new directories will be fetched
1021       component.refreshAllDirectories();
1022       const dirsAfterRefresh = dirsByPath();
1023       expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(2);
1024       expect(dirsAfterRefresh.includes('/a/c/has_dir_now')).toBe(true);
1025       expect(dirsAfterRefresh.includes('/a/c/a/b/has_dir_now_too')).toBe(true);
1026     });
1027
1028     it('should remove deleted directories', () => {
1029       // Create one new directory and refresh in order to have it added to the directories list
1030       mockLib.mkDir('/a/c', 'will_be_removed_shortly', 0, 0);
1031       component.refreshAllDirectories();
1032       const dirsBeforeRefresh = dirsByPath();
1033       expect(dirsBeforeRefresh.includes('/a/c/will_be_removed_shortly')).toBe(true);
1034       mockData.createdDirs = []; // Mocks the deletion of the directory
1035       // Now the deleted directory will be missing on refresh
1036       component.refreshAllDirectories();
1037       const dirsAfterRefresh = dirsByPath();
1038       expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(-1);
1039       expect(dirsAfterRefresh.includes('/a/c/will_be_removed_shortly')).toBe(false);
1040     });
1041
1042     describe('loading indicator', () => {
1043       beforeEach(() => {
1044         noAsyncUpdate = true;
1045       });
1046
1047       it('should have set loading indicator to false after refreshing all dirs', fakeAsync(() => {
1048         component.refreshAllDirectories();
1049         expect(component.loadingIndicator).toBe(true);
1050         tick(3000); // To resolve all promises
1051         expect(component.loadingIndicator).toBe(false);
1052       }));
1053
1054       it('should only update the tree once and not on every call', fakeAsync(() => {
1055         const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough();
1056         component.refreshAllDirectories();
1057         expect(spy).toHaveBeenCalledTimes(0);
1058         tick(3000); // To resolve all promises
1059         // Called during the interval and at the end of timeout
1060         expect(spy).toHaveBeenCalledTimes(2);
1061       }));
1062
1063       it('should have set all loaded dirs as attribute names of "indicators"', () => {
1064         noAsyncUpdate = false;
1065         component.refreshAllDirectories();
1066         expect(Object.keys(component.loading).sort()).toEqual(calledPaths);
1067       });
1068
1069       it('should set an indicator to true during load', () => {
1070         lsDirSpy.and.callFake(() => new Observable((): null => null));
1071         component.refreshAllDirectories();
1072         expect(Object.values(component.loading).every((b) => b)).toBe(true);
1073         expect(component.loadingIndicator).toBe(true);
1074       });
1075     });
1076   });
1077 });