1 import { LOCALE_ID, TRANSLATIONS, TRANSLATIONS_FORMAT } from '@angular/core';
2 import { async, ComponentFixture, TestBed } from '@angular/core/testing';
3 import { AbstractControl } from '@angular/forms';
4 import { By } from '@angular/platform-browser';
6 import { I18n } from '@ngx-translate/i18n-polyfill';
7 import * as _ from 'lodash';
9 import { TableActionsComponent } from '../app/shared/datatable/table-actions/table-actions.component';
10 import { CdFormGroup } from '../app/shared/forms/cd-form-group';
11 import { Permission } from '../app/shared/models/permissions';
14 AlertmanagerNotification,
15 AlertmanagerNotificationAlert,
17 } from '../app/shared/models/prometheus-alerts';
18 import { _DEV_ } from '../unit-test-configuration';
20 export function configureTestBed(configuration, useOldMethod?) {
21 if (_DEV_ && !useOldMethod) {
22 const resetTestingModule = TestBed.resetTestingModule;
25 TestBed.resetTestingModule();
26 TestBed.configureTestingModule(configuration);
27 // prevent Angular from resetting testing module
28 TestBed.resetTestingModule = () => TestBed;
34 TestBed.resetTestingModule = resetTestingModule;
37 beforeEach(async(() => {
38 TestBed.configureTestingModule(configuration);
43 export class PermissionHelper {
44 tableActions: TableActionsComponent;
45 permission: Permission;
46 getTableActionComponent: () => TableActionsComponent;
48 constructor(permission: Permission, getTableActionComponent: () => TableActionsComponent) {
49 this.permission = permission;
50 this.getTableActionComponent = getTableActionComponent;
53 setPermissionsAndGetActions(
54 createPerm: number | boolean,
55 updatePerm: number | boolean,
56 deletePerm: number | boolean
57 ): TableActionsComponent {
58 this.permission.create = Boolean(createPerm);
59 this.permission.update = Boolean(updatePerm);
60 this.permission.delete = Boolean(deletePerm);
61 this.tableActions = this.getTableActionComponent();
62 return this.tableActions;
65 // Overwrite if needed
66 createSelection(): object {
80 singleExecuting?: any; // uses 'single' if not defined
81 multiple?: any; // uses 'empty' if not defined
84 // 'multiple selections'
85 [this.createSelection(), this.createSelection()],
87 _.isUndefined(multiple) ? empty : multiple
89 const executing = this.createSelection();
90 executing['cdExecuting'] = 'someAction';
92 // 'select executing item'
95 _.isUndefined(singleExecuting) ? single : singleExecuting
97 this.testScenario([this.createSelection()], fn, single); // 'select non-executing item'
98 this.testScenario([], fn, empty); // 'no selection'
101 private testScenario(selection: object[], fn: () => any, expected: any) {
102 this.setSelection(selection);
103 expect(fn()).toBe(expected);
106 setSelection(selection: object[]) {
107 this.tableActions.selection.selected = selection;
108 this.tableActions.selection.update();
112 export class FormHelper {
115 constructor(form: CdFormGroup) {
120 * Changes multiple values in multiple controls
122 setMultipleValues(values: { [controlName: string]: any }, markAsDirty?: boolean) {
123 Object.keys(values).forEach((key) => {
124 this.setValue(key, values[key], markAsDirty);
129 * Changes the value of a control
131 setValue(control: AbstractControl | string, value: any, markAsDirty?: boolean): AbstractControl {
132 control = this.getControl(control);
134 control.markAsDirty();
136 control.setValue(value);
140 private getControl(control: AbstractControl | string): AbstractControl {
141 if (typeof control === 'string') {
142 return this.form.get(control);
148 * Change the value of the control and expect the control to be valid afterwards.
150 expectValidChange(control: AbstractControl | string, value: any, markAsDirty?: boolean) {
151 this.expectValid(this.setValue(control, value, markAsDirty));
155 * Expect that the given control is valid.
157 expectValid(control: AbstractControl | string) {
158 // 'isValid' would be false for disabled controls
159 expect(this.getControl(control).errors).toBe(null);
163 * Change the value of the control and expect a specific error.
166 control: AbstractControl | string,
169 markAsDirty?: boolean
171 this.expectError(this.setValue(control, value, markAsDirty), error);
175 * Expect a specific error for the given control.
177 expectError(control: AbstractControl | string, error: string) {
178 expect(this.getControl(control).hasError(error)).toBeTruthy();
182 export class FixtureHelper {
183 fixture: ComponentFixture<any>;
185 constructor(fixture: ComponentFixture<any>) {
186 this.fixture = fixture;
190 * Expect a list of id elements to be visible or not.
192 expectIdElementsVisible(ids: string[], visibility: boolean) {
193 ids.forEach((css) => {
194 this.expectElementVisible(`#${css}`, visibility);
199 * Expect a specific element to be visible or not.
201 expectElementVisible(css: string, visibility: boolean) {
202 expect(Boolean(this.getElementByCss(css))).toBe(visibility);
205 expectFormFieldToBe(css: string, value: string) {
206 const props = this.getElementByCss(css).properties;
207 expect(props['value'] || props['checked'].toString()).toBe(value);
210 clickElement(css: string) {
211 this.getElementByCss(css).triggerEventHandler('click', null);
212 this.fixture.detectChanges();
215 getText(css: string) {
216 const e = this.getElementByCss(css);
217 return e ? e.nativeElement.textContent.trim() : null;
220 getElementByCss(css: string) {
221 this.fixture.detectChanges();
222 return this.fixture.debugElement.query(By.css(css));
226 export class PrometheusHelper {
230 createdBy: `Creator of ${id}`,
231 comment: `A comment for ${id}`,
232 startsAt: new Date('2022-02-22T22:22:00').toISOString(),
233 endsAt: new Date('2022-02-23T22:22:00').toISOString(),
244 createRule(name, severity, alerts: any[]): PrometheusRule {
254 createAlert(name, state = 'active', timeMultiplier = 1): AlertmanagerAlert {
260 instance: 'someInstance',
262 severity: 'someSeverity'
265 summary: `${name} is ${state}`
267 generatorURL: `http://${name}`,
268 startsAt: new Date(new Date('2022-02-22').getTime() * timeMultiplier).toString()
269 } as AlertmanagerAlert;
272 createNotificationAlert(name, status = 'firing'): AlertmanagerNotificationAlert {
279 summary: `${name} is ${status}`
281 generatorURL: `http://${name}`
282 } as AlertmanagerNotificationAlert;
285 createNotification(alertNumber = 1, status = 'firing'): AlertmanagerNotification {
287 for (let i = 0; i < alertNumber; i++) {
288 alerts.push(this.createNotificationAlert('alert' + i, status));
290 return { alerts, status } as AlertmanagerNotification;
294 return `<a href="${url}" target="_blank"><i class="fa fa-line-chart"></i></a>`;
298 const XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
299 <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
300 <file source-language="en" datatype="plaintext" original="ng2.template">
307 const i18nProviders = [
308 { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
309 { provide: TRANSLATIONS, useValue: XLIFF },
310 { provide: LOCALE_ID, useValue: 'en' },
314 export { i18nProviders };