Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/upgrade.interface.ts
export interface UpgradeInfoInterface { image: string; registry: string; versions: string[]; }
101
16
39
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/wizard-steps.ts
export interface WizardStepModel { stepIndex: number; isComplete: boolean; }
81
15.4
34
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/array.pipe.spec.ts
import { ArrayPipe } from './array.pipe'; describe('ArrayPipe', () => { const pipe = new ArrayPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms string to array', () => { expect(pipe.transform('foo')).toStrictEqual(['foo']); }); it('transforms array to array', () => { expect(pipe.transform(['foo'], true)).toStrictEqual([['foo']]); }); it('do not transforms array to array', () => { expect(pipe.transform(['foo'])).toStrictEqual(['foo']); }); });
523
22.818182
67
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/array.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; /** * Convert the given value to an array. */ @Pipe({ name: 'array' }) export class ArrayPipe implements PipeTransform { /** * Convert the given value into an array. If the value is already an * array, then nothing happens, except the `force` flag is set. * @param value The value to process. * @param force Convert the specified value to an array, either it is * already an array. */ transform(value: any, force = false): any[] { let result = value; if (!_.isArray(value) || (_.isArray(value) && force)) { result = [value]; } return result; } }
688
24.518519
71
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/boolean-text.pipe.spec.ts
import { BooleanTextPipe } from './boolean-text.pipe'; describe('BooleanTextPipe', () => { let pipe: BooleanTextPipe; beforeEach(() => { pipe = new BooleanTextPipe(); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms true', () => { expect(pipe.transform(true)).toEqual('Yes'); }); it('transforms true, alternative text', () => { expect(pipe.transform(true, 'foo')).toEqual('foo'); }); it('transforms 1', () => { expect(pipe.transform(1)).toEqual('Yes'); }); it('transforms false', () => { expect(pipe.transform(false)).toEqual('No'); }); it('transforms false, alternative text', () => { expect(pipe.transform(false, 'foo', 'bar')).toEqual('bar'); }); it('transforms 0', () => { expect(pipe.transform(0)).toEqual('No'); }); });
835
21
63
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/boolean-text.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'booleanText' }) export class BooleanTextPipe implements PipeTransform { transform( value: any, truthyText: string = $localize`Yes`, falsyText: string = $localize`No` ): string { return Boolean(value) ? truthyText : falsyText; } }
323
20.6
55
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/boolean.pipe.spec.ts
import { BooleanPipe } from './boolean.pipe'; describe('BooleanPipe', () => { const pipe = new BooleanPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms to false [1/4]', () => { expect(pipe.transform('n')).toBe(false); }); it('transforms to false [2/4]', () => { expect(pipe.transform(false)).toBe(false); }); it('transforms to false [3/4]', () => { expect(pipe.transform('bar')).toBe(false); }); it('transforms to false [4/4]', () => { expect(pipe.transform(2)).toBe(false); }); it('transforms to true [1/8]', () => { expect(pipe.transform(true)).toBe(true); }); it('transforms to true [2/8]', () => { expect(pipe.transform(1)).toBe(true); }); it('transforms to true [3/8]', () => { expect(pipe.transform('y')).toBe(true); }); it('transforms to true [4/8]', () => { expect(pipe.transform('yes')).toBe(true); }); it('transforms to true [5/8]', () => { expect(pipe.transform('t')).toBe(true); }); it('transforms to true [6/8]', () => { expect(pipe.transform('true')).toBe(true); }); it('transforms to true [7/8]', () => { expect(pipe.transform('on')).toBe(true); }); it('transforms to true [8/8]', () => { expect(pipe.transform('1')).toBe(true); }); });
1,309
21.586207
46
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/boolean.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; /** * Convert the given value to a boolean value. */ @Pipe({ name: 'boolean' }) export class BooleanPipe implements PipeTransform { transform(value: any): boolean { let result = false; switch (value) { case true: case 1: case 'y': case 'yes': case 't': case 'true': case 'on': case '1': result = true; break; } return result; } }
472
16.518519
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/cd-date.pipe.spec.ts
import { DatePipe } from '@angular/common'; import moment from 'moment'; import { CdDatePipe } from './cd-date.pipe'; describe('CdDatePipe', () => { const datePipe = new DatePipe('en-US'); let pipe = new CdDatePipe(datePipe); it('create an instance', () => { pipe = new CdDatePipe(datePipe); expect(pipe).toBeTruthy(); }); it('transforms without value', () => { expect(pipe.transform('')).toBe(''); }); it('transforms with some date', () => { const result = moment(1527085564486).format('M/D/YY LTS'); expect(pipe.transform(1527085564486)).toBe(result); }); });
604
23.2
62
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/cd-date.pipe.ts
import { DatePipe } from '@angular/common'; import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'cdDate' }) export class CdDatePipe implements PipeTransform { constructor(private datePipe: DatePipe) {} transform(value: any): any { if (value === null || value === '') { return ''; } return ( this.datePipe.transform(value, 'shortDate') + ' ' + this.datePipe.transform(value, 'mediumTime') ); } }
460
20.952381
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/ceph-release-name.pipe.spec.ts
import { CephReleaseNamePipe } from './ceph-release-name.pipe'; describe('CephReleaseNamePipe', () => { const pipe = new CephReleaseNamePipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('recognizes a stable release', () => { const value = 'ceph version 13.2.1 \ (5533ecdc0fda920179d7ad84e0aa65a127b20d77) mimic (stable)'; expect(pipe.transform(value)).toBe('mimic'); }); it('recognizes a development release as the main branch', () => { const value = 'ceph version 13.1.0-534-g23d3751b89 \ (23d3751b897b31d2bda57aeaf01acb5ff3c4a9cd) nautilus (dev)'; expect(pipe.transform(value)).toBe('main'); }); it('transforms with wrong version format', () => { const value = 'foo'; expect(pipe.transform(value)).toBe('foo'); }); });
823
27.413793
67
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/ceph-release-name.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'cephReleaseName' }) export class CephReleaseNamePipe implements PipeTransform { transform(value: any): any { // Expect "ceph version 13.1.0-419-g251e2515b5 // (251e2515b563856349498c6caf34e7a282f62937) nautilus (dev)" const result = /ceph version\s+[^ ]+\s+\(.+\)\s+(.+)\s+\((.+)\)/.exec(value); if (result) { if (result[2] === 'dev') { // Assume this is actually main return 'main'; } else { // Return the "nautilus" part return result[1]; } } else { // Unexpected format, pass it through return value; } } }
679
26.2
81
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/ceph-short-version.pipe.spec.ts
import { CephShortVersionPipe } from './ceph-short-version.pipe'; describe('CephShortVersionPipe', () => { const pipe = new CephShortVersionPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms with correct version format', () => { const value = 'ceph version 13.1.0-534-g23d3751b89 \ (23d3751b897b31d2bda57aeaf01acb5ff3c4a9cd) nautilus (dev)'; expect(pipe.transform(value)).toBe('13.1.0-534-g23d3751b89'); }); it('transforms with wrong version format', () => { const value = 'foo'; expect(pipe.transform(value)).toBe('foo'); }); });
618
27.136364
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/ceph-short-version.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'cephShortVersion' }) export class CephShortVersionPipe implements PipeTransform { transform(value: any): any { // Expect "ceph version 1.2.3-g9asdasd (as98d7a0s8d7)" const result = /ceph version\s+([^ ]+)\s+\(.+\)/.exec(value); if (result) { // Return the "1.2.3-g9asdasd" part return result[1]; } else { // Unexpected format, pass it through return value; } } }
482
24.421053
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/dimless-binary-per-second.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { FormatterService } from '../services/formatter.service'; @Pipe({ name: 'dimlessBinaryPerSecond' }) export class DimlessBinaryPerSecondPipe implements PipeTransform { constructor(private formatter: FormatterService) {} transform(value: any): any { return this.formatter.format_number(value, 1024, [ 'B/s', 'KiB/s', 'MiB/s', 'GiB/s', 'TiB/s', 'PiB/s', 'EiB/s', 'ZiB/s', 'YiB/s' ]); } }
519
19.8
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/dimless-binary.pipe.spec.ts
import { FormatterService } from '../services/formatter.service'; import { DimlessBinaryPipe } from './dimless-binary.pipe'; describe('DimlessBinaryPipe', () => { const formatterService = new FormatterService(); const pipe = new DimlessBinaryPipe(formatterService); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms 1024^0', () => { const value = Math.pow(1024, 0); expect(pipe.transform(value)).toBe('1 B'); }); it('transforms 1024^1', () => { const value = Math.pow(1024, 1); expect(pipe.transform(value)).toBe('1 KiB'); }); it('transforms 1024^2', () => { const value = Math.pow(1024, 2); expect(pipe.transform(value)).toBe('1 MiB'); }); it('transforms 1024^3', () => { const value = Math.pow(1024, 3); expect(pipe.transform(value)).toBe('1 GiB'); }); it('transforms 1024^4', () => { const value = Math.pow(1024, 4); expect(pipe.transform(value)).toBe('1 TiB'); }); it('transforms 1024^5', () => { const value = Math.pow(1024, 5); expect(pipe.transform(value)).toBe('1 PiB'); }); it('transforms 1024^6', () => { const value = Math.pow(1024, 6); expect(pipe.transform(value)).toBe('1 EiB'); }); it('transforms 1024^7', () => { const value = Math.pow(1024, 7); expect(pipe.transform(value)).toBe('1 ZiB'); }); it('transforms 1024^8', () => { const value = Math.pow(1024, 8); expect(pipe.transform(value)).toBe('1 YiB'); }); });
1,489
25.140351
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/dimless-binary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { FormatterService } from '../services/formatter.service'; @Pipe({ name: 'dimlessBinary' }) export class DimlessBinaryPipe implements PipeTransform { constructor(private formatter: FormatterService) {} transform(value: any): any { return this.formatter.format_number(value, 1024, [ 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB' ]); } }
483
18.36
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/dimless.pipe.spec.ts
import { FormatterService } from '../services/formatter.service'; import { DimlessPipe } from './dimless.pipe'; describe('DimlessPipe', () => { const formatterService = new FormatterService(); const pipe = new DimlessPipe(formatterService); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms 1000^0', () => { const value = Math.pow(1000, 0); expect(pipe.transform(value)).toBe('1'); }); it('transforms 1000^1', () => { const value = Math.pow(1000, 1); expect(pipe.transform(value)).toBe('1 k'); }); it('transforms 1000^2', () => { const value = Math.pow(1000, 2); expect(pipe.transform(value)).toBe('1 M'); }); it('transforms 1000^3', () => { const value = Math.pow(1000, 3); expect(pipe.transform(value)).toBe('1 G'); }); it('transforms 1000^4', () => { const value = Math.pow(1000, 4); expect(pipe.transform(value)).toBe('1 T'); }); it('transforms 1000^5', () => { const value = Math.pow(1000, 5); expect(pipe.transform(value)).toBe('1 P'); }); it('transforms 1000^6', () => { const value = Math.pow(1000, 6); expect(pipe.transform(value)).toBe('1 E'); }); it('transforms 1000^7', () => { const value = Math.pow(1000, 7); expect(pipe.transform(value)).toBe('1 Z'); }); it('transforms 1000^8', () => { const value = Math.pow(1000, 8); expect(pipe.transform(value)).toBe('1 Y'); }); });
1,446
24.385965
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/dimless.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { FormatterService } from '../services/formatter.service'; @Pipe({ name: 'dimless' }) export class DimlessPipe implements PipeTransform { constructor(private formatter: FormatterService) {} transform(value: any): any { return this.formatter.format_number(value, 1000, ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']); } }
394
25.333333
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/duration.pipe.spec.ts
import { DurationPipe } from './duration.pipe'; describe('DurationPipe', () => { const pipe = new DurationPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms seconds into a human readable duration', () => { expect(pipe.transform(0)).toBe(''); expect(pipe.transform(6)).toBe('6 seconds'); expect(pipe.transform(60)).toBe('1 minute'); expect(pipe.transform(600)).toBe('10 minutes'); expect(pipe.transform(6000)).toBe('1 hour 40 minutes'); }); });
517
27.777778
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/duration.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'duration', pure: false }) export class DurationPipe implements PipeTransform { /** * Translates seconds into human readable format of seconds, minutes, hours, days, and years * source: https://stackoverflow.com/a/34270811 * * @param {number} seconds The number of seconds to be processed * @return {string} The phrase describing the the amount of time */ transform(seconds: number): string { if (seconds === null || seconds <= 0) { return ''; } const levels = [ [`${Math.floor(seconds / 31536000)}`, 'years'], [`${Math.floor((seconds % 31536000) / 86400)}`, 'days'], [`${Math.floor((seconds % 86400) / 3600)}`, 'hours'], [`${Math.floor((seconds % 3600) / 60)}`, 'minutes'], [`${Math.floor(seconds % 60)}`, 'seconds'] ]; let returntext = ''; for (let i = 0, max = levels.length; i < max; i++) { if (levels[i][0] === '0') { continue; } returntext += ' ' + levels[i][0] + ' ' + (levels[i][0] === '1' ? levels[i][1].substr(0, levels[i][1].length - 1) : levels[i][1]); } return returntext.trim() || '1 second'; } }
1,243
29.341463
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/empty.pipe.spec.ts
import { EmptyPipe } from './empty.pipe'; describe('EmptyPipe', () => { const pipe = new EmptyPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms with empty value', () => { expect(pipe.transform(undefined)).toBe('-'); }); it('transforms with some value', () => { const value = 'foo'; expect(pipe.transform(value)).toBe('foo'); }); });
404
20.315789
48
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/empty.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'empty' }) export class EmptyPipe implements PipeTransform { transform(value: any): any { if (_.isUndefined(value) || _.isNull(value)) { return '-'; } else if (_.isNaN(value)) { return 'N/A'; } return value; } }
339
17.888889
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/encode-uri.pipe.spec.ts
import { EncodeUriPipe } from './encode-uri.pipe'; describe('EncodeUriPipe', () => { it('create an instance', () => { const pipe = new EncodeUriPipe(); expect(pipe).toBeTruthy(); }); it('should transforms the value', () => { const pipe = new EncodeUriPipe(); expect(pipe.transform('rbd/name')).toBe('rbd%2Fname'); }); });
348
23.928571
58
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/encode-uri.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'encodeUri' }) export class EncodeUriPipe implements PipeTransform { transform(value: any): any { return encodeURIComponent(value); } }
214
18.545455
53
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/filter.pipe.spec.ts
import { FilterPipe } from './filter.pipe'; describe('FilterPipe', () => { const pipe = new FilterPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('filter words with "foo"', () => { const value = ['foo', 'bar', 'foobar']; const filters = [ { value: 'foo', applyFilter: (row: any[], val: any) => { return row.indexOf(val) !== -1; } } ]; expect(pipe.transform(value, filters)).toEqual(['foo', 'foobar']); }); it('filter words with "foo" and "bar"', () => { const value = ['foo', 'bar', 'foobar']; const filters = [ { value: 'foo', applyFilter: (row: any[], val: any) => { return row.indexOf(val) !== -1; } }, { value: 'bar', applyFilter: (row: any[], val: any) => { return row.indexOf(val) !== -1; } } ]; expect(pipe.transform(value, filters)).toEqual(['foobar']); }); it('filter with no value', () => { const value = ['foo', 'bar', 'foobar']; const filters = [ { value: '', applyFilter: () => { return false; } } ]; expect(pipe.transform(value, filters)).toEqual(['foo', 'bar', 'foobar']); }); });
1,282
22.327273
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implements PipeTransform { transform(value: any, args?: any): any { return value.filter((row: any) => { let result = true; args.forEach((filter: any): boolean | void => { if (!filter.value) { return undefined; } result = result && filter.applyFilter(row, filter.value); if (!result) { return result; } }); return result; }); } }
534
19.576923
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/health-color.pipe.spec.ts
import { CssHelper } from '~/app/shared/classes/css-helper'; import { HealthColorPipe } from '~/app/shared/pipes/health-color.pipe'; class CssHelperStub extends CssHelper { propertyValue(propertyName: string) { if (propertyName === 'health-color-healthy') { return 'fakeGreen'; } if (propertyName === 'health-color-warning') { return 'fakeOrange'; } if (propertyName === 'health-color-error') { return 'fakeRed'; } return ''; } } describe('HealthColorPipe', () => { const pipe = new HealthColorPipe(new CssHelperStub()); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "HEALTH_OK"', () => { expect(pipe.transform('HEALTH_OK')).toEqual({ color: 'fakeGreen' }); }); it('transforms "HEALTH_WARN"', () => { expect(pipe.transform('HEALTH_WARN')).toEqual({ color: 'fakeOrange' }); }); it('transforms "HEALTH_ERR"', () => { expect(pipe.transform('HEALTH_ERR')).toEqual({ color: 'fakeRed' }); }); it('transforms others', () => { expect(pipe.transform('abc')).toBe(null); }); });
1,131
22.583333
71
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/health-color.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { HealthColor } from '~/app/shared/enum/health-color.enum'; @Pipe({ name: 'healthColor' }) export class HealthColorPipe implements PipeTransform { constructor(private cssHelper: CssHelper) {} transform(value: any): any { return Object.keys(HealthColor).includes(value as HealthColor) ? { color: this.cssHelper.propertyValue(HealthColor[value]) } : null; } }
506
27.166667
67
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/health-icon.pipe.spec.ts
import { HealthIconPipe } from './health-icon.pipe'; describe('HealthIconPipe', () => { const pipe = new HealthIconPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "HEALTH_OK"', () => { expect(pipe.transform('HEALTH_OK')).toEqual('fa fa-check-circle'); }); it('transforms "HEALTH_WARN"', () => { expect(pipe.transform('HEALTH_WARN')).toEqual('fa fa-exclamation-triangle'); }); it('transforms "HEALTH_ERR"', () => { expect(pipe.transform('HEALTH_ERR')).toEqual('fa fa-exclamation-circle'); }); });
573
26.333333
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/health-icon.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { HealthIcon } from '../enum/health-icon.enum'; @Pipe({ name: 'healthIcon' }) export class HealthIconPipe implements PipeTransform { transform(value: string): string { return Object.keys(HealthIcon).includes(value as HealthIcon) ? HealthIcon[value] : ''; } }
331
24.538462
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/health-label.pipe.spec.ts
import { HealthLabelPipe } from './health-label.pipe'; describe('HealthLabelPipe', () => { const pipe = new HealthLabelPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "HEALTH_OK"', () => { expect(pipe.transform('HEALTH_OK')).toEqual('ok'); }); it('transforms "HEALTH_WARN"', () => { expect(pipe.transform('HEALTH_WARN')).toEqual('warning'); }); it('transforms "HEALTH_ERR"', () => { expect(pipe.transform('HEALTH_ERR')).toEqual('error'); }); it('transforms others', () => { expect(pipe.transform('abc')).toBe(null); }); });
610
23.44
61
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/health-label.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { HealthLabel } from '~/app/shared/enum/health-label.enum'; @Pipe({ name: 'healthLabel' }) export class HealthLabelPipe implements PipeTransform { transform(value: any): any { return Object.keys(HealthLabel).includes(value as HealthLabel) ? HealthLabel[value] : null; } }
344
25.538462
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/iops.pipe.spec.ts
import { IopsPipe } from './iops.pipe'; describe('IopsPipe', () => { it('create an instance', () => { const pipe = new IopsPipe(); expect(pipe).toBeTruthy(); }); });
179
19
39
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/iops.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'iops' }) export class IopsPipe implements PipeTransform { transform(value: any): any { return `${value} IOPS`; } }
194
16.727273
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/iscsi-backstore.pipe.spec.ts
import { IscsiBackstorePipe } from './iscsi-backstore.pipe'; describe('IscsiBackstorePipe', () => { const pipe = new IscsiBackstorePipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "user:rbd"', () => { expect(pipe.transform('user:rbd')).toBe('user:rbd (tcmu-runner)'); }); it('transforms "other"', () => { expect(pipe.transform('other')).toBe('other'); }); });
428
22.833333
70
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/iscsi-backstore.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'iscsiBackstore' }) export class IscsiBackstorePipe implements PipeTransform { transform(value: any): any { switch (value) { case 'user:rbd': return 'user:rbd (tcmu-runner)'; default: return value; } } }
314
18.6875
58
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/join.pipe.spec.ts
import { JoinPipe } from './join.pipe'; describe('ListPipe', () => { const pipe = new JoinPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "[1,2,3]"', () => { expect(pipe.transform([1, 2, 3])).toBe('1, 2, 3'); }); });
277
18.857143
54
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/join.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'join' }) export class JoinPipe implements PipeTransform { transform(value: Array<any>): string { return value.join(', '); } }
205
17.727273
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/log-priority.pipe.spec.ts
import { LogPriorityPipe } from './log-priority.pipe'; describe('LogPriorityPipe', () => { const pipe = new LogPriorityPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "INF"', () => { const value = '[INF]'; const result = 'info'; expect(pipe.transform(value)).toEqual(result); }); it('transforms "WRN"', () => { const value = '[WRN]'; const result = 'warn'; expect(pipe.transform(value)).toEqual(result); }); it('transforms "ERR"', () => { const value = '[ERR]'; const result = 'err'; expect(pipe.transform(value)).toEqual(result); }); it('transforms others', () => { const value = '[foo]'; expect(pipe.transform(value)).toBe(''); }); });
753
21.848485
54
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/log-priority.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'logPriority' }) export class LogPriorityPipe implements PipeTransform { transform(value: any): any { if (value === '[DBG]') { return 'debug'; } else if (value === '[INF]') { return 'info'; } else if (value === '[WRN]') { return 'warn'; } else if (value === '[ERR]') { return 'err'; } else { return ''; // Inherit } } }
448
20.380952
55
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/map.pipe.spec.ts
import { MapPipe } from './map.pipe'; describe('MapPipe', () => { const pipe = new MapPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('map value [1]', () => { expect(pipe.transform('foo')).toBe('foo'); }); it('map value [2]', () => { expect(pipe.transform('foo', { '-1': 'disabled', 0: 'unlimited' })).toBe('foo'); }); it('map value [3]', () => { expect(pipe.transform(-1, { '-1': 'disabled', 0: 'unlimited' })).toBe('disabled'); }); it('map value [4]', () => { expect(pipe.transform(0, { '-1': 'disabled', 0: 'unlimited' })).toBe('unlimited'); }); });
628
23.192308
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/map.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'map' }) export class MapPipe implements PipeTransform { transform(value: string | number, map?: object): any { if (!_.isPlainObject(map)) { return value; } return _.get(map, value, value); } }
311
18.5
56
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/mds-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MdsSummaryPipe } from './mds-summary.pipe'; describe('MdsSummaryPipe', () => { let pipe: MdsSummaryPipe; configureTestBed({ providers: [MdsSummaryPipe] }); beforeEach(() => { pipe = TestBed.inject(MdsSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms with 0 active and 2 standy', () => { const payload = { standbys: [{ name: 'a' }], filesystems: [{ mdsmap: { info: [{ state: 'up:standby-replay' }] } }] }; expect(pipe.transform(payload)).toEqual({ success: 0, info: 2, total: 2 }); }); it('transforms with 1 active and 1 standy', () => { const payload = { standbys: [{ name: 'b' }], filesystems: [{ mdsmap: { info: [{ state: 'up:active', name: 'a' }] } }] }; expect(pipe.transform(payload)).toEqual({ success: 1, info: 1, total: 2 }); }); it('transforms with 0 filesystems', () => { const payload: Record<string, any> = { standbys: [0], filesystems: [] }; expect(pipe.transform(payload)).toEqual({ success: 0, info: 0, total: 0 }); }); it('transforms without filesystem', () => { const payload = { standbys: [{ name: 'a' }] }; expect(pipe.transform(payload)).toEqual({ success: 0, info: 1, total: 1 }); }); it('transforms without value', () => { expect(pipe.transform(undefined)).toEqual({ success: 0, info: 0, total: 0 }); }); });
1,652
20.467532
78
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/mds-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'mdsSummary' }) export class MdsSummaryPipe implements PipeTransform { transform(value: any): any { if (!value) { return { success: 0, info: 0, total: 0 }; } let activeCount = 0; let standbyCount = 0; let standbys = 0; let active = 0; let standbyReplay = 0; _.each(value.standbys, () => { standbys += 1; }); if (value.standbys && !value.filesystems) { standbyCount = standbys; activeCount = 0; } else if (value.filesystems.length === 0) { activeCount = 0; } else { _.each(value.filesystems, (fs) => { _.each(fs.mdsmap.info, (mds) => { if (mds.state === 'up:standby-replay') { standbyReplay += 1; } else { active += 1; } }); }); activeCount = active; standbyCount = standbys + standbyReplay; } const totalCount = activeCount + standbyCount; const mdsSummary = { success: activeCount, info: standbyCount, total: totalCount }; return mdsSummary; } }
1,190
20.267857
54
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/mgr-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MgrSummaryPipe } from './mgr-summary.pipe'; describe('MgrSummaryPipe', () => { let pipe: MgrSummaryPipe; configureTestBed({ providers: [MgrSummaryPipe] }); beforeEach(() => { pipe = TestBed.inject(MgrSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms without value', () => { expect(pipe.transform(undefined)).toEqual({ success: 0, info: 0, total: 0 }); }); it('transforms with 1 active and 2 standbys', () => { const payload = { active_name: 'x', standbys: [{ name: 'y' }, { name: 'z' }] }; const expected = { success: 1, info: 2, total: 3 }; expect(pipe.transform(payload)).toEqual(expected); }); });
865
21.205128
62
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/mgr-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'mgrSummary' }) export class MgrSummaryPipe implements PipeTransform { transform(value: any): any { if (!value) { return { success: 0, info: 0, total: 0 }; } let activeCount: number; const activeTitleText = _.isUndefined(value.active_name) ? '' : `${$localize`active daemon`}: ${value.active_name}`; // There is always one standbyreplay to replace active daemon, if active one is down if (activeTitleText.length > 0) { activeCount = 1; } const standbyCount = value.standbys.length; const totalCount = activeCount + standbyCount; const mgrSummary = { success: activeCount, info: standbyCount, total: totalCount }; return mgrSummary; } }
858
21.605263
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/milliseconds.pipe.spec.ts
import { MillisecondsPipe } from './milliseconds.pipe'; describe('MillisecondsPipe', () => { it('create an instance', () => { const pipe = new MillisecondsPipe(); expect(pipe).toBeTruthy(); }); });
211
22.555556
55
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/milliseconds.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'milliseconds' }) export class MillisecondsPipe implements PipeTransform { transform(value: any): any { return `${value} ms`; } }
208
18
56
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/not-available.pipe.spec.ts
import { NotAvailablePipe } from './not-available.pipe'; describe('NotAvailablePipe', () => { let pipe: NotAvailablePipe; beforeEach(() => { pipe = new NotAvailablePipe(); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms not available (1)', () => { expect(pipe.transform('')).toBe('n/a'); }); it('transforms not available (2)', () => { expect(pipe.transform('', 'Unknown')).toBe('Unknown'); }); it('transform not necessary (1)', () => { expect(pipe.transform(0)).toBe(0); expect(pipe.transform(1)).toBe(1); }); it('transform not necessary (2)', () => { expect(pipe.transform('foo')).toBe('foo'); }); });
699
21.580645
58
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/not-available.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'notAvailable' }) export class NotAvailablePipe implements PipeTransform { transform(value: any, text?: string): any { if (value === '') { return _.defaultTo(text, $localize`n/a`); } return value; } }
318
18.9375
56
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/ordinal.pipe.spec.ts
import { OrdinalPipe } from './ordinal.pipe'; describe('OrdinalPipe', () => { it('create an instance', () => { const pipe = new OrdinalPipe(); expect(pipe).toBeTruthy(); }); });
191
20.333333
45
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/ordinal.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'ordinal' }) export class OrdinalPipe implements PipeTransform { transform(value: any): any { const num = parseInt(value, 10); if (isNaN(num)) { return value; } return ( value + (Math.floor(num / 10) === 1 ? 'th' : num % 10 === 1 ? 'st' : num % 10 === 2 ? 'nd' : num % 10 === 3 ? 'rd' : 'th') ); } }
476
17.346154
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/osd-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdSummaryPipe } from './osd-summary.pipe'; describe('OsdSummaryPipe', () => { let pipe: OsdSummaryPipe; configureTestBed({ providers: [OsdSummaryPipe] }); beforeEach(() => { pipe = TestBed.inject(OsdSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms without value', () => { expect(pipe.transform(undefined)).toBe(''); }); it('transforms having 3 osd with 3 up, 3 in, 0 down, 0 out', () => { const value = { osds: [ { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 1, state: ['up', 'exists'] } ] }; expect(pipe.transform(value)).toEqual({ total: 3, down: 0, out: 0, up: 3, in: 3, nearfull: 0, full: 0 }); }); });
969
21.045455
70
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/osd-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'osdSummary' }) export class OsdSummaryPipe implements PipeTransform { transform(value: any): any { if (!value) { return ''; } let inCount = 0; let upCount = 0; let nearFullCount = 0; let fullCount = 0; _.each(value.osds, (osd) => { if (osd.in) { inCount++; } if (osd.up) { upCount++; } if (osd.state.includes('nearfull')) { nearFullCount++; } if (osd.state.includes('full')) { fullCount++; } }); const downCount = value.osds.length - upCount; const outCount = value.osds.length - inCount; const osdSummary = { total: value.osds.length, down: downCount, out: outCount, up: upCount, in: inCount, nearfull: nearFullCount, full: fullCount }; return osdSummary; } }
943
19.085106
54
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/pipes.module.ts
import { CommonModule, DatePipe } from '@angular/common'; import { NgModule } from '@angular/core'; import { ArrayPipe } from './array.pipe'; import { BooleanTextPipe } from './boolean-text.pipe'; import { BooleanPipe } from './boolean.pipe'; import { CdDatePipe } from './cd-date.pipe'; import { CephReleaseNamePipe } from './ceph-release-name.pipe'; import { CephShortVersionPipe } from './ceph-short-version.pipe'; import { DimlessBinaryPerSecondPipe } from './dimless-binary-per-second.pipe'; import { DimlessBinaryPipe } from './dimless-binary.pipe'; import { DimlessPipe } from './dimless.pipe'; import { DurationPipe } from './duration.pipe'; import { EmptyPipe } from './empty.pipe'; import { EncodeUriPipe } from './encode-uri.pipe'; import { FilterPipe } from './filter.pipe'; import { HealthColorPipe } from './health-color.pipe'; import { HealthIconPipe } from './health-icon.pipe'; import { HealthLabelPipe } from './health-label.pipe'; import { IopsPipe } from './iops.pipe'; import { IscsiBackstorePipe } from './iscsi-backstore.pipe'; import { JoinPipe } from './join.pipe'; import { LogPriorityPipe } from './log-priority.pipe'; import { MapPipe } from './map.pipe'; import { MdsSummaryPipe } from './mds-summary.pipe'; import { MgrSummaryPipe } from './mgr-summary.pipe'; import { MillisecondsPipe } from './milliseconds.pipe'; import { NotAvailablePipe } from './not-available.pipe'; import { OrdinalPipe } from './ordinal.pipe'; import { OsdSummaryPipe } from './osd-summary.pipe'; import { RbdConfigurationSourcePipe } from './rbd-configuration-source.pipe'; import { RelativeDatePipe } from './relative-date.pipe'; import { RoundPipe } from './round.pipe'; import { SanitizeHtmlPipe } from './sanitize-html.pipe'; import { SearchHighlightPipe } from './search-highlight.pipe'; import { TruncatePipe } from './truncate.pipe'; import { UpperFirstPipe } from './upper-first.pipe'; @NgModule({ imports: [CommonModule], declarations: [ ArrayPipe, BooleanPipe, BooleanTextPipe, DimlessBinaryPipe, DimlessBinaryPerSecondPipe, HealthColorPipe, HealthLabelPipe, DimlessPipe, CephShortVersionPipe, CephReleaseNamePipe, RelativeDatePipe, IscsiBackstorePipe, JoinPipe, LogPriorityPipe, FilterPipe, CdDatePipe, EmptyPipe, EncodeUriPipe, RoundPipe, OrdinalPipe, MillisecondsPipe, NotAvailablePipe, IopsPipe, UpperFirstPipe, RbdConfigurationSourcePipe, DurationPipe, MapPipe, TruncatePipe, SanitizeHtmlPipe, SearchHighlightPipe, HealthIconPipe, MgrSummaryPipe, MdsSummaryPipe, OsdSummaryPipe ], exports: [ ArrayPipe, BooleanPipe, BooleanTextPipe, DimlessBinaryPipe, DimlessBinaryPerSecondPipe, HealthColorPipe, HealthLabelPipe, DimlessPipe, CephShortVersionPipe, CephReleaseNamePipe, RelativeDatePipe, IscsiBackstorePipe, JoinPipe, LogPriorityPipe, FilterPipe, CdDatePipe, EmptyPipe, EncodeUriPipe, RoundPipe, OrdinalPipe, MillisecondsPipe, NotAvailablePipe, IopsPipe, UpperFirstPipe, RbdConfigurationSourcePipe, DurationPipe, MapPipe, TruncatePipe, SanitizeHtmlPipe, SearchHighlightPipe, HealthIconPipe, MgrSummaryPipe, MdsSummaryPipe, OsdSummaryPipe ], providers: [ ArrayPipe, BooleanPipe, BooleanTextPipe, DatePipe, CephShortVersionPipe, CephReleaseNamePipe, DimlessBinaryPipe, DimlessBinaryPerSecondPipe, DimlessPipe, RelativeDatePipe, IscsiBackstorePipe, JoinPipe, LogPriorityPipe, CdDatePipe, EmptyPipe, EncodeUriPipe, OrdinalPipe, IopsPipe, MillisecondsPipe, NotAvailablePipe, UpperFirstPipe, DurationPipe, MapPipe, TruncatePipe, SanitizeHtmlPipe, HealthIconPipe, MgrSummaryPipe, MdsSummaryPipe, OsdSummaryPipe ] }) export class PipesModule {}
3,962
26.143836
78
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/rbd-configuration-source.pipe.spec.ts
import { RbdConfigurationSourcePipe } from './rbd-configuration-source.pipe'; describe('RbdConfigurationSourcePipePipe', () => { let pipe: RbdConfigurationSourcePipe; beforeEach(() => { pipe = new RbdConfigurationSourcePipe(); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('should transform correctly', () => { expect(pipe.transform('foo')).not.toBeDefined(); expect(pipe.transform(-1)).not.toBeDefined(); expect(pipe.transform(0)).toBe('global'); expect(pipe.transform(1)).toBe('pool'); expect(pipe.transform(2)).toBe('image'); expect(pipe.transform(-3)).not.toBeDefined(); }); });
658
27.652174
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/rbd-configuration-source.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'rbdConfigurationSource' }) export class RbdConfigurationSourcePipe implements PipeTransform { transform(value: any): any { const sourceMap = { 0: 'global', 1: 'pool', 2: 'image' }; return sourceMap[value]; } }
315
18.75
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/relative-date.pipe.spec.ts
import moment from 'moment'; import { RelativeDatePipe } from './relative-date.pipe'; describe('RelativeDatePipe', () => { const pipe = new RelativeDatePipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms date into a human readable relative time (1)', () => { const date: Date = moment().subtract(130, 'seconds').toDate(); expect(pipe.transform(date)).toBe('2 minutes ago'); }); it('transforms date into a human readable relative time (2)', () => { const date: Date = moment().subtract(65, 'minutes').toDate(); expect(pipe.transform(date)).toBe('An hour ago'); }); it('transforms date into a human readable relative time (3)', () => { const date: string = moment().subtract(130, 'minutes').toISOString(); expect(pipe.transform(date)).toBe('2 hours ago'); }); it('transforms date into a human readable relative time (4)', () => { const date: string = moment().subtract(30, 'seconds').toISOString(); expect(pipe.transform(date, false)).toBe('a few seconds ago'); }); it('transforms date into a human readable relative time (5)', () => { const date: number = moment().subtract(3, 'days').unix(); expect(pipe.transform(date)).toBe('3 days ago'); }); it('invalid input (1)', () => { expect(pipe.transform('')).toBe(''); }); it('invalid input (2)', () => { expect(pipe.transform('2011-10-10T10:20:90')).toBe(''); }); });
1,445
31.133333
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/relative-date.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; import moment from 'moment'; moment.updateLocale('en', { relativeTime: { future: $localize`in %s`, past: $localize`%s ago`, s: $localize`a few seconds`, ss: $localize`%d seconds`, m: $localize`a minute`, mm: $localize`%d minutes`, h: $localize`an hour`, hh: $localize`%d hours`, d: $localize`a day`, dd: $localize`%d days`, w: $localize`a week`, ww: $localize`%d weeks`, M: $localize`a month`, MM: $localize`%d months`, y: $localize`a year`, yy: $localize`%d years` } }); @Pipe({ name: 'relativeDate', pure: false }) export class RelativeDatePipe implements PipeTransform { /** * Convert a time into a human readable form, e.g. '2 minutes ago'. * @param {Date | string | number} value The date to convert, should be * an ISO8601 string, an Unix timestamp (seconds) or Date object. * @param {boolean} upperFirst Set to `true` to start the sentence * upper case. Defaults to `true`. * @return {string} The time in human readable form or an empty string * on failure (e.g. invalid input). */ transform(value: Date | string | number, upperFirst = true): string { let date: moment.Moment; if (_.isNumber(value)) { date = moment.unix(value); } else { date = moment(value); } if (!date.isValid()) { return ''; } let relativeDate: string = date.fromNow(); if (upperFirst) { relativeDate = _.upperFirst(relativeDate); } return relativeDate; } }
1,588
26.396552
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/round.pipe.spec.ts
import { RoundPipe } from './round.pipe'; describe('RoundPipe', () => { const pipe = new RoundPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "1500"', () => { expect(pipe.transform(1.52, 1)).toEqual(1.5); }); });
273
18.571429
49
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/round.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'round' }) export class RoundPipe implements PipeTransform { transform(value: any, precision: number): any { return _.round(value, precision); } }
250
18.307692
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/sanitize-html.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { DomSanitizer } from '@angular/platform-browser'; import { SanitizeHtmlPipe } from '~/app/shared/pipes/sanitize-html.pipe'; import { configureTestBed } from '~/testing/unit-test-helper'; describe('SanitizeHtmlPipe', () => { let pipe: SanitizeHtmlPipe; let domSanitizer: DomSanitizer; configureTestBed({ providers: [DomSanitizer] }); beforeEach(() => { domSanitizer = TestBed.inject(DomSanitizer); pipe = new SanitizeHtmlPipe(domSanitizer); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); // There is no way to inject a working DomSanitizer in unit tests, // so it is not possible to test the `transform` method. });
735
26.259259
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/sanitize-html.pipe.ts
import { Pipe, PipeTransform, SecurityContext } from '@angular/core'; import { DomSanitizer, SafeValue } from '@angular/platform-browser'; @Pipe({ name: 'sanitizeHtml' }) export class SanitizeHtmlPipe implements PipeTransform { constructor(private domSanitizer: DomSanitizer) {} transform(value: SafeValue | string | null): string | null { return this.domSanitizer.sanitize(SecurityContext.HTML, value); } }
422
29.214286
69
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/search-highlight.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { SearchHighlightPipe } from './search-highlight.pipe'; describe('SearchHighlightPipe', () => { let pipe: SearchHighlightPipe; configureTestBed({ providers: [SearchHighlightPipe] }); beforeEach(() => { pipe = TestBed.inject(SearchHighlightPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms with a matching keyword ', () => { const value = 'overall HEALTH_WARN Dashboard debug mode is enabled'; const args = 'Dashboard'; const expected = 'overall HEALTH_WARN <mark>Dashboard</mark> debug mode is enabled'; expect(pipe.transform(value, args)).toEqual(expected); }); it('transforms with a matching keyword having regex character', () => { const value = 'loreum ipsum .? dolor sit amet'; const args = '.?'; const expected = 'loreum ipsum <mark>.?</mark> dolor sit amet'; expect(pipe.transform(value, args)).toEqual(expected); }); it('transforms with empty search keyword', () => { const value = 'overall HEALTH_WARN Dashboard debug mode is enabled'; expect(pipe.transform(value, '')).toBe(value); }); });
1,247
28.714286
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/search-highlight.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchHighlight' }) export class SearchHighlightPipe implements PipeTransform { transform(value: string, args: string): string { if (!args) { return value; } args = this.escapeRegExp(args); const regex = new RegExp(args, 'gi'); const match = value.match(regex); if (!match) { return value; } return value.replace(regex, '<mark>$&</mark>'); } private escapeRegExp(str: string) { // $& means the whole matched string return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } }
604
21.407407
59
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/truncate.pipe.spec.ts
import { TruncatePipe } from './truncate.pipe'; describe('TruncatePipe', () => { const pipe = new TruncatePipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('should truncate string (1)', () => { expect(pipe.transform('fsdfdsfs asdasd', 5, '')).toEqual('fsdfd'); }); it('should truncate string (2)', () => { expect(pipe.transform('fsdfdsfs asdasd', 10, '...')).toEqual('fsdfdsf...'); }); it('should not truncate number', () => { expect(pipe.transform(2, 6, '...')).toBe(2); }); });
544
23.772727
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/truncate.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'truncate' }) export class TruncatePipe implements PipeTransform { transform(value: any, length: number, omission?: string): any { if (!_.isString(value)) { return value; } omission = _.defaultTo(omission, ''); return _.truncate(value, { length, omission }); } }
384
21.647059
65
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/upper-first.pipe.spec.ts
import { UpperFirstPipe } from './upper-first.pipe'; describe('UpperFirstPipe', () => { const pipe = new UpperFirstPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "foo"', () => { expect(pipe.transform('foo')).toEqual('Foo'); }); it('transforms "BAR"', () => { expect(pipe.transform('BAR')).toEqual('BAR'); }); });
383
20.333333
52
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/pipes/upper-first.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'upperFirst' }) export class UpperFirstPipe implements PipeTransform { transform(value: string): string { return _.upperFirst(value); } }
241
17.615385
54
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/rxjs/operators/page-visibilty.operator.ts
import { fromEvent, Observable, partition } from 'rxjs'; import { repeatWhen, shareReplay, takeUntil } from 'rxjs/operators'; export function whenPageVisible() { const visibilitychange$ = fromEvent(document, 'visibilitychange').pipe( shareReplay({ refCount: true, bufferSize: 1 }) ); const [pageVisible$, pageHidden$] = partition( visibilitychange$, () => document.visibilityState === 'visible' ); return function <T>(source: Observable<T>) { return source.pipe( takeUntil(pageHidden$), repeatWhen(() => pageVisible$) ); }; }
573
26.333333
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/api-interceptor.service.spec.ts
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Router } from '@angular/router'; import { ToastrService } from 'ngx-toastr'; import { AppModule } from '~/app/app.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { NotificationType } from '../enum/notification-type.enum'; import { CdNotification, CdNotificationConfig } from '../models/cd-notification'; import { ApiInterceptorService } from './api-interceptor.service'; import { NotificationService } from './notification.service'; describe('ApiInterceptorService', () => { let notificationService: NotificationService; let httpTesting: HttpTestingController; let httpClient: HttpClient; let router: Router; const url = 'api/xyz'; const httpError = (error: any, errorOpts: object, done = (_resp: any): any => undefined) => { httpClient.get(url).subscribe( () => true, (resp) => { // Error must have been forwarded by the interceptor. expect(resp instanceof HttpErrorResponse).toBeTruthy(); done(resp); } ); httpTesting.expectOne(url).error(error, errorOpts); }; const runRouterTest = (errorOpts: object, expectedCallParams: any[]) => { httpError(new ErrorEvent('abc'), errorOpts); httpTesting.verify(); expect(router.navigate).toHaveBeenCalledWith(...expectedCallParams); }; const runNotificationTest = ( error: any, errorOpts: object, expectedCallParams: CdNotification ) => { httpError(error, errorOpts); httpTesting.verify(); expect(notificationService.show).toHaveBeenCalled(); expect(notificationService.save).toHaveBeenCalledWith(expectedCallParams); }; const createCdNotification = ( type: NotificationType, title?: string, message?: string, options?: any, application?: string ) => { return new CdNotification(new CdNotificationConfig(type, title, message, options, application)); }; configureTestBed({ imports: [AppModule, HttpClientTestingModule], providers: [ NotificationService, { provide: ToastrService, useValue: { error: () => true } } ] }); beforeEach(() => { const baseTime = new Date('2022-02-22'); spyOn(global, 'Date').and.returnValue(baseTime); httpClient = TestBed.inject(HttpClient); httpTesting = TestBed.inject(HttpTestingController); notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.callThrough(); spyOn(notificationService, 'save'); router = TestBed.inject(Router); spyOn(router, 'navigate'); }); it('should be created', () => { const service = TestBed.inject(ApiInterceptorService); expect(service).toBeTruthy(); }); describe('test different error behaviours', () => { beforeEach(() => { spyOn(window, 'setTimeout').and.callFake((fn) => fn()); }); it('should redirect 401', () => { runRouterTest( { status: 401 }, [['/login']] ); }); it('should redirect 403', () => { runRouterTest( { status: 403 }, [['error'], {'state': {'header': 'Access Denied', 'icon': 'fa fa-lock', 'message': 'Sorry, you don’t have permission to view this page or resource.', 'source': 'forbidden'}}] // prettier-ignore ); }); it('should show notification (error string)', () => { runNotificationTest( 'foobar', { status: 500, statusText: 'Foo Bar' }, createCdNotification(0, '500 - Foo Bar', 'foobar') ); }); it('should show notification (error object, triggered from backend)', () => { runNotificationTest( { detail: 'abc' }, { status: 504, statusText: 'AAA bbb CCC' }, createCdNotification(0, '504 - AAA bbb CCC', 'abc') ); }); it('should show notification (error object with unknown keys)', () => { runNotificationTest( { type: 'error' }, { status: 0, statusText: 'Unknown Error', message: 'Http failure response for (unknown url): 0 Unknown Error', name: 'HttpErrorResponse', ok: false, url: null }, createCdNotification( 0, '0 - Unknown Error', 'Http failure response for api/xyz: 0 Unknown Error' ) ); }); it('should show notification (undefined error)', () => { runNotificationTest( undefined, { status: 502 }, createCdNotification(0, '502 - Unknown Error', 'Http failure response for api/xyz: 502 ') ); }); it('should show 400 notification', () => { spyOn(notificationService, 'notifyTask'); httpError({ task: { name: 'mytask', metadata: { component: 'foobar' } } }, { status: 400 }); httpTesting.verify(); expect(notificationService.show).toHaveBeenCalledTimes(0); expect(notificationService.notifyTask).toHaveBeenCalledWith({ exception: { task: { metadata: { component: 'foobar' }, name: 'mytask' } }, metadata: { component: 'foobar' }, name: 'mytask', success: false }); }); }); describe('interceptor error handling', () => { const expectSaveToHaveBeenCalled = (called: boolean) => { tick(510); if (called) { expect(notificationService.save).toHaveBeenCalled(); } else { expect(notificationService.save).not.toHaveBeenCalled(); } }; it('should show default behaviour', fakeAsync(() => { httpError(undefined, { status: 500 }); expectSaveToHaveBeenCalled(true); })); it('should prevent the default behaviour with preventDefault', fakeAsync(() => { httpError(undefined, { status: 500 }, (resp) => resp.preventDefault()); expectSaveToHaveBeenCalled(false); })); it('should be able to use preventDefault with 400 errors', fakeAsync(() => { httpError( { task: { name: 'someName', metadata: { component: 'someComponent' } } }, { status: 400 }, (resp) => resp.preventDefault() ); expectSaveToHaveBeenCalled(false); })); it('should prevent the default behaviour by status code', fakeAsync(() => { httpError(undefined, { status: 500 }, (resp) => resp.ignoreStatusCode(500)); expectSaveToHaveBeenCalled(false); })); it('should use different application icon (default Ceph) in error message', fakeAsync(() => { const msg = 'Cannot connect to Alertmanager'; httpError(undefined, { status: 500 }, (resp) => { (resp.application = 'Prometheus'), (resp.message = msg); }); expectSaveToHaveBeenCalled(true); expect(notificationService.save).toHaveBeenCalledWith( createCdNotification(0, '500 - Unknown Error', msg, undefined, 'Prometheus') ); })); }); });
7,149
30.359649
201
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/api-interceptor.service.ts
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import _ from 'lodash'; import { Observable, throwError as observableThrowError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { CdHelperClass } from '~/app/shared/classes/cd-helper.class'; import { NotificationType } from '../enum/notification-type.enum'; import { CdNotificationConfig } from '../models/cd-notification'; import { FinishedTask } from '../models/finished-task'; import { AuthStorageService } from './auth-storage.service'; import { NotificationService } from './notification.service'; export class CdHttpErrorResponse extends HttpErrorResponse { preventDefault: Function; ignoreStatusCode: Function; } @Injectable({ providedIn: 'root' }) export class ApiInterceptorService implements HttpInterceptor { constructor( private router: Router, private authStorageService: AuthStorageService, public notificationService: NotificationService ) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const acceptHeader = request.headers.get('Accept'); let reqWithVersion: HttpRequest<any>; if (acceptHeader && acceptHeader.startsWith('application/vnd.ceph.api.v')) { reqWithVersion = request.clone(); } else { reqWithVersion = request.clone({ setHeaders: { Accept: CdHelperClass.cdVersionHeader('1', '0') } }); } return next.handle(reqWithVersion).pipe( catchError((resp: CdHttpErrorResponse) => { if (resp instanceof HttpErrorResponse) { let timeoutId: number; switch (resp.status) { case 400: const finishedTask = new FinishedTask(); const task = resp.error.task; if (_.isPlainObject(task)) { task.metadata.component = task.metadata.component || resp.error.component; finishedTask.name = task.name; finishedTask.metadata = task.metadata; } else { finishedTask.metadata = resp.error; } finishedTask.success = false; finishedTask.exception = resp.error; timeoutId = this.notificationService.notifyTask(finishedTask); break; case 401: this.authStorageService.remove(); this.router.navigate(['/login']); break; case 403: this.router.navigate(['error'], { state: { message: $localize`Sorry, you don’t have permission to view this page or resource.`, header: $localize`Access Denied`, icon: 'fa fa-lock', source: 'forbidden' } }); break; default: timeoutId = this.prepareNotification(resp); } /** * Decorated preventDefault method (in case error previously had * preventDefault method defined). If called, it will prevent a * notification to be shown. */ resp.preventDefault = () => { this.notificationService.cancel(timeoutId); }; /** * If called, it will prevent a notification for the specific status code. * @param {number} status The status code to be ignored. */ resp.ignoreStatusCode = function (status: number) { if (this.status === status) { this.preventDefault(); } }; } // Return the error to the method that called it. return observableThrowError(resp); }) ); } private prepareNotification(resp: any): number { return this.notificationService.show(() => { let message = ''; if (_.isPlainObject(resp.error) && _.isString(resp.error.detail)) { message = resp.error.detail; // Error was triggered by the backend. } else if (_.isString(resp.error)) { message = resp.error; } else if (_.isString(resp.message)) { message = resp.message; } return new CdNotificationConfig( NotificationType.error, `${resp.status} - ${resp.statusText}`, message, undefined, resp['application'] ); }); } }
4,488
32.5
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/auth-guard.service.spec.ts
import { Component, NgZone } from '@angular/core'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AuthGuardService } from './auth-guard.service'; import { AuthStorageService } from './auth-storage.service'; describe('AuthGuardService', () => { let service: AuthGuardService; let authStorageService: AuthStorageService; let ngZone: NgZone; let route: ActivatedRouteSnapshot; let state: RouterStateSnapshot; @Component({ selector: 'cd-login', template: '' }) class LoginComponent {} const routes: Routes = [{ path: 'login', component: LoginComponent }]; configureTestBed({ imports: [RouterTestingModule.withRoutes(routes)], providers: [AuthGuardService, AuthStorageService], declarations: [LoginComponent] }); beforeEach(() => { service = TestBed.inject(AuthGuardService); authStorageService = TestBed.inject(AuthStorageService); ngZone = TestBed.inject(NgZone); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should allow the user if loggedIn', () => { route = null; state = { url: '/', root: null }; spyOn(authStorageService, 'isLoggedIn').and.returnValue(true); expect(service.canActivate(route, state)).toBe(true); }); it('should prevent user if not loggedIn and redirect to login page', fakeAsync(() => { const router = TestBed.inject(Router); state = { url: '/pool', root: null }; ngZone.run(() => { expect(service.canActivate(route, state)).toBe(false); }); tick(); expect(router.url).toBe('/login?returnUrl=%2Fpool'); })); });
1,828
32.254545
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/auth-guard.service.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router'; import { AuthStorageService } from './auth-storage.service'; @Injectable({ providedIn: 'root' }) export class AuthGuardService implements CanActivate, CanActivateChild { constructor(private router: Router, private authStorageService: AuthStorageService) {} canActivate(_route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (this.authStorageService.isLoggedIn()) { return true; } this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); return false; } canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return this.canActivate(childRoute, state); } }
837
26.933333
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/auth-storage.service.spec.ts
import { AuthStorageService } from './auth-storage.service'; describe('AuthStorageService', () => { let service: AuthStorageService; const username = 'foobar'; beforeEach(() => { service = new AuthStorageService(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should store username', () => { service.set(username, ''); expect(localStorage.getItem('dashboard_username')).toBe(username); }); it('should remove username', () => { service.set(username, ''); service.remove(); expect(localStorage.getItem('dashboard_username')).toBe(null); }); it('should be loggedIn', () => { service.set(username, ''); expect(service.isLoggedIn()).toBe(true); }); it('should not be loggedIn', () => { service.remove(); expect(service.isLoggedIn()).toBe(false); }); it('should be SSO', () => { service.set(username, {}, true); expect(localStorage.getItem('sso')).toBe('true'); expect(service.isSSO()).toBe(true); }); it('should not be SSO', () => { service.set(username); expect(localStorage.getItem('sso')).toBe('false'); expect(service.isSSO()).toBe(false); }); });
1,189
23.791667
70
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/auth-storage.service.ts
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { Permissions } from '../models/permissions'; @Injectable({ providedIn: 'root' }) export class AuthStorageService { isPwdDisplayedSource = new BehaviorSubject(false); isPwdDisplayed$ = this.isPwdDisplayedSource.asObservable(); set( username: string, permissions = {}, sso = false, pwdExpirationDate: number = null, pwdUpdateRequired: boolean = false ) { localStorage.setItem('dashboard_username', username); localStorage.setItem('dashboard_permissions', JSON.stringify(new Permissions(permissions))); localStorage.setItem('user_pwd_expiration_date', String(pwdExpirationDate)); localStorage.setItem('user_pwd_update_required', String(pwdUpdateRequired)); localStorage.setItem('sso', String(sso)); } remove() { localStorage.removeItem('dashboard_username'); localStorage.removeItem('user_pwd_expiration_data'); localStorage.removeItem('user_pwd_update_required'); } isLoggedIn() { return localStorage.getItem('dashboard_username') !== null; } getUsername() { return localStorage.getItem('dashboard_username'); } getPermissions(): Permissions { return JSON.parse( localStorage.getItem('dashboard_permissions') || JSON.stringify(new Permissions({})) ); } getPwdExpirationDate(): number { return Number(localStorage.getItem('user_pwd_expiration_date')); } getPwdUpdateRequired(): boolean { return localStorage.getItem('user_pwd_update_required') === 'true'; } isSSO() { return localStorage.getItem('sso') === 'true'; } }
1,645
26.433333
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/cd-table-server-side.service.spec.ts
import { TestBed } from '@angular/core/testing'; import { CdTableServerSideService } from './cd-table-server-side.service'; describe('CdTableServerSideService', () => { let service: CdTableServerSideService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(CdTableServerSideService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
415
23.470588
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/cd-table-server-side.service.ts
import { HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CdTableServerSideService { /* tslint:disable:no-empty */ constructor() {} static getCount(resp: HttpResponse<any>): number { return Number(resp.headers?.get('X-Total-Count')); } }
342
21.866667
54
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/change-password-guard.service.spec.ts
import { Component, NgZone } from '@angular/core'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AuthStorageService } from './auth-storage.service'; import { ChangePasswordGuardService } from './change-password-guard.service'; describe('ChangePasswordGuardService', () => { let service: ChangePasswordGuardService; let authStorageService: AuthStorageService; let ngZone: NgZone; let route: ActivatedRouteSnapshot; let state: RouterStateSnapshot; @Component({ selector: 'cd-login-password-form', template: '' }) class LoginPasswordFormComponent {} const routes: Routes = [{ path: 'login-change-password', component: LoginPasswordFormComponent }]; configureTestBed({ imports: [RouterTestingModule.withRoutes(routes)], providers: [ChangePasswordGuardService, AuthStorageService], declarations: [LoginPasswordFormComponent] }); beforeEach(() => { service = TestBed.inject(ChangePasswordGuardService); authStorageService = TestBed.inject(AuthStorageService); ngZone = TestBed.inject(NgZone); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should do nothing (not logged in)', () => { spyOn(authStorageService, 'isLoggedIn').and.returnValue(false); expect(service.canActivate(route, state)).toBeTruthy(); }); it('should do nothing (SSO enabled)', () => { spyOn(authStorageService, 'isLoggedIn').and.returnValue(true); spyOn(authStorageService, 'isSSO').and.returnValue(true); expect(service.canActivate(route, state)).toBeTruthy(); }); it('should do nothing (no update pwd required)', () => { spyOn(authStorageService, 'isLoggedIn').and.returnValue(true); spyOn(authStorageService, 'getPwdUpdateRequired').and.returnValue(false); expect(service.canActivate(route, state)).toBeTruthy(); }); it('should redirect to change password page by preserving the query params', fakeAsync(() => { route = null; state = { url: '/host', root: null }; spyOn(authStorageService, 'isLoggedIn').and.returnValue(true); spyOn(authStorageService, 'isSSO').and.returnValue(false); spyOn(authStorageService, 'getPwdUpdateRequired').and.returnValue(true); const router = TestBed.inject(Router); ngZone.run(() => { expect(service.canActivate(route, state)).toBeFalsy(); }); tick(); expect(router.url).toBe('/login-change-password?returnUrl=%2Fhost'); })); });
2,666
37.652174
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/change-password-guard.service.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router'; import { AuthStorageService } from './auth-storage.service'; /** * This service guard checks if a user must be redirected to a special * page at '/login-change-password' to set a new password. */ @Injectable({ providedIn: 'root' }) export class ChangePasswordGuardService implements CanActivate, CanActivateChild { constructor(private router: Router, private authStorageService: AuthStorageService) {} canActivate(_route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { // Redirect to '/login-change-password' when the following constraints // are fulfilled: // - The user must be logged in. // - SSO must be disabled. // - The flag 'User must change password at next logon' must be set. if ( this.authStorageService.isLoggedIn() && !this.authStorageService.isSSO() && this.authStorageService.getPwdUpdateRequired() ) { this.router.navigate(['/login-change-password'], { queryParams: { returnUrl: state.url } }); return false; } return true; } canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return this.canActivate(childRoute, state); } }
1,351
30.44186
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/crud-form-adapter.service.spec.ts
import { TestBed } from '@angular/core/testing'; import { CrudFormAdapterService } from './crud-form-adapter.service'; import { RouterTestingModule } from '@angular/router/testing'; describe('CrudFormAdapterService', () => { let service: CrudFormAdapterService; beforeEach(() => { TestBed.configureTestingModule({ imports: [RouterTestingModule] }); service = TestBed.inject(CrudFormAdapterService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
509
24.5
69
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/crud-form-adapter.service.ts
import { Injectable } from '@angular/core'; import { FormlyJsonschema } from '@ngx-formly/core/json-schema'; import { CrudTaskInfo, JsonFormUISchema } from '../forms/crud-form/crud-form.model'; import { setupValidators } from '../forms/crud-form/helpers'; @Injectable({ providedIn: 'root' }) export class CrudFormAdapterService { constructor(private formlyJsonschema: FormlyJsonschema) {} processJsonSchemaForm(response: any, path: string): JsonFormUISchema { let form = 0; while (form < response.forms.length) { if (response.forms[form].path == path) { break; } form++; } form %= response.forms.length; const title = response.forms[form].control_schema.title; const uiSchema = response.forms[form].ui_schema; const cSchema = response.forms[form].control_schema; let controlSchema = this.formlyJsonschema.toFieldConfig(cSchema).fieldGroup; for (let i = 0; i < controlSchema.length; i++) { for (let j = 0; j < uiSchema.length; j++) { if (controlSchema[i].key == uiSchema[j].key) { controlSchema[i].props.templateOptions = uiSchema[j].templateOptions; controlSchema[i].props.readonly = uiSchema[j].readonly; setupValidators(controlSchema[i], uiSchema); } } } let taskInfo: CrudTaskInfo = { metadataFields: response.forms[form].task_info.metadataFields, message: response.forms[form].task_info.message }; const methodType = response.forms[form].method_type; const model = response.forms[form].model || {}; return { title, uiSchema, controlSchema, taskInfo, methodType, model }; } }
1,645
37.27907
84
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/data-gateway.service.spec.ts
/* tslint:disable:no-unused-variable */ import { HttpClientTestingModule } from '@angular/common/http/testing'; import { inject, TestBed } from '@angular/core/testing'; import { DataGatewayService } from './data-gateway.service'; import { RouterTestingModule } from '@angular/router/testing'; describe('Service: DataGateway', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule, RouterTestingModule], providers: [DataGatewayService] }); }); it('should ...', inject([DataGatewayService], (service: DataGatewayService) => { expect(service).toBeTruthy(); })); });
639
29.47619
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/data-gateway.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { JsonFormUISchema } from '../forms/crud-form/crud-form.model'; import { CrudFormAdapterService } from './crud-form-adapter.service'; @Injectable({ providedIn: 'root' }) export class DataGatewayService { cache: { [keys: string]: Observable<any> } = {}; selected: any; constructor(private http: HttpClient, private crudFormAdapater: CrudFormAdapterService) {} list(dataPath: string): Observable<any> { const cacheable = this.getCacheable(dataPath, 'get'); if (this.cache[cacheable] === undefined) { const { url, version } = this.getUrlAndVersion(dataPath); this.cache[cacheable] = this.http.get<any>(url, { headers: { Accept: `application/vnd.ceph.api.v${version}+json` } }); } return this.cache[cacheable]; } submit(dataPath: string, data: any, methodType: string): Observable<any> { const { url, version } = this.getUrlAndVersion(dataPath); return this.http[methodType]<any>(url, data, { headers: { Accept: `application/vnd.ceph.api.v${version}+json` } }); } delete(dataPath: string, key: string): Observable<any> { const { url, version } = this.getUrlAndVersion(dataPath); return this.http.delete<any>(`${url}/${key}`, { headers: { Accept: `application/vnd.ceph.api.v${version}+json` }, observe: 'response' }); } form(dataPath: string, formPath: string, modelKey: string = ''): Observable<JsonFormUISchema> { const cacheable = this.getCacheable(dataPath, 'get', modelKey); const params = { model_key: modelKey }; if (this.cache[cacheable] === undefined) { const { url, version } = this.getUrlAndVersion(dataPath); this.cache[cacheable] = this.http.get<any>(url, { headers: { Accept: `application/vnd.ceph.api.v${version}+json` }, params: params }); } return this.cache[cacheable].pipe( map((response) => { return this.crudFormAdapater.processJsonSchemaForm(response, formPath); }) ); } model(dataPath: string, params: HttpParams): Observable<any> { const cacheable = this.getCacheable(dataPath, 'get'); if (this.cache[cacheable] === undefined) { const { url, version } = this.getUrlAndVersion(dataPath); this.cache[cacheable] = this.http.get<any>(`${url}/model`, { headers: { Accept: `application/vnd.ceph.api.v${version}+json` }, params: params }); } return this.cache[cacheable]; } getCacheable(dataPath: string, method: string, key: string = '') { return dataPath + method + key; } getUrlAndVersion(dataPath: string) { const match = dataPath.match(/(?<url>[^@]+)(?:@(?<version>.+))?/); const url = match.groups.url.split('.').join('/'); const version = match.groups.version || '1.0'; return { url: url, version: version }; } }
3,004
32.021978
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/device.service.spec.ts
import { TestBed } from '@angular/core/testing'; import moment from 'moment'; import { CdDevice } from '../models/devices'; import { DeviceService } from './device.service'; describe('DeviceService', () => { let service: DeviceService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(DeviceService); }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('should test getDevices pipe', () => { let now: jasmine.Spy = null; const newDevice = (data: object): CdDevice => { const device: CdDevice = { devid: '', location: [{ host: '', dev: '' }], daemons: [] }; Object.assign(device, data); return device; }; beforeEach(() => { // Mock 'moment.now()' to simplify testing by enabling testing with fixed dates. now = spyOn(moment, 'now').and.returnValue( moment('2019-10-01T00:00:00.00000+0100').valueOf() ); }); afterEach(() => { expect(now).toHaveBeenCalled(); }); it('should return status "good" for life expectancy > 6 weeks', () => { const preparedDevice = service.calculateAdditionalData( newDevice({ life_expectancy_min: '2019-11-14T01:00:00.000000+0100', life_expectancy_max: '0.000000', life_expectancy_stamp: '2019-10-01T02:08:48.627312+0100' }) ); expect(preparedDevice.life_expectancy_weeks).toEqual({ max: null, min: 6 }); expect(preparedDevice.state).toBe('good'); }); it('should return status "warning" for life expectancy <= 4 weeks', () => { const preparedDevice = service.calculateAdditionalData( newDevice({ life_expectancy_min: '2019-10-14T01:00:00.000000+0100', life_expectancy_max: '2019-11-14T01:00:00.000000+0100', life_expectancy_stamp: '2019-10-01T00:00:00.00000+0100' }) ); expect(preparedDevice.life_expectancy_weeks).toEqual({ max: 6, min: 2 }); expect(preparedDevice.state).toBe('warning'); }); it('should return status "bad" for life expectancy <= 2 weeks', () => { const preparedDevice = service.calculateAdditionalData( newDevice({ life_expectancy_min: '0.000000', life_expectancy_max: '2019-10-12T01:00:00.000000+0100', life_expectancy_stamp: '2019-10-01T00:00:00.00000+0100' }) ); expect(preparedDevice.life_expectancy_weeks).toEqual({ max: 2, min: null }); expect(preparedDevice.state).toBe('bad'); }); it('should return status "stale" for time stamp that is older than a week', () => { const preparedDevice = service.calculateAdditionalData( newDevice({ life_expectancy_min: '0.000000', life_expectancy_max: '0.000000', life_expectancy_stamp: '2019-09-21T00:00:00.00000+0100' }) ); expect(preparedDevice.life_expectancy_weeks).toEqual({ max: null, min: null }); expect(preparedDevice.state).toBe('stale'); }); }); });
3,065
31.967742
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/device.service.ts
import { Injectable } from '@angular/core'; import moment from 'moment'; import { CdDevice } from '../models/devices'; @Injectable({ providedIn: 'root' }) export class DeviceService { /** * Calculates additional data and appends them as new attributes to the given device. */ calculateAdditionalData(device: CdDevice): CdDevice { if (!device.life_expectancy_min || !device.life_expectancy_max) { device.state = 'unknown'; return device; } const hasDate = (float: string): boolean => !!Number.parseFloat(float); const weeks = (isoDate1: string, isoDate2: string): number => !isoDate1 || !isoDate2 || !hasDate(isoDate1) || !hasDate(isoDate2) ? null : moment.duration(moment(isoDate1).diff(moment(isoDate2))).asWeeks(); const ageOfStamp = moment .duration(moment(moment.now()).diff(moment(device.life_expectancy_stamp))) .asWeeks(); const max = weeks(device.life_expectancy_max, device.life_expectancy_stamp); const min = weeks(device.life_expectancy_min, device.life_expectancy_stamp); if (ageOfStamp > 1) { device.state = 'stale'; } else if (max !== null && max <= 2) { device.state = 'bad'; } else if (min !== null && min <= 4) { device.state = 'warning'; } else { device.state = 'good'; } device.life_expectancy_weeks = { max: max !== null ? Math.round(max) : null, min: min !== null ? Math.round(min) : null }; return device; } readable(device: CdDevice): CdDevice { device.readableDaemons = device.daemons.join(' '); return device; } prepareDevice(device: CdDevice): CdDevice { return this.readable(this.calculateAdditionalData(device)); } }
1,730
28.844828
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/doc.service.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { Subscriber } from 'rxjs'; import { configureTestBed } from '~/testing/unit-test-helper'; import { SharedModule } from '../shared.module'; import { DocService } from './doc.service'; describe('DocService', () => { let service: DocService; configureTestBed({ imports: [HttpClientTestingModule, SharedModule] }); beforeEach(() => { service = TestBed.inject(DocService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return full URL', () => { expect(service.urlGenerator('iscsi', 'foo')).toBe( 'https://docs.ceph.com/en/foo/mgr/dashboard/#enabling-iscsi-management' ); }); it('should return latest version URL for main', () => { expect(service.urlGenerator('orch', 'main')).toBe( 'https://docs.ceph.com/en/latest/mgr/orchestrator' ); }); describe('Name of the group', () => { let result: string; let i: number; const nextSummary = (newData: any) => service['releaseDataSource'].next(newData); const callback = (response: string) => { i++; result = response; }; beforeEach(() => { i = 0; result = undefined; nextSummary(undefined); }); it('should call subscribeOnce without releaseName', () => { const subscriber = service.subscribeOnce('prometheus', callback); expect(subscriber).toEqual(jasmine.any(Subscriber)); expect(i).toBe(0); expect(result).toEqual(undefined); }); it('should call subscribeOnce with releaseName', () => { const subscriber = service.subscribeOnce('prometheus', callback); expect(subscriber).toEqual(jasmine.any(Subscriber)); expect(i).toBe(0); expect(result).toEqual(undefined); nextSummary('foo'); expect(result).toEqual( 'https://docs.ceph.com/en/foo/mgr/dashboard/#enabling-prometheus-alerting' ); expect(i).toBe(1); expect(subscriber.closed).toBe(true); }); }); });
2,091
26.526316
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/doc.service.ts
import { Injectable } from '@angular/core'; import { BehaviorSubject, Subscription } from 'rxjs'; import { filter, first, map } from 'rxjs/operators'; import { CephReleaseNamePipe } from '../pipes/ceph-release-name.pipe'; import { SummaryService } from './summary.service'; @Injectable({ providedIn: 'root' }) export class DocService { private releaseDataSource = new BehaviorSubject<string>(null); releaseData$ = this.releaseDataSource.asObservable(); constructor( private summaryservice: SummaryService, private cephReleaseNamePipe: CephReleaseNamePipe ) { this.summaryservice.subscribeOnce((summary) => { const releaseName = this.cephReleaseNamePipe.transform(summary.version); this.releaseDataSource.next(releaseName); }); } urlGenerator(section: string, release = 'main'): string { const docVersion = release === 'main' ? 'latest' : release; const domain = `https://docs.ceph.com/en/${docVersion}/`; const domainCeph = `https://ceph.io`; const domainCephOld = `https://old.ceph.com`; const sections = { iscsi: `${domain}mgr/dashboard/#enabling-iscsi-management`, prometheus: `${domain}mgr/dashboard/#enabling-prometheus-alerting`, 'nfs-ganesha': `${domain}mgr/dashboard/#configuring-nfs-ganesha-in-the-dashboard`, 'rgw-nfs': `${domain}radosgw/nfs`, rgw: `${domain}mgr/dashboard/#enabling-the-object-gateway-management-frontend`, 'rgw-multisite': `${domain}/radosgw/multisite/#failover-and-disaster-recovery`, dashboard: `${domain}mgr/dashboard`, grafana: `${domain}mgr/dashboard/#enabling-the-embedding-of-grafana-dashboards`, orch: `${domain}mgr/orchestrator`, pgs: `${domainCephOld}/pgcalc`, help: `${domainCeph}/en/users/`, security: `${domainCeph}/en/security/`, trademarks: `${domainCeph}/en/trademarks/`, 'dashboard-landing-page-status': `${domain}mgr/dashboard/#dashboard-landing-page-status`, 'dashboard-landing-page-performance': `${domain}mgr/dashboard/#dashboard-landing-page-performance`, 'dashboard-landing-page-capacity': `${domain}mgr/dashboard/#dashboard-landing-page-capacity` }; return sections[section]; } subscribeOnce( section: string, next: (release: string) => void, error?: (error: any) => void ): Subscription { return this.releaseData$ .pipe( filter((value) => !!value), map((release) => this.urlGenerator(section, release)), first() ) .subscribe(next, error); } }
2,536
36.308824
105
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/favicon.service.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { configureTestBed } from '~/testing/unit-test-helper'; import { FaviconService } from './favicon.service'; describe('FaviconService', () => { let service: FaviconService; configureTestBed({ imports: [HttpClientTestingModule], providers: [FaviconService, CssHelper] }); beforeEach(() => { service = TestBed.inject(FaviconService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
629
25.25
71
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/favicon.service.ts
import { DOCUMENT } from '@angular/common'; import { Inject, Injectable, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { HealthColor } from '~/app/shared/enum/health-color.enum'; import { SummaryService } from './summary.service'; @Injectable() export class FaviconService implements OnDestroy { sub: Subscription; oldStatus: string; url: string; constructor( @Inject(DOCUMENT) private document: HTMLDocument, private summaryService: SummaryService, private cssHelper: CssHelper ) {} init() { this.url = this.document.getElementById('cdFavicon')?.getAttribute('href'); this.sub = this.summaryService.subscribe((summary) => { this.changeIcon(summary.health_status); }); } changeIcon(status?: string) { if (status === this.oldStatus) { return; } this.oldStatus = status; const favicon = this.document.getElementById('cdFavicon'); const faviconSize = 16; const radius = faviconSize / 4; const canvas = this.document.createElement('canvas'); canvas.width = faviconSize; canvas.height = faviconSize; const context = canvas.getContext('2d'); const img = this.document.createElement('img'); img.src = this.url; img.onload = () => { // Draw Original Favicon as Background context.drawImage(img, 0, 0, faviconSize, faviconSize); if (Object.keys(HealthColor).includes(status as HealthColor)) { // Cut notification circle area context.save(); context.globalCompositeOperation = 'destination-out'; context.beginPath(); context.arc(canvas.width - radius, radius, radius + 2, 0, 2 * Math.PI); context.fill(); context.restore(); // Draw Notification Circle context.beginPath(); context.arc(canvas.width - radius, radius, radius, 0, 2 * Math.PI); context.fillStyle = this.cssHelper.propertyValue(HealthColor[status]); context.fill(); } // Replace favicon favicon.setAttribute('href', canvas.toDataURL('image/png')); }; } ngOnDestroy() { this.changeIcon(); this.sub?.unsubscribe(); } }
2,233
26.925
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/feature-toggles-guard.service.spec.ts
import { Component, NgZone } from '@angular/core'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ActivatedRouteSnapshot, Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { of as observableOf } from 'rxjs'; import { DashboardNotFoundError } from '~/app/core/error/error'; import { configureTestBed } from '~/testing/unit-test-helper'; import { FeatureTogglesGuardService } from './feature-toggles-guard.service'; import { FeatureTogglesService } from './feature-toggles.service'; describe('FeatureTogglesGuardService', () => { let service: FeatureTogglesGuardService; let fakeFeatureTogglesService: FeatureTogglesService; let router: Router; let ngZone: NgZone; @Component({ selector: 'cd-cephfs', template: '' }) class CephfsComponent {} @Component({ selector: 'cd-404', template: '' }) class NotFoundComponent {} const routes: Routes = [ { path: 'cephfs', component: CephfsComponent }, { path: '404', component: NotFoundComponent } ]; configureTestBed({ imports: [RouterTestingModule.withRoutes(routes)], providers: [ { provide: FeatureTogglesService, useValue: { get: null } }, FeatureTogglesGuardService ], declarations: [CephfsComponent, NotFoundComponent] }); beforeEach(() => { service = TestBed.inject(FeatureTogglesGuardService); fakeFeatureTogglesService = TestBed.inject(FeatureTogglesService); ngZone = TestBed.inject(NgZone); router = TestBed.inject(Router); }); it('should be created', () => { expect(service).toBeTruthy(); }); function testCanActivate(path: string, feature_toggles_map: object) { let result: boolean; spyOn(fakeFeatureTogglesService, 'get').and.returnValue(observableOf(feature_toggles_map)); ngZone.run(() => { service .canActivate(<ActivatedRouteSnapshot>{ routeConfig: { path: path } }) .subscribe((val) => (result = val)); }); tick(); return result; } it('should allow the feature if enabled', fakeAsync(() => { expect(testCanActivate('cephfs', { cephfs: true })).toBe(true); expect(router.url).toBe('/'); })); it('should throw error if disable', fakeAsync(() => { expect(() => testCanActivate('cephfs', { cephfs: false })).toThrowError(DashboardNotFoundError); })); });
2,369
31.465753
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/feature-toggles-guard.service.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, CanActivateChild } from '@angular/router'; import { map } from 'rxjs/operators'; import { DashboardNotFoundError } from '~/app/core/error/error'; import { FeatureTogglesMap, FeatureTogglesService } from './feature-toggles.service'; @Injectable({ providedIn: 'root' }) export class FeatureTogglesGuardService implements CanActivate, CanActivateChild { constructor(private featureToggles: FeatureTogglesService) {} canActivate(route: ActivatedRouteSnapshot) { return this.featureToggles.get().pipe( map((enabledFeatures: FeatureTogglesMap) => { if (enabledFeatures[route.routeConfig.path] === false) { throw new DashboardNotFoundError(); return false; } return true; }) ); } canActivateChild(route: ActivatedRouteSnapshot) { return this.canActivate(route.parent); } }
941
29.387097
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/feature-toggles.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { discardPeriodicTasks, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { FeatureTogglesService } from './feature-toggles.service'; describe('FeatureTogglesService', () => { let httpTesting: HttpTestingController; let service: FeatureTogglesService; configureTestBed({ providers: [FeatureTogglesService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(FeatureTogglesService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should fetch HTTP endpoint once and only once', fakeAsync(() => { const mockFeatureTogglesMap = [ { rbd: true, mirroring: true, iscsi: true, cephfs: true, rgw: true } ]; service .get() .subscribe((featureTogglesMap) => expect(featureTogglesMap).toEqual(mockFeatureTogglesMap)); tick(); // Second subscription shouldn't trigger a new HTTP request service .get() .subscribe((featureTogglesMap) => expect(featureTogglesMap).toEqual(mockFeatureTogglesMap)); const req = httpTesting.expectOne(service.API_URL); req.flush(mockFeatureTogglesMap); discardPeriodicTasks(); })); });
1,507
26.418182
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/feature-toggles.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { TimerService } from './timer.service'; export class FeatureTogglesMap { rbd = true; mirroring = true; iscsi = true; cephfs = true; rgw = true; nfs = true; dashboardV3 = true; } export type Features = keyof FeatureTogglesMap; export type FeatureTogglesMap$ = Observable<FeatureTogglesMap>; @Injectable({ providedIn: 'root' }) export class FeatureTogglesService { readonly API_URL: string = 'api/feature_toggles'; readonly REFRESH_INTERVAL: number = 30000; private featureToggleMap$: FeatureTogglesMap$; constructor(private http: HttpClient, private timerService: TimerService) { this.featureToggleMap$ = this.timerService.get( () => this.http.get<FeatureTogglesMap>(this.API_URL), this.REFRESH_INTERVAL ); } get(): FeatureTogglesMap$ { return this.featureToggleMap$; } }
969
23.871795
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/formatter.service.spec.ts
import { configureTestBed } from '~/testing/unit-test-helper'; import { DimlessBinaryPipe } from '../pipes/dimless-binary.pipe'; import { DimlessPipe } from '../pipes/dimless.pipe'; import { FormatterService } from './formatter.service'; describe('FormatterService', () => { let service: FormatterService; let dimlessBinaryPipe: DimlessBinaryPipe; let dimlessPipe: DimlessPipe; const convertToBytesAndBack = (value: string, newValue?: string) => { expect(dimlessBinaryPipe.transform(service.toBytes(value))).toBe(newValue || value); }; configureTestBed({ providers: [FormatterService, DimlessBinaryPipe] }); beforeEach(() => { service = new FormatterService(); dimlessBinaryPipe = new DimlessBinaryPipe(service); dimlessPipe = new DimlessPipe(service); }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('format_number', () => { const formats = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; it('should return minus for unsupported values', () => { expect(service.format_number(service, 1024, formats)).toBe('-'); expect(service.format_number(undefined, 1024, formats)).toBe('-'); expect(service.format_number(null, 1024, formats)).toBe('-'); }); it('should test some values', () => { expect(service.format_number('0', 1024, formats)).toBe('0 B'); expect(service.format_number('0.1', 1024, formats)).toBe('0.1 B'); expect(service.format_number('1.2', 1024, formats)).toBe('1.2 B'); expect(service.format_number('1', 1024, formats)).toBe('1 B'); expect(service.format_number('1024', 1024, formats)).toBe('1 KiB'); expect(service.format_number(23.45678 * Math.pow(1024, 3), 1024, formats)).toBe('23.5 GiB'); expect(service.format_number(23.45678 * Math.pow(1024, 3), 1024, formats, 2)).toBe( '23.46 GiB' ); }); it('should test some dimless values', () => { expect(dimlessPipe.transform(0.6)).toBe('0.6'); expect(dimlessPipe.transform(1000.608)).toBe('1 k'); expect(dimlessPipe.transform(1e10)).toBe('10 G'); expect(dimlessPipe.transform(2.37e16)).toBe('23.7 P'); }); }); describe('formatNumberFromTo', () => { const formats = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; const formats2 = ['ns', 'μs', 'ms', 's']; it('should test some values and data units', () => { expect(service.formatNumberFromTo('0.1', 'B', 'TiB', 1024, formats)).toBe('0 TiB'); expect(service.formatNumberFromTo('1024', 'B', 'KiB', 1024, formats)).toBe('1 KiB'); expect(service.formatNumberFromTo(1000, 'mib', 'gib', 1024, formats, 3)).toBe('0.977 gib'); expect(service.formatNumberFromTo(1024, 'GiB', 'MiB', 1024, formats)).toBe('1048576 MiB'); expect( service.formatNumberFromTo(23.45678 * Math.pow(1024, 3), 'B', 'GiB', 1024, formats) ).toBe('23.5 GiB'); expect( service.formatNumberFromTo(23.45678 * Math.pow(1024, 3), 'B', 'GiB', 1024, formats, 2) ).toBe('23.46 GiB'); expect(service.formatNumberFromTo('128', 'ns', 'ms', 1000, formats2)).toBe('0 ms'); expect(service.formatNumberFromTo(128, 'ns', 'ms', 1000, formats2, 4)).toBe('0.0001 ms'); expect(service.formatNumberFromTo(20, 's', 'ms', 1000, formats2, 4)).toBe('20000 ms'); }); }); describe('toBytes', () => { it('should not convert wrong values', () => { expect(service.toBytes('10xyz')).toBeNull(); expect(service.toBytes('1.1.1KiB')).toBeNull(); expect(service.toBytes('1.1 KiloByte')).toBeNull(); expect(service.toBytes('1.1 kib')).toBeNull(); expect(service.toBytes('1.kib')).toBeNull(); expect(service.toBytes('1 ki')).toBeNull(); expect(service.toBytes(undefined)).toBeNull(); expect(service.toBytes('')).toBeNull(); expect(service.toBytes('-')).toBeNull(); expect(service.toBytes(null)).toBeNull(); }); it('should convert values to bytes', () => { expect(service.toBytes('4815162342')).toBe(4815162342); expect(service.toBytes('100M')).toBe(104857600); expect(service.toBytes('100 M')).toBe(104857600); expect(service.toBytes('100 mIb')).toBe(104857600); expect(service.toBytes('100 mb')).toBe(104857600); expect(service.toBytes('100MIB')).toBe(104857600); expect(service.toBytes('1.532KiB')).toBe(Math.round(1.532 * 1024)); expect(service.toBytes('0.000000000001TiB')).toBe(1); }); it('should convert values to human readable again', () => { convertToBytesAndBack('1.1 MiB'); convertToBytesAndBack('1.0MiB', '1 MiB'); convertToBytesAndBack('8.9 GiB'); convertToBytesAndBack('123.5 EiB'); }); }); });
4,756
41.097345
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/formatter.service.ts
import { Injectable } from '@angular/core'; import _ from 'lodash'; @Injectable({ providedIn: 'root' }) export class FormatterService { format_number(n: any, divisor: number, units: string[], decimals: number = 1): string { if (_.isString(n)) { n = Number(n); } if (!_.isNumber(n)) { return '-'; } if (_.isNaN(n)) { return 'N/A'; } let unit = n < 1 ? 0 : Math.floor(Math.log(n) / Math.log(divisor)); unit = unit >= units.length ? units.length - 1 : unit; let result = _.round(n / Math.pow(divisor, unit), decimals).toString(); if (result === '') { return '-'; } if (units[unit] !== '') { result = `${result} ${units[unit]}`; } return result; } /** * Converts a value from one set of units to another using a conversion factor * @param n The value to be converted * @param units The data units of the value * @param targetedUnits The wanted data units to convert to * @param conversionFactor The factor of convesion * @param unitsArray An ordered array containing the data units * @param decimals The number of decimals on the returned value * @returns Returns a string of the given value formated to the targeted data units. */ formatNumberFromTo( n: any, units: any, targetedUnits: string, conversionFactor: number, unitsArray: string[], decimals: number = 1 ): string { if (_.isString(n)) { n = Number(n); } if (!_.isNumber(n)) { return '-'; } const unitsArrayLowerCase = unitsArray.map((str) => str.toLowerCase()); if ( !unitsArrayLowerCase.includes(units.toLowerCase()) || !unitsArrayLowerCase.includes(targetedUnits.toLowerCase()) ) { return `${n} ${units}`; } const index = unitsArrayLowerCase.indexOf(units.toLowerCase()) - unitsArrayLowerCase.indexOf(targetedUnits.toLocaleLowerCase()); const convertedN = index > 0 ? n * Math.pow(conversionFactor, index) : n / Math.pow(conversionFactor, Math.abs(index)); let result = _.round(convertedN, decimals).toString(); result = `${result} ${targetedUnits}`; return result; } /** * Convert the given value into bytes. * @param {string} value The value to be converted, e.g. 1024B, 10M, 300KiB or 1ZB. * @param error_value The value returned in case the regular expression did not match. Defaults to * null. * @returns Returns the given value in bytes without any unit appended or the defined error value * in case xof an error. */ toBytes(value: string, error_value: number = null): number | null { const base = 1024; const units = ['b', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y']; const m = RegExp('^(\\d+(.\\d+)?) ?([' + units.join('') + ']?(b|ib|B/s)?)?$', 'i').exec(value); if (m === null) { return error_value; } let bytes = parseFloat(m[1]); if (_.isString(m[3])) { bytes = bytes * Math.pow(base, units.indexOf(m[3].toLowerCase()[0])); } return Math.round(bytes); } /** * Converts `x ms` to `x` (currently) or `0` if the conversion fails */ toMilliseconds(value: string): number { const pattern = /^\s*(\d+)\s*(ms)?\s*$/i; const testResult = pattern.exec(value); if (testResult !== null) { return +testResult[1]; } return 0; } /** * Converts `x IOPS` to `x` (currently) or `0` if the conversion fails */ toIops(value: string): number { const pattern = /^\s*(\d+)\s*(IOPS)?\s*$/i; const testResult = pattern.exec(value); if (testResult !== null) { return +testResult[1]; } return 0; } }
3,695
28.806452
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/js-error-handler.service.ts
import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { Router } from '@angular/router'; import { DashboardError } from '~/app/core/error/error'; import { LoggingService } from '../api/logging.service'; @Injectable() export class JsErrorHandler implements ErrorHandler { constructor(private injector: Injector, private router: Router) {} handleError(error: any) { const loggingService = this.injector.get(LoggingService); const url = window.location.href; const message = error && error.message; const stack = error && error.stack; loggingService.jsError(url, message, stack).subscribe(); if (error.rejection instanceof DashboardError) { setTimeout( () => this.router.navigate(['error'], { state: { message: error.rejection.message, header: error.rejection.header, icon: error.rejection.icon } }), 50 ); } else { throw error; } } }
1,014
28.852941
68
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/language.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { LanguageService } from './language.service'; describe('LanguageService', () => { let service: LanguageService; let httpTesting: HttpTestingController; configureTestBed({ providers: [LanguageService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(LanguageService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call create', () => { service.getLanguages().subscribe(); const req = httpTesting.expectOne('ui-api/langs'); expect(req.request.method).toBe('GET'); }); });
919
25.285714
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/services/language.service.ts
import { HttpClient } from '@angular/common/http'; import { Inject, Injectable, LOCALE_ID } from '@angular/core'; import { environment } from '~/environments/environment'; @Injectable({ providedIn: 'root' }) export class LanguageService { constructor(private http: HttpClient, @Inject(LOCALE_ID) protected localeId: string) {} getLocale(): string { return this.localeId || environment.default_lang; } setLocale(lang: string) { document.cookie = `cd-lang=${lang}`; } getLanguages() { return this.http.get<string[]>('ui-api/langs'); } }
568
22.708333
89
ts