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