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';
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';
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';
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';
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;
49 // Get's private attributes or functions
51 nodeIds: (): { [path: string]: CephfsDir } => component['nodeIds'],
52 dirs: (): CephfsDir[] => component['dirs'],
53 requestedPaths: (): string[] => component['requestedPaths']
56 // Object contains mock data that will be reset before each test.
60 createdSnaps: CephfsSnapshot[] | any[];
61 deletedSnaps: CephfsSnapshot[] | any[];
62 updatedQuotas: { [path: string]: CephfsQuotas };
63 createdDirs: CephfsDir[];
66 // Object contains mock functions
68 quotas: (max_bytes: number, max_files: number): CephfsQuotas => ({ max_bytes, max_files }),
69 snapshots: (dirPath: string, howMany: number): CephfsSnapshot[] => {
70 const name = 'someSnapshot';
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 });
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);
88 const deletedSnapshots = mockData.deletedSnaps
89 .filter((s) => s.path === dirPath)
91 if (deletedSnapshots.length > 0) {
92 snapshots = snapshots.filter((s) => !deletedSnapshots.includes(s.name));
98 quotas: Object.assign(
99 mockLib.quotas(1024 * modifier, 10 * modifier),
100 mockData.updatedQuotas[dirPath] || {}
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
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)
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));
127 if (path === '' || path === '/') {
128 // Adds root directory on ls of '/' to the directories list.
129 const root = mockLib.dir(path, '/', 1);
131 root.parent = undefined;
132 root.quotas = undefined;
133 data = [root].concat(data);
137 mkSnapshot: (_id: any, path: string, name: string): Observable<string> => {
138 mockData.createdSnaps.push({
141 created: new Date().toString()
145 rmSnapshot: (_id: any, path: string, name: string): Observable<string> => {
146 mockData.deletedSnaps.push({
149 created: new Date().toString()
153 updateQuota: (_id: any, path: string, updated: CephfsQuotas): Observable<string> => {
154 mockData.updatedQuotas[path] = Object.assign(mockData.updatedQuotas[path] || {}, updated);
155 return of('Response');
157 modalShow: (comp: Type<any>, init: any): any => {
158 modal = modalServiceShow(comp, init);
161 getNodeById: (path: string) => {
162 return mockLib.useNode(path);
164 updateNodes: (path: string) => {
165 const p: Promise<any[]> = component.treeOptions.getChildren({ id: path });
166 return noAsyncUpdate ? () => p : mockLib.asyncNodeUpdate(p);
168 asyncNodeUpdate: fakeAsync((p: Promise<any[]>) => {
170 mockData.nodes = mockData.nodes.concat(nodes);
174 changeId: (id: number) => {
175 // For some reason this spy has to be renewed after usage
176 spyOn(global, 'setTimeout').and.callFake((fn) => fn());
178 component.ngOnChanges();
179 mockData.nodes = component.nodes.concat(mockData.nodes);
181 selectNode: (path: string) => {
182 component.treeOptions.actionMapping.mouse.click(undefined, mockLib.useNode(path), undefined);
184 // Creates TreeNode with parents until root
185 useNode: (path: string): { id: string; parent: any; data: any; loadNodeChildren: Function } => {
186 const parentPath = path.split('/');
188 const parentIsRoot = parentPath.length === 1;
189 const parent = parentIsRoot ? { id: '/' } : mockLib.useNode(parentPath.join('/'));
194 loadNodeChildren: () => mockLib.updateNodes(path)
198 toggleActive: (_a: any, node: any, _b: any) => {
199 return mockLib.updateNodes(node.id);
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 });
211 createSnapshotThroughModal: (name: string) => {
212 component.createSnapshot();
213 modal.component.onSubmitForm({ name });
215 deleteSnapshotsThroughModal: (snapshots: CephfsSnapshot[]) => {
216 component.snapshot.selection.selected = snapshots;
217 component.deleteSnapshotModal();
218 modal.component.callSubmitAction();
220 updateQuotaThroughModal: (attribute: string, value: number) => {
221 component.quota.selection.selected = component.settings.filter(
222 (q) => q.quotaKey === attribute
224 component.updateQuotaModal();
225 modal.component.onSubmitForm({ [attribute]: value });
227 unsetQuotaThroughModal: (attribute: string) => {
228 component.quota.selection.selected = component.settings.filter(
229 (q) => q.quotaKey === attribute
231 component.unsetQuotaModal();
232 modal.component.onSubmit();
234 setFourQuotaDirs: (quotas: number[][]) => {
235 expect(quotas.length).toBe(4); // Make sure this function is used correctly
237 quotas.forEach((quota, index) => {
239 mockLib.mkDir(path === '' ? '/' : path, index.toString(), quota[0], quota[1]);
251 parent: { value: '/', id: '/' }
255 mockLib.selectNode('/1/2/3/4');
259 // Expects that are used frequently
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);
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 });
274 noQuota: (key: 'bytes' | 'files') => {
275 assert.quotaRow(key, '', 0, '');
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);
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);
288 key: 'bytes' | 'files',
289 shownValue: number | string,
290 nextTreeMaximum: number,
293 const isBytes = key === 'bytes';
294 expect(component.settings[isBytes ? 1 : 0]).toEqual({
296 name: `Max ${isBytes ? 'size' : key}`,
300 quotaKey: `max_${key}`,
301 dirValue: expect.any(Number),
303 value: nextTreeMaximum,
304 path: expect.any(String)
308 quotaUnsetModalTexts: (titleText: string, message: string, notificationMsg: string) => {
309 expect(modalShowSpy).toHaveBeenCalledWith(ConfirmationModalComponent, {
310 initialState: expect.objectContaining({
312 description: message,
316 expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg);
318 quotaUpdateModalTexts: (titleText: string, message: string, notificationMsg: string) => {
319 expect(modalShowSpy).toHaveBeenCalledWith(FormModalComponent, {
320 initialState: expect.objectContaining({
323 submitButtonText: 'Save'
326 expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg);
328 quotaUpdateModalField: (
334 errors?: { [key: string]: string }
336 expect(modalShowSpy).toHaveBeenCalledWith(FormModalComponent, {
337 initialState: expect.objectContaining({
345 validators: expect.anything(),
351 if (type === 'binary') {
352 expect(minBinaryValidator).toHaveBeenCalledWith(0);
353 expect(maxBinaryValidator).toHaveBeenCalledWith(max);
355 expect(minValidator).toHaveBeenCalledWith(0);
356 expect(maxValidator).toHaveBeenCalledWith(max);
363 HttpClientTestingModule,
366 TreeModule.forRoot(),
367 NgBootstrapFormValidationModule.forRoot(),
368 ToastrModule.forRoot(),
369 ModalModule.forRoot()
371 declarations: [CephfsDirectoriesComponent],
372 providers: [i18nProviders, BsModalRef]
376 noAsyncUpdate = false;
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);
392 modalShowSpy = spyOn(TestBed.get(BsModalService), 'show').and.callFake(mockLib.modalShow);
393 notificationShowSpy = spyOn(TestBed.get(NotificationService), 'show').and.stub();
395 fixture = TestBed.createComponent(CephfsDirectoriesComponent);
396 component = fixture.componentInstance;
397 fixture.detectChanges();
399 spyOn(TREE_ACTIONS, 'TOGGLE_ACTIVE').and.callFake(mockLib.treeActions.toggleActive);
401 component.treeComponent = {
402 sizeChanged: () => null,
403 treeModel: { getNodeById: mockLib.getNodeById, update: () => null }
407 it('should create', () => {
408 expect(component).toBeTruthy();
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([
415 name: 'someSnapshot1',
416 path: '/a/.snap/someSnapshot1'
419 expect(mockLib.snapshots('/a/b', 3).map((s) => ({ name: s.name, path: s.path }))).toEqual([
421 name: 'someSnapshot1',
422 path: '/a/b/.snap/someSnapshot1'
425 name: 'someSnapshot2',
426 path: '/a/b/.snap/someSnapshot2'
429 name: 'someSnapshot3',
430 path: '/a/b/.snap/someSnapshot3'
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']);
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([
462 describe('test quota update mock', () => {
466 const updateQuota = (quotas: CephfsQuotas) => mockLib.updateQuota(ID, PATH, quotas);
468 const expectMockUpdate = (max_bytes?: number, max_files?: number) =>
469 expect(mockData.updatedQuotas[PATH]).toEqual({
474 const expectLsUpdate = (max_bytes?: number, max_files?: number) => {
476 mockLib.lsDir(ID, '/').subscribe((dirs) => (dir = dirs.find((d) => d.path === PATH)));
477 expect(dir.quotas).toEqual({
483 it('tests to set quotas', () => {
484 expectLsUpdate(1024, 10);
486 updateQuota({ max_bytes: 512 });
487 expectMockUpdate(512);
488 expectLsUpdate(512, 10);
490 updateQuota({ max_files: 100 });
491 expectMockUpdate(512, 100);
492 expectLsUpdate(512, 100);
495 it('tests to unset quotas', () => {
496 updateQuota({ max_files: 0 });
497 expectMockUpdate(undefined, 0);
498 expectLsUpdate(1024, 0);
500 updateQuota({ max_bytes: 0 });
501 expectMockUpdate(0, 0);
502 expectLsUpdate(0, 0);
507 it('calls lsDir only if an id exits', () => {
508 assert.lsDirCalledTimes(0);
511 assert.lsDirCalledTimes(1);
512 expect(lsDirSpy).toHaveBeenCalledWith(1, '/');
515 assert.lsDirCalledTimes(2);
516 expect(lsDirSpy).toHaveBeenCalledWith(2, '/');
519 describe('listing sub directories', () => {
523 * Tree looks like this:
531 it('expands first level', () => {
532 // Tree will only show '*' if nor 'loadChildren' or 'children' are defined
534 mockData.nodes.map((node: any) => ({
535 [node.id]: node.hasChildren || node.isExpanded || Boolean(node.children)
537 ).toEqual([{ '/': true }, { '/a': true }, { '/b': false }, { '/c': true }]);
540 it('resets all dynamic content on id change', () => {
541 mockLib.selectNode('/a');
543 * Tree looks like this:
552 assert.requestedPaths(['/', '/a']);
553 assert.nodeLength(7);
554 assert.dirLength(16);
555 expect(component.selectedDir).toBeDefined();
557 mockLib.changeId(undefined);
559 assert.requestedPaths([]);
560 expect(component.selectedDir).not.toBeDefined();
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);
571 it('should extend the list by subdirectories when expanding', () => {
572 mockLib.selectNode('/a');
573 mockLib.selectNode('/a/c');
575 * Tree looks like this:
587 assert.lsDirCalledTimes(3);
588 assert.requestedPaths(['/', '/a', '/a/c']);
589 assert.dirLength(22);
590 assert.nodeLength(10);
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);
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');
610 it('should refresh directories with no sub directories as they could have some now', () => {
611 mockLib.selectNode('/b');
613 * Tree looks like this:
619 assert.lsDirCalledTimes(2);
620 assert.requestedPaths(['/', '/b']);
621 assert.nodeLength(4);
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);
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);
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);
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);
655 describe('snapshots', () => {
658 mockLib.selectNode('/a');
661 it('should create a snapshot', () => {
662 mockLib.createSnapshotThroughModal('newSnap');
663 expect(cephfsService.mkSnapshot).toHaveBeenCalledWith(1, '/a', 'newSnap');
664 assert.snapshotsByName(['someSnapshot1', 'newSnap']);
667 it('should delete a snapshot', () => {
668 mockLib.createSnapshotThroughModal('deleteMe');
669 mockLib.deleteSnapshotsThroughModal([component.selectedDir.snapshots[1]]);
670 assert.snapshotsByName(['someSnapshot1']);
673 it('should delete all snapshots', () => {
674 mockLib.createSnapshotThroughModal('deleteAll');
675 mockLib.deleteSnapshotsThroughModal(component.selectedDir.snapshots);
676 assert.snapshotsByName([]);
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
686 expect(tableActions).toEqual({
687 'create,update,delete': {
688 actions: ['Create', 'Delete'],
689 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
693 primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
696 actions: ['Create', 'Delete'],
697 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
701 primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
705 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
709 primary: { multiple: '', executing: '', single: '', no: '' }
713 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
717 primary: { multiple: '', executing: '', single: '', no: '' }
722 describe('quotas', () => {
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();
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);
740 describe('update modal', () => {
741 describe('max_files', () => {
743 mockLib.updateQuotaThroughModal('max_files', 5);
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);
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'
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'"
767 describe('max_bytes', () => {
769 mockLib.updateQuotaThroughModal('max_bytes', 512);
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);
777 it('uses the correct form field', () => {
778 mockLib.updateQuotaThroughModal('max_bytes', 512);
779 assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 2048, 1024);
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'"
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);
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'"
810 describe('unset modal', () => {
811 describe('max_files', () => {
813 mockLib.updateQuotaThroughModal('max_files', 5); // Sets usable quota
814 mockLib.unsetQuotaThroughModal('max_files');
817 it('should unset max_files correctly', () => {
818 expect(cephfsService.updateQuota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 0 });
819 assert.dirQuotas(2048, 0);
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'"
831 describe('max_bytes', () => {
833 mockLib.updateQuotaThroughModal('max_bytes', 512); // Sets usable quota
834 mockLib.unsetQuotaThroughModal('max_bytes');
837 it('should unset max_files correctly', () => {
838 expect(cephfsService.updateQuota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 0 });
839 assert.dirQuotas(0, 20);
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'"
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'"
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'"
875 describe('table actions', () => {
876 let actions: CdTableAction[];
878 const empty = (): CdTableSelection => new CdTableSelection();
880 const select = (value: number): CdTableSelection => {
881 const selection = new CdTableSelection();
882 selection.selected = [{ dirValue: value }];
887 actions = component.quota.tableActions;
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);
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);
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);
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
917 expect(tableActions).toEqual({
918 'create,update,delete': {
919 actions: ['Set', 'Update', 'Unset'],
920 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
923 actions: ['Set', 'Update', 'Unset'],
924 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
928 primary: { multiple: '', executing: '', single: '', no: '' }
932 primary: { multiple: '', executing: '', single: '', no: '' }
935 actions: ['Set', 'Update', 'Unset'],
936 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
939 actions: ['Set', 'Update', 'Unset'],
940 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
944 primary: { multiple: '', executing: '', single: '', no: '' }
948 primary: { multiple: '', executing: '', single: '', no: '' }
954 describe('reload all', () => {
955 const calledPaths = ['/', '/a', '/a/c', '/a/c/a', '/a/c/a/b'];
957 const dirsByPath = (): string[] => get.dirs().map((d) => d.path);
961 mockLib.selectNode('/a');
962 mockLib.selectNode('/a/c');
963 mockLib.selectNode('/a/c/a');
964 mockLib.selectNode('/a/c/a/b');
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);
975 it('should reload all requested paths if not selected anything', () => {
976 lsDirSpy.calls.reset();
978 assert.lsDirHasBeenCalledWith(2, ['/']);
979 lsDirSpy.calls.reset();
980 component.refreshAllDirectories();
981 assert.lsDirHasBeenCalledWith(2, ['/']);
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);
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);
1012 describe('loading indicator', () => {
1014 noAsyncUpdate = true;
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);
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);
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);
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);