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 '@circlon/angular-tree-component';
8 import { NgbActiveModal, NgbModalModule, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
9 import { ToastrModule } from 'ngx-toastr';
10 import { Observable, of } from 'rxjs';
12 import { CephfsService } from '~/app/shared/api/cephfs.service';
13 import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component';
14 import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component';
15 import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component';
16 import { NotificationType } from '~/app/shared/enum/notification-type.enum';
17 import { CdValidators } from '~/app/shared/forms/cd-validators';
18 import { CdTableAction } from '~/app/shared/models/cd-table-action';
19 import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
24 } from '~/app/shared/models/cephfs-directory-models';
25 import { ModalService } from '~/app/shared/services/modal.service';
26 import { NotificationService } from '~/app/shared/services/notification.service';
27 import { SharedModule } from '~/app/shared/shared.module';
28 import { configureTestBed, modalServiceShow, PermissionHelper } from '~/testing/unit-test-helper';
29 import { CephfsDirectoriesComponent } from './cephfs-directories.component';
31 describe('CephfsDirectoriesComponent', () => {
32 let component: CephfsDirectoriesComponent;
33 let fixture: ComponentFixture<CephfsDirectoriesComponent>;
34 let cephfsService: CephfsService;
35 let noAsyncUpdate: boolean;
36 let lsDirSpy: jasmine.Spy;
37 let modalShowSpy: jasmine.Spy;
38 let notificationShowSpy: jasmine.Spy;
39 let minValidator: jasmine.Spy;
40 let maxValidator: jasmine.Spy;
41 let minBinaryValidator: jasmine.Spy;
42 let maxBinaryValidator: jasmine.Spy;
43 let modal: NgbModalRef;
45 // Get's private attributes or functions
47 nodeIds: (): { [path: string]: CephfsDir } => component['nodeIds'],
48 dirs: (): CephfsDir[] => component['dirs'],
49 requestedPaths: (): string[] => component['requestedPaths']
52 // Object contains mock data that will be reset before each test.
56 createdSnaps: CephfsSnapshot[] | any[];
57 deletedSnaps: CephfsSnapshot[] | any[];
58 updatedQuotas: { [path: string]: CephfsQuotas };
59 createdDirs: CephfsDir[];
62 // Object contains mock functions
64 quotas: (max_bytes: number, max_files: number): CephfsQuotas => ({ max_bytes, max_files }),
65 snapshots: (dirPath: string, howMany: number): CephfsSnapshot[] => {
66 const name = 'someSnapshot';
68 const oneDay = 3600 * 24 * 1000;
69 for (let i = 0; i < howMany; i++) {
70 const snapName = `${name}${i + 1}`;
71 const path = `${dirPath}/.snap/${snapName}`;
72 const created = new Date(+new Date() - oneDay * i).toString();
73 snapshots.push({ name: snapName, path, created });
77 dir: (parentPath: string, name: string, modifier: number): CephfsDir => {
78 const dirPath = `${parentPath === '/' ? '' : parentPath}/${name}`;
79 let snapshots = mockLib.snapshots(parentPath, modifier);
80 const extraSnapshots = mockData.createdSnaps.filter((s) => s.path === dirPath);
81 if (extraSnapshots.length > 0) {
82 snapshots = snapshots.concat(extraSnapshots);
84 const deletedSnapshots = mockData.deletedSnaps
85 .filter((s) => s.path === dirPath)
87 if (deletedSnapshots.length > 0) {
88 snapshots = snapshots.filter((s) => !deletedSnapshots.includes(s.name));
94 quotas: Object.assign(
95 mockLib.quotas(1024 * modifier, 10 * modifier),
96 mockData.updatedQuotas[dirPath] || {}
101 // Only used inside other mocks
102 lsSingleDir: (path = ''): CephfsDir[] => {
103 const customDirs = mockData.createdDirs.filter((d) => d.parent === path);
104 const isCustomDir = mockData.createdDirs.some((d) => d.path === path);
105 if (isCustomDir || path.includes('b')) {
106 // 'b' has no sub directories
109 return customDirs.concat([
110 // Directories are not sorted!
111 mockLib.dir(path, 'c', 3),
112 mockLib.dir(path, 'a', 1),
113 mockLib.dir(path, 'b', 2)
116 lsDir: (_id: number, path = ''): Observable<CephfsDir[]> => {
117 // will return 2 levels deep
118 let data = mockLib.lsSingleDir(path);
119 const paths = data.map((dir) => dir.path);
120 paths.forEach((pathL2) => {
121 data = data.concat(mockLib.lsSingleDir(pathL2));
123 if (path === '' || path === '/') {
124 // Adds root directory on ls of '/' to the directories list.
125 const root = mockLib.dir(path, '/', 1);
127 root.parent = undefined;
128 root.quotas = undefined;
129 data = [root].concat(data);
133 mkSnapshot: (_id: any, path: string, name: string): Observable<string> => {
134 mockData.createdSnaps.push({
137 created: new Date().toString()
141 rmSnapshot: (_id: any, path: string, name: string): Observable<string> => {
142 mockData.deletedSnaps.push({
145 created: new Date().toString()
149 updateQuota: (_id: any, path: string, updated: CephfsQuotas): Observable<string> => {
150 mockData.updatedQuotas[path] = Object.assign(mockData.updatedQuotas[path] || {}, updated);
151 return of('Response');
153 modalShow: (comp: Type<any>, init: any): any => {
154 modal = modalServiceShow(comp, init);
157 getNodeById: (path: string) => {
158 return mockLib.useNode(path);
160 updateNodes: (path: string) => {
161 const p: Promise<any[]> = component.treeOptions.getChildren({ id: path });
162 return noAsyncUpdate ? () => p : mockLib.asyncNodeUpdate(p);
164 asyncNodeUpdate: fakeAsync((p: Promise<any[]>) => {
166 mockData.nodes = mockData.nodes.concat(nodes);
170 changeId: (id: number) => {
171 // For some reason this spy has to be renewed after usage
172 spyOn(global, 'setTimeout').and.callFake((fn) => fn());
174 component.ngOnChanges();
175 mockData.nodes = component.nodes.concat(mockData.nodes);
177 selectNode: (path: string) => {
178 component.treeOptions.actionMapping.mouse.click(undefined, mockLib.useNode(path), undefined);
180 // Creates TreeNode with parents until root
181 useNode: (path: string): { id: string; parent: any; data: any; loadNodeChildren: Function } => {
182 const parentPath = path.split('/');
184 const parentIsRoot = parentPath.length === 1;
185 const parent = parentIsRoot ? { id: '/' } : mockLib.useNode(parentPath.join('/'));
190 loadNodeChildren: () => mockLib.updateNodes(path)
194 toggleActive: (_a: any, node: any, _b: any) => {
195 return mockLib.updateNodes(node.id);
198 mkDir: (path: string, name: string, maxFiles: number, maxBytes: number) => {
199 const dir = mockLib.dir(path, name, 3);
200 dir.quotas.max_bytes = maxBytes * 1024;
201 dir.quotas.max_files = maxFiles;
202 mockData.createdDirs.push(dir);
203 // Below is needed for quota tests only where 4 dirs are mocked
204 get.nodeIds()[dir.path] = dir;
205 mockData.nodes.push({ id: dir.path });
207 createSnapshotThroughModal: (name: string) => {
208 component.createSnapshot();
209 modal.componentInstance.onSubmitForm({ name });
211 deleteSnapshotsThroughModal: (snapshots: CephfsSnapshot[]) => {
212 component.snapshot.selection.selected = snapshots;
213 component.deleteSnapshotModal();
214 modal.componentInstance.callSubmitAction();
216 updateQuotaThroughModal: (attribute: string, value: number) => {
217 component.quota.selection.selected = component.settings.filter(
218 (q) => q.quotaKey === attribute
220 component.updateQuotaModal();
221 modal.componentInstance.onSubmitForm({ [attribute]: value });
223 unsetQuotaThroughModal: (attribute: string) => {
224 component.quota.selection.selected = component.settings.filter(
225 (q) => q.quotaKey === attribute
227 component.unsetQuotaModal();
228 modal.componentInstance.onSubmit();
230 setFourQuotaDirs: (quotas: number[][]) => {
231 expect(quotas.length).toBe(4); // Make sure this function is used correctly
233 quotas.forEach((quota, index) => {
235 mockLib.mkDir(path === '' ? '/' : path, index.toString(), quota[0], quota[1]);
247 parent: { value: '/', id: '/' }
251 mockLib.selectNode('/1/2/3/4');
255 // Expects that are used frequently
257 dirLength: (n: number) => expect(get.dirs().length).toBe(n),
258 nodeLength: (n: number) => expect(mockData.nodes.length).toBe(n),
259 lsDirCalledTimes: (n: number) => expect(lsDirSpy).toHaveBeenCalledTimes(n),
260 lsDirHasBeenCalledWith: (id: number, paths: string[]) => {
261 paths.forEach((path) => expect(lsDirSpy).toHaveBeenCalledWith(id, path));
262 assert.lsDirCalledTimes(paths.length);
264 requestedPaths: (expected: string[]) => expect(get.requestedPaths()).toEqual(expected),
265 snapshotsByName: (snaps: string[]) =>
266 expect(component.selectedDir.snapshots.map((s) => s.name)).toEqual(snaps),
267 dirQuotas: (bytes: number, files: number) => {
268 expect(component.selectedDir.quotas).toEqual({ max_bytes: bytes, max_files: files });
270 noQuota: (key: 'bytes' | 'files') => {
271 assert.quotaRow(key, '', 0, '');
273 quotaIsNotInherited: (key: 'bytes' | 'files', shownValue: any, nextMaximum: number) => {
274 const dir = component.selectedDir;
275 const path = dir.path;
276 assert.quotaRow(key, shownValue, nextMaximum, path);
278 quotaIsInherited: (key: 'bytes' | 'files', shownValue: any, path: string) => {
279 const isBytes = key === 'bytes';
280 const nextMaximum = get.nodeIds()[path].quotas[isBytes ? 'max_bytes' : 'max_files'];
281 assert.quotaRow(key, shownValue, nextMaximum, path);
284 key: 'bytes' | 'files',
285 shownValue: number | string,
286 nextTreeMaximum: number,
289 const isBytes = key === 'bytes';
290 expect(component.settings[isBytes ? 1 : 0]).toEqual({
292 name: `Max ${isBytes ? 'size' : key}`,
296 quotaKey: `max_${key}`,
297 dirValue: expect.any(Number),
299 value: nextTreeMaximum,
300 path: expect.any(String)
304 quotaUnsetModalTexts: (titleText: string, message: string, notificationMsg: string) => {
305 expect(modalShowSpy).toHaveBeenCalledWith(
306 ConfirmationModalComponent,
307 expect.objectContaining({
309 description: message,
313 expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg);
315 quotaUpdateModalTexts: (titleText: string, message: string, notificationMsg: string) => {
316 expect(modalShowSpy).toHaveBeenCalledWith(
318 expect.objectContaining({
321 submitButtonText: 'Save'
324 expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg);
326 quotaUpdateModalField: (
332 errors?: { [key: string]: string }
334 expect(modalShowSpy).toHaveBeenCalledWith(
336 expect.objectContaining({
344 validators: expect.anything(),
350 if (type === 'binary') {
351 expect(minBinaryValidator).toHaveBeenCalledWith(0);
352 expect(maxBinaryValidator).toHaveBeenCalledWith(max);
354 expect(minValidator).toHaveBeenCalledWith(0);
355 expect(maxValidator).toHaveBeenCalledWith(max);
363 HttpClientTestingModule,
367 ToastrModule.forRoot(),
370 declarations: [CephfsDirectoriesComponent],
371 providers: [NgbActiveModal]
373 [CriticalConfirmationModalComponent, FormModalComponent, ConfirmationModalComponent]
377 noAsyncUpdate = false;
387 cephfsService = TestBed.inject(CephfsService);
388 lsDirSpy = spyOn(cephfsService, 'lsDir').and.callFake(mockLib.lsDir);
389 spyOn(cephfsService, 'mkSnapshot').and.callFake(mockLib.mkSnapshot);
390 spyOn(cephfsService, 'rmSnapshot').and.callFake(mockLib.rmSnapshot);
391 spyOn(cephfsService, 'quota').and.callFake(mockLib.updateQuota);
393 modalShowSpy = spyOn(TestBed.inject(ModalService), 'show').and.callFake(mockLib.modalShow);
394 notificationShowSpy = spyOn(TestBed.inject(NotificationService), 'show').and.stub();
396 fixture = TestBed.createComponent(CephfsDirectoriesComponent);
397 component = fixture.componentInstance;
398 fixture.detectChanges();
400 spyOn(TREE_ACTIONS, 'TOGGLE_ACTIVE').and.callFake(mockLib.treeActions.toggleActive);
402 component.treeComponent = {
403 sizeChanged: () => null,
404 treeModel: { getNodeById: mockLib.getNodeById, update: () => null }
408 it('should create', () => {
409 expect(component).toBeTruthy();
412 describe('mock self test', () => {
413 it('tests snapshots mock', () => {
414 expect(mockLib.snapshots('/a', 1).map((s) => ({ name: s.name, path: s.path }))).toEqual([
416 name: 'someSnapshot1',
417 path: '/a/.snap/someSnapshot1'
420 expect(mockLib.snapshots('/a/b', 3).map((s) => ({ name: s.name, path: s.path }))).toEqual([
422 name: 'someSnapshot1',
423 path: '/a/b/.snap/someSnapshot1'
426 name: 'someSnapshot2',
427 path: '/a/b/.snap/someSnapshot2'
430 name: 'someSnapshot3',
431 path: '/a/b/.snap/someSnapshot3'
436 it('tests dir mock', () => {
437 const path = '/a/b/c';
438 mockData.createdSnaps = [
439 { path, name: 's1' },
442 mockData.deletedSnaps = [
443 { path, name: 'someSnapshot2' },
446 const dir = mockLib.dir('/a/b', 'c', 2);
447 expect(dir.path).toBe('/a/b/c');
448 expect(dir.parent).toBe('/a/b');
449 expect(dir.quotas).toEqual({ max_bytes: 2048, max_files: 20 });
450 expect(dir.snapshots.map((s) => s.name)).toEqual(['someSnapshot1', 's1']);
453 it('tests lsdir mock', () => {
454 let dirs: CephfsDir[] = [];
455 mockLib.lsDir(2, '/a').subscribe((x) => (dirs = x));
456 expect(dirs.map((d) => d.path)).toEqual([
469 describe('test quota update mock', () => {
473 const updateQuota = (quotas: CephfsQuotas) => mockLib.updateQuota(ID, PATH, quotas);
475 const expectMockUpdate = (max_bytes?: number, max_files?: number) =>
476 expect(mockData.updatedQuotas[PATH]).toEqual({
481 const expectLsUpdate = (max_bytes?: number, max_files?: number) => {
483 mockLib.lsDir(ID, '/').subscribe((dirs) => (dir = dirs.find((d) => d.path === PATH)));
484 expect(dir.quotas).toEqual({
490 it('tests to set quotas', () => {
491 expectLsUpdate(1024, 10);
493 updateQuota({ max_bytes: 512 });
494 expectMockUpdate(512);
495 expectLsUpdate(512, 10);
497 updateQuota({ max_files: 100 });
498 expectMockUpdate(512, 100);
499 expectLsUpdate(512, 100);
502 it('tests to unset quotas', () => {
503 updateQuota({ max_files: 0 });
504 expectMockUpdate(undefined, 0);
505 expectLsUpdate(1024, 0);
507 updateQuota({ max_bytes: 0 });
508 expectMockUpdate(0, 0);
509 expectLsUpdate(0, 0);
514 it('calls lsDir only if an id exits', () => {
515 assert.lsDirCalledTimes(0);
518 assert.lsDirCalledTimes(1);
519 expect(lsDirSpy).toHaveBeenCalledWith(1, '/');
522 assert.lsDirCalledTimes(2);
523 expect(lsDirSpy).toHaveBeenCalledWith(2, '/');
526 describe('listing sub directories', () => {
530 * Tree looks like this:
538 it('expands first level', () => {
539 // Tree will only show '*' if nor 'loadChildren' or 'children' are defined
541 mockData.nodes.map((node: any) => ({
542 [node.id]: node.hasChildren || node.isExpanded || Boolean(node.children)
544 ).toEqual([{ '/': true }, { '/a': true }, { '/b': false }, { '/c': true }]);
547 it('resets all dynamic content on id change', () => {
548 mockLib.selectNode('/a');
550 * Tree looks like this:
559 assert.requestedPaths(['/', '/a']);
560 assert.nodeLength(7);
561 assert.dirLength(16);
562 expect(component.selectedDir).toBeDefined();
564 mockLib.changeId(undefined);
566 assert.requestedPaths([]);
567 expect(component.selectedDir).not.toBeDefined();
570 it('should select a node and show the directory contents', () => {
571 mockLib.selectNode('/a');
572 const dir = get.dirs().find((d) => d.path === '/a');
573 expect(component.selectedDir).toEqual(dir);
574 assert.quotaIsNotInherited('files', 10, 0);
575 assert.quotaIsNotInherited('bytes', '1 KiB', 0);
578 it('should extend the list by subdirectories when expanding', () => {
579 mockLib.selectNode('/a');
580 mockLib.selectNode('/a/c');
582 * Tree looks like this:
594 assert.lsDirCalledTimes(3);
595 assert.requestedPaths(['/', '/a', '/a/c']);
596 assert.dirLength(22);
597 assert.nodeLength(10);
600 it('should update the tree after each selection', () => {
601 const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough();
602 expect(spy).toHaveBeenCalledTimes(0);
603 mockLib.selectNode('/a');
604 expect(spy).toHaveBeenCalledTimes(1);
605 mockLib.selectNode('/a/c');
606 expect(spy).toHaveBeenCalledTimes(2);
609 it('should select parent by path', () => {
610 mockLib.selectNode('/a');
611 mockLib.selectNode('/a/c');
612 mockLib.selectNode('/a/c/a');
613 component.selectOrigin('/a');
614 expect(component.selectedDir.path).toBe('/a');
617 it('should refresh directories with no sub directories as they could have some now', () => {
618 mockLib.selectNode('/b');
620 * Tree looks like this:
626 assert.lsDirCalledTimes(2);
627 assert.requestedPaths(['/', '/b']);
628 assert.nodeLength(4);
631 describe('used quotas', () => {
632 it('should use no quota if none is set', () => {
633 mockLib.setFourQuotaDirs([
639 assert.noQuota('files');
640 assert.noQuota('bytes');
641 assert.dirQuotas(0, 0);
644 it('should use quota from upper parents', () => {
645 mockLib.setFourQuotaDirs([
651 assert.quotaIsInherited('files', 100, '/1');
652 assert.quotaIsInherited('bytes', '8 KiB', '/1/2');
653 assert.dirQuotas(0, 0);
656 it('should use quota from the parent with the lowest value (deep inheritance)', () => {
657 mockLib.setFourQuotaDirs([
663 assert.quotaIsInherited('files', 100, '/1/2');
664 assert.quotaIsInherited('bytes', '1 KiB', '/1');
665 assert.dirQuotas(2048, 300);
668 it('should use current value', () => {
669 mockLib.setFourQuotaDirs([
675 assert.quotaIsNotInherited('files', 100, 200);
676 assert.quotaIsNotInherited('bytes', '1 KiB', 2048);
677 assert.dirQuotas(1024, 100);
682 describe('snapshots', () => {
685 mockLib.selectNode('/a');
688 it('should create a snapshot', () => {
689 mockLib.createSnapshotThroughModal('newSnap');
690 expect(cephfsService.mkSnapshot).toHaveBeenCalledWith(1, '/a', 'newSnap');
691 assert.snapshotsByName(['someSnapshot1', 'newSnap']);
694 it('should delete a snapshot', () => {
695 mockLib.createSnapshotThroughModal('deleteMe');
696 mockLib.deleteSnapshotsThroughModal([component.selectedDir.snapshots[1]]);
697 assert.snapshotsByName(['someSnapshot1']);
700 it('should delete all snapshots', () => {
701 mockLib.createSnapshotThroughModal('deleteAll');
702 mockLib.deleteSnapshotsThroughModal(component.selectedDir.snapshots);
703 assert.snapshotsByName([]);
707 it('should test all snapshot table actions combinations', () => {
708 const permissionHelper: PermissionHelper = new PermissionHelper(component.permission);
709 const tableActions = permissionHelper.setPermissionsAndGetActions(
710 component.snapshot.tableActions
713 expect(tableActions).toEqual({
714 'create,update,delete': {
715 actions: ['Create', 'Delete'],
716 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
720 primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
723 actions: ['Create', 'Delete'],
724 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' }
728 primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
732 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
736 primary: { multiple: '', executing: '', single: '', no: '' }
740 primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
744 primary: { multiple: '', executing: '', single: '', no: '' }
749 describe('quotas', () => {
752 minValidator = spyOn(Validators, 'min').and.callThrough();
753 maxValidator = spyOn(Validators, 'max').and.callThrough();
754 minBinaryValidator = spyOn(CdValidators, 'binaryMin').and.callThrough();
755 maxBinaryValidator = spyOn(CdValidators, 'binaryMax').and.callThrough();
758 mockLib.selectNode('/a');
759 mockLib.selectNode('/a/c');
760 mockLib.selectNode('/a/c/b');
761 // Quotas after selection
762 assert.quotaIsInherited('files', 10, '/a');
763 assert.quotaIsInherited('bytes', '1 KiB', '/a');
764 assert.dirQuotas(2048, 20);
767 describe('update modal', () => {
768 describe('max_files', () => {
770 mockLib.updateQuotaThroughModal('max_files', 5);
773 it('should update max_files correctly', () => {
774 expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 5 });
775 assert.quotaIsNotInherited('files', 5, 10);
778 it('uses the correct form field', () => {
779 assert.quotaUpdateModalField('number', 'Max files', 'max_files', 20, 10, {
780 min: 'Value has to be at least 0 or more',
781 max: 'Value has to be at most 10 or less'
785 it('shows the right texts', () => {
786 assert.quotaUpdateModalTexts(
787 `Update CephFS files quota for '/a/c/b'`,
788 `The inherited files quota 10 from '/a' is the maximum value to be used.`,
789 `Updated CephFS files quota for '/a/c/b'`
794 describe('max_bytes', () => {
796 mockLib.updateQuotaThroughModal('max_bytes', 512);
799 it('should update max_files correctly', () => {
800 expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 512 });
801 assert.quotaIsNotInherited('bytes', '512 B', 1024);
804 it('uses the correct form field', () => {
805 mockLib.updateQuotaThroughModal('max_bytes', 512);
806 assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 2048, 1024);
809 it('shows the right texts', () => {
810 assert.quotaUpdateModalTexts(
811 `Update CephFS size quota for '/a/c/b'`,
812 `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`,
813 `Updated CephFS size quota for '/a/c/b'`
818 describe('action behaviour', () => {
819 it('opens with next maximum as maximum if directory holds the current maximum', () => {
820 mockLib.updateQuotaThroughModal('max_bytes', 512);
821 mockLib.updateQuotaThroughModal('max_bytes', 888);
822 assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 512, 1024);
825 it(`uses 'Set' action instead of 'Update' if the quota is not set (0)`, () => {
826 mockLib.updateQuotaThroughModal('max_bytes', 0);
827 mockLib.updateQuotaThroughModal('max_bytes', 200);
828 assert.quotaUpdateModalTexts(
829 `Set CephFS size quota for '/a/c/b'`,
830 `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`,
831 `Set CephFS size quota for '/a/c/b'`
837 describe('unset modal', () => {
838 describe('max_files', () => {
840 mockLib.updateQuotaThroughModal('max_files', 5); // Sets usable quota
841 mockLib.unsetQuotaThroughModal('max_files');
844 it('should unset max_files correctly', () => {
845 expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 0 });
846 assert.dirQuotas(2048, 0);
849 it('shows the right texts', () => {
850 assert.quotaUnsetModalTexts(
851 `Unset CephFS files quota for '/a/c/b'`,
852 `Unset files quota 5 from '/a/c/b' in order to inherit files quota 10 from '/a'.`,
853 `Unset CephFS files quota for '/a/c/b'`
858 describe('max_bytes', () => {
860 mockLib.updateQuotaThroughModal('max_bytes', 512); // Sets usable quota
861 mockLib.unsetQuotaThroughModal('max_bytes');
864 it('should unset max_files correctly', () => {
865 expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 0 });
866 assert.dirQuotas(0, 20);
869 it('shows the right texts', () => {
870 assert.quotaUnsetModalTexts(
871 `Unset CephFS size quota for '/a/c/b'`,
872 `Unset size quota 512 B from '/a/c/b' in order to inherit size quota 1 KiB from '/a'.`,
873 `Unset CephFS size quota for '/a/c/b'`
878 describe('action behaviour', () => {
879 it('uses different Text if no quota is inherited', () => {
880 mockLib.selectNode('/a');
881 mockLib.unsetQuotaThroughModal('max_bytes');
882 assert.quotaUnsetModalTexts(
883 `Unset CephFS size quota for '/a'`,
884 `Unset size quota 1 KiB from '/a' in order to have no quota on the directory.`,
885 `Unset CephFS size quota for '/a'`
889 it('uses different Text if quota is already inherited', () => {
890 mockLib.unsetQuotaThroughModal('max_bytes');
891 assert.quotaUnsetModalTexts(
892 `Unset CephFS size quota for '/a/c/b'`,
893 `Unset size quota 2 KiB from '/a/c/b' which isn't used because of the inheritance ` +
894 `of size quota 1 KiB from '/a'.`,
895 `Unset CephFS size quota for '/a/c/b'`
902 describe('table actions', () => {
903 let actions: CdTableAction[];
905 const empty = (): CdTableSelection => new CdTableSelection();
907 const select = (value: number): CdTableSelection => {
908 const selection = new CdTableSelection();
909 selection.selected = [{ dirValue: value }];
914 actions = component.quota.tableActions;
917 it(`shows 'Set' for empty and not set quotas`, () => {
918 const isSetVisible = actions[0].visible;
919 expect(isSetVisible(empty())).toBe(true);
920 expect(isSetVisible(select(0))).toBe(true);
921 expect(isSetVisible(select(1))).toBe(false);
924 it(`shows 'Update' for set quotas only`, () => {
925 const isUpdateVisible = actions[1].visible;
926 expect(isUpdateVisible(empty())).toBeFalsy();
927 expect(isUpdateVisible(select(0))).toBe(false);
928 expect(isUpdateVisible(select(1))).toBe(true);
931 it(`only enables 'Unset' for set quotas only`, () => {
932 const isUnsetDisabled = actions[2].disable;
933 expect(isUnsetDisabled(empty())).toBe(true);
934 expect(isUnsetDisabled(select(0))).toBe(true);
935 expect(isUnsetDisabled(select(1))).toBe(false);
938 it('should test all quota table actions permission combinations', () => {
939 const permissionHelper: PermissionHelper = new PermissionHelper(component.permission, {
940 single: { dirValue: 0 },
941 multiple: [{ dirValue: 0 }, {}]
943 const tableActions = permissionHelper.setPermissionsAndGetActions(
944 component.quota.tableActions
947 expect(tableActions).toEqual({
948 'create,update,delete': {
949 actions: ['Set', 'Update', 'Unset'],
950 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
953 actions: ['Set', 'Update', 'Unset'],
954 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
958 primary: { multiple: '', executing: '', single: '', no: '' }
962 primary: { multiple: '', executing: '', single: '', no: '' }
965 actions: ['Set', 'Update', 'Unset'],
966 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
969 actions: ['Set', 'Update', 'Unset'],
970 primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' }
974 primary: { multiple: '', executing: '', single: '', no: '' }
978 primary: { multiple: '', executing: '', single: '', no: '' }
984 describe('reload all', () => {
985 const calledPaths = ['/', '/a', '/a/c', '/a/c/a', '/a/c/a/b'];
987 const dirsByPath = (): string[] => get.dirs().map((d) => d.path);
991 mockLib.selectNode('/a');
992 mockLib.selectNode('/a/c');
993 mockLib.selectNode('/a/c/a');
994 mockLib.selectNode('/a/c/a/b');
997 it('should reload all requested paths', () => {
998 assert.lsDirHasBeenCalledWith(1, calledPaths);
999 lsDirSpy.calls.reset();
1000 assert.lsDirHasBeenCalledWith(1, []);
1001 component.refreshAllDirectories();
1002 assert.lsDirHasBeenCalledWith(1, calledPaths);
1005 it('should reload all requested paths if not selected anything', () => {
1006 lsDirSpy.calls.reset();
1007 mockLib.changeId(2);
1008 assert.lsDirHasBeenCalledWith(2, ['/']);
1009 lsDirSpy.calls.reset();
1010 component.refreshAllDirectories();
1011 assert.lsDirHasBeenCalledWith(2, ['/']);
1014 it('should add new directories', () => {
1015 // Create two new directories in preparation
1016 const dirsBeforeRefresh = dirsByPath();
1017 expect(dirsBeforeRefresh.includes('/a/c/has_dir_now')).toBe(false);
1018 mockLib.mkDir('/a/c', 'has_dir_now', 0, 0);
1019 mockLib.mkDir('/a/c/a/b', 'has_dir_now_too', 0, 0);
1020 // Now the new directories will be fetched
1021 component.refreshAllDirectories();
1022 const dirsAfterRefresh = dirsByPath();
1023 expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(2);
1024 expect(dirsAfterRefresh.includes('/a/c/has_dir_now')).toBe(true);
1025 expect(dirsAfterRefresh.includes('/a/c/a/b/has_dir_now_too')).toBe(true);
1028 it('should remove deleted directories', () => {
1029 // Create one new directory and refresh in order to have it added to the directories list
1030 mockLib.mkDir('/a/c', 'will_be_removed_shortly', 0, 0);
1031 component.refreshAllDirectories();
1032 const dirsBeforeRefresh = dirsByPath();
1033 expect(dirsBeforeRefresh.includes('/a/c/will_be_removed_shortly')).toBe(true);
1034 mockData.createdDirs = []; // Mocks the deletion of the directory
1035 // Now the deleted directory will be missing on refresh
1036 component.refreshAllDirectories();
1037 const dirsAfterRefresh = dirsByPath();
1038 expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(-1);
1039 expect(dirsAfterRefresh.includes('/a/c/will_be_removed_shortly')).toBe(false);
1042 describe('loading indicator', () => {
1044 noAsyncUpdate = true;
1047 it('should have set loading indicator to false after refreshing all dirs', fakeAsync(() => {
1048 component.refreshAllDirectories();
1049 expect(component.loadingIndicator).toBe(true);
1050 tick(3000); // To resolve all promises
1051 expect(component.loadingIndicator).toBe(false);
1054 it('should only update the tree once and not on every call', fakeAsync(() => {
1055 const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough();
1056 component.refreshAllDirectories();
1057 expect(spy).toHaveBeenCalledTimes(0);
1058 tick(3000); // To resolve all promises
1059 // Called during the interval and at the end of timeout
1060 expect(spy).toHaveBeenCalledTimes(2);
1063 it('should have set all loaded dirs as attribute names of "indicators"', () => {
1064 noAsyncUpdate = false;
1065 component.refreshAllDirectories();
1066 expect(Object.keys(component.loading).sort()).toEqual(calledPaths);
1069 it('should set an indicator to true during load', () => {
1070 lsDirSpy.and.callFake(() => new Observable((): null => null));
1071 component.refreshAllDirectories();
1072 expect(Object.values(component.loading).every((b) => b)).toBe(true);
1073 expect(component.loadingIndicator).toBe(true);