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 { TreeComponent, TreeModule, TREE_ACTIONS } 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.inject(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.inject(BsModalService), 'show').and.callFake(mockLib.modalShow);
393 notificationShowSpy = spyOn(TestBed.inject(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 = [
438 { path, name: 's1' },
441 mockData.deletedSnaps = [
442 { path, name: 'someSnapshot2' },
445 const dir = mockLib.dir('/a/b', 'c', 2);
446 expect(dir.path).toBe('/a/b/c');
447 expect(dir.parent).toBe('/a/b');
448 expect(dir.quotas).toEqual({ max_bytes: 2048, max_files: 20 });
449 expect(dir.snapshots.map((s) => s.name)).toEqual(['someSnapshot1', 's1']);
452 it('tests lsdir mock', () => {
453 let dirs: CephfsDir[] = [];
454 mockLib.lsDir(2, '/a').subscribe((x) => (dirs = x));
455 expect(dirs.map((d) => d.path)).toEqual([
468 describe('test quota update mock', () => {
472 const updateQuota = (quotas: CephfsQuotas) => mockLib.updateQuota(ID, PATH, quotas);
474 const expectMockUpdate = (max_bytes?: number, max_files?: number) =>
475 expect(mockData.updatedQuotas[PATH]).toEqual({
480 const expectLsUpdate = (max_bytes?: number, max_files?: number) => {
482 mockLib.lsDir(ID, '/').subscribe((dirs) => (dir = dirs.find((d) => d.path === PATH)));
483 expect(dir.quotas).toEqual({
489 it('tests to set quotas', () => {
490 expectLsUpdate(1024, 10);
492 updateQuota({ max_bytes: 512 });
493 expectMockUpdate(512);
494 expectLsUpdate(512, 10);
496 updateQuota({ max_files: 100 });
497 expectMockUpdate(512, 100);
498 expectLsUpdate(512, 100);
501 it('tests to unset quotas', () => {
502 updateQuota({ max_files: 0 });
503 expectMockUpdate(undefined, 0);
504 expectLsUpdate(1024, 0);
506 updateQuota({ max_bytes: 0 });
507 expectMockUpdate(0, 0);
508 expectLsUpdate(0, 0);
513 it('calls lsDir only if an id exits', () => {
514 assert.lsDirCalledTimes(0);
517 assert.lsDirCalledTimes(1);
518 expect(lsDirSpy).toHaveBeenCalledWith(1, '/');
521 assert.lsDirCalledTimes(2);
522 expect(lsDirSpy).toHaveBeenCalledWith(2, '/');
525 describe('listing sub directories', () => {
529 * Tree looks like this:
537 it('expands first level', () => {
538 // Tree will only show '*' if nor 'loadChildren' or 'children' are defined
540 mockData.nodes.map((node: any) => ({
541 [node.id]: node.hasChildren || node.isExpanded || Boolean(node.children)
543 ).toEqual([{ '/': true }, { '/a': true }, { '/b': false }, { '/c': true }]);
546 it('resets all dynamic content on id change', () => {
547 mockLib.selectNode('/a');
549 * Tree looks like this:
558 assert.requestedPaths(['/', '/a']);
559 assert.nodeLength(7);
560 assert.dirLength(16);
561 expect(component.selectedDir).toBeDefined();
563 mockLib.changeId(undefined);
565 assert.requestedPaths([]);
566 expect(component.selectedDir).not.toBeDefined();
569 it('should select a node and show the directory contents', () => {
570 mockLib.selectNode('/a');
571 const dir = get.dirs().find((d) => d.path === '/a');
572 expect(component.selectedDir).toEqual(dir);
573 assert.quotaIsNotInherited('files', 10, 0);
574 assert.quotaIsNotInherited('bytes', '1 KiB', 0);
577 it('should extend the list by subdirectories when expanding', () => {
578 mockLib.selectNode('/a');
579 mockLib.selectNode('/a/c');
581 * Tree looks like this:
593 assert.lsDirCalledTimes(3);
594 assert.requestedPaths(['/', '/a', '/a/c']);
595 assert.dirLength(22);
596 assert.nodeLength(10);
599 it('should update the tree after each selection', () => {
600 const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough();
601 expect(spy).toHaveBeenCalledTimes(0);
602 mockLib.selectNode('/a');
603 expect(spy).toHaveBeenCalledTimes(1);
604 mockLib.selectNode('/a/c');
605 expect(spy).toHaveBeenCalledTimes(2);
608 it('should select parent by path', () => {
609 mockLib.selectNode('/a');
610 mockLib.selectNode('/a/c');
611 mockLib.selectNode('/a/c/a');
612 component.selectOrigin('/a');
613 expect(component.selectedDir.path).toBe('/a');
616 it('should refresh directories with no sub directories as they could have some now', () => {
617 mockLib.selectNode('/b');
619 * Tree looks like this:
625 assert.lsDirCalledTimes(2);
626 assert.requestedPaths(['/', '/b']);
627 assert.nodeLength(4);
630 describe('used quotas', () => {
631 it('should use no quota if none is set', () => {
632 mockLib.setFourQuotaDirs([
638 assert.noQuota('files');
639 assert.noQuota('bytes');
640 assert.dirQuotas(0, 0);
643 it('should use quota from upper parents', () => {
644 mockLib.setFourQuotaDirs([
650 assert.quotaIsInherited('files', 100, '/1');
651 assert.quotaIsInherited('bytes', '8 KiB', '/1/2');
652 assert.dirQuotas(0, 0);
655 it('should use quota from the parent with the lowest value (deep inheritance)', () => {
656 mockLib.setFourQuotaDirs([
662 assert.quotaIsInherited('files', 100, '/1/2');
663 assert.quotaIsInherited('bytes', '1 KiB', '/1');
664 assert.dirQuotas(2048, 300);
667 it('should use current value', () => {
668 mockLib.setFourQuotaDirs([
674 assert.quotaIsNotInherited('files', 100, 200);
675 assert.quotaIsNotInherited('bytes', '1 KiB', 2048);
676 assert.dirQuotas(1024, 100);
681 describe('snapshots', () => {
684 mockLib.selectNode('/a');
687 it('should create a snapshot', () => {
688 mockLib.createSnapshotThroughModal('newSnap');
689 expect(cephfsService.mkSnapshot).toHaveBeenCalledWith(1, '/a', 'newSnap');
690 assert.snapshotsByName(['someSnapshot1', 'newSnap']);
693 it('should delete a snapshot', () => {
694 mockLib.createSnapshotThroughModal('deleteMe');
695 mockLib.deleteSnapshotsThroughModal([component.selectedDir.snapshots[1]]);
696 assert.snapshotsByName(['someSnapshot1']);
699 it('should delete all snapshots', () => {
700 mockLib.createSnapshotThroughModal('deleteAll');
701 mockLib.deleteSnapshotsThroughModal(component.selectedDir.snapshots);
702 assert.snapshotsByName([]);
706 it('should test all snapshot table actions combinations', () => {
707 const permissionHelper: PermissionHelper = new PermissionHelper(component.permission);
708 const tableActions = permissionHelper.setPermissionsAndGetActions(
709 component.snapshot.tableActions
712 expect(tableActions).toEqual({
713 'create,update,delete': {
714 actions: ['Create', 'Delete'],
715 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
719 primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
722 actions: ['Create', 'Delete'],
723 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
727 primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
731 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
735 primary: { multiple: '', executing: '', single: '', no: '' }
739 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
743 primary: { multiple: '', executing: '', single: '', no: '' }
748 describe('quotas', () => {
751 minValidator = spyOn(Validators, 'min').and.callThrough();
752 maxValidator = spyOn(Validators, 'max').and.callThrough();
753 minBinaryValidator = spyOn(CdValidators, 'binaryMin').and.callThrough();
754 maxBinaryValidator = spyOn(CdValidators, 'binaryMax').and.callThrough();
757 mockLib.selectNode('/a');
758 mockLib.selectNode('/a/c');
759 mockLib.selectNode('/a/c/b');
760 // Quotas after selection
761 assert.quotaIsInherited('files', 10, '/a');
762 assert.quotaIsInherited('bytes', '1 KiB', '/a');
763 assert.dirQuotas(2048, 20);
766 describe('update modal', () => {
767 describe('max_files', () => {
769 mockLib.updateQuotaThroughModal('max_files', 5);
772 it('should update max_files correctly', () => {
773 expect(cephfsService.updateQuota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 5 });
774 assert.quotaIsNotInherited('files', 5, 10);
777 it('uses the correct form field', () => {
778 assert.quotaUpdateModalField('number', 'Max files', 'max_files', 20, 10, {
779 min: 'Value has to be at least 0 or more',
780 max: 'Value has to be at most 10 or less'
784 it('shows the right texts', () => {
785 assert.quotaUpdateModalTexts(
786 `Update CephFS files quota for '/a/c/b'`,
787 `The inherited files quota 10 from '/a' is the maximum value to be used.`,
788 `Updated CephFS files quota for '/a/c/b'`
793 describe('max_bytes', () => {
795 mockLib.updateQuotaThroughModal('max_bytes', 512);
798 it('should update max_files correctly', () => {
799 expect(cephfsService.updateQuota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 512 });
800 assert.quotaIsNotInherited('bytes', '512 B', 1024);
803 it('uses the correct form field', () => {
804 mockLib.updateQuotaThroughModal('max_bytes', 512);
805 assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 2048, 1024);
808 it('shows the right texts', () => {
809 assert.quotaUpdateModalTexts(
810 `Update CephFS size quota for '/a/c/b'`,
811 `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`,
812 `Updated CephFS size quota for '/a/c/b'`
817 describe('action behaviour', () => {
818 it('opens with next maximum as maximum if directory holds the current maximum', () => {
819 mockLib.updateQuotaThroughModal('max_bytes', 512);
820 mockLib.updateQuotaThroughModal('max_bytes', 888);
821 assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 512, 1024);
824 it(`uses 'Set' action instead of 'Update' if the quota is not set (0)`, () => {
825 mockLib.updateQuotaThroughModal('max_bytes', 0);
826 mockLib.updateQuotaThroughModal('max_bytes', 200);
827 assert.quotaUpdateModalTexts(
828 `Set CephFS size quota for '/a/c/b'`,
829 `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`,
830 `Set CephFS size quota for '/a/c/b'`
836 describe('unset modal', () => {
837 describe('max_files', () => {
839 mockLib.updateQuotaThroughModal('max_files', 5); // Sets usable quota
840 mockLib.unsetQuotaThroughModal('max_files');
843 it('should unset max_files correctly', () => {
844 expect(cephfsService.updateQuota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 0 });
845 assert.dirQuotas(2048, 0);
848 it('shows the right texts', () => {
849 assert.quotaUnsetModalTexts(
850 `Unset CephFS files quota for '/a/c/b'`,
851 `Unset files quota 5 from '/a/c/b' in order to inherit files quota 10 from '/a'.`,
852 `Unset CephFS files quota for '/a/c/b'`
857 describe('max_bytes', () => {
859 mockLib.updateQuotaThroughModal('max_bytes', 512); // Sets usable quota
860 mockLib.unsetQuotaThroughModal('max_bytes');
863 it('should unset max_files correctly', () => {
864 expect(cephfsService.updateQuota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 0 });
865 assert.dirQuotas(0, 20);
868 it('shows the right texts', () => {
869 assert.quotaUnsetModalTexts(
870 `Unset CephFS size quota for '/a/c/b'`,
871 `Unset size quota 512 B from '/a/c/b' in order to inherit size quota 1 KiB from '/a'.`,
872 `Unset CephFS size quota for '/a/c/b'`
877 describe('action behaviour', () => {
878 it('uses different Text if no quota is inherited', () => {
879 mockLib.selectNode('/a');
880 mockLib.unsetQuotaThroughModal('max_bytes');
881 assert.quotaUnsetModalTexts(
882 `Unset CephFS size quota for '/a'`,
883 `Unset size quota 1 KiB from '/a' in order to have no quota on the directory.`,
884 `Unset CephFS size quota for '/a'`
888 it('uses different Text if quota is already inherited', () => {
889 mockLib.unsetQuotaThroughModal('max_bytes');
890 assert.quotaUnsetModalTexts(
891 `Unset CephFS size quota for '/a/c/b'`,
892 `Unset size quota 2 KiB from '/a/c/b' which isn't used because of the inheritance ` +
893 `of size quota 1 KiB from '/a'.`,
894 `Unset CephFS size quota for '/a/c/b'`
901 describe('table actions', () => {
902 let actions: CdTableAction[];
904 const empty = (): CdTableSelection => new CdTableSelection();
906 const select = (value: number): CdTableSelection => {
907 const selection = new CdTableSelection();
908 selection.selected = [{ dirValue: value }];
913 actions = component.quota.tableActions;
916 it(`shows 'Set' for empty and not set quotas`, () => {
917 const isSetVisible = actions[0].visible;
918 expect(isSetVisible(empty())).toBe(true);
919 expect(isSetVisible(select(0))).toBe(true);
920 expect(isSetVisible(select(1))).toBe(false);
923 it(`shows 'Update' for set quotas only`, () => {
924 const isUpdateVisible = actions[1].visible;
925 expect(isUpdateVisible(empty())).toBeFalsy();
926 expect(isUpdateVisible(select(0))).toBe(false);
927 expect(isUpdateVisible(select(1))).toBe(true);
930 it(`only enables 'Unset' for set quotas only`, () => {
931 const isUnsetDisabled = actions[2].disable;
932 expect(isUnsetDisabled(empty())).toBe(true);
933 expect(isUnsetDisabled(select(0))).toBe(true);
934 expect(isUnsetDisabled(select(1))).toBe(false);
937 it('should test all quota table actions permission combinations', () => {
938 const permissionHelper: PermissionHelper = new PermissionHelper(component.permission);
939 const tableActions = permissionHelper.setPermissionsAndGetActions(
940 component.quota.tableActions
943 expect(tableActions).toEqual({
944 'create,update,delete': {
945 actions: ['Set', 'Update', 'Unset'],
946 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
949 actions: ['Set', 'Update', 'Unset'],
950 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
954 primary: { multiple: '', executing: '', single: '', no: '' }
958 primary: { multiple: '', executing: '', single: '', no: '' }
961 actions: ['Set', 'Update', 'Unset'],
962 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
965 actions: ['Set', 'Update', 'Unset'],
966 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
970 primary: { multiple: '', executing: '', single: '', no: '' }
974 primary: { multiple: '', executing: '', single: '', no: '' }
980 describe('reload all', () => {
981 const calledPaths = ['/', '/a', '/a/c', '/a/c/a', '/a/c/a/b'];
983 const dirsByPath = (): string[] => get.dirs().map((d) => d.path);
987 mockLib.selectNode('/a');
988 mockLib.selectNode('/a/c');
989 mockLib.selectNode('/a/c/a');
990 mockLib.selectNode('/a/c/a/b');
993 it('should reload all requested paths', () => {
994 assert.lsDirHasBeenCalledWith(1, calledPaths);
995 lsDirSpy.calls.reset();
996 assert.lsDirHasBeenCalledWith(1, []);
997 component.refreshAllDirectories();
998 assert.lsDirHasBeenCalledWith(1, calledPaths);
1001 it('should reload all requested paths if not selected anything', () => {
1002 lsDirSpy.calls.reset();
1003 mockLib.changeId(2);
1004 assert.lsDirHasBeenCalledWith(2, ['/']);
1005 lsDirSpy.calls.reset();
1006 component.refreshAllDirectories();
1007 assert.lsDirHasBeenCalledWith(2, ['/']);
1010 it('should add new directories', () => {
1011 // Create two new directories in preparation
1012 const dirsBeforeRefresh = dirsByPath();
1013 expect(dirsBeforeRefresh.includes('/a/c/has_dir_now')).toBe(false);
1014 mockLib.mkDir('/a/c', 'has_dir_now', 0, 0);
1015 mockLib.mkDir('/a/c/a/b', 'has_dir_now_too', 0, 0);
1016 // Now the new directories will be fetched
1017 component.refreshAllDirectories();
1018 const dirsAfterRefresh = dirsByPath();
1019 expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(2);
1020 expect(dirsAfterRefresh.includes('/a/c/has_dir_now')).toBe(true);
1021 expect(dirsAfterRefresh.includes('/a/c/a/b/has_dir_now_too')).toBe(true);
1024 it('should remove deleted directories', () => {
1025 // Create one new directory and refresh in order to have it added to the directories list
1026 mockLib.mkDir('/a/c', 'will_be_removed_shortly', 0, 0);
1027 component.refreshAllDirectories();
1028 const dirsBeforeRefresh = dirsByPath();
1029 expect(dirsBeforeRefresh.includes('/a/c/will_be_removed_shortly')).toBe(true);
1030 mockData.createdDirs = []; // Mocks the deletion of the directory
1031 // Now the deleted directory will be missing on refresh
1032 component.refreshAllDirectories();
1033 const dirsAfterRefresh = dirsByPath();
1034 expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(-1);
1035 expect(dirsAfterRefresh.includes('/a/c/will_be_removed_shortly')).toBe(false);
1038 describe('loading indicator', () => {
1040 noAsyncUpdate = true;
1043 it('should have set loading indicator to false after refreshing all dirs', fakeAsync(() => {
1044 component.refreshAllDirectories();
1045 expect(component.loadingIndicator).toBe(true);
1046 tick(3000); // To resolve all promises
1047 expect(component.loadingIndicator).toBe(false);
1050 it('should only update the tree once and not on every call', fakeAsync(() => {
1051 const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough();
1052 component.refreshAllDirectories();
1053 expect(spy).toHaveBeenCalledTimes(0);
1054 tick(3000); // To resolve all promises
1055 // Called during the interval and at the end of timeout
1056 expect(spy).toHaveBeenCalledTimes(2);
1059 it('should have set all loaded dirs as attribute names of "indicators"', () => {
1060 noAsyncUpdate = false;
1061 component.refreshAllDirectories();
1062 expect(Object.keys(component.loading).sort()).toEqual(calledPaths);
1065 it('should set an indicator to true during load', () => {
1066 lsDirSpy.and.callFake(() => new Observable((): null => null));
1067 component.refreshAllDirectories();
1068 expect(Object.values(component.loading).every((b) => b)).toBe(true);
1069 expect(component.loadingIndicator).toBe(true);