repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
yegobox/kraken
frontend/projects/storage/src/lib/storage-dialogs/delete-files-dialog/delete-files-dialog.component.spec.ts
<gh_stars>1-10 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {DeleteFilesDialogComponent} from './delete-files-dialog.component'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material'; import {dialogRefSpy} from 'projects/commons/src/lib/mock/material.mock.spec'; import {testStorageNodes} from 'projects/storage/src/lib/entities/storage-node.spec'; describe('DeleteFilesDialogComponent', () => { let component: DeleteFilesDialogComponent; let fixture: ComponentFixture<DeleteFilesDialogComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [DeleteFilesDialogComponent], providers: [ {provide: MAT_DIALOG_DATA, useValue: {nodes: testStorageNodes()}}, {provide: MatDialogRef, useValue: dialogRefSpy()}, ] }) .overrideTemplate(DeleteFilesDialogComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DeleteFilesDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(component.directoriesCount).toBe(6); expect(component.filesCount).toBe(7); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/buttons/edit-node-button/edit-node-button.component.spec.ts
<gh_stars>1-10 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {EditNodeButtonComponent} from './edit-node-button.component'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; describe('EditNodeButtonComponent', () => { let component: EditNodeButtonComponent; let fixture: ComponentFixture<EditNodeButtonComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [EditNodeButtonComponent], providers: [ {provide: StorageService, useValue: storageServiceSpy()} ] }) .overrideTemplate(EditNodeButtonComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(EditNodeButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/administration/src/app/workspace/workspace.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {WorkspaceRoutingModule} from './workspace-routing.module'; import {WorkspaceComponent} from './workspace/workspace.component'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {WorkspacesModule} from 'projects/workspaces/src/lib/workspaces.module'; import {NotificationModule} from 'projects/notification/src/lib/notification.module'; import {HelpModule} from 'projects/help/src/lib/help.module'; import {StorageModule} from 'projects/storage/src/lib/storage.module'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import {NotificationService} from 'projects/notification/src/lib/notification.service'; import {TabsService} from 'projects/tabs/src/lib/tabs.service'; import {RuntimeHostModule} from 'projects/runtime/src/lib/runtime-host/runtime-host.module'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; @NgModule({ declarations: [ WorkspaceComponent, ], imports: [ CommonModule, WorkspaceRoutingModule, ComponentsModule, VendorsModule, WorkspacesModule, NotificationModule, HelpModule, IconModule, StorageModule.forRoot( 'administration-storage', [] ), RuntimeHostModule, ], providers: [ NotificationService, TabsService, RuntimeHostService, ], }) export class WorkspaceModule { constructor(tabsService: TabsService, hostService: RuntimeHostService) { // inject services to force initialization hostService.hosts().subscribe(); } }
yegobox/kraken
frontend/projects/analysis/src/lib/analysis.module.ts
import {NgModule} from '@angular/core'; import {HTTP_INTERCEPTORS} from '@angular/common/http'; import {AnalysisApplicationIdService} from 'projects/analysis/src/lib/analysis-application-id.service'; @NgModule({ providers: [ {provide: HTTP_INTERCEPTORS, useClass: AnalysisApplicationIdService, multi: true}, ] }) export class AnalysisModule { }
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/buttons/menu-node-button/menu-node-button.component.spec.ts
<gh_stars>1-10 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {MenuNodeButtonComponent} from './menu-node-button.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; describe('MenuNodeButtonComponent', () => { let component: MenuNodeButtonComponent; let fixture: ComponentFixture<MenuNodeButtonComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [MenuNodeButtonComponent], providers: [ {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()} ] }) .overrideTemplate(MenuNodeButtonComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MenuNodeButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/workspaces/src/lib/workspace.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {WorkspaceComponent} from './workspace.component'; import {Component, NgModule} from '@angular/core'; import {WorkspacesModule} from './workspaces.module'; import {ComponentPortal} from '@angular/cdk/portal'; import {EMPTY_SIDE_CONFIG, SideConfiguration} from './side-configuration'; import {TabsConfiguration} from './tabs-configuration'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {newTestTab} from 'projects/tabs/src/lib/tab-header/tab-header.component.spec'; @Component({ selector: 'lib-test', template: `test` }) class TestComponent { } @NgModule({ imports: [CoreTestModule, WorkspacesModule], declarations: [TestComponent], entryComponents: [ TestComponent, ], }) class TestModule { } describe('WorkspaceComponent', () => { let component: WorkspaceComponent; let fixture: ComponentFixture<WorkspaceComponent>; const tabsConf = new TabsConfiguration( [newTestTab(TestComponent)], 0, 50 ); const sideConf = new SideConfiguration( tabsConf, tabsConf, 20, ); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [TestModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(WorkspaceComponent); component = fixture.componentInstance; }); it('should create with all sides', () => { component.center = new ComponentPortal(TestComponent); component.centerMinWidth = 40; component.centerMinHeight = 40; component.left = sideConf; component.right = sideConf; component.bottom = sideConf; fixture.detectChanges(); expect(component).toBeTruthy(); expect(component.verticalSplits.length).toBe(2); expect(component.horizontalSplits.length).toBe(3); }); it('should create no bottom', () => { component.center = new ComponentPortal(TestComponent); component.left = sideConf; component.right = sideConf; component.bottom = EMPTY_SIDE_CONFIG; fixture.detectChanges(); expect(component).toBeTruthy(); expect(component.verticalSplits.length).toBe(1); expect(component.horizontalSplits.length).toBe(3); }); it('should create no right', () => { component.center = new ComponentPortal(TestComponent); component.left = sideConf; component.right = EMPTY_SIDE_CONFIG; component.bottom = sideConf; fixture.detectChanges(); expect(component).toBeTruthy(); expect(component.verticalSplits.length).toBe(2); expect(component.horizontalSplits.length).toBe(2); }); it('should create no right', () => { component.center = new ComponentPortal(TestComponent); component.left = EMPTY_SIDE_CONFIG; component.right = sideConf; component.bottom = sideConf; fixture.detectChanges(); expect(component).toBeTruthy(); expect(component.verticalSplits.length).toBe(2); expect(component.horizontalSplits.length).toBe(2); }); it('should create only bottom', () => { component.center = new ComponentPortal(TestComponent); component.left = EMPTY_SIDE_CONFIG; component.right = EMPTY_SIDE_CONFIG; component.bottom = sideConf; fixture.detectChanges(); expect(component).toBeTruthy(); expect(component.verticalSplits.length).toBe(2); expect(component.horizontalSplits.length).toBe(1); }); describe('with all tabs', () => { beforeEach(() => { component.center = new ComponentPortal(TestComponent); component.left = sideConf; component.right = sideConf; component.bottom = sideConf; fixture.detectChanges(); }); it('should bottomPaneExpanded', () => { const spy = spyOn(component.verticalSplit, 'show'); component.bottomPaneExpanded(); expect(spy).toHaveBeenCalledWith(1); }); it('should bottomPaneCollapsed', () => { const spy = spyOn(component.verticalSplit, 'hide'); component.bottomPaneCollapsed(); expect(spy).toHaveBeenCalledWith(1); }); it('should bottomPaneHidden', () => { const spy = spyOn(component.bottomSideSplit, 'closeTabs'); component.bottomPaneHidden(); expect(spy).toHaveBeenCalled(); }); it('should bottomPaneHidden', () => { const spy = spyOn(component.bottomSideSplit, 'closeTabs'); component.bottomPaneHidden(); expect(spy).toHaveBeenCalled(); }); it('should leftPaneExpanded', () => { const spy = spyOn(component.horizontalSplit, 'show'); component.leftPaneExpanded(); expect(spy).toHaveBeenCalledWith(0); }); it('should leftPaneCollapsed', () => { const spy = spyOn(component.horizontalSplit, 'hide'); component.leftPaneCollapsed(); expect(spy).toHaveBeenCalledWith(0); }); it('should rightPaneExpanded', () => { const spy = spyOn(component.horizontalSplit, 'show'); component.rightPaneExpanded(); expect(spy).toHaveBeenCalledWith(2); }); it('should rightPaneCollapsed', () => { const spy = spyOn(component.horizontalSplit, 'hide'); component.rightPaneCollapsed(); expect(spy).toHaveBeenCalledWith(2); }); it('should leftRightPaneHidden left', () => { const spy = spyOn(component.leftSideSplit, 'closeTabs'); component.leftRightPaneHidden([0, null]); expect(spy).toHaveBeenCalled(); }); it('should leftRightPaneHidden right', () => { const spy = spyOn(component.rightSideSplit, 'closeTabs'); component.leftRightPaneHidden([2, null]); expect(spy).toHaveBeenCalled(); }); it('should leftRightPaneHidden kamoulox', () => { component.leftRightPaneHidden([42, null]); expect().nothing(); }); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/hosts-table/hosts-table.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {HostsTableComponent} from './hosts-table.component'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {runtimeHostServiceSpy} from 'projects/runtime/src/lib/runtime-host/runtime-host.service.spec'; import {of} from 'rxjs'; import SpyObj = jasmine.SpyObj; import {testHosts} from 'projects/runtime/src/lib/entities/host.spec'; describe('HostsTableComponent', () => { let component: HostsTableComponent; let fixture: ComponentFixture<HostsTableComponent>; let hostService: SpyObj<RuntimeHostService>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [CoreTestModule], declarations: [HostsTableComponent], providers: [ {provide: RuntimeHostService, useValue: runtimeHostServiceSpy()}, ] }) .overrideTemplate(HostsTableComponent, '') .compileComponents(); hostService = TestBed.get(RuntimeHostService); })); beforeEach(() => { fixture = TestBed.createComponent(HostsTableComponent); component = fixture.componentInstance; fixture.detectChanges(); }); afterEach(() => { component.ngOnDestroy(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should init', () => { spyOn(component, 'refresh'); component.ngOnInit(); expect(component.refresh).toHaveBeenCalled(); }); it('should refresh', () => { hostService.hosts.and.returnValue(of(testHosts())); component.refresh(); expect(component.loading).toBe(true); expect(hostService.hosts).toHaveBeenCalled(); }); it('should set images', () => { const hosts = testHosts(); hostService.hostsSubject.next(hosts); expect(component.dataSource.data).toBe(hosts); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-editor/storage-node-tab-header/storage-node-tab-header.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {StorageNodeTabHeaderComponent} from './storage-node-tab-header.component'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import {CloseTabsEvent} from 'projects/tabs/src/lib/close-tabs-event'; describe('StorageNodeTabHeaderComponent', () => { let component: StorageNodeTabHeaderComponent; let fixture: ComponentFixture<StorageNodeTabHeaderComponent>; let eventBus: EventBusService; beforeEach(async(() => { eventBus = eventBusSpy(); TestBed.configureTestingModule({ declarations: [StorageNodeTabHeaderComponent], providers: [ {provide: EventBusService, useValue: eventBus}, ] }) .overrideTemplate(StorageNodeTabHeaderComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(StorageNodeTabHeaderComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should expand', () => { component.expand(); expect(eventBus.publish).toHaveBeenCalledWith(new CloseTabsEvent()); }); });
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-editor/simulation-editor.component.ts
<filename>frontend/projects/gatling/src/app/simulations/simulation-editor/simulation-editor.component.ts import {Component, Inject} from '@angular/core'; import {StorageNodeEditorContentService} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service'; import {DefaultStorageNodeEditorComponent} from 'projects/storage/src/lib/storage-editor/storage-node-editors/default-storage-node-editor/default-storage-node-editor.component'; import {DEBUG_ICON, PLAY_ICON} from 'projects/icon/src/lib/icons'; import {STORAGE_NODE} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service'; import {GatlingVariablesAutoCompleter} from 'projects/gatling/src/app/simulations/simulation-editor/completion/gatling-variables-auto-completer'; @Component({ selector: 'app-simulation-editor', templateUrl: './simulation-editor.component.html', styleUrls: ['./simulation-editor.component.scss'], providers: [ StorageNodeEditorContentService, GatlingVariablesAutoCompleter, ] }) export class SimulationEditorComponent extends DefaultStorageNodeEditorComponent { public readonly runIcon = PLAY_ICON; public readonly debugIcon = DEBUG_ICON; constructor(@Inject(STORAGE_NODE) node: StorageNode, contentService: StorageNodeEditorContentService, private simulation: SimulationService, private autoCompleter: GatlingVariablesAutoCompleter) { super(node, contentService); } }
yegobox/kraken
frontend/projects/analysis/src/lib/results/debug/debug-editor/debug-editor.component.spec.ts
<reponame>yegobox/kraken<gh_stars>0 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {DebugEditorComponent} from 'projects/analysis/src/lib/results/debug/debug-editor/debug-editor.component'; import {DebugEditorContentService} from 'projects/analysis/src/lib/results/debug/debug-editor/debug-editor-content.service'; import {debugEditorContentServiceSpy} from 'projects/analysis/src/lib/results/debug/debug-editor/debug-editor-content.service.spec'; import {StorageNodeEditorContentService} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service'; import {STORAGE_NODE} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor'; import {testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import SpyObj = jasmine.SpyObj; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; import {dialogsServiceSpy} from 'projects/dialog/src/lib/dialog.service.spec'; import {testDebugEntry} from 'projects/analysis/src/lib/results/debug/debug-entries-table/debug-entries-table.service.spec'; describe('DebugEditorComponent', () => { let component: DebugEditorComponent; let fixture: ComponentFixture<DebugEditorComponent>; let debug: SpyObj<DebugEditorContentService>; let dialogs: SpyObj<DialogService>; beforeEach(async(() => { debug = debugEditorContentServiceSpy(); dialogs = dialogsServiceSpy(); TestBed.configureTestingModule({ declarations: [DebugEditorComponent], providers: [ {provide: StorageNodeEditorContentService, useValue: debug}, {provide: STORAGE_NODE, useValue: testStorageFileNode()}, {provide: DialogService, useValue: dialogs} ] }) .overrideProvider(StorageNodeEditorContentService, {useValue: debug}) .overrideTemplate(DebugEditorComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DebugEditorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(component.debug).toBeTruthy(); expect(component.splits).toBeTruthy(); }); it('inspectSession create', () => { component.debug = {entry: testDebugEntry()} as any; component.inspectSession(); expect(dialogs.inspect).toHaveBeenCalledWith('Gatling Session', 'session'); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/runtime-host.module.ts
import {NgModule} from '@angular/core'; import {HostsTableComponent} from 'projects/runtime/src/lib/runtime-host/hosts-table/hosts-table.component'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {CapacityToStringPipe} from './capacity-to-string.pipe'; import {AddressesToStringPipe} from './addresses-to-string.pipe'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import {HostIdToNamePipe} from './host-id-to-name.pipe'; import {HostIdToDescriptionPipe} from './host-id-to-description.pipe'; import {PrettyStringPipe} from 'projects/tools/src/lib/pretty-string.pipe'; import {HostsSelectorComponent} from 'projects/runtime/src/lib/runtime-host/hosts-selector/hosts-selector.component'; import {CommonModule} from '@angular/common'; import {EnvironmentVariablesListComponent} from './environment-variables-list/environment-variables-list.component'; @NgModule({ imports: [ CommonModule, ComponentsModule, VendorsModule, IconModule, ], declarations: [ HostsSelectorComponent, HostsTableComponent, CapacityToStringPipe, AddressesToStringPipe, HostIdToNamePipe, HostIdToDescriptionPipe, EnvironmentVariablesListComponent, ], exports: [ HostsTableComponent, HostsSelectorComponent, HostIdToNamePipe, HostIdToDescriptionPipe, EnvironmentVariablesListComponent, ], entryComponents: [ HostsTableComponent, ], providers: [ PrettyStringPipe, CapacityToStringPipe, AddressesToStringPipe, HostIdToNamePipe, HostIdToDescriptionPipe, ] }) export class RuntimeHostModule { }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-watcher/runtime-watcher.service.ts
import {Injectable, OnDestroy} from '@angular/core'; import {Observer, Subscription} from 'rxjs'; import {Retry} from 'projects/tools/src/lib/retry'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {EventSourceService} from 'projects/tools/src/lib/event-source.service'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import {HttpClient} from '@angular/common/http'; import {RetriesService} from 'projects/tools/src/lib/retries.service'; import {DurationToStringPipe} from 'projects/date/src/lib/duration-to-string.pipe'; import {NotificationEvent} from 'projects/notification/src/lib/notification-event'; import {BaseNotification} from 'projects/notification/src/lib/base-notification'; import {NotificationLevel} from 'projects/notification/src/lib/notification-level'; import {RuntimeConfigurationService} from 'projects/runtime/src/lib/runtime-configuration.service'; import {SSEWrapper} from 'projects/tools/src/lib/sse-wrapper'; import {LogEvent} from 'projects/runtime/src/lib/events/log-event'; import {TasksRefreshEvent} from 'projects/runtime/src/lib/events/tasks-refresh-event'; @Injectable() export class RuntimeWatcherService implements OnDestroy, Observer<SSEWrapper> { private sseUnwrappers = { LOG: (sseWrapper: SSEWrapper) => new LogEvent(sseWrapper.value), TASKS: (sseWrapper: SSEWrapper) => new TasksRefreshEvent(sseWrapper.value), }; _eventSourceSubscription: Subscription; _retry: Retry; closed = false; constructor(private eventBus: EventBusService, private eventSourceService: EventSourceService, private configuration: ConfigurationService, private runtimeConfiguration: RuntimeConfigurationService, private http: HttpClient, retries: RetriesService, private durationToString: DurationToStringPipe) { this._retry = retries.get(); this.watch(); } ngOnDestroy() { if (this._eventSourceSubscription) { this._eventSourceSubscription.unsubscribe(); } this.closed = true; } watch() { if (this._eventSourceSubscription) { this._eventSourceSubscription.unsubscribe(); } // ApplicationId Header cannot be used here as it is not supported by SSE this._eventSourceSubscription = this.eventSourceService .newObservable(this.runtimeConfiguration.runtimeApiUrl(`/watch/${this.configuration.applicationId}`), {converter: JSON.parse}) .subscribe(this); } next(sseWrapper: SSEWrapper) { this._retry.reset(); this.eventBus.publish(this.sseUnwrappers[sseWrapper.type](sseWrapper)); } error(err: any) { const delay = this._retry.getDelay(); this.eventBus.publish(new NotificationEvent( new BaseNotification( `An error occurred while listening for runtime events. Will reconnect in ${this.durationToString.transform(delay)}.`, NotificationLevel.ERROR))); if (!this.closed) { setTimeout(this.watch.bind(this), delay); } } complete() { this.error(null); } }
yegobox/kraken
frontend/projects/notification/src/lib/notifications-tab-header/notifications-tab-header.component.ts
import {Component, Inject, OnInit} from '@angular/core'; import {SIDE_HEADER_DATA, TAB_HEADER_DATA, TabHeaderComponent} from 'projects/tabs/src/lib/tab-header/tab-header.component'; import {TabsSide} from 'projects/tabs/src/lib/tabs-side'; import {NotificationService} from 'projects/notification/src/lib/notification.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {TabsService} from 'projects/tabs/src/lib/tabs.service'; import {IconFaCounter} from 'projects/icon/src/lib/icon-fa-counter'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {Tab} from 'projects/tabs/src/lib/tab'; @Component({ selector: 'lib-notifications-tab-header', templateUrl: './notifications-tab-header.component.html', styleUrls: ['./notifications-tab-header.component.scss'] }) export class NotificationsTabHeaderComponent extends TabHeaderComponent implements OnInit { public icon: IconFaCounter; constructor(@Inject(TAB_HEADER_DATA) tab: Tab, @Inject(SIDE_HEADER_DATA) side: TabsSide, tabsService: TabsService, eventBus: EventBusService, public notificationsService: NotificationService) { super(tab, side, tabsService, eventBus); } ngOnInit() { this.icon = new IconFaCounter(this.tab.icon as IconFa, '', 'error'); this.notificationsService.notificationsSubject.subscribe(() => { this.icon.content = `${Math.min(this.notificationsService.count, 99)}`; }); } }
yegobox/kraken
frontend/projects/workspaces/src/lib/side-split/side-split.component.ts
import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core'; import {Portal} from '@angular/cdk/portal'; import {TabsContentComponent} from 'projects/tabs/src/lib/tabs-content/tabs-content.component'; import {SplitPanesComponent} from 'projects/split/src/lib/split-panes/split-panes.component'; import {TabsSide} from 'projects/tabs/src/lib/tabs-side'; import {SideConfiguration} from 'projects/workspaces/src/lib/side-configuration'; import {TabsConfiguration} from 'projects/workspaces/src/lib/tabs-configuration'; import {SplitDirection} from 'projects/split/src/lib/split-direction'; import {SplitPane} from 'projects/split/src/lib/split-pane'; import {TabsPosition} from 'projects/tabs/src/lib/tabs-position'; import {Tab} from 'projects/tabs/src/lib/tab'; @Component({ selector: 'lib-side-split', templateUrl: './side-split.component.html', styleUrls: ['./side-split.component.scss'] }) export class SideSplitComponent implements OnInit { // Tabs portals @ViewChild('startTabsPortal', { static: true }) startTabsPortal: Portal<any>; @ViewChild('endTabsPortal', { static: true }) endTabsPortal: Portal<any>; // Tabs @ViewChild('startTabsContent', { static: false }) startTabsContent: TabsContentComponent; @ViewChild('endTabsContent', { static: false }) endTabsContent: TabsContentComponent; // Splits @ViewChild('split', { static: true }) split: SplitPanesComponent; @Input() id: string; @Input() side: TabsSide; @Input() config: SideConfiguration; @Output() collapse = new EventEmitter<void>(); @Output() expand = new EventEmitter<void>(); start: TabsConfiguration; end: TabsConfiguration; direction: SplitDirection; startTabsIndex = -1; endTabsIndex = -1; splits: SplitPane[] = []; constructor() { } ngOnInit() { const sideHandlers = {}; sideHandlers[TabsSide.TOP] = () => this.direction = 'horizontal'; sideHandlers[TabsSide.RIGHT] = () => this.direction = 'vertical'; sideHandlers[TabsSide.BOTTOM] = () => this.direction = 'horizontal'; sideHandlers[TabsSide.LEFT] = () => this.direction = 'vertical'; sideHandlers[this.side](); this.start = this.config.start; this.end = this.config.end; if (!this.start.empty) { this.startTabsIndex = 0; this.splits.push(this.start.toSplitPane(this.startTabsPortal, this.end)); } if (!this.end.empty) { this.endTabsIndex = this.startTabsIndex + 1; this.splits.push(this.end.toSplitPane(this.endTabsPortal, this.start)); } } tabUnselected(position: TabsPosition) { if (position === TabsPosition.START) { this.split.hide(this.startTabsIndex); } else { this.split.hide(this.endTabsIndex); } if (!this.startTabsSelected && !this.endTabsSelected) { this.collapse.emit(); } } tabSelected(position: TabsPosition, $event: [number, Tab]) { if (position === TabsPosition.START) { this.split.show(this.startTabsIndex); if (!this.endTabsSelected) { this.split.hide(this.endTabsIndex); } } else { this.split.show(this.endTabsIndex); if (!this.startTabsSelected) { this.split.hide(this.startTabsIndex); } } this.expand.emit(); } paneHidden($event: [number, SplitPane]) { if ($event[0] === this.startTabsIndex) { this.startTabsContent.unselectTab(); } else if ($event[0] === this.endTabsIndex) { this.endTabsContent.unselectTab(); } } paneShown($event: [number, SplitPane]) { // Nothing to do } closeTabs() { if (this.startTabsContent) { this.startTabsContent.unselectTab(); } if (this.endTabsContent) { this.endTabsContent.unselectTab(); } } get startTabsSelected(): boolean { return this.startTabsContent && this.startTabsContent.hasSelectedTab(); } get endTabsSelected(): boolean { return this.endTabsContent && this.endTabsContent.hasSelectedTab(); } }
yegobox/kraken
frontend/projects/commons/src/lib/config/application-id-header-interceptor.service.ts
<filename>frontend/projects/commons/src/lib/config/application-id-header-interceptor.service.ts<gh_stars>1-10 import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; import {Observable} from 'rxjs'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import * as _ from 'lodash'; export class ApplicationIdHeaderInterceptor implements HttpInterceptor { constructor(private configuration: ConfigurationService, private url: () => string[]) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (_.findIndex(this.url(), url => _.includes(request.url, url)) !== -1) { const withApp = request.clone({ headers: request.headers.set('ApplicationId', this.configuration.applicationId) }); return next.handle(withApp); } return next.handle(request); } }
yegobox/kraken
frontend/projects/tools/src/lib/window.service.ts
import * as _ from 'lodash'; import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class WindowService { window = window; _resizeDebounced = _.debounce(this._resize.bind(this), 50, {'maxWait': 1000}); resize() { this._resizeDebounced(); } resizeNow() { setTimeout(this._resize.bind(this)); } _resize() { this.window.dispatchEvent(new Event('resize')); } open(url: Observable<string>) { const tab = this.window.open(); url.subscribe((tabLocation) => tab.location.href = tabLocation, () => tab.close()); } }
yegobox/kraken
frontend/projects/help/src/lib/help-panel/help-page-id.ts
export type HelpPageId = 'HOME' | 'TEST' | 'EDITOR_MARKDOWN' | 'EDITOR_GATLING' | 'EDITOR_DEBUG' | 'ADMIN_FILE_EDITOR' | 'administration-storage' | 'resources-tree' | 'simulations-tree' | 'GATLING_IMPORT_HAR' | 'GATLING_DEBUG_DIALOG' | 'GATLING_COMPARE_DEBUG' | 'GATLING_RUN_DIALOG' | 'ADMIN_CREATE_FILE' | 'ADMIN_DELETE_FILE' | 'ADMIN_DELETE_CONTAINER' | 'ADMIN_DELETE_IMAGE' | 'ADMIN_UPLOAD_FILE' | 'ADMIN_DOWNLOAD_FILE' | 'ADMIN_RUN_CONTAINER' | 'ADMIN_INSPECT_CONTAINER' | 'ADMIN_INSPECT_IMAGE' | 'ADMIN_PULL_IMAGE' | 'ADMIN_RUN_SCRIPT' | 'ADMIN_RUN_COMMAND' | 'ADMIN_CONFIGURATION' | 'GATLING_RESOURCES' | 'GATLING_SIMULATIONS' | 'GATLING_EXECUTIONS' | 'GATLING_RESULT_LIST' | 'GATLING_DEBUG_LIST' | 'ADMIN_CONTAINERS' | 'ADMIN_IMAGES' | 'ADMIN_EXECUTIONS' ;
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-watcher/runtime-watcher.module.ts
<filename>frontend/projects/runtime/src/lib/runtime-watcher/runtime-watcher.module.ts import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {RuntimeWatcherService} from 'projects/runtime/src/lib/runtime-watcher/runtime-watcher.service'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; @NgModule({ declarations: [], imports: [ CommonModule ], providers: [ RuntimeWatcherService, ] }) export class RuntimeWatcherModule { constructor(watcher: RuntimeWatcherService) { // inject services to force initialization } }
yegobox/kraken
frontend/projects/runtime/src/lib/events/task-executed-event.ts
import {BusEvent} from 'projects/event/src/lib/bus-event'; import {ExecutionContext} from 'projects/runtime/src/lib/entities/execution-context'; export class TaskExecutedEvent extends BusEvent { public static readonly CHANNEL = 'task-executed-event'; constructor(public readonly taskId: string, public readonly context: ExecutionContext) { super(TaskExecutedEvent.CHANNEL); } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-configuration.service.spec.ts
import {TestBed} from '@angular/core/testing'; import {RuntimeConfigurationService} from './runtime-configuration.service'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import {configurationServiceSpy} from 'projects/commons/src/lib/config/configuration.service.spec'; import {HttpClientTestingModule} from '@angular/common/http/testing'; import SpyObj = jasmine.SpyObj; export const runtimeConfigurationServiceSpy = () => { const spy = jasmine.createSpyObj('RuntimeConfigurationService', [ 'hostApiUrl', 'runtimeApiUrl', 'taskApiUrl', 'containerApiUrl', ]); spy.hostApiUrl.and.callFake((path = '') => `hostApiUrl/host${path}`); spy.runtimeApiUrl.and.callFake((path = '') => `runtimeApiUrl/runtime${path}`); spy.taskApiUrl.and.callFake((path = '') => `taskApiUrl/task${path}`); spy.containerApiUrl.and.callFake((path = '') => `containerApiUrl/container${path}`); return spy; }; describe('RuntimeConfigurationService', () => { let service: RuntimeConfigurationService; let configuration: SpyObj<ConfigurationService>; beforeEach(() => { configuration = configurationServiceSpy(); TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ ConfigurationService, { provide: ConfigurationService, useValue: configuration, }, ] }); service = TestBed.get(RuntimeConfigurationService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return hostApiUrl', () => { configuration.url.and.returnValue('url'); expect(service.hostApiUrl('/path')).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/host/path'); }); it('should return hostApiUrl no param', () => { configuration.url.and.returnValue('url'); expect(service.hostApiUrl()).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/host'); }); it('should return runtimeApiUrl', () => { configuration.url.and.returnValue('url'); expect(service.runtimeApiUrl('/path')).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/runtime/path'); }); it('should return runtimeApiUrl no param', () => { configuration.url.and.returnValue('url'); expect(service.runtimeApiUrl()).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/runtime'); }); it('should return taskApiUrl', () => { configuration.url.and.returnValue('url'); expect(service.taskApiUrl('/path')).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/task/path'); }); it('should return taskApiUrl no param', () => { configuration.url.and.returnValue('url'); expect(service.taskApiUrl()).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/task'); }); it('should return containerApiUrl', () => { configuration.url.and.returnValue('url'); expect(service.containerApiUrl('/path')).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/container/path'); }); it('should return containerApiUrl no param', () => { configuration.url.and.returnValue('url'); expect(service.containerApiUrl()).toBe('url'); expect(configuration.url).toHaveBeenCalledWith('runtimeApiUrl', '/container'); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/host-id-to-description.pipe.spec.ts
import {HostIdToDescriptionPipe} from './host-id-to-description.pipe'; import {runtimeHostServiceSpy} from 'projects/runtime/src/lib/runtime-host/runtime-host.service.spec'; import {AddressesToStringPipe} from 'projects/runtime/src/lib/runtime-host/addresses-to-string.pipe'; import {CapacityToStringPipe} from 'projects/runtime/src/lib/runtime-host/capacity-to-string.pipe'; import {testHost} from 'projects/runtime/src/lib/entities/host.spec'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; import SpyObj = jasmine.SpyObj; describe('HostIdToDescriptionPipe', () => { let pipe: HostIdToDescriptionPipe; let hostService: SpyObj<RuntimeHostService>; beforeEach(() => { hostService = runtimeHostServiceSpy(); pipe = new HostIdToDescriptionPipe(hostService, new AddressesToStringPipe(), new CapacityToStringPipe()); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('create convert host', () => { const host = testHost(); hostService.host.and.returnValue(host); expect(pipe.transform(host.id)).toEqual('Addresses: type=address - Capacity: key=value'); expect(hostService.host).toHaveBeenCalledWith(host.id); }); it('create convert not found', () => { const id = 'id'; hostService.host.and.returnValue(undefined); expect(pipe.transform(id)).toEqual(id); expect(hostService.host).toHaveBeenCalledWith(id); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/capacity-to-string.pipe.spec.ts
<filename>frontend/projects/runtime/src/lib/runtime-host/capacity-to-string.pipe.spec.ts<gh_stars>0 import { CapacityToStringPipe } from './capacity-to-string.pipe'; describe('CapacityToStringPipe', () => { it('create an instance', () => { const pipe = new CapacityToStringPipe(); expect(pipe).toBeTruthy(); expect(pipe.transform({foo: 'bar', hello: 'world'})) .toEqual('foo=bar, hello=world'); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service.ts
import {Injectable, OnDestroy} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {debounce, filter} from 'rxjs/operators'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {NodeModifiedEvent} from 'projects/storage/src/lib/events/node-modified-event'; import * as _ from 'lodash'; import {BehaviorSubject, Subscription, timer} from 'rxjs'; import {NodePendingSaveEvent} from 'projects/storage/src/lib/events/node-pending-save-event'; import {SaveNodeEvent} from 'projects/storage/src/lib/events/save-node-event'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; @Injectable() export class StorageNodeEditorContentService implements OnDestroy { public static readonly DEBOUNCE_DELAY = 2000; public state: 'loading' | 'loaded' | 'error' = 'loading'; public error: string; _node: StorageNode; _contentSubject = new BehaviorSubject<string>(null); _silentUpdate = false; private subscriptions: Subscription[] = []; constructor(protected configuration: StorageConfigurationService, protected storage: StorageService, protected http: HttpClient, protected eventBus: EventBusService) { this.subscriptions.push(this.eventBus.of<NodeModifiedEvent>(NodeModifiedEvent.CHANNEL) .pipe(filter(event => event.node.path === this._node.path), filter(event => event.node.lastModified > this._node.lastModified)) .subscribe(this._nodeModified.bind(this))); this.subscriptions.push( this.eventBus.of<SaveNodeEvent>(SaveNodeEvent.CHANNEL) .pipe( filter(() => !!this._node), filter(event => event.node.path === this._node.path) ).subscribe(this.save.bind(this)) ); this.subscriptions.push(this._contentSubject.pipe( filter(() => !this._silentUpdate), filter(() => !!this._node), filter(content => content !== null), debounce(() => { this.eventBus.publish(new NodePendingSaveEvent(this._node, true)); return timer(StorageNodeEditorContentService.DEBOUNCE_DELAY); })) .subscribe(this.save.bind(this))); } ngOnDestroy() { // Force the remote content update on editor tab closing this._contentSubject.complete(); _.invokeMap(this.subscriptions, 'unsubscribe'); } public save() { this.http.post<StorageNode>(this.configuration.storageApiUrl('/set/content'), this._contentSubject.value, { params: { path: this._node.path } }).subscribe((node) => { this._node = node; this.eventBus.publish(new NodePendingSaveEvent(this._node, false)); }); } public load(node: StorageNode) { this._node = node; this.storage.getContent(node).subscribe((content: string) => { this._setContent(content); this.state = 'loaded'; }, () => this.state = 'error'); } get content(): string { return this._contentSubject.value; } set content(content: string) { this._contentSubject.next(content); } _setContent(content: string) { // Set content and prevent the trigger of the save listener this._silentUpdate = true; this._contentSubject.next(content); this._silentUpdate = false; } _nodeModified(event: NodeModifiedEvent) { this.http.get(this.configuration.storageApiUrl('/get/content'), { responseType: 'text', params: { path: this._node.path } }).subscribe(this._setContent.bind(this)); } }
yegobox/kraken
frontend/projects/analysis/src/lib/results/debug/debug-entries-table/debug-entries-table.service.ts
<gh_stars>0 import {Injectable, OnDestroy} from '@angular/core'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {NodeEventToNodePipe} from 'projects/storage/src/lib/storage-pipes/node-event-to-node.pipe'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {DebugEntry} from 'projects/analysis/src/lib/entities/debug-entry'; import {ResultsTableService} from 'projects/analysis/src/lib/results/results-table/results-table.service'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; import {Subscription} from 'rxjs'; import {SelectNodeEvent} from 'projects/storage/src/lib/events/select-node-event'; import {map} from 'rxjs/operators'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {IsDebugEntryStorageNodePipe} from 'projects/analysis/src/lib/results/is-debug-entry-storage-node.pipe'; import {CompareDialogComponent} from 'projects/analysis/src/lib/results/debug/compare/compare-dialog/compare-dialog.component'; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; import {DialogSize} from 'projects/dialog/src/lib/dialog-size'; import {StorageJsonService} from 'projects/storage/src/lib/storage-json.service'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {Result} from 'projects/analysis/src/lib/entities/result'; import {DebugEntryToPathPipe} from 'projects/analysis/src/lib/results/debug/debug-pipes/debug-entry-to-path.pipe'; @Injectable() export class DebugEntriesTableService extends StorageJsonService<DebugEntry> implements OnDestroy { public static readonly ENTRY_EXT = '.debug'; private _selection: DebugEntry | null; private _resultSelectionSubscription: Subscription; private _nodeSelectionSubscription: Subscription; private _result: Result; private _lastSelectedNode: StorageNode; constructor( storage: StorageService, storageList: StorageListService, private toNode: NodeEventToNodePipe, private eventBus: EventBusService, private analysisConfiguration: AnalysisConfigurationService, private resultsList: ResultsTableService, private toPath: DebugEntryToPathPipe, private dialogs: DialogService, ) { super(storage, storageList, node => { const result = node.path.match(IsDebugEntryStorageNodePipe.PATH_REGEXP); return result ? `${result[2]}_${result[1]}` : ''; }, value => `${value.id}_${value.resultId}`); this._resultSelectionSubscription = this.resultsList.selectionChanged.subscribe(this.init.bind(this)); this._nodeSelectionSubscription = this.eventBus.of<SelectNodeEvent>(SelectNodeEvent.CHANNEL) .pipe(map(this.toNode.transform)) .subscribe(node => this._lastSelectedNode = node); } ngOnDestroy() { super.clearSubscriptions(); this._resultSelectionSubscription.unsubscribe(); } public init() { this.selection = null; const result = this.resultsList.selection; if (!result || result === this._result) { return; } this.values = []; this._result = result; super.init(`${this.analysisConfiguration.analysisRootNode.path}/${this._result.id}`, '.*\\.debug', 2); this._subscriptions.push(this.eventBus.of<SelectNodeEvent>(SelectNodeEvent.CHANNEL) .pipe(map(this.toNode.transform)) .subscribe(this._selectNode.bind(this))); } public open(entry: DebugEntry) { const path = `${this.toPath.transform(entry)}/${entry.id}${DebugEntriesTableService.ENTRY_EXT}`; this.storage.get(path).subscribe(node => this.storage.edit(node)); this._selection = entry; } public compare() { this.dialogs.open(CompareDialogComponent, DialogSize.SIZE_FULL, { left: this._selection, right: this._selection, results: this.resultsList.values, }).subscribe(); } public set selection(entry: DebugEntry) { this._selection = entry; } public get selection(): DebugEntry { return this._selection; } public isSelected(entry: DebugEntry): boolean { return !!this._selection && this._selection === entry; } protected _nodesListed(nodes: StorageNode[]) { this.storage.listJSON<DebugEntry>(nodes).subscribe((values: DebugEntry[]) => { this.values = values; this._selectNode(this._lastSelectedNode); }); } private _selectNode(node: StorageNode) { if (!node) { this._selection = null; return; } const entry = this.find(node); if (entry) { this._selection = entry; } } }
yegobox/kraken
frontend/projects/notification/src/lib/notification.service.spec.ts
<filename>frontend/projects/notification/src/lib/notification.service.spec.ts import {inject, TestBed} from '@angular/core/testing'; import {NotificationModule} from 'projects/notification/src/lib/notification.module'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {NotificationService} from 'projects/notification/src/lib/notification.service'; import {TabsService} from 'projects/tabs/src/lib/tabs.service'; import {HighlightService} from 'projects/help/src/lib/highlight/highlight.service'; import {tabsServiceSpy} from 'projects/tabs/src/lib/tabs.service.spec'; import {highlightServiceSpy} from 'projects/help/src/lib/highlight/highlight.service.spec'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {NotificationEvent} from 'projects/notification/src/lib/notification-event'; import {OpenNotificationsEvent} from 'projects/notification/src/lib/open-notifications-event'; import Spy = jasmine.Spy; import {testNotification} from 'projects/notification/src/lib/base-notification.spec'; describe('NotificationService', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [CoreTestModule, NotificationModule], providers: [ NotificationService, {provide: TabsService, useValue: tabsServiceSpy()}, {provide: HighlightService, useValue: highlightServiceSpy()}, ], }); }); it('should be created', inject([NotificationService], (service: NotificationService) => { expect(service).toBeTruthy(); })); it('should count', inject([NotificationService], (service: NotificationService) => { TestBed.get(EventBusService).publish(new NotificationEvent(testNotification())); const count = service.count; expect(count).toBe(1); expect(service.notifications.length).toBe(1); expect(service.notificationsSubject.getValue()).toBe(service.notifications); })); it('should be destroyed', inject([NotificationService], (service: NotificationService) => { service.ngOnDestroy(); expect().nothing(); })); it('should publish event on snackbar action', inject([NotificationService, EventBusService, TabsService], (service: NotificationService, eventBus: EventBusService, tabsService: TabsService) => { (tabsService.isSelected as Spy).and.returnValue(false); spyOn(eventBus, 'publish'); service._snackbarAction(); expect(eventBus.publish).toHaveBeenCalledWith(new OpenNotificationsEvent()); })); it('should publish event on snackbar action', inject([NotificationService, EventBusService, TabsService, HighlightService], (service: NotificationService, eventBus: EventBusService, tabsService: TabsService, highlight: HighlightService) => { (tabsService.isSelected as Spy).and.returnValue(true); spyOn(eventBus, 'publish'); service._snackbarAction(); expect(highlight.highlight).toHaveBeenCalledWith('lib-notification-table'); })); it('should clear', inject([NotificationService], (service: NotificationService) => { service.clear(); expect(service.notifications).toEqual([]); })); });
yegobox/kraken
frontend/projects/analysis/src/lib/results/debug/debug-entries-table/debug-entries-table.service.spec.ts
import {TestBed} from '@angular/core/testing'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {of, ReplaySubject} from 'rxjs'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {StorageNodeToNamePipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-name.pipe'; import {NodeEventToNodePipe} from 'projects/storage/src/lib/storage-pipes/node-event-to-node.pipe'; import {DebugEntry} from 'projects/analysis/src/lib/entities/debug-entry'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; import {analysisConfigurationServiceSpy} from 'projects/analysis/src/lib/analysis-configuration.service.spec'; import {ResultsTableService} from 'projects/analysis/src/lib/results/results-table/results-table.service'; import * as _ from 'lodash'; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; import {dialogsServiceSpy} from 'projects/dialog/src/lib/dialog.service.spec'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {storageListServiceSpy} from 'projects/storage/src/lib/storage-list.service.spec'; import SpyObj = jasmine.SpyObj; import {SelectNodeEvent} from 'projects/storage/src/lib/events/select-node-event'; import {DebugEntriesTableService} from 'projects/analysis/src/lib/results/debug/debug-entries-table/debug-entries-table.service'; import { resultsTableServiceSpy, testResult } from 'projects/analysis/src/lib/results/results-table/results-table.service.spec'; import {DebugEntryToPathPipe} from 'projects/analysis/src/lib/results/debug/debug-pipes/debug-entry-to-path.pipe'; export const testDebugEntry: () => DebugEntry = () => { return { id: 'some-id', resultId: 'debug-uuid', date: 42, requestName: 'requestName', requestStatus: 'requestStatus', session: 'session', requestUrl: 'requestUrl', requestHeaders: [{key: 'key', value: 'value'}], requestCookies: ['cookie'], requestBodyFile: 'requestBodyFile', responseStatus: 'responseStatus', responseHeaders: [{key: 'key', value: 'value'}], responseBodyFile: 'responseBodyFile', }; }; export const testDebugResultNode: () => StorageNode = () => { return { path: 'gatling/results/debug-uuid/debug/some-id.debug', type: 'FILE', depth: 2, length: 0, lastModified: 0 }; }; export const debugEntriesTableServiceSpy: () => SpyObj<DebugEntriesTableService> = () => { const spy = jasmine.createSpyObj('DebugEntriesTableService', [ 'ngOnDestroy', 'init', 'open', 'compare', 'isSelected', ]); spy.valuesSubject = new ReplaySubject<DebugEntry[]>(1); return spy; }; describe('DebugEntriesTableService', () => { let service: DebugEntriesTableService; let storage: SpyObj<StorageService>; let storageList: SpyObj<StorageListService>; let eventBus: SpyObj<EventBusService>; let dialogs: SpyObj<DialogService>; let results: SpyObj<ResultsTableService>; let debugEntryNode: StorageNode; let debugEntry: DebugEntry; beforeEach(() => { debugEntryNode = testDebugResultNode(); debugEntry = testDebugEntry(); storage = storageServiceSpy(); storage.listJSON.and.returnValue(of([])); storageList = storageListServiceSpy(); TestBed.configureTestingModule({ providers: [ {provide: StorageService, useValue: storage}, {provide: StorageListService, useValue: storageList}, {provide: AnalysisConfigurationService, useValue: analysisConfigurationServiceSpy()}, {provide: ResultsTableService, useValue: resultsTableServiceSpy()}, {provide: DialogService, useValue: dialogsServiceSpy()}, DebugEntryToPathPipe, StorageNodeToNamePipe, NodeEventToNodePipe, DebugEntriesTableService, ] }); service = TestBed.get(DebugEntriesTableService); results = TestBed.get(ResultsTableService); eventBus = TestBed.get(EventBusService); dialogs = TestBed.get(DialogService); }); afterEach(() => { service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should find', () => { service.values = [debugEntry]; expect(service.find(debugEntryNode)).toBe(debugEntry); }); it('should compare', () => { dialogs.open.and.returnValue(of('ok')); service.compare(); expect(dialogs.open).toHaveBeenCalled(); }); it('should open', () => { storage.get.and.returnValue(of(debugEntryNode)); service.open(debugEntry); expect(storage.get).toHaveBeenCalledWith(debugEntryNode.path); expect(storage.edit).toHaveBeenCalledWith(debugEntryNode); }); it('should isSelected', () => { expect(service.isSelected(debugEntry)).toBeFalsy(); service.selection = debugEntry; expect(service.isSelected(debugEntry)).toBeTruthy(); expect(service.isSelected(_.cloneDeep(debugEntry))).toBeFalsy(); }); it('should not init', () => { service.init(); expect(storageList.init).not.toHaveBeenCalled(); }); describe('should init and', () => { beforeEach(() => { results.selection = testResult(); service.init(); }); it('should list', () => { expect(storageList.init).toHaveBeenCalledWith('gatling/results/uuid', '.*\\.debug', 2); }); it('should unselect node', () => { service.selection = debugEntry; eventBus.publish(new SelectNodeEvent(null)); expect(service.selection).toBeNull(); }); it('should select do not find node', () => { eventBus.publish(new SelectNodeEvent(debugEntryNode)); expect(service.selection).toBeNull(); }); it('should select', () => { spyOn(service, 'find').and.returnValue(debugEntry); eventBus.publish(new SelectNodeEvent(debugEntryNode)); expect(service.selection).toEqual(debugEntry); }); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-tree/storage-tree/storage-tree.component.ts
<reponame>yegobox/kraken<gh_stars>1-10 import {Component, Inject, InjectionToken, OnInit, Optional} from '@angular/core'; import {IconFaAddon} from 'projects/icon/src/lib/icon-fa-addon'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {faEllipsisV} from '@fortawesome/free-solid-svg-icons/faEllipsisV'; import {library} from '@fortawesome/fontawesome-svg-core'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {StorageTreeDataSourceService} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {CopyPasteService} from 'projects/storage/src/lib/storage-tree/copy-paste.service'; import {faChevronDown} from '@fortawesome/free-solid-svg-icons/faChevronDown'; import {faMinus} from '@fortawesome/free-solid-svg-icons/faMinus'; import {ComponentPortal} from '@angular/cdk/portal'; import {StorageContextualMenuComponent} from 'projects/storage/src/lib/storage-menu/storage-contextual-menu/storage-contextual-menu.component'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {SelectHelpEvent} from 'projects/help/src/lib/help-panel/select-help-event'; import {HelpPageId} from 'projects/help/src/lib/help-panel/help-page-id'; library.add( faEllipsisV, faChevronDown, faMinus ); export const STORAGE_CONTEXTUAL_MENU = new InjectionToken<any /*ComponentType<any>*/>('StorageContextualMenu'); export const STORAGE_TREE_LABEL = new InjectionToken<string>('StorageTreeLabel'); @Component({ selector: 'lib-storage-tree', templateUrl: './storage-tree.component.html', styleUrls: ['./storage-tree.component.scss'], providers: [ StorageListService, StorageTreeDataSourceService, StorageTreeControlService, CopyPasteService, ] }) export class StorageTreeComponent implements OnInit { // Icons readonly menuIcon = new IconFa(faEllipsisV, 'primary'); readonly expandAllIcon = new IconFaAddon( new IconFa(faChevronDown, 'foreground', 'down-4'), new IconFa(faMinus, 'foreground', 'up-6'), ); public contextualMenu: ComponentPortal<any>; public label: string; constructor(public treeControl: StorageTreeControlService, public dataSource: StorageTreeDataSourceService, public copyPaste: CopyPasteService, @Inject(STORAGE_CONTEXTUAL_MENU) @Optional() contextualMenuType: any /*ComponentType<any>*/, @Inject(STORAGE_TREE_LABEL) @Optional() label: string, @Inject(STORAGE_ID) public id: string, private eventBus: EventBusService) { dataSource.treeControl = treeControl; this.contextualMenu = new ComponentPortal<any>(contextualMenuType ? contextualMenuType : StorageContextualMenuComponent); this.label = label ? label : 'Files'; } ngOnInit() { this.dataSource.init(); } selectHelpPage() { this.eventBus.publish(new SelectHelpEvent(this.id as HelpPageId)); } hasChild = (_number: number, _nodeData: StorageNode) => _nodeData.type === 'DIRECTORY'; }
yegobox/kraken
frontend/projects/analysis/src/lib/results/results-table/results-table.service.spec.ts
import {TestBed} from '@angular/core/testing'; import {ResultsTableService} from 'projects/analysis/src/lib/results/results-table/results-table.service'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {storageServiceSpy} from 'projects/storage/src/lib/storage.service.spec'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {StorageNodeToNamePipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-name.pipe'; import {StorageNodeToParentPathPipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-parent-path.pipe'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import {Result, ResultStatus} from 'projects/analysis/src/lib/entities/result'; import {of, ReplaySubject} from 'rxjs'; import {NodeEventToNodePipe} from 'projects/storage/src/lib/storage-pipes/node-event-to-node.pipe'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; import {analysisConfigurationServiceSpy} from 'projects/analysis/src/lib/analysis-configuration.service.spec'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {EventEmitter} from '@angular/core'; import {IsDebugEntryStorageNodePipe} from 'projects/analysis/src/lib/results/is-debug-entry-storage-node.pipe'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {OpenDebugEvent} from 'projects/analysis/src/lib/events/open-debug-event'; import {SelectNodeEvent} from 'projects/storage/src/lib/events/select-node-event'; import {StorageListService} from 'projects/storage/src/lib/storage-list.service'; import {storageListServiceSpy} from 'projects/storage/src/lib/storage-list.service.spec'; import SpyObj = jasmine.SpyObj; export const testResultStatus: (status: ResultStatus) => Result = (status: ResultStatus) => { return { id: 'uuid', startDate: 42, endDate: 1337, status: status, description: 'BasicSimulation', type: 'RUN', }; }; export const testResult: () => Result = () => { return testResultStatus('COMPLETED'); }; export const testResultDebug: () => Result = () => { return { id: 'debug-uuid', startDate: 42, endDate: 1337, status: 'COMPLETED', description: 'BasicSimulation', type: 'DEBUG', }; }; export const testResultNode: () => StorageNode = () => { return { path: 'gatling/results/uuid/result.json', type: 'FILE', depth: 3, length: 0, lastModified: 0 }; }; export const resultsTableServiceSpy: () => SpyObj<ResultsTableService> = () => { const spy = jasmine.createSpyObj('ResultsTableService', [ 'ngOnDestroy', 'init', 'select', 'isSelected', 'get', ]); spy.valuesSubject = new ReplaySubject<Result[]>(1); spy.selectionChanged = new EventEmitter(); spy.values = []; return spy; }; describe('ResultsListService', () => { let service: ResultsTableService; let storage: SpyObj<StorageService>; let storageList: SpyObj<StorageListService>; let events: SpyObj<EventBusService>; let localStorage: LocalStorageService; let resultNode: StorageNode; let result: Result; let debugResult: Result; beforeEach(() => { resultNode = testResultNode(); result = testResult(); debugResult = testResultDebug(); storage = storageServiceSpy(); storage.listJSON.and.returnValue(of([])); storageList = storageListServiceSpy(); TestBed.configureTestingModule({ imports: [ CoreTestModule, ], providers: [ {provide: StorageService, useValue: storage}, {provide: StorageListService, useValue: storageList}, {provide: AnalysisConfigurationService, useValue: analysisConfigurationServiceSpy()}, StorageNodeToNamePipe, StorageNodeToParentPathPipe, NodeEventToNodePipe, ResultsTableService, IsDebugEntryStorageNodePipe, ] }); service = TestBed.get(ResultsTableService); events = TestBed.get(EventBusService); localStorage = TestBed.get(LocalStorageService); }); afterEach(() => { service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should find', () => { service.values = [result]; expect(service.find(resultNode)).toBe(result); }); it('should return hasSelection', () => { expect(service.hasSelection).toBeFalsy(); service.selection = result; expect(service.hasSelection).toBeTruthy(); }); it('should return selection', () => { expect(service.selection).toBeNull(); service.selection = result; expect(service.selection).toEqual(result); }); it('should return isSelected', () => { expect(service.isSelected(result)).toBeFalsy(); service.selection = result; expect(service.isSelected(result)).toBeTruthy(); }); it('should select emit', () => { const spy = spyOn(service.selectionChanged, 'emit'); service.selection = result; expect(spy).toHaveBeenCalledWith(result); }); it('should init selection', () => { spyOn(localStorage, 'getItem').and.returnValue(result); service.init(); }); describe('should init and', () => { beforeEach(() => { service.init(); }); it('should _nodeCreated', () => { storage.getJSON.and.returnValue(of(result)); storageList.nodeCreated.emit(testStorageFileNode()); expect(service.values[0]).toEqual(result); }); it('should _nodeCreated debug', () => { storage.getJSON.and.returnValue(of(debugResult)); storageList.nodeCreated.emit(testStorageFileNode()); expect(service.values[0]).toEqual(debugResult); expect(service.selection).toEqual(debugResult); }); it('should _nodeCreated prevent duplicates', () => { service.values = [result]; storage.getJSON.and.returnValue(of(result)); storageList.nodeCreated.emit(testStorageFileNode()); expect(service.values.length).toBe(1); }); it('should handle selection change', () => { spyOn(events, 'publish'); service.selection = result; expect(localStorage.getItem(ResultsTableService.ID)).toEqual(result); expect(events.publish).not.toHaveBeenCalledWith(new OpenDebugEvent()); }); it('should handle selection change debug', () => { spyOn(events, 'publish'); service.selection = debugResult; expect(localStorage.getItem(ResultsTableService.ID)).toEqual(debugResult); expect(events.publish).toHaveBeenCalledWith(new OpenDebugEvent()); }); it('should handle selection clear', () => { service.selection = debugResult; (service as any)._selection.clear(); expect(localStorage.getItem(ResultsTableService.ID)).toBeUndefined(); }); it('should update selection on list change', () => { service.selection = debugResult; service.valuesSubject.next([result, debugResult]); expect(service.isSelected(debugResult)).toBeTruthy(); }); it('should update selection on list change', () => { service.selection = debugResult; service.valuesSubject.next([result]); expect(service.hasSelection).toBeFalsy(); }); it('should not update selection on list change', () => { service.valuesSubject.next([result]); expect(service.hasSelection).toBeFalsy(); }); it('should update selection on editor change', () => { service.values = [debugResult]; events.publish(new SelectNodeEvent({ path: 'gatling/results/debug-uuid/debug/my_request.debug', type: 'FILE', depth: 4, length: 42, lastModified: 1337 })); expect(service.isSelected(debugResult)).toBeTruthy(); }); }); });
yegobox/kraken
frontend/projects/analysis/src/lib/results/is-debug-entry-storage-node.pipe.ts
<filename>frontend/projects/analysis/src/lib/results/is-debug-entry-storage-node.pipe.ts import {Pipe, PipeTransform} from '@angular/core'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; @Pipe({ name: 'isDebugEntryStorageNode' }) export class IsDebugEntryStorageNodePipe implements PipeTransform { public static readonly PATH_REGEXP = /([0-9a-z\-]*)\/debug\/(.*?).debug$/; constructor(private analysisConfiguration: AnalysisConfigurationService) { } transform(node: StorageNode): boolean { const rootDepth = this.analysisConfiguration.analysisRootNode.depth + 3; return node && node.depth === rootDepth && node.path.startsWith(this.analysisConfiguration.analysisRootNode.path) && !!node.path.match(IsDebugEntryStorageNodePipe.PATH_REGEXP); } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-dialogs/simulation-dialogs.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {ExecuteSimulationDialogComponent} from 'projects/gatling/src/app/simulations/simulation-dialogs/execute-simulation-dialog/execute-simulation-dialog.component'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import { ImportHarDialogComponent } from 'projects/gatling/src/app/simulations/simulation-dialogs/import-har-dialog/import-har-dialog.component'; import {HelpModule} from 'projects/help/src/lib/help.module'; import {ToolsModule} from 'projects/tools/src/lib/tools.module'; import {RuntimeHostModule} from 'projects/runtime/src/lib/runtime-host/runtime-host.module'; import {DescriptionInputComponent} from 'projects/gatling/src/app/simulations/simulation-dialogs/description-input/description-input.component'; @NgModule({ declarations: [DescriptionInputComponent, ExecuteSimulationDialogComponent, ImportHarDialogComponent], exports: [ExecuteSimulationDialogComponent, ImportHarDialogComponent], entryComponents: [ExecuteSimulationDialogComponent, ImportHarDialogComponent], imports: [ CommonModule, VendorsModule, ComponentsModule, IconModule, ComponentsModule, HelpModule, ToolsModule, RuntimeHostModule, ] }) export class SimulationDialogsModule { }
yegobox/kraken
frontend/projects/dialog/src/lib/wait-dialog/wait-dialog.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {WaitDialogComponent} from './wait-dialog.component'; import {MAT_DIALOG_DATA} from '@angular/material'; import {WaitDialogProgress} from 'projects/dialog/src/lib/wait-dialog/wait-dialog-progress'; describe('WaitDialogComponent', () => { let component: WaitDialogComponent; let fixture: ComponentFixture<WaitDialogComponent>; let progress: WaitDialogProgress; beforeEach(async(() => { progress = { title: 'title', progress: 50 }; TestBed.configureTestingModule({ declarations: [WaitDialogComponent], providers: [ {provide: MAT_DIALOG_DATA, useValue: progress}, ] }) .overrideTemplate(WaitDialogComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(WaitDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should get progress', () => { expect(component.progress).toEqual(progress); }); it('should set progress', () => { const progressBis: WaitDialogProgress = { title: 't2', progress: 42 }; component.progress = progressBis; expect(component.progress).toEqual(progressBis); }); });
yegobox/kraken
frontend/projects/tools/src/lib/query-params-to-string.pipe.ts
import {Pipe, PipeTransform} from '@angular/core'; import * as _ from 'lodash'; @Pipe({ name: 'queryParamsToString' }) export class QueryParamsToStringPipe implements PipeTransform { transform(value?: { [key in string]: string }): string { if (!value || _.isEmpty(value)) { return ''; } return '?' + _.join(_.map(value, (val, key) => `${key}=${val}`), '&'); } }
yegobox/kraken
frontend/projects/tools/src/lib/tools.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {PrettyStringPipe} from './pretty-string.pipe'; import { FileSizePipe } from './file-size.pipe'; import { MarkdownToHtmlPipe } from './markdown-to-html.pipe'; import { QueryParamsToStringPipe } from './query-params-to-string.pipe'; @NgModule({ imports: [ CommonModule, ], declarations: [PrettyStringPipe, FileSizePipe, MarkdownToHtmlPipe, QueryParamsToStringPipe], exports: [PrettyStringPipe, FileSizePipe, MarkdownToHtmlPipe, QueryParamsToStringPipe], providers: [QueryParamsToStringPipe] }) export class ToolsModule { }
yegobox/kraken
frontend/projects/notification/src/lib/notifications-tab-header/notifications-tab-header.component.spec.ts
<reponame>yegobox/kraken<filename>frontend/projects/notification/src/lib/notifications-tab-header/notifications-tab-header.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {Component} from '@angular/core'; import {NotificationsTabHeaderComponent} from 'projects/notification/src/lib/notifications-tab-header/notifications-tab-header.component'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {NotificationModule} from 'projects/notification/src/lib/notification.module'; import {NotificationService} from 'projects/notification/src/lib/notification.service'; import {TabsService} from 'projects/tabs/src/lib/tabs.service'; import {SIDE_HEADER_DATA, TAB_HEADER_DATA} from 'projects/tabs/src/lib/tab-header/tab-header.component'; import {newTestTab} from 'projects/tabs/src/lib/tab-header/tab-header.component.spec'; import {TabsSide} from 'projects/tabs/src/lib/tabs-side'; @Component({ selector: 'lib-test', template: `test` }) class TestComponent { } describe('NotificationsTabHeaderComponent', () => { let component: NotificationsTabHeaderComponent; let fixture: ComponentFixture<NotificationsTabHeaderComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [CoreTestModule, NotificationModule], declarations: [TestComponent], providers: [ NotificationService, TabsService, {provide: TAB_HEADER_DATA, useValue: newTestTab(TestComponent)}, {provide: SIDE_HEADER_DATA, useValue: TabsSide.TOP}, ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(NotificationsTabHeaderComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-tree/link-selection-button/link-selection-button.component.ts
import {Component, Inject, OnDestroy} from '@angular/core'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {SelectNodeEvent} from 'projects/storage/src/lib/events/select-node-event'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; import {BehaviorSubject, Subscription} from 'rxjs'; import {IconDynamic} from 'projects/icon/src/lib/icon-dynamic'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {faLink} from '@fortawesome/free-solid-svg-icons/faLink'; import {faUnlink} from '@fortawesome/free-solid-svg-icons/faUnlink'; import {library} from '@fortawesome/fontawesome-svg-core'; import * as _ from 'lodash'; import {filter} from 'rxjs/operators'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {STORAGE_ROOT_NODE} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; library.add(faLink, faUnlink); @Component({ selector: 'lib-link-selection-button', templateUrl: './link-selection-button.component.html', styleUrls: ['./link-selection-button.component.css'] }) export class LinkSelectionButtonComponent implements OnDestroy { readonly linkSelectionIcon = new IconDynamic( new IconFa(faLink), { unlink: new IconFa(faUnlink) } ); public link: BehaviorSubject<boolean>; private subscriptions: Subscription[] = []; constructor(@Inject(STORAGE_ID) private id: string, @Inject(STORAGE_ROOT_NODE) private rootNode: StorageNode, private treeControl: StorageTreeControlService, private eventBus: EventBusService, private localStorage: LocalStorageService) { const linkId = this.id + 'link-selection'; this.link = new BehaviorSubject<boolean>(this.localStorage.getBoolean(linkId, true)); this.subscriptions.push(this.link.subscribe((value) => this.localStorage.set(linkId, value))); this.subscriptions.push(this.eventBus.of<SelectNodeEvent>(SelectNodeEvent.CHANNEL) .pipe(filter((event) => { return this.link.value && event.node && event.node.path.startsWith(rootNode.path); })) .subscribe((event) => this.treeControl.selectOne(event.node))); } ngOnDestroy() { _.invokeMap(this.subscriptions, 'unsubscribe'); } switchLink() { this.link.next(!this.link.value); } }
yegobox/kraken
frontend/projects/storage/src/lib/storage-watcher.service.spec.ts
import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {StorageWatcherService} from './storage-watcher.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import {NodeCreatedEvent} from 'projects/storage/src/lib/events/node-created-event'; import {NodeDeletedEvent} from 'projects/storage/src/lib/events/node-deleted-event'; import {NotificationEvent} from 'projects/notification/src/lib/notification-event'; import {NodeModifiedEvent} from 'projects/storage/src/lib/events/node-modified-event'; import {testStorageDirectoryNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import {QueryParamsToStringPipe} from 'projects/tools/src/lib/query-params-to-string.pipe'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {storageConfigurationServiceSpy} from 'projects/storage/src/lib/storage-configuration.service.spec'; import {RetriesService} from 'projects/tools/src/lib/retries.service'; import {retriesServiceSpy} from 'projects/tools/src/lib/retries.service.spec'; import {DurationToStringPipe} from 'projects/date/src/lib/duration-to-string.pipe'; import {EventEmitter} from '@angular/core'; export const storageWatcherServiceSpy = () => { const spy = jasmine.createSpyObj('StorageWatcherService', [ 'watch', ]); spy.reconnected = new EventEmitter<void>(); return spy; }; describe('StorageWatcherService', () => { let service: StorageWatcherService; let eventBus: EventBusService; beforeEach(() => { TestBed.configureTestingModule({ providers: [ {provide: StorageConfigurationService, useValue: storageConfigurationServiceSpy()}, {provide: EventBusService, useValue: eventBusSpy()}, {provide: RetriesService, useValue: retriesServiceSpy()}, StorageWatcherService, QueryParamsToStringPipe, DurationToStringPipe, ] }); service = TestBed.get(StorageWatcherService); eventBus = TestBed.get(EventBusService); }); afterEach(() => { service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should create an event source', () => { service.watch(); expect(service._subscription).toBeTruthy(); const subscription = service._subscription = jasmine.createSpyObj('_subscription', ['unsubscribe']); service.watch(); expect(subscription.unsubscribe).toHaveBeenCalled(); }); it('should handle CREATE message', () => { const node = testStorageDirectoryNode(); service.next({node, event: 'CREATE'}); expect(eventBus.publish).toHaveBeenCalledWith(new NodeCreatedEvent(node)); expect(service._retry.reset).toHaveBeenCalled(); }); it('should handle DELETE message', () => { const node = testStorageDirectoryNode(); service.next({node, event: 'DELETE'}); expect(eventBus.publish).toHaveBeenCalledWith(new NodeDeletedEvent(node)); }); it('should handle MODIFY message', () => { const node = testStorageDirectoryNode(); service.next({node, event: 'MODIFY'}); expect(eventBus.publish).toHaveBeenCalledWith(new NodeModifiedEvent(node)); }); it('should handle error', fakeAsync(() => { const reconnected = spyOn(service.reconnected, 'emit'); const watch = spyOn(service, 'watch'); service.error(null); expect(eventBus.publish).toHaveBeenCalledWith(jasmine.any(NotificationEvent)); tick(1000); expect(watch).toHaveBeenCalled(); expect(reconnected).toHaveBeenCalled(); })); it('should not handle error destroyed', fakeAsync(() => { const reconnected = spyOn(service.reconnected, 'emit'); const watch = spyOn(service, 'watch'); service.ngOnDestroy(); service.complete(); expect(eventBus.publish).toHaveBeenCalledWith(jasmine.any(NotificationEvent)); tick(1000); expect(watch).not.toHaveBeenCalled(); expect(reconnected).not.toHaveBeenCalled(); })); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/host-id-to-name.pipe.spec.ts
import {HostIdToNamePipe} from './host-id-to-name.pipe'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; import {runtimeHostServiceSpy} from 'projects/runtime/src/lib/runtime-host/runtime-host.service.spec'; import {testHost} from 'projects/runtime/src/lib/entities/host.spec'; import SpyObj = jasmine.SpyObj; describe('HostIdToNamePipe', () => { let pipe: HostIdToNamePipe; let hostService: SpyObj<RuntimeHostService>; beforeEach(() => { hostService = runtimeHostServiceSpy(); pipe = new HostIdToNamePipe(hostService); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('create convert host', () => { const host = testHost(); hostService.host.and.returnValue(host); expect(pipe.transform(host.id)).toEqual('name0'); expect(hostService.host).toHaveBeenCalledWith(host.id); }); it('create convert not found', () => { const id = 'id'; hostService.host.and.returnValue(undefined); expect(pipe.transform(id)).toEqual(id); expect(hostService.host).toHaveBeenCalledWith(id); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/environment-variables-list/environment-variables-list.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {EnvironmentVariablesListComponent} from './environment-variables-list.component'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {localStorageServiceSpy} from 'projects/tools/src/lib/local-storage.service.spec'; import {FormBuilder, FormGroup} from '@angular/forms'; import SpyObj = jasmine.SpyObj; describe('EnvironmentVariablesListComponent', () => { let component: EnvironmentVariablesListComponent; let fixture: ComponentFixture<EnvironmentVariablesListComponent>; let localStorage: SpyObj<LocalStorageService>; beforeEach(async(() => { localStorage = localStorageServiceSpy(); TestBed.configureTestingModule({ declarations: [EnvironmentVariablesListComponent], providers: [ {provide: LocalStorageService, useValue: localStorage}, FormBuilder, ] }) .overrideTemplate(EnvironmentVariablesListComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(EnvironmentVariablesListComponent); component = fixture.componentInstance; component.formGroup = new FormGroup({}); component.hostIds = ['hostId']; component.storageId = 'id'; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should init form', () => { localStorage.getItem.and.returnValue([{key: 'key', value: 'value', scope: null}, { key: 'key', value: 'value', scope: 'hostId' }]); component.ngOnInit(); expect(component.environment).toEqual({key: 'value'}); expect(component.hosts).toEqual({hostId: {key: 'value'}}); }); it('should addVariableIfEmpty', fakeAsync(() => { component.envKeyChildren = { last: { nativeElement: { focus: jasmine.createSpy('focus') } } } as any; component.addVariableIfEmpty(); component.addVariableIfEmpty(); expect(component.variables.length).toBe(1); expect(component.getKey(0).value).toBe(''); expect(component.getValue(0).value).toBe(''); tick(100); expect(component.envKeyChildren.last.nativeElement.focus).toHaveBeenCalled(); })); it('should remove variable', () => { component.envKeyChildren = { last: { nativeElement: { focus: jasmine.createSpy('focus') } } } as any; component.addVariable(); expect(component.variables.length).toBe(1); component.removeVariable(0); expect(component.variables.length).toBe(0); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-pipes/storage-node-to-parent-path.pipe.ts
<filename>frontend/projects/storage/src/lib/storage-pipes/storage-node-to-parent-path.pipe.ts import {Pipe, PipeTransform} from '@angular/core'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import * as _ from 'lodash'; @Pipe({ name: 'storageNodeToParentPath' }) export class StorageNodeToParentPathPipe implements PipeTransform { transform(node: StorageNode, args?: any): string { return _.join(_.dropRight(_.split(node.path, '/'), 1), '/'); } }
yegobox/kraken
frontend/projects/commons/src/lib/config/configuration.ts
<gh_stars>0 export interface Configuration { version: string; applicationId: string; runtimeApiUrl: string; storageApiUrl: string; docUrl: string; }
yegobox/kraken
frontend/projects/runtime/src/lib/entities/host.ts
<gh_stars>0 import {HostAddress} from 'projects/runtime/src/lib/entities/host-address'; export interface Host { readonly id: string; readonly name: string; readonly capacity: {[key in string]: string}; readonly addresses: HostAddress[]; }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/host-id-to-name.pipe.ts
import {Pipe, PipeTransform} from '@angular/core'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; @Pipe({ name: 'hostIdToName' }) export class HostIdToNamePipe implements PipeTransform { constructor(private hostService: RuntimeHostService) { } transform(id: string): string { const host = this.hostService.host(id); return host ? host.name : id; } }
yegobox/kraken
frontend/projects/tree/src/lib/contextual-menu/contextual-menu.component.ts
<reponame>yegobox/kraken import {Component, ViewChild} from '@angular/core'; import { MatMenuTrigger } from '@angular/material/menu'; @Component({ selector: 'lib-contextual-menu', templateUrl: './contextual-menu.component.html', styleUrls: ['./contextual-menu.component.scss'] }) export class ContextualMenuComponent { contextMenuPosition = {x: 0, y: 0}; @ViewChild(MatMenuTrigger, { static: true }) contextMenu: MatMenuTrigger; open(event: MouseEvent) { event.preventDefault(); this.contextMenuPosition.x = event.clientX; this.contextMenuPosition.y = event.clientY; this.contextMenu.openMenu(); document.getElementsByClassName('cdk-overlay-backdrop')[0].addEventListener('contextmenu', (offEvent: any) => { offEvent.preventDefault(); this.contextMenu.closeMenu(); }); } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-watcher/runtime-watcher.service.spec.ts
import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {RuntimeWatcherService} from './runtime-watcher.service'; import {HttpTestingController} from '@angular/common/http/testing'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {eventSourceSpy} from 'projects/tools/src/lib/event-source.service.spec'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import {configurationServiceMock} from 'projects/commons/src/lib/config/configuration.service.spec'; import {RetriesService} from 'projects/tools/src/lib/retries.service'; import {retriesServiceSpy} from 'projects/tools/src/lib/retries.service.spec'; import {DurationToStringPipe} from 'projects/date/src/lib/duration-to-string.pipe'; import {RuntimeConfigurationService} from 'projects/runtime/src/lib/runtime-configuration.service'; import {runtimeConfigurationServiceSpy} from 'projects/runtime/src/lib/runtime-configuration.service.spec'; import {NotificationEvent} from 'projects/notification/src/lib/notification-event'; import {Log} from 'projects/runtime/src/lib/entities/log'; import {testLog} from 'projects/runtime/src/lib/entities/log.spec'; import {LogEvent} from 'projects/runtime/src/lib/events/log-event'; import {Task} from 'projects/runtime/src/lib/entities/task'; import {testTasks} from 'projects/runtime/src/lib/entities/task.spec'; import {TasksRefreshEvent} from 'projects/runtime/src/lib/events/tasks-refresh-event'; import {QueryParamsToStringPipe} from 'projects/tools/src/lib/query-params-to-string.pipe'; export const runtimeWatcherServiceSpy = () => { const spy = jasmine.createSpyObj('RuntimeWatcherService', [ 'watch', ]); return spy; }; describe('RuntimeWatcherService', () => { let service: RuntimeWatcherService; let httpTestingController: HttpTestingController; let eventBus: EventBusService; let eventSource: EventSource; beforeEach(() => { eventSource = eventSourceSpy(); TestBed.configureTestingModule({ imports: [CoreTestModule], providers: [ {provide: EventBusService, useValue: eventBusSpy()}, {provide: ConfigurationService, useValue: configurationServiceMock()}, {provide: RuntimeConfigurationService, useValue: runtimeConfigurationServiceSpy()}, {provide: RetriesService, useValue: retriesServiceSpy()}, RuntimeWatcherService, DurationToStringPipe, QueryParamsToStringPipe, ] }); eventBus = TestBed.get(EventBusService); service = TestBed.get(RuntimeWatcherService); httpTestingController = TestBed.get(HttpTestingController); }); afterEach(() => { httpTestingController.verify(); service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should watch', () => { service.watch(); expect(service._eventSourceSubscription).toBeTruthy(); const subscription = service._eventSourceSubscription = jasmine.createSpyObj('_subscription', ['unsubscribe']); service.watch(); expect(subscription.unsubscribe).toHaveBeenCalled(); }); it('should handle error', fakeAsync(() => { const watch = spyOn(service, 'watch'); service.error(null); expect(eventBus.publish).toHaveBeenCalledWith(jasmine.any(NotificationEvent)); tick(1000); expect(watch).toHaveBeenCalled(); })); it('should not handle error destroyed', fakeAsync(() => { const watch = spyOn(service, 'watch'); service.ngOnDestroy(); service.complete(); expect(eventBus.publish).toHaveBeenCalledWith(jasmine.any(NotificationEvent)); tick(1000); expect(watch).not.toHaveBeenCalled(); })); it('should send event on LOG message', () => { const log: Log = testLog(); service.next({type: 'LOG', value: log}); expect(service._retry.reset).toHaveBeenCalled(); expect(eventBus.publish).toHaveBeenCalledWith(new LogEvent(log)); }); it('should send event on TASKS message', () => { const tasks: Task[] = testTasks(); service.next({type: 'TASKS', value: tasks}); expect(service._retry.reset).toHaveBeenCalled(); expect(eventBus.publish).toHaveBeenCalledWith(new TasksRefreshEvent(tasks)); }); });
yegobox/kraken
frontend/projects/components/src/lib/table-overlay/table-overlay.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {MatTableDataSource} from '@angular/material'; @Component({ selector: 'lib-table-overlay', templateUrl: './table-overlay.component.html', styleUrls: ['./table-overlay.component.scss'] }) export class TableOverlayComponent implements OnInit { @Input() loading: boolean; @Input() dataSource: MatTableDataSource<any>; @Input() noDataLabel: string; ngOnInit(): void { this.noDataLabel = this.noDataLabel || 'No data'; } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/hosts-selector/hosts-selector.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {HostsSelectorComponent} from './hosts-selector.component'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; import {runtimeHostServiceSpy} from 'projects/runtime/src/lib/runtime-host/runtime-host.service.spec'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {localStorageServiceSpy} from 'projects/tools/src/lib/local-storage.service.spec'; import {FormControl, FormGroup} from '@angular/forms'; import {of} from 'rxjs'; import {testHosts} from 'projects/runtime/src/lib/entities/host.spec'; import SpyObj = jasmine.SpyObj; describe('HostsSelectorComponent', () => { let component: HostsSelectorComponent; let fixture: ComponentFixture<HostsSelectorComponent>; let hostService: SpyObj<RuntimeHostService>; let storage: SpyObj<LocalStorageService>; beforeEach(async(() => { hostService = runtimeHostServiceSpy(); storage = localStorageServiceSpy(); TestBed.configureTestingModule({ declarations: [HostsSelectorComponent], providers: [ {provide: RuntimeHostService, useValue: hostService}, {provide: LocalStorageService, useValue: storage}, ] }) .overrideTemplate(HostsSelectorComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HostsSelectorComponent); component = fixture.componentInstance; component.formGroup = new FormGroup({}); component.storageId = 'id'; component.multiple = true; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should load hosts', () => { const hosts = testHosts(); hostService.hosts.and.returnValue(of(hosts)); storage.getItem.and.returnValue([hosts[0].id]); component.ngOnInit(); expect(component.hosts.value).toEqual([hosts[0].id]); }); it('should load host', () => { const hosts = testHosts(); hostService.hosts.and.returnValue(of(hosts)); storage.getItem.and.returnValue([]); component.multiple = false; component.ngOnInit(); expect(component.hosts.value).toBe(hosts[0].id); }); it('should get hostIds', () => { expect(component.hostIds).toEqual([]); const ids = ['id0', 'id1']; component.formGroup.addControl('hosts', new FormControl(ids, [])); expect(component.hostIds).toBe(ids); }); it('should get hostId', () => { expect(component.hostId).toBeNull(); const id = 'id'; component.formGroup.addControl('hosts', new FormControl(id, [])); expect(component.hostId).toBe(id); }); });
yegobox/kraken
frontend/projects/storage/src/lib/entities/storage-node.ts
export type StorageNodeType = 'FILE' | 'DIRECTORY' | 'NONE'; export interface StorageNode { path: string; type: StorageNodeType; depth: number; length: number; lastModified: number; }
yegobox/kraken
frontend/projects/storage/src/lib/storage-tree/storage-node/storage-node.component.spec.ts
<filename>frontend/projects/storage/src/lib/storage-tree/storage-node/storage-node.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {STORAGE_NODE_BUTTONS, StorageNodeComponent} from './storage-node.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {StorageNodeButtonsComponent} from 'projects/storage/src/lib/storage-menu/storage-node-buttons/storage-node-buttons.component'; describe('StorageNodeComponent', () => { let component: StorageNodeComponent; let fixture: ComponentFixture<StorageNodeComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [StorageNodeComponent], providers: [ {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()}, {provide: STORAGE_NODE_BUTTONS, useValue: StorageNodeButtonsComponent}, ] }) .overrideTemplate(StorageNodeComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(StorageNodeComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-tree/storage-node/storage-node.component.ts
<filename>frontend/projects/storage/src/lib/storage-tree/storage-node/storage-node.component.ts import {Component, Inject, InjectionToken, Injector, Input, OnInit, Optional} from '@angular/core'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {ComponentPortal, ComponentType, PortalInjector} from '@angular/cdk/portal'; import {STORAGE_NODE} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor'; import {StorageNodeButtonsComponent} from 'projects/storage/src/lib/storage-menu/storage-node-buttons/storage-node-buttons.component'; export const STORAGE_NODE_BUTTONS = new InjectionToken<ComponentType<any>>('StorageNodeButtons'); @Component({ selector: 'lib-storage-node', templateUrl: './storage-node.component.html', styleUrls: ['./storage-node.component.scss'] }) export class StorageNodeComponent implements OnInit { @Input() node: StorageNode; @Input() expanded: boolean; public nodeButtons: ComponentPortal<any>; constructor(public treeControl: StorageTreeControlService, private injector: Injector, @Inject(STORAGE_NODE_BUTTONS) @Optional() private nodeButtonsType: any /*ComponentType<any>*/) { } ngOnInit() { this.nodeButtons = new ComponentPortal(this.nodeButtonsType ? this.nodeButtonsType : StorageNodeButtonsComponent, null, new PortalInjector(this.injector, new WeakMap([[STORAGE_NODE, this.node]]))); } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-contextual-menu/simulation-contextual-menu.component.spec.ts
<filename>frontend/projects/gatling/src/app/simulations/simulation-contextual-menu/simulation-contextual-menu.component.spec.ts import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {SimulationContextualMenuComponent} from './simulation-contextual-menu.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service'; import {simulationServiceSpy} from 'projects/gatling/src/app/simulations/simulation.service.spec'; import SpyObj = jasmine.SpyObj; import {testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; describe('SimulationContextualMenuComponent', () => { let component: SimulationContextualMenuComponent; let fixture: ComponentFixture<SimulationContextualMenuComponent>; let treeControl: SpyObj<StorageTreeControlService>; let simulation: SpyObj<SimulationService>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [SimulationContextualMenuComponent], providers: [ {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()}, {provide: SimulationService, useValue: simulationServiceSpy()}, ] }) .overrideTemplate(SimulationContextualMenuComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SimulationContextualMenuComponent); component = fixture.componentInstance; treeControl = component.treeControl as any; simulation = component.simulation as any; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should not showDivider', () => { (component.treeControl as any).hasSingleSelection = false; (component.treeControl as any).hasSelection = true; expect(component.showDivider).toBeFalsy(); }); it('should showDivider no selection', () => { (treeControl as any).hasSingleSelection = false; (treeControl as any).hasSelection = false; expect(component.showDivider).toBeTruthy(); }); it('should showDivider HAR selection', () => { (treeControl as any).fisrt = testStorageFileNode(); (treeControl as any).hasSingleSelection = true; (treeControl as any).hasSelection = false; simulation.isHarNode.and.returnValue(true); simulation.isSimulationNode.and.returnValue(false); expect(component.showDivider).toBeTruthy(); }); it('should showDivider Simulation selection', () => { (treeControl as any).fisrt = testStorageFileNode(); (treeControl as any).hasSingleSelection = true; (treeControl as any).hasSelection = false; simulation.isHarNode.and.returnValue(false); simulation.isSimulationNode.and.returnValue(true); expect(component.showDivider).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/tools/src/lib/event-source.service.ts
import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import * as _ from 'lodash'; import {QueryParamsToStringPipe} from 'projects/tools/src/lib/query-params-to-string.pipe'; import {NativeEventSource, EventSourcePolyfill} from 'event-source-polyfill'; const EventSource = NativeEventSource || EventSourcePolyfill; @Injectable({ providedIn: 'root' }) export class EventSourceService { constructor(private paramsToString: QueryParamsToStringPipe) { } newEventSource(path: string): EventSource { return new EventSource(path); } newObservable<R>(path: string, options: { errorMessage?: string, params?: { [key in string]: string }, converter?: (data: string) => R } = {}): Observable<R> { options = _.defaults(options, { errorMessage: '', converter: _.identity, }); return new Observable(observer => { const eventSource = this.newEventSource(path + this.paramsToString.transform(options.params)); eventSource.onmessage = event => { observer.next(options.converter(event.data)); }; eventSource.onerror = () => { if (eventSource.readyState !== eventSource.CONNECTING) { observer.error(options.errorMessage); } eventSource.close(); observer.complete(); }; return () => { eventSource.close(); }; }); } }
yegobox/kraken
frontend/projects/runtime/src/lib/entities/task-type.ts
<reponame>yegobox/kraken export type TaskType = 'RUN' | 'DEBUG' | 'RECORD';
yegobox/kraken
frontend/projects/storage/src/lib/storage-editor/storage-node-editors/default-storage-node-editor/default-storage-node-editor.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {DefaultStorageNodeEditorComponent} from './default-storage-node-editor.component'; import {StorageNodeEditorContentService} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service'; import {storageNodeEditorContentServiceSpy} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service.spec'; import {STORAGE_NODE} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor'; import SpyObj = jasmine.SpyObj; import {testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; describe('DefaultStorageNodeEditorComponent', () => { let component: DefaultStorageNodeEditorComponent; let fixture: ComponentFixture<DefaultStorageNodeEditorComponent>; let contentService: SpyObj<StorageNodeEditorContentService>; beforeEach(async(() => { contentService = storageNodeEditorContentServiceSpy(); TestBed.configureTestingModule({ declarations: [DefaultStorageNodeEditorComponent], providers: [ {provide: StorageNodeEditorContentService, useValue: contentService}, {provide: STORAGE_NODE, useValue: testStorageFileNode()}, ] }) .overrideProvider(StorageNodeEditorContentService, {useValue: contentService}) .overrideTemplate(DefaultStorageNodeEditorComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DefaultStorageNodeEditorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/tools/src/lib/pretty-string.pipe.spec.ts
<filename>frontend/projects/tools/src/lib/pretty-string.pipe.spec.ts import {PrettyStringPipe} from './pretty-string.pipe'; import {StringToolsService} from './string-tools.service'; import {TestBed} from '@angular/core/testing'; describe('PrettyStringPipe', () => { let pipe: PrettyStringPipe; beforeEach(() => { TestBed.configureTestingModule({declarations: [PrettyStringPipe], providers: [PrettyStringPipe, StringToolsService]}); pipe = TestBed.get(PrettyStringPipe); }); it('create an instance', () => { expect(pipe.transform('MY_UGLY_STRING')).toBe('My ugly string'); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/storage-menu.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {StorageContextualMenuComponent} from './storage-contextual-menu/storage-contextual-menu.component'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {TreeModule} from 'projects/tree/src/lib/tree.module'; import {StorageNodeButtonsComponent} from './storage-node-buttons/storage-node-buttons.component'; import {EditNodeButtonComponent} from './buttons/edit-node-button/edit-node-button.component'; import {RenameNodeButtonComponent} from './buttons/rename-node-button/rename-node-button.component'; import {MenuNodeButtonComponent} from './buttons/menu-node-button/menu-node-button.component'; import {NewDirectoryMenuItemComponent} from './menu-items/new-directory-menu-item/new-directory-menu-item.component'; import {NewFileMenuItemComponent} from './menu-items/new-file-menu-item/new-file-menu-item.component'; import {UploadMenuItemComponent} from './menu-items/upload-menu-item/upload-menu-item.component'; import {DownloadMenuItemComponent} from './menu-items/download-menu-item/download-menu-item.component'; import {CopyMenuItemComponent} from './menu-items/copy-menu-item/copy-menu-item.component'; import {CutMenuItemComponent} from './menu-items/cut-menu-item/cut-menu-item.component'; import {PasteMenuItemComponent} from './menu-items/paste-menu-item/paste-menu-item.component'; import {DeleteMenuItemComponent} from './menu-items/delete-menu-item/delete-menu-item.component'; import { RenameMenuItemComponent } from './menu-items/rename-menu-item/rename-menu-item.component'; @NgModule({ declarations: [ StorageContextualMenuComponent, StorageNodeButtonsComponent, EditNodeButtonComponent, RenameNodeButtonComponent, MenuNodeButtonComponent, NewDirectoryMenuItemComponent, NewFileMenuItemComponent, UploadMenuItemComponent, DownloadMenuItemComponent, CopyMenuItemComponent, CutMenuItemComponent, PasteMenuItemComponent, DeleteMenuItemComponent, RenameMenuItemComponent, ], exports: [ StorageContextualMenuComponent, StorageNodeButtonsComponent, EditNodeButtonComponent, RenameNodeButtonComponent, MenuNodeButtonComponent, ], entryComponents: [ StorageContextualMenuComponent, StorageNodeButtonsComponent, ], imports: [ CommonModule, VendorsModule, IconModule, TreeModule, ] }) export class StorageMenuModule { }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation.service.ts
<gh_stars>0 import {Injectable} from '@angular/core'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {StorageNodeToExtPipe} from 'projects/storage/src/lib/storage-pipes/storage-node-to-ext.pipe'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {filter, map} from 'rxjs/operators'; import {DialogService} from 'projects/dialog/src/lib/dialog.service'; import {DateTimeToStringPipe} from 'projects/date/src/lib/date-time-to-string.pipe'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {AnalysisService} from 'projects/analysis/src/lib/analysis.service'; import {FileUploadDialogComponent} from 'projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload-dialog.component'; import {GatlingConfigurationService} from 'projects/gatling/src/app/gatling-configuration.service'; import {DialogSize} from 'projects/dialog/src/lib/dialog-size'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {TaskType} from 'projects/runtime/src/lib/entities/task-type'; import { ExecuteSimulationDialogComponent, ExecuteSimulationDialogData } from 'projects/gatling/src/app/simulations/simulation-dialogs/execute-simulation-dialog/execute-simulation-dialog.component'; import {ExecutionContext} from 'projects/runtime/src/lib/entities/execution-context'; import {RuntimeTaskService} from 'projects/runtime/src/lib/runtime-task/runtime-task.service'; import {ImportHarDialogComponent} from 'projects/gatling/src/app/simulations/simulation-dialogs/import-har-dialog/import-har-dialog.component'; import {OpenResultsEvent} from 'projects/analysis/src/lib/events/open-results-event'; import {OpenTasksEvent} from 'projects/runtime/src/lib/events/open-tasks-event'; @Injectable() export class SimulationService { constructor(private toExt: StorageNodeToExtPipe, private storage: StorageService, private dialogs: DialogService, private eventBus: EventBusService, private storageConfiguration: StorageConfigurationService, private gatlingConfiguration: GatlingConfigurationService, private taskService: RuntimeTaskService) { } run(node: StorageNode) { this._start(node, 'RUN'); } debug(node: StorageNode) { this._start(node, 'DEBUG'); } private _start(node: StorageNode, type: TaskType) { const packageRegexp = /^\s*package\s+(\S+)\s*\n/gm; const classRegexp = /^\s*class\s+(\S+)\s+extends\s+Simulation/gm; const injectRegExp = /\.inject\(atOnceUsers\(1\)\)/gm; this.storage.getContent(node) .pipe(map((content) => { const simulationPackageExec = packageRegexp.exec(content); const simulationPackage = simulationPackageExec ? simulationPackageExec[1] : ''; const simulationClassExec = classRegexp.exec(content); const simulationClass = simulationClassExec ? simulationClassExec[1] : ''; const atOnce = content.search(injectRegExp) > -1; return {type, simulationPackage, simulationClass, atOnce}; })) .subscribe((data: ExecuteSimulationDialogData) => { this.dialogs.open(ExecuteSimulationDialogComponent, DialogSize.SIZE_LG, data) .subscribe((context: ExecutionContext) => this.taskService.execute(context).subscribe(taskId => { this.eventBus.publish(new OpenResultsEvent()); this.eventBus.publish(new OpenTasksEvent()); })); }); } isSimulationNode(node: StorageNode) { return node && node.type === 'FILE' && this.toExt.transform(node) === 'scala'; } isHarNode(node: StorageNode) { return node && node.type === 'FILE' && this.toExt.transform(node) === 'har'; } uploadHar() { const path = this.gatlingConfiguration.simulationsRootNode.path; const endpoint = this.storageConfiguration.storageApiUrl(`/set/file?path=${path}`); this.dialogs.open(FileUploadDialogComponent, DialogSize.SIZE_MD, { endpoint, multiple: false, accept: '.har', title: 'Upload HAR File', }).pipe(filter(filesNames => !!filesNames[0])).subscribe((fileNames: string[]) => { const harPath = path + '/' + fileNames[0]; this.importHar({path: harPath} as StorageNode); }); } importHar(node: StorageNode) { this.dialogs.open(ImportHarDialogComponent, DialogSize.SIZE_MD, {harPath: node.path}) .subscribe((context: ExecutionContext) => this.taskService.execute(context).subscribe()); } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/runtime-host.service.ts
<reponame>yegobox/kraken import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {RuntimeConfigurationService} from 'projects/runtime/src/lib/runtime-configuration.service'; import {BehaviorSubject, Observable} from 'rxjs'; import {Host} from 'projects/runtime/src/lib/entities/host'; import {tap} from 'rxjs/operators'; @Injectable() export class RuntimeHostService { public hostsSubject: BehaviorSubject<Host[]>; private readonly hostsMap = new Map<string, Host>(); constructor( private http: HttpClient, private runtimeConfiguration: RuntimeConfigurationService, ) { this.hostsSubject = new BehaviorSubject([]); } public hosts(): Observable<Host[]> { return this.http.get<Host[]>(this.runtimeConfiguration.hostApiUrl('/list')).pipe(tap(data => { this.hostsSubject.next(data); this.hostsMap.clear(); data.forEach(host => this.hostsMap.set(host.id, host)); })); } public host(id: string): Host | undefined { return this.hostsMap.get(id); } }
yegobox/kraken
frontend/projects/workspaces/src/lib/workspace.component.ts
import {Component, Input, OnInit, ViewChild} from '@angular/core'; import {Portal} from '@angular/cdk/portal'; import {SplitPanesComponent} from 'projects/split/src/lib/split-panes/split-panes.component'; import {SideSplitComponent} from 'projects/workspaces/src/lib/side-split/side-split.component'; import {SideConfiguration} from 'projects/workspaces/src/lib/side-configuration'; import {SplitPane} from 'projects/split/src/lib/split-pane'; @Component({ selector: 'lib-workspace', templateUrl: './workspace.component.html', styleUrls: ['./workspace.component.scss'] }) export class WorkspaceComponent implements OnInit { // Split portals @ViewChild('horizontalSplitPortal', { static: true }) horizontalSplitPortal: Portal<any>; // Splits @ViewChild('verticalSplit', { static: true }) verticalSplit: SplitPanesComponent; @ViewChild('horizontalSplit', { static: false }) horizontalSplit: SplitPanesComponent; // Side Splits @ViewChild('leftSideSplit', { static: false }) leftSideSplit: SideSplitComponent; @ViewChild('rightSideSplit', { static: false }) rightSideSplit: SideSplitComponent; @ViewChild('bottomSideSplit', { static: false }) bottomSideSplit: SideSplitComponent; @ViewChild('leftSideSplitPortal', { static: true }) leftSideSplitPortal: Portal<any>; @ViewChild('rightSideSplitPortal', { static: true }) rightSideSplitPortal: Portal<any>; @ViewChild('bottomSideSplitPortal', { static: true }) bottomSideSplitPortal: Portal<any>; @Input() id: string; @Input() center: Portal<any>; @Input() centerMinWidth?: number; @Input() centerMinHeight?: number; @Input() bottom: SideConfiguration; @Input() left: SideConfiguration; @Input() right: SideConfiguration; verticalSplits: SplitPane[] = []; horizontalSplits: SplitPane[] = []; rightTabsIndex = 1; constructor() { } ngOnInit() { this.centerMinWidth = this.centerMinWidth || 30; this.centerMinHeight = this.centerMinHeight || 30; let centerDefaultWidth = 100; let centerInitWidth = 100; if (!this.left.empty) { this.horizontalSplits.push(this.left.toSplitPane(this.leftSideSplitPortal)); centerDefaultWidth -= this.left.defaultSize; centerInitWidth -= this.left.initSize; this.rightTabsIndex = 2; } if (!this.right.empty) { centerDefaultWidth -= this.right.defaultSize; centerInitWidth -= this.right.initSize; } this.horizontalSplits.push(new SplitPane(this.center, centerDefaultWidth, this.centerMinHeight, centerInitWidth)); if (!this.right.empty) { this.horizontalSplits.push(this.right.toSplitPane(this.rightSideSplitPortal)); } this.verticalSplits.push(new SplitPane(this.horizontalSplitPortal, 100 - this.bottom.defaultSize, this.centerMinHeight, 100 - this.bottom.initSize)); if (!this.bottom.empty) { this.verticalSplits.push(this.bottom.toSplitPane(this.bottomSideSplitPortal)); } } bottomPaneExpanded() { this.verticalSplit.show(1); } bottomPaneCollapsed() { this.verticalSplit.hide(1); } bottomPaneHidden() { this.bottomSideSplit.closeTabs(); } leftPaneExpanded() { this.horizontalSplit.show(0); } leftPaneCollapsed() { this.horizontalSplit.hide(0); } rightPaneExpanded() { this.horizontalSplit.show(this.rightTabsIndex); } rightPaneCollapsed() { this.horizontalSplit.hide(this.rightTabsIndex); } leftRightPaneHidden($event: [number, SplitPane]) { const index = $event[0]; if (index === 0) { this.leftSideSplit.closeTabs(); } else if (index === this.rightTabsIndex) { this.rightSideSplit.closeTabs(); } } }
yegobox/kraken
frontend/projects/workspaces/src/lib/side-split/side-split.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {SideSplitComponent} from './side-split.component'; import {Component, NgModule} from '@angular/core'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {WorkspacesModule} from 'projects/workspaces/src/lib/workspaces.module'; import {TabsSide} from 'projects/tabs/src/lib/tabs-side'; import {SideConfiguration} from 'projects/workspaces/src/lib/side-configuration'; import {EMPTY_TABS_CONFIG, TabsConfiguration} from 'projects/workspaces/src/lib/tabs-configuration'; import {newTestTab} from 'projects/tabs/src/lib/tab-header/tab-header.component.spec'; import {TabsPosition} from 'projects/tabs/src/lib/tabs-position'; @Component({ selector: 'lib-test', template: `test` }) class TestComponent { } @NgModule({ imports: [CoreTestModule, WorkspacesModule], declarations: [TestComponent], entryComponents: [ TestComponent, ], }) class TestModule { } describe('SideSplitComponent', () => { let component: SideSplitComponent; let fixture: ComponentFixture<SideSplitComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [TestModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SideSplitComponent); component = fixture.componentInstance; component.id = 'test'; component.side = TabsSide.TOP; }); it('should ngOnInit no start', () => { component.config = new SideConfiguration( EMPTY_TABS_CONFIG, new TabsConfiguration( [newTestTab(TestComponent)], 0, 50 ), 42 ); fixture.detectChanges(); expect(component.splits.length).toBe(1); expect(component.endTabsIndex).toBe(0); }); it('should ngOnInit no end', () => { component.config = new SideConfiguration( new TabsConfiguration( [newTestTab(TestComponent)], 0, 50 ), EMPTY_TABS_CONFIG, 42 ); fixture.detectChanges(); expect(component.splits.length).toBe(1); }); it('should ngOnInit unselected', () => { component.config = new SideConfiguration( new TabsConfiguration( [newTestTab(TestComponent)], -1, 50 ), new TabsConfiguration( [newTestTab(TestComponent)], -1, 50 ), 42 ); fixture.detectChanges(); expect(component.startTabsSelected).toBe(false); expect(component.endTabsSelected).toBe(false); }); describe('with both tabs', () => { beforeEach(() => { component.id = 'test'; component.side = TabsSide.TOP; component.config = new SideConfiguration( new TabsConfiguration( [newTestTab(TestComponent)], 0, 50 ), new TabsConfiguration( [newTestTab(TestComponent)], 0, 50 ), 42 ); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(component.start).toBe(component.config.start); expect(component.end).toBe(component.config.end); expect(component.splits.length).toBe(2); }); it('should tabUnselected', () => { const hide = spyOn(component.split, 'hide'); const emit = spyOn(component.collapse, 'emit'); component.tabUnselected(TabsPosition.START); expect(hide).toHaveBeenCalledWith(0); expect(emit).not.toHaveBeenCalled(); component.tabUnselected(TabsPosition.END); expect(hide).toHaveBeenCalledWith(1); expect(emit).not.toHaveBeenCalled(); component.startTabsContent.selectedTab = null; component.endTabsContent.selectedTab = null; component.tabUnselected(TabsPosition.END); expect(emit).toHaveBeenCalled(); }); it('should tabSelected start ', () => { const show = spyOn(component.split, 'show'); const hide = spyOn(component.split, 'hide'); const emit = spyOn(component.expand, 'emit'); component.startTabsContent.selectedTab = null; component.tabSelected(TabsPosition.START, null); expect(show).toHaveBeenCalledWith(0); expect(hide).not.toHaveBeenCalled(); expect(emit).toHaveBeenCalled(); }); it('should tabSelected start also hide end', () => { const show = spyOn(component.split, 'show'); const hide = spyOn(component.split, 'hide'); const emit = spyOn(component.expand, 'emit'); component.startTabsContent.selectedTab = null; component.endTabsContent.selectedTab = null; component.tabSelected(TabsPosition.START, null); expect(show).toHaveBeenCalledWith(0); expect(hide).toHaveBeenCalled(); expect(emit).toHaveBeenCalled(); }); it('should tabSelected end ', () => { const show = spyOn(component.split, 'show'); const hide = spyOn(component.split, 'hide'); const emit = spyOn(component.expand, 'emit'); component.endTabsContent.selectedTab = null; component.tabSelected(TabsPosition.END, null); expect(show).toHaveBeenCalledWith(1); expect(hide).not.toHaveBeenCalled(); expect(emit).toHaveBeenCalled(); }); it('should tabSelected end also hide start', () => { const show = spyOn(component.split, 'show'); const hide = spyOn(component.split, 'hide'); const emit = spyOn(component.expand, 'emit'); component.endTabsContent.selectedTab = null; component.startTabsContent.selectedTab = null; component.tabSelected(TabsPosition.END, null); expect(show).toHaveBeenCalledWith(1); expect(hide).toHaveBeenCalled(); expect(emit).toHaveBeenCalled(); }); it('should paneHidden start', () => { const unselectTab = spyOn(component.startTabsContent, 'unselectTab'); component.paneHidden([0, null]); expect(unselectTab).toHaveBeenCalled(); }); it('should paneHidden end', () => { const unselectTab = spyOn(component.endTabsContent, 'unselectTab'); component.paneHidden([1, null]); expect(unselectTab).toHaveBeenCalled(); }); it('should paneHidden kamoulox', () => { component.paneHidden([42, null]); expect().nothing(); }); it('should paneShown', () => { component.paneShown([0, null]); expect().nothing(); }); it('should closeTabs', () => { const unselectStartTab = spyOn(component.startTabsContent, 'unselectTab'); const unselectEndTab = spyOn(component.endTabsContent, 'unselectTab'); component.closeTabs(); expect(unselectStartTab).toHaveBeenCalled(); expect(unselectEndTab).toHaveBeenCalled(); }); it('should closeTabs', () => { component.startTabsContent = null; component.endTabsContent = null; component.closeTabs(); expect(true).toBe(true); }); }); });
yegobox/kraken
frontend/projects/editor/src/lib/path-to-code-editor-mode.pipe.spec.ts
<filename>frontend/projects/editor/src/lib/path-to-code-editor-mode.pipe.spec.ts import {PathToCodeEditorModePipe} from './path-to-code-editor-mode.pipe'; import {TestBed} from '@angular/core/testing'; import {FormatterService} from 'projects/editor/src/lib/formatter.service'; describe('PathToCodeEditorModePipe', () => { let pipe: PathToCodeEditorModePipe; beforeEach(() => { TestBed.configureTestingModule({ providers: [PathToCodeEditorModePipe] }); pipe = TestBed.get(PathToCodeEditorModePipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('create an instance with custom matcher', () => { expect(new PathToCodeEditorModePipe([])).toBeTruthy(); }); it('administration.Dockerfile', () => { expect(pipe.transform('administration.Dockerfile')).toBe('dockerfile'); expect(pipe.transform('/root/test/administration.Dockerfile')).toBe('dockerfile'); expect(pipe.transform('/root/test/administration.Dockerfile.txt')).toBe('text'); }); it('css', () => { expect(pipe.transform('/root/test/file.css')).toBe('css'); expect(pipe.transform('/root/test/file.css.txt')).toBe('text'); }); it('html', () => { expect(pipe.transform('/root/test/file.html')).toBe('html'); }); it('ini', () => { expect(pipe.transform('/root/test/file.ini')).toBe('ini'); }); it('markdown', () => { expect(pipe.transform('/root/test/file.markdown')).toBe('markdown'); expect(pipe.transform('/root/test/file.md')).toBe('markdown'); }); it('Makefile', () => { expect(pipe.transform('Makefile')).toBe('makefile'); expect(pipe.transform('/root/test/Makefile')).toBe('makefile'); expect(pipe.transform('/root/test/Makefile.txt')).toBe('text'); }); it('other file', () => { expect(pipe.transform('/root/test/other.file')).toBe('text'); }); });
yegobox/kraken
frontend/projects/tree/src/lib/contextual-menu/contextual-menu.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {ContextualMenuComponent} from './contextual-menu.component'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {TreeModule} from 'projects/tree/src/lib/tree.module'; describe('ContextualMenuComponent', () => { let component: ContextualMenuComponent; let fixture: ComponentFixture<ContextualMenuComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [CoreTestModule, TreeModule], }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ContextualMenuComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should open and close', () => { spyOn(component.contextMenu, 'openMenu').and.callThrough(); spyOn(component.contextMenu, 'closeMenu').and.callThrough(); const event = {clientX: 10, clientY: 10, preventDefault: jasmine.createSpy('preventDefault')}; component.open(event as any); expect(event.preventDefault).toHaveBeenCalled(); expect(component.contextMenu.openMenu).toHaveBeenCalled(); expect(component.contextMenuPosition).toEqual({x: 10, y: 10}); fixture.detectChanges(); document.getElementsByClassName('cdk-overlay-backdrop')[0].dispatchEvent(new Event('contextmenu')); fixture.detectChanges(); expect(component.contextMenu.closeMenu).toHaveBeenCalled(); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/entities/container-status.ts
export type ContainerStatus = 'CREATING' | 'STARTING' | 'PREPARING' | 'READY' | 'RUNNING' | 'STOPPING' | 'DONE';
yegobox/kraken
frontend/projects/commons/src/lib/mock/router.mock.spec.ts
<reponame>yegobox/kraken<gh_stars>1-10 import {ActivatedRoute, Params} from '@angular/router'; import {cold} from 'jasmine-marbles'; export const routerSpy = () => jasmine.createSpyObj('Router', ['navigate']); export const activatedRouteSpy = (params: Params): ActivatedRoute => { return {params: cold('---x|', {x: params})} as any; };
yegobox/kraken
frontend/projects/tabs/src/lib/tabs-content/tabs-content.component.spec.ts
import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing'; import {Component, NgModule} from '@angular/core'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {TabsModule} from 'projects/tabs/src/lib/tabs.module'; import {BusEvent} from 'projects/event/src/lib/bus-event'; import {TabsContentComponent} from 'projects/tabs/src/lib/tabs-content/tabs-content.component'; import {newTestTab} from 'projects/tabs/src/lib/tab-header/tab-header.component.spec'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {TabSelectedEvent} from 'projects/tabs/src/lib/tab-selected-event'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {TabUnselectedEvent} from 'projects/tabs/src/lib/tab-unselected-event'; import {localStorageServiceSpy} from 'projects/tools/src/lib/local-storage.service.spec'; import Spy = jasmine.Spy; import {SelectHelpEvent} from 'projects/help/src/lib/help-panel/select-help-event'; @Component({ selector: 'lib-test', template: `test` }) class TestComponent { } @NgModule({ imports: [CoreTestModule, TabsModule], declarations: [TestComponent], entryComponents: [ TestComponent, ], }) class TestModule { } class TestEvent extends BusEvent { constructor() { super('test'); } } describe('TabsContentComponent', () => { let component: TabsContentComponent; let fixture: ComponentFixture<TabsContentComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [TestModule], providers: [ {provide: LocalStorageService, useValue: localStorageServiceSpy()} ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TabsContentComponent); component = fixture.componentInstance; component.id = 'test'; component.tabs = [ newTestTab(TestComponent), ]; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should fire _selection event on creation', inject([EventBusService], (eventBus: EventBusService) => { const publish = spyOn(eventBus, 'publish'); component.defaultTabIndex = 0; component.ngOnInit(); expect(publish).toHaveBeenCalledWith(new TabSelectedEvent(component.selectedTab)); })); it('should selectOn', inject([EventBusService], (service: EventBusService) => { component.selectedTab = null; const spy = spyOn(component, 'selectTab'); service.publish(new TestEvent()); expect(spy).toHaveBeenCalledWith(0); })); it('should not selectOn', inject([EventBusService], (service: EventBusService) => { component.selectedTab = component.tabs[0]; const spy = spyOn(component, 'selectTab'); service.publish(new TestEvent()); expect(spy).not.toHaveBeenCalled(); })); it('should load conf from storage', inject([LocalStorageService], (storage: LocalStorageService) => { (storage.getNumber as Spy).and.returnValue(0); component.ngOnInit(); expect(component.selectedTab).toBe(component.tabs[0]); })); it('should load default conf', inject([LocalStorageService], (storage: LocalStorageService) => { (storage.getNumber as Spy).and.returnValue(-1); component.ngOnInit(); expect(component.selectedTab).toBeUndefined(); })); it('should selectTab', inject([LocalStorageService, EventBusService], (storage: LocalStorageService, eventBus: EventBusService) => { const publish = spyOn(eventBus, 'publish'); const emit = spyOn(component.tabSelected, 'emit'); component.selectTab(0); expect(component.selectedTab).toBe(component.tabs[0]); expect(storage.set).toHaveBeenCalledWith(component.id, 0); expect(emit).toHaveBeenCalledWith([0, component.tabs[0]]); expect(publish).toHaveBeenCalledWith(new TabSelectedEvent(component.selectedTab)); expect(publish).toHaveBeenCalledWith(new SelectHelpEvent('TEST')); })); it('should other selectTab', inject([LocalStorageService, EventBusService], (storage: LocalStorageService, eventBus: EventBusService) => { const publish = spyOn(eventBus, 'publish'); const emit = spyOn(component.tabSelected, 'emit'); const otherTab = newTestTab(TestComponent); component.selectedTab = otherTab; component.selectTab(0); expect(component.selectedTab).toBe(component.tabs[0]); expect(storage.set).toHaveBeenCalledWith(component.id, 0); expect(emit).toHaveBeenCalledWith([0, component.tabs[0]]); expect(publish).toHaveBeenCalledWith(new TabSelectedEvent(component.tabs[0])); expect(publish).toHaveBeenCalledWith(new TabUnselectedEvent(otherTab)); })); it('should unselectTab', inject([LocalStorageService, EventBusService], (storage: LocalStorageService, eventBus: EventBusService) => { const publish = spyOn(eventBus, 'publish'); const tab = component.selectedTab = component.tabs[0]; const emit = spyOn(component.tabUnselected, 'emit'); component.unselectTab(); expect(component.selectedTab).toBeNull(); expect(storage.set).toHaveBeenCalledWith(component.id, -1); expect(emit).toHaveBeenCalled(); expect(publish).toHaveBeenCalledWith(new TabUnselectedEvent(tab)); })); it('should unselectTab do nothing', inject([LocalStorageService], (storage: LocalStorageService) => { component.selectedTab = null; const emit = spyOn(component.tabUnselected, 'emit'); component.unselectTab(); expect(emit).not.toHaveBeenCalled(); })); });
yegobox/kraken
frontend/projects/icon/src/lib/icons.ts
import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {faSync} from '@fortawesome/free-solid-svg-icons/faSync'; import {library} from '@fortawesome/fontawesome-svg-core'; import {IconDynamic} from 'projects/icon/src/lib/icon-dynamic'; import {faTrash} from '@fortawesome/free-solid-svg-icons/faTrash'; import {faSearch} from '@fortawesome/free-solid-svg-icons/faSearch'; import {faTimesCircle} from '@fortawesome/free-regular-svg-icons/faTimesCircle'; import {faEllipsisV} from '@fortawesome/free-solid-svg-icons/faEllipsisV'; import {faPlay} from '@fortawesome/free-solid-svg-icons/faPlay'; import {IconFaAddon} from 'projects/icon/src/lib/icon-fa-addon'; import {faSquare} from '@fortawesome/free-regular-svg-icons/faSquare'; import {faICursor} from '@fortawesome/free-solid-svg-icons/faICursor'; import {faBug} from '@fortawesome/free-solid-svg-icons/faBug'; import {faFileAlt} from '@fortawesome/free-solid-svg-icons/faFileAlt'; import {faPlus} from '@fortawesome/free-solid-svg-icons/faPlus'; import {faStop} from '@fortawesome/free-solid-svg-icons/faStop'; library.add(faPlus, faSync, faTimesCircle, faTrash, faSearch, faEllipsisV, faPlay, faSquare, faICursor, faBug, faFileAlt, faStop); export const LOADING_ICON = new IconFa(faSync, 'muted', '', true); export const REFRESH_ICON = new IconDynamic(new IconFa(faSync, 'primary'), { loading: LOADING_ICON }); export const MENU_ICON = new IconFa(faEllipsisV, 'primary'); export const ADD_ICON = new IconFa(faPlus, 'success'); export const DELETE_ICON = new IconFa(faTrash, 'error'); export const INSPECT_ICON = new IconFa(faSearch); export const CLOSE_ICON = new IconDynamic(new IconFa(faTimesCircle), {'selected': new IconFa(faTimesCircle, 'error')}); export const PLAY_ICON = new IconFa(faPlay, 'success'); export const STOP_ICON = new IconFa(faStop, 'error') export const DEBUG_ICON = new IconFa(faBug, 'primary'); export const RENAME_ICON = new IconFaAddon( new IconFa(faSquare, 'foreground', 'shrink-3 down-2'), new IconFa(faICursor, 'accent', 'right-5 grow-2 down-2'), ); export const LOGS_ICON = new IconFa(faFileAlt);
yegobox/kraken
frontend/projects/analysis/src/lib/results/debug/debug-editor/debug-editor-content.service.ts
<reponame>yegobox/kraken import {Injectable} from '@angular/core'; import {StorageNodeEditorContentService} from 'projects/storage/src/lib/storage-editor/storage-node-editors/storage-node-editor-content.service'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {HttpClient} from '@angular/common/http'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {DebugEntry} from 'projects/analysis/src/lib/entities/debug-entry'; import {of, zip} from 'rxjs'; import {tap} from 'rxjs/operators'; import {WindowService} from 'projects/tools/src/lib/window.service'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; import {DebugEntryToPathPipe} from 'projects/analysis/src/lib/results/debug/debug-pipes/debug-entry-to-path.pipe'; @Injectable() export class DebugEditorContentService extends StorageNodeEditorContentService { private static readonly HEADER_HEIGHT = '36px'; private static readonly HEADER_HEIGHT_2X = '72px'; public _entry: DebugEntry; public requestHeadersFlex: string; public requestCookiesFlex: string; public requestBodyFlex: string; public responseHeadersFlex: string; public responseBodyFlex: string; public hasRequestCookies: boolean; public hasRequestBody: boolean; public hasResponseBody: boolean; public requestBody: string; public responseBody: string; constructor(configuration: StorageConfigurationService, storage: StorageService, http: HttpClient, eventBus: EventBusService, private analysisConfiguration: AnalysisConfigurationService, private window: WindowService, private toPath: DebugEntryToPathPipe) { super(configuration, storage, http, eventBus); } public load(node: StorageNode) { this._node = node; this.storage.getJSON(node).subscribe((entry: DebugEntry) => { this._setEntry(entry); const getRequestBody = this.hasRequestBody ? this.storage.getContent({ path: `${this.toPath.transform(entry)}/${this._entry.requestBodyFile}` } as StorageNode).pipe(tap(requestBody => this.requestBody = requestBody)) : of('ok'); const getResponseBody = this.hasResponseBody ? this.storage.getContent({ path: this._responseBodyPath } as StorageNode).pipe(tap(responseBody => this.responseBody = responseBody)) : of('ok'); zip(getRequestBody, getResponseBody).subscribe(() => this.state = 'loaded', () => this.state = 'error'); }, () => this.state = 'error'); } private _setEntry(entry: DebugEntry) { this._entry = entry; this.hasRequestCookies = !!entry.requestCookies.length; this.hasRequestBody = !!entry.requestBodyFile.length; this.hasResponseBody = !!entry.responseBodyFile.length; if (this.hasRequestBody) { if (this.hasRequestCookies) { this.requestBodyFlex = `calc(40% - ${DebugEditorContentService.HEADER_HEIGHT})`; this.requestCookiesFlex = '25%'; this.requestHeadersFlex = `calc(35% - ${DebugEditorContentService.HEADER_HEIGHT_2X})`; } else { this.requestBodyFlex = `calc(45% - ${DebugEditorContentService.HEADER_HEIGHT})`; this.requestHeadersFlex = `calc(55% - ${DebugEditorContentService.HEADER_HEIGHT_2X})`; } } else { if (this.hasRequestCookies) { this.requestCookiesFlex = '35%'; this.requestHeadersFlex = `calc(65% - ${DebugEditorContentService.HEADER_HEIGHT_2X})`; } else { this.requestHeadersFlex = `calc(100% - ${DebugEditorContentService.HEADER_HEIGHT_2X})`; } } if (this.hasResponseBody) { this.responseBodyFlex = `calc(60% - ${DebugEditorContentService.HEADER_HEIGHT})`; this.responseHeadersFlex = `calc(40% - ${DebugEditorContentService.HEADER_HEIGHT})`; } else { this.responseHeadersFlex = `calc(100% - ${DebugEditorContentService.HEADER_HEIGHT})`; } } private get _responseBodyPath(): string { return `${this.toPath.transform(this._entry)}/${this._entry.responseBodyFile}`; } public get entry(): DebugEntry { return this._entry; } public openResponseBody() { const url = of(this.analysisConfiguration.staticApiUrl('/' + this._responseBodyPath)); this.window.open(url); } }
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/menu-items/copy-menu-item/copy-menu-item.component.spec.ts
<reponame>yegobox/kraken import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {CopyMenuItemComponent} from './copy-menu-item.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {CopyPasteService} from 'projects/storage/src/lib/storage-tree/copy-paste.service'; import {copyPasteServiceSpy} from 'projects/storage/src/lib/storage-tree/copy-paste.service.spec'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; describe('CopyMenuItemComponent', () => { let component: CopyMenuItemComponent; let fixture: ComponentFixture<CopyMenuItemComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [CopyMenuItemComponent], providers: [ {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()}, {provide: CopyPasteService, useValue: copyPasteServiceSpy()}, {provide: STORAGE_ID, useValue: 'storage'}, ] }) .overrideTemplate(CopyMenuItemComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CopyMenuItemComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should copy key binding', () => { const binding = component.binding; expect(binding.key).toBe('ctrl + c'); spyOn(component, '_handleKey'); binding.binding(null); expect(component._handleKey).toHaveBeenCalledWith(jasmine.any(Function)); }); });
yegobox/kraken
frontend/projects/components/src/lib/lazy-if.directive.spec.ts
<gh_stars>1-10 import {LazyIfDirective} from './lazy-if.directive'; import {Input, TemplateRef, ViewContainerRef} from '@angular/core'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import SpyObj = jasmine.SpyObj; describe('LazyIfDirective', () => { let directive: LazyIfDirective; let viewContainer: SpyObj<ViewContainerRef>; let templateRef: SpyObj<TemplateRef<any>>; beforeEach(() => { viewContainer = jasmine.createSpyObj('viewContainer', ['createEmbeddedView']); templateRef = jasmine.createSpyObj('templateRef', ['nope']); directive = new LazyIfDirective(templateRef, viewContainer); }); it('should create an instance', () => { expect(directive).toBeTruthy(); }); it('should lazy load', () => { directive.libLazyIf = true; directive.libLazyIf = true; expect(viewContainer.createEmbeddedView).toHaveBeenCalledWith(templateRef); expect(viewContainer.createEmbeddedView).toHaveBeenCalledTimes(1); expect(directive).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/commons/src/lib/config/error-interceptor.service.spec.ts
import {TestBed} from '@angular/core/testing'; import {ErrorInterceptor} from './error-interceptor.service'; import {HttpErrorResponse, HttpHandler, HttpRequest} from '@angular/common/http'; import {throwError} from 'rxjs'; import {RestServerError} from './rest-server-error'; import {eventBusSpy} from 'projects/event/src/lib/event-bus.service.spec'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import Spy = jasmine.Spy; describe('ErrorInterceptor', () => { let interceptor: ErrorInterceptor; let next: HttpHandler; let eventBus: EventBusService; beforeEach(() => { eventBus = eventBusSpy(); TestBed.configureTestingModule({ providers: [ {provide: ErrorInterceptor, useValue: new ErrorInterceptor(eventBus)} ] } ); interceptor = TestBed.get(ErrorInterceptor); next = jasmine.createSpyObj('next', ['handle']); }); it('should be created', () => { expect(interceptor).toBeTruthy(); }); it('should intercept', () => { (next.handle as Spy).and.returnValue(throwError(new HttpErrorResponse({ status: 404, error: JSON.stringify({type: 'ItemNotFound', message: 'message'}) }))); const req = new HttpRequest('GET', 'apiUrl/path'); interceptor.intercept(req, next).subscribe(() => fail('should return error'), (error) => expect(error).toEqual(new RestServerError('Error 404', 'message'))); expect(next.handle).toHaveBeenCalledWith(req); expect(eventBus.publish).toHaveBeenCalled(); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/entities/host.spec.ts
import {Host} from 'projects/runtime/src/lib/entities/host'; export const testHost: () => Host = () => { return {id: 'id0', name: 'name0', capacity: {'key': 'value'}, addresses: [{type: 'type', address: 'address'}]}; }; export const testHosts: () => Host[] = () => { return [ testHost(), {id: 'id1', name: 'name1', capacity: {}, addresses: []}, ]; };
yegobox/kraken
frontend/projects/storage/src/lib/storage-watcher.service.ts
<filename>frontend/projects/storage/src/lib/storage-watcher.service.ts<gh_stars>1-10 import {EventEmitter, Injectable, OnDestroy} from '@angular/core'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {NotificationEvent} from 'projects/notification/src/lib/notification-event'; import {NotificationLevel} from 'projects/notification/src/lib/notification-level'; import {StorageWatcherEvent} from 'projects/storage/src/lib/entities/storage-watcher-event'; import {NodeCreatedEvent} from 'projects/storage/src/lib/events/node-created-event'; import {NodeDeletedEvent} from 'projects/storage/src/lib/events/node-deleted-event'; import {NodeModifiedEvent} from 'projects/storage/src/lib/events/node-modified-event'; import {EventSourceService} from 'projects/tools/src/lib/event-source.service'; import {BaseNotification} from 'projects/notification/src/lib/base-notification'; import {Observer, Subscription} from 'rxjs'; import {StorageConfigurationService} from 'projects/storage/src/lib/storage-configuration.service'; import {DurationToStringPipe} from 'projects/date/src/lib/duration-to-string.pipe'; import {RetriesService} from 'projects/tools/src/lib/retries.service'; import {OpenStorageTreeEvent} from 'projects/storage/src/lib/events/open-storage-tree-event'; import {Retry} from 'projects/tools/src/lib/retry'; @Injectable() export class StorageWatcherService implements OnDestroy, Observer<StorageWatcherEvent> { _subscription: Subscription; _retry: Retry; closed = false; public reconnected: EventEmitter<void> = new EventEmitter<void>(); constructor(private configuration: StorageConfigurationService, private eventBus: EventBusService, private eventSourceService: EventSourceService, retries: RetriesService, private durationToString: DurationToStringPipe) { this._retry = retries.get(); this.watch(); } ngOnDestroy(): void { this._subscription.unsubscribe(); this.closed = true; } watch() { if (this._subscription) { this._subscription.unsubscribe(); } this._subscription = this.eventSourceService.newObservable(this.configuration.storageApiUrl('/watch'), {converter: JSON.parse}) .subscribe(this); } next(watcherEvent: StorageWatcherEvent) { this._retry.reset(); switch (watcherEvent.event) { case 'CREATE': this.eventBus.publish(new NodeCreatedEvent(watcherEvent.node)); break; case 'DELETE': this.eventBus.publish(new NodeDeletedEvent(watcherEvent.node)); break; case 'MODIFY': this.eventBus.publish(new NodeModifiedEvent(watcherEvent.node)); break; } } error(err: any) { const delay = this._retry.getDelay(); this.eventBus.publish(new NotificationEvent(new BaseNotification( `An error occurred while listening for file events. Will reconnect in ${this.durationToString.transform(delay)}.`, NotificationLevel.ERROR, null, { selector: 'lib-storage-tree', busEvent: new OpenStorageTreeEvent() }))); if (this.closed) { return; } setTimeout(() => { this.watch(); this.reconnected.emit(); }, delay); } complete() { this.error(null); } }
yegobox/kraken
frontend/projects/storage/src/lib/storage-menu/menu-items/delete-menu-item/delete-menu-item.component.ts
<reponame>yegobox/kraken import {Component, Inject} from '@angular/core'; import {StorageService} from 'projects/storage/src/lib/storage.service'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {DELETE_ICON} from 'projects/icon/src/lib/icons'; import {KeyBoundMenuItem} from 'projects/storage/src/lib/storage-menu/menu-items/key-bound-menu-item'; import {KeyBinding, KeyBindingsService} from 'projects/tools/src/lib/key-bindings.service'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; @Component({ selector: 'lib-delete-menu-item', templateUrl: './delete-menu-item.component.html', styles: [] }) export class DeleteMenuItemComponent extends KeyBoundMenuItem { readonly deleteIcon = DELETE_ICON; constructor(@Inject(STORAGE_ID) private id: string, public storage: StorageService, public treeControl: StorageTreeControlService, keys: KeyBindingsService) { super(treeControl, keys, new KeyBinding('Delete', () => this._handleKey(this.storage.deleteFiles.bind(this.storage)), id)); } }
yegobox/kraken
frontend/projects/analysis/src/lib/analysis-application-id.service.ts
<reponame>yegobox/kraken<filename>frontend/projects/analysis/src/lib/analysis-application-id.service.ts import {Injectable} from '@angular/core'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import {ApplicationIdHeaderInterceptor} from 'projects/commons/src/lib/config/application-id-header-interceptor.service'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; @Injectable() export class AnalysisApplicationIdService extends ApplicationIdHeaderInterceptor { constructor(configuration: ConfigurationService, analysisConfiguration: AnalysisConfigurationService) { super(configuration, () => [analysisConfiguration.analysisApiUrl('')]); } }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/runtime-host.service.spec.ts
<reponame>yegobox/kraken import {TestBed} from '@angular/core/testing'; import {RuntimeHostService} from './runtime-host.service'; import {cold} from 'jasmine-marbles'; import {Host} from 'projects/runtime/src/lib/entities/host'; import {HttpTestingController} from '@angular/common/http/testing'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {runtimeConfigurationServiceSpy} from 'projects/runtime/src/lib/runtime-configuration.service.spec'; import {RuntimeConfigurationService} from 'projects/runtime/src/lib/runtime-configuration.service'; import {BehaviorSubject} from 'rxjs'; import {testHosts} from 'projects/runtime/src/lib/entities/host.spec'; export const runtimeHostServiceSpy = () => { const spy = jasmine.createSpyObj('RuntimeHostService', [ 'hosts', 'host', ]); spy.hosts.and.returnValue(cold('---x|', {x: testHosts()})); spy.hostsSubject = new BehaviorSubject([]); return spy; }; describe('HostService', () => { let service: RuntimeHostService; let httpTestingController: HttpTestingController; let hosts: Host[]; beforeEach(() => { const config = runtimeConfigurationServiceSpy(); TestBed.configureTestingModule({ imports: [CoreTestModule], providers: [ {provide: RuntimeConfigurationService, useValue: config}, RuntimeHostService, ] }); service = TestBed.get(RuntimeHostService); httpTestingController = TestBed.get(HttpTestingController); hosts = testHosts(); }); afterEach(() => { httpTestingController.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should list', () => { service.hosts().subscribe(value => expect(value).toBe(hosts), () => fail('list failed')); const request = httpTestingController.expectOne('hostApiUrl/host/list'); expect(request.request.method).toBe('GET'); request.flush(hosts); expect(service.hostsSubject.value).toBe(hosts); expect(service.host(hosts[0].id)).toBe(hosts[0]); }); });
yegobox/kraken
frontend/projects/help/src/lib/highlight/highlight.service.spec.ts
import {fakeAsync, inject, TestBed, tick} from '@angular/core/testing'; import {Overlay} from '@angular/cdk/overlay'; import {HighlightModule} from 'projects/help/src/lib/highlight/highlight.module'; import {HighlightService} from 'projects/help/src/lib/highlight/highlight.service'; export const highlightServiceSpy = () => jasmine.createSpyObj('HighlightService', ['highlight']); describe('HighlightService', () => { let overlay; let overlayRef; let document; let element; const rect = {top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0}; beforeEach(() => { overlay = jasmine.createSpyObj('overlay', ['create']); overlayRef = jasmine.createSpyObj('overlayRef', ['attach', 'detach']); document = jasmine.createSpyObj('document', ['querySelector']); element = jasmine.createSpyObj('element', ['getBoundingClientRect']); overlay.create.and.returnValue(overlayRef); document.querySelector.and.returnValue(element); element.getBoundingClientRect.and.returnValue(rect); TestBed.configureTestingModule({ imports: [HighlightModule], providers: [ {provide: Overlay, useValue: overlay} ] }); }); it('should be created', inject([HighlightService], (service: HighlightService) => { expect(service).toBeTruthy(); expect(service.overlayRef).toBe(overlayRef); })); it('should highlight default duration', fakeAsync(() => { const highlightService = TestBed.get(HighlightService); highlightService.document = document; highlightService.highlight('someShit'); expect(overlayRef.attach).toHaveBeenCalled(); expect(overlayRef.detach).not.toHaveBeenCalled(); tick(801); expect(overlayRef.detach).toHaveBeenCalled(); })); it('should highlight custom duration', fakeAsync(() => { const highlightService = TestBed.get(HighlightService); highlightService.document = document; highlightService.highlight('someShit', 200); expect(overlayRef.attach).toHaveBeenCalled(); expect(overlayRef.detach).not.toHaveBeenCalled(); tick(201); expect(overlayRef.detach).not.toHaveBeenCalled(); tick(100); // min 300 ms expect(overlayRef.detach).toHaveBeenCalled(); })); it('should not highlight', () => { const highlightService = TestBed.get(HighlightService); highlightService.document = document; document.querySelector.and.returnValue(null); highlightService.highlight('someShit', 200); expect(overlayRef.attach).not.toHaveBeenCalled(); }); });
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-log/runtime-log.service.spec.ts
<filename>frontend/projects/runtime/src/lib/runtime-log/runtime-log.service.spec.ts<gh_stars>0 import {TestBed} from '@angular/core/testing'; import {RuntimeLogService} from './runtime-log.service'; import {EventEmitter} from '@angular/core'; import {RuntimeTaskService} from 'projects/runtime/src/lib/runtime-task/runtime-task.service'; import {EventBusService} from 'projects/event/src/lib/event-bus.service'; import {CoreTestModule} from 'projects/commons/src/lib/core/core.module.spec'; import {RuntimeContainerService} from 'projects/runtime/src/lib/runtime-task/runtime-container.service'; import {runtimeContainerServiceSpy} from 'projects/runtime/src/lib/runtime-task/runtime-container.service.spec'; import {runtimeTaskServiceSpy} from 'projects/runtime/src/lib/runtime-task/runtime-task.service.spec'; import {TaskExecutedEvent} from 'projects/runtime/src/lib/events/task-executed-event'; import {testExecutionContext} from 'projects/runtime/src/lib/entities/execution-context.spec'; import {LogsAttachedEvent} from 'projects/runtime/src/lib/events/logs-attached-event'; import {testContainer} from 'projects/runtime/src/lib/entities/container.spec'; import {Log} from 'projects/runtime/src/lib/entities/log'; import SpyObj = jasmine.SpyObj; import {of} from 'rxjs'; import {testTask} from 'projects/runtime/src/lib/entities/task.spec'; import {TaskCancelledEvent} from 'projects/runtime/src/lib/events/task-cancelled-event'; export const runtimeLogServiceSpy = () => { const spy = jasmine.createSpyObj('RuntimeLogService', [ 'cancel', 'label', 'removeLabel', ]); spy.logLabelsChanged = new EventEmitter<void>(); return spy; }; describe('RuntimeLogService', () => { let service: RuntimeLogService; let eventBus: EventBusService; let runtimeContainerService: SpyObj<RuntimeContainerService>; let runtimeTaskService: SpyObj<RuntimeTaskService>; beforeEach(() => { TestBed.configureTestingModule({ imports: [CoreTestModule], providers: [ {provide: RuntimeContainerService, useValue: runtimeContainerServiceSpy()}, {provide: RuntimeTaskService, useValue: runtimeTaskServiceSpy()}, EventBusService, RuntimeLogService, ] }); eventBus = TestBed.get(EventBusService); service = TestBed.get(RuntimeLogService); runtimeContainerService = TestBed.get(RuntimeContainerService); runtimeTaskService = TestBed.get(RuntimeTaskService); }); afterEach(() => { service.ngOnDestroy(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should handle task executed event', () => { let count = 0; service.logLabelsChanged.subscribe(() => count++); const taskId = 'taskId'; const context = testExecutionContext(); eventBus.publish(new TaskExecutedEvent(taskId, context)); expect(service.label(taskId)).toEqual({name: 'description', title: 'RUN task description'}); service.removeLabel(taskId); expect(service.label(taskId)).toBeUndefined(); expect(count).toBe(1); }); it('should handle task cancel event', () => { let count = 0; service.logLabelsChanged.subscribe(() => count++); const task = testTask(); eventBus.publish(new TaskCancelledEvent(task)); expect(service.label(task.id)).toEqual({name: 'description', title: 'RUN task description'}); service.removeLabel(task.id); expect(service.label(task.id)).toBeUndefined(); expect(count).toBe(1); }); it('should handle container events', () => { let count = 0; service.logLabelsChanged.subscribe(() => count++); const logsId = 'logsId'; const container = testContainer(); eventBus.publish(new LogsAttachedEvent(logsId, container)); expect(service.label(logsId)).toEqual({name: 'label', title: 'name on hostId'}); service.removeLabel(logsId); expect(service.label(logsId)).toBeUndefined(); expect(count).toBe(1); }); it('should cancel container log', () => { runtimeContainerService.detachLogs.and.returnValue(of('true')); const log: Log = {applicationId: 'applicationId', id: 'id', type: 'CONTAINER', text: 'text', status: 'RUNNING'}; service.cancel(log); expect(runtimeContainerService.detachLogs).toHaveBeenCalledWith('id'); }); });
yegobox/kraken
frontend/projects/storage/src/lib/storage-dialogs/storage-dialogs.module.ts
<gh_stars>1-10 import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {FileNameDialogComponent} from 'projects/storage/src/lib/storage-dialogs/file-name-dialog/file-name-dialog.component'; import {DeleteFilesDialogComponent} from 'projects/storage/src/lib/storage-dialogs/delete-files-dialog/delete-files-dialog.component'; import {FileUploadDialogComponent} from 'projects/storage/src/lib/storage-dialogs/file-upload-dialog/file-upload-dialog.component'; import {StoragePipesModule} from 'projects/storage/src/lib/storage-pipes/storage-pipes.module'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {ComponentsModule} from 'projects/components/src/lib/components.module'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import {HelpModule} from 'projects/help/src/lib/help.module'; @NgModule({ declarations: [ FileNameDialogComponent, DeleteFilesDialogComponent, FileUploadDialogComponent, ], imports: [ StoragePipesModule, CommonModule, VendorsModule, ComponentsModule, IconModule, HelpModule, ], exports: [ FileNameDialogComponent, DeleteFilesDialogComponent, FileUploadDialogComponent, ], entryComponents: [ FileNameDialogComponent, DeleteFilesDialogComponent, FileUploadDialogComponent, ] }) export class StorageDialogsModule { }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/import-har-menu-item/import-har-menu-item.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {ImportHarMenuItemComponent} from './import-har-menu-item.component'; import {StorageTreeControlService} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service'; import {storageTreeControlServiceSpy} from 'projects/storage/src/lib/storage-tree/storage-tree-control.service.spec'; import {SimulationService} from 'projects/gatling/src/app/simulations/simulation.service'; import {simulationServiceSpy} from 'projects/gatling/src/app/simulations/simulation.service.spec'; describe('ImportHarMenuItemComponent', () => { let component: ImportHarMenuItemComponent; let fixture: ComponentFixture<ImportHarMenuItemComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ImportHarMenuItemComponent], providers: [ {provide: StorageTreeControlService, useValue: storageTreeControlServiceSpy()}, {provide: SimulationService, useValue: simulationServiceSpy()}, ] }) .overrideTemplate(ImportHarMenuItemComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ImportHarMenuItemComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
yegobox/kraken
frontend/projects/components/src/lib/components.module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {ToolsModule} from 'projects/tools/src/lib/tools.module'; import {EventModule} from 'projects/event/src/lib/event.module'; import {ColorModule} from 'projects/color/src/lib/color.module'; import {FullPageComponent} from 'projects/components/src/lib/full-page/full-page.component'; import {LoadingIconComponent} from 'projects/components/src/lib/loading-icon/loading-icon.component'; import {RouterProgressComponent} from 'projects/components/src/lib/router-progress/router-progress.component'; import {HeaderComponent} from 'projects/components/src/lib/header/header.component'; import {TableOverlayComponent} from 'projects/components/src/lib/table-overlay/table-overlay.component'; import {SpinnerComponent} from 'projects/components/src/lib/spinner/spinner.component'; import {MessageComponent} from 'projects/components/src/lib/message/message.component'; import {IconModule} from 'projects/icon/src/lib/icon.module'; import { LazyIfDirective } from './lazy-if.directive'; @NgModule({ imports: [ CommonModule, VendorsModule, ToolsModule, EventModule, ColorModule, IconModule, ], declarations: [ FullPageComponent, LoadingIconComponent, RouterProgressComponent, HeaderComponent, TableOverlayComponent, SpinnerComponent, MessageComponent, LazyIfDirective, ], exports: [ FullPageComponent, LoadingIconComponent, RouterProgressComponent, HeaderComponent, TableOverlayComponent, SpinnerComponent, MessageComponent, LazyIfDirective, ], entryComponents: [], }) export class ComponentsModule { }
yegobox/kraken
frontend/projects/runtime/src/lib/runtime-host/hosts-selector/hosts-selector.component.ts
<reponame>yegobox/kraken import {Component, Input, OnInit} from '@angular/core'; import {RuntimeHostService} from 'projects/runtime/src/lib/runtime-host/runtime-host.service'; import {AbstractControl, FormControl, FormGroup, Validators} from '@angular/forms'; import {Host} from 'projects/runtime/src/lib/entities/host'; import * as _ from 'lodash'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; @Component({ selector: 'lib-hosts-selector', templateUrl: './hosts-selector.component.html', styleUrls: ['./hosts-selector.component.scss'] }) export class HostsSelectorComponent implements OnInit { private static readonly ID_PREFIX = 'host-selector-'; @Input() storageId: string; @Input() formGroup: FormGroup; @Input() multiple: boolean; public hostsList: Host[] = []; public loading = true; constructor(private hostService: RuntimeHostService, private localStorage: LocalStorageService) { } ngOnInit() { this.hostService.hosts().subscribe(hosts => { this.loading = false; this.hostsList = hosts; const hostIds = _.map(this.hostsList, 'id'); const savedIds = this.localStorage.getItem<string[]>(HostsSelectorComponent.ID_PREFIX + this.storageId, []); const intersect = _.intersection(hostIds, savedIds); const selectedHostIds = intersect.length ? intersect : hostIds; const selectedHostId = _.first(hostIds); this.formGroup.addControl('hosts', new FormControl(this.multiple ? selectedHostIds : selectedHostId, [Validators.required])); }); } get hosts(): AbstractControl { return this.formGroup.get('hosts'); } get hostIds(): string[] { const hostIds = this.hosts ? this.multiple ? this.hosts.value : [this.hosts.value] : []; this.localStorage.setItem(HostsSelectorComponent.ID_PREFIX + this.storageId, hostIds); return hostIds; } get hostId(): string { const hostId = this.hosts ? this.hosts.value : null; this.localStorage.setItem(HostsSelectorComponent.ID_PREFIX + this.storageId, [hostId]); return hostId; } }
yegobox/kraken
frontend/projects/runtime/src/lib/entities/task.ts
import {ContainerStatus} from 'projects/runtime/src/lib/entities/container-status'; import {TaskType} from 'projects/runtime/src/lib/entities/task-type'; import {Container} from 'projects/runtime/src/lib/entities/container'; export interface Task { readonly id: string; readonly startDate: number; readonly status: ContainerStatus; readonly type: TaskType; readonly containers: Container[]; readonly expectedCount: number; readonly description: string; }
yegobox/kraken
frontend/projects/administration/src/app/workspace/workspace/workspace.component.ts
<gh_stars>0 import {Component, InjectionToken, Injector, OnInit} from '@angular/core'; import {SideConfiguration} from 'projects/workspaces/src/lib/side-configuration'; import {ComponentPortal, PortalInjector} from '@angular/cdk/portal'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {faBell} from '@fortawesome/free-regular-svg-icons'; import {EMPTY_TABS_CONFIG, TabsConfiguration} from 'projects/workspaces/src/lib/tabs-configuration'; import {Tab} from 'projects/tabs/src/lib/tab'; import {HelpPanelComponent} from 'projects/help/src/lib/help-panel/help-panel.component'; import {faQuestionCircle} from '@fortawesome/free-regular-svg-icons/faQuestionCircle'; import {NotificationsTableComponent} from 'projects/notification/src/lib/notifications-table/notifications-table.component'; import {NotificationsTabHeaderComponent} from 'projects/notification/src/lib/notifications-tab-header/notifications-tab-header.component'; import {library} from '@fortawesome/fontawesome-svg-core'; import {transition, trigger, useAnimation} from '@angular/animations'; import {fadeInAnimation} from 'projects/commons/src/lib/animations'; import {StorageTreeComponent} from 'projects/storage/src/lib/storage-tree/storage-tree/storage-tree.component'; import {IconDynamic} from 'projects/icon/src/lib/icon-dynamic'; import {faFolder} from '@fortawesome/free-regular-svg-icons/faFolder'; import {faFolderOpen} from '@fortawesome/free-regular-svg-icons/faFolderOpen'; import {StorageEditorComponent} from 'projects/storage/src/lib/storage-editor/storage-editor/storage-editor.component'; import {OpenHelpEvent} from 'projects/help/src/lib/help-panel/open-help-event'; import {OpenNotificationsEvent} from 'projects/notification/src/lib/open-notifications-event'; import {StorageNode} from 'projects/storage/src/lib/entities/storage-node'; import {STORAGE_ROOT_NODE} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; import {OpenStorageTreeEvent} from 'projects/storage/src/lib/events/open-storage-tree-event'; import {HostsTableComponent} from 'projects/runtime/src/lib/runtime-host/hosts-table/hosts-table.component'; import {faServer} from '@fortawesome/free-solid-svg-icons/faServer'; library.add(faFolder, faFolderOpen, faQuestionCircle, faBell, faServer); @Component({ selector: 'app-workspace', templateUrl: './workspace.component.html', styleUrls: ['./workspace.component.scss'], animations: [ trigger('insertWorkspace', [ transition(':enter', useAnimation(fadeInAnimation, {params: {duration: '1s'}})) ]), ], }) export class WorkspaceComponent implements OnInit { left: SideConfiguration; right: SideConfiguration; bottom: SideConfiguration; center: ComponentPortal<StorageEditorComponent>; constructor(private injector: Injector) { } ngOnInit() { this.center = new ComponentPortal<StorageEditorComponent>(StorageEditorComponent); const treeRoot: StorageNode = { path: '', type: 'DIRECTORY', depth: -1, length: 0, lastModified: 0, }; const adminTree = new ComponentPortal(StorageTreeComponent, null, new PortalInjector(this.injector, new WeakMap<InjectionToken<any>, any>([ [STORAGE_ROOT_NODE, treeRoot], ]))); this.left = new SideConfiguration( new TabsConfiguration( [new Tab(adminTree, 'Configuration', new IconDynamic(new IconFa(faFolder), {'selected': new IconFa(faFolderOpen)}), 'ADMIN_CONFIGURATION', false, [OpenStorageTreeEvent.CHANNEL])], 0, 100, ), EMPTY_TABS_CONFIG, 25, ); this.right = new SideConfiguration( new TabsConfiguration( [ new Tab(new ComponentPortal(HelpPanelComponent), 'Help', new IconFa(faQuestionCircle, 'accent'), null, false, [OpenHelpEvent.CHANNEL]), ], -1, 100 ), EMPTY_TABS_CONFIG, 25 ); this.bottom = new SideConfiguration( new TabsConfiguration( [ new Tab(new ComponentPortal(HostsTableComponent), 'Hosts', new IconFa(faServer), null, true, []), ], 0, 50 ), new TabsConfiguration( [ new Tab(new ComponentPortal(NotificationsTableComponent), 'Notifications', new IconFa(faBell), null, false, [OpenNotificationsEvent.CHANNEL], NotificationsTabHeaderComponent), ], -1, 50 ), 40 ); } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-dialogs/execute-simulation-dialog/execute-simulation-dialog.component.ts
import {Component, Inject, ViewChild} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog'; import {LocalStorageService} from 'projects/tools/src/lib/local-storage.service'; import {TaskType} from 'projects/runtime/src/lib/entities/task-type'; import {Host} from 'projects/runtime/src/lib/entities/host'; import {PrettyStringPipe} from 'projects/tools/src/lib/pretty-string.pipe'; import {DescriptionInputComponent} from 'projects/gatling/src/app/simulations/simulation-dialogs/description-input/description-input.component'; import {EnvironmentVariablesListComponent} from 'projects/runtime/src/lib/runtime-host/environment-variables-list/environment-variables-list.component'; import {ExecutionContext} from 'projects/runtime/src/lib/entities/execution-context'; export interface ExecuteSimulationDialogData { simulationPackage: string; simulationClass: string; type: TaskType; atOnce: boolean; } @Component({ selector: 'app-execute-simulation-dialog', templateUrl: './execute-simulation-dialog.component.html', }) export class ExecuteSimulationDialogComponent { simulationForm: FormGroup; @ViewChild('descriptionInput', {static: true}) descriptionInput: DescriptionInputComponent; @ViewChild('envVarList', {static: true}) envVarList: EnvironmentVariablesListComponent; constructor(public dialogRef: MatDialogRef<ExecuteSimulationDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: ExecuteSimulationDialogData, private fb: FormBuilder) { this.simulationForm = this.fb.group({ simulationName: [data.simulationPackage + '.' + data.simulationClass, [ Validators.required, Validators.pattern(/^(\w+\.)*\w+$/), ]], }); } get simulationName() { return this.simulationForm.get('simulationName'); } run() { const env = this.envVarList.environment; env.KRAKEN_GATLING_SIMULATION = this.simulationName.value; const context = new ExecutionContext( this.data.type, this.descriptionInput.description.value, env, this.envVarList.hosts ); this.dialogRef.close(context); } }
yegobox/kraken
frontend/projects/gatling/src/app/simulations/simulation-dialogs/import-har-dialog/import-har-dialog.component.spec.ts
<reponame>yegobox/kraken<gh_stars>0 import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {ImportHarDialogComponent} from 'projects/gatling/src/app/simulations/simulation-dialogs/import-har-dialog/import-har-dialog.component'; import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog'; import {dialogRefSpy} from 'projects/commons/src/lib/mock/material.mock.spec'; import {VendorsModule} from 'projects/vendors/src/lib/vendors.module'; import {ExecutionContext} from 'projects/runtime/src/lib/entities/execution-context'; import SpyObj = jasmine.SpyObj; describe('ImportHarDialogComponent', () => { let component: ImportHarDialogComponent; let fixture: ComponentFixture<ImportHarDialogComponent>; let dialogRef: SpyObj<MatDialogRef<any>>; beforeEach(async(() => { dialogRef = dialogRefSpy(); TestBed.configureTestingModule({ imports: [VendorsModule], declarations: [ImportHarDialogComponent], providers: [ {provide: MatDialogRef, useValue: dialogRef}, { provide: MAT_DIALOG_DATA, useValue: { harPath: 'harPath' } }, ] }) .overrideTemplate(ImportHarDialogComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ImportHarDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should return simulationPackage', () => { expect(component.simulationPackage.value).toBe(''); }); it('should return simulationClass', () => { expect(component.simulationClass.value).toBe(''); }); it('should import', () => { component.hostsSelector = { hostId: 'local' } as any; component.import(); expect(dialogRef.close).toHaveBeenCalledWith(new ExecutionContext( 'RECORD', 'Import har .', { KRAKEN_GATLING_SIMULATION_CLASS: '', KRAKEN_GATLING_SIMULATION_PACKAGE: '', KRAKEN_GATLING_HAR_PATH_REMOTE: 'harPath' }, { 'local': {} } )); }); });
yegobox/kraken
frontend/projects/tools/src/lib/event-source.service.spec.ts
import {TestBed} from '@angular/core/testing'; import {EventSourceService} from './event-source.service'; import {ToolsModule} from './tools.module'; export const eventSourceSpy = () => { const spy = jasmine.createSpyObj('EventSource', ['onerror', 'onmessage', 'onopen', 'close']); spy.readyState = 0; spy.CONNECTING = 0; spy.OPEN = 1; spy.CLOSED = 2; return spy; }; export const eventSourceServiceSpy = () => jasmine.createSpyObj('EventSourceService', ['newEventSource', 'newObservable']); describe('EventSourceService', () => { let service: EventSourceService; beforeEach(() => { TestBed.configureTestingModule({ imports: [ToolsModule] }); service = TestBed.get(EventSourceService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return eventSource', () => { expect(service.newEventSource('test')).toBeTruthy(); }); it('should newObservable cancel', () => { const eventSource = eventSourceSpy(); spyOn(service, 'newEventSource').and.returnValue(eventSource); const observable = service.newObservable('path'); observable.subscribe().unsubscribe(); expect(service.newEventSource).toHaveBeenCalledWith('path'); expect(eventSource.close).toHaveBeenCalled(); }); it('should newObservable succeed', () => { const eventSource = eventSourceSpy(); spyOn(service, 'newEventSource').and.returnValue(eventSource); const observable = service.newObservable<string>('path'); let complete = false; let data: string; observable.subscribe(d => data = d, () => { console.log('FUUUUU'); }, () => complete = true); expect(service.newEventSource).toHaveBeenCalledWith('path'); eventSource.onmessage({data: 'data'}); eventSource.onerror(null); expect(data).toBe('data'); expect(eventSource.close).toHaveBeenCalled(); expect(complete).toBeTruthy(); }); it('should newObservable fail', () => { const eventSource = eventSourceSpy(); spyOn(service, 'newEventSource').and.returnValue(eventSource); const observable = service.newObservable<string>('path', {errorMessage: 'error'}); let error; observable.subscribe(() => { }, (err) => error = err, () => { }); expect(service.newEventSource).toHaveBeenCalledWith('path'); (eventSource as any).readyState = 2; eventSource.onerror(null); expect(eventSource.close).toHaveBeenCalled(); expect(error).toBeDefined(); }); });
yegobox/kraken
frontend/projects/analysis/src/lib/analysis-configuration.service.spec.ts
<gh_stars>0 import {TestBed} from '@angular/core/testing'; import {AnalysisConfigurationService} from 'projects/analysis/src/lib/analysis-configuration.service'; import {HttpClientTestingModule} from '@angular/common/http/testing'; import {ConfigurationService} from 'projects/commons/src/lib/config/configuration.service'; import SpyObj = jasmine.SpyObj; import {testStorageFileNode} from 'projects/storage/src/lib/entities/storage-node.spec'; import {configurationServiceSpy} from 'projects/commons/src/lib/config/configuration.service.spec'; export const analysisConfigurationServiceSpy = () => { const spy = jasmine.createSpyObj('AnalysisConfigurationService', [ 'analysisApiUrl', 'grafanaUrl', 'staticApiUrl', ]); spy.staticApiUrl.and.callFake((path) => 'staticApiUrl' + path); spy.analysisApiUrl.and.callFake((path = '') => `analysisApiUrl/result${path}`); spy.grafanaUrl.and.callFake((path) => 'grafanaUrl' + path); spy.analysisRootNode = { 'path': 'gatling/results', 'type': 'DIRECTORY', 'depth': 1, 'length': 0, 'lastModified': 0 }; return spy; }; describe('AnalysisConfigurationService', () => { let service: AnalysisConfigurationService; let configuration: SpyObj<ConfigurationService>; beforeEach(() => { configuration = configurationServiceSpy(); TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ ConfigurationService, { provide: ConfigurationService, useValue: configuration, }, ] }); service = TestBed.get(AnalysisConfigurationService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return analysisApiUrl', () => { configuration.url.and.returnValue('url'); expect(service.analysisApiUrl('path')).toBe('url'); }); it('should return grafanaUrl', () => { configuration.url.and.returnValue('url'); expect(service.grafanaUrl('path')).toBe('url'); }); it('should return analysisRootNode', () => { const node = testStorageFileNode(); configuration.value.and.returnValue(node); expect(service.analysisRootNode).toEqual(node); }); it('should return staticApiUrl', () => { configuration.url.and.returnValue('url'); expect(service.staticApiUrl('path')).toBe('url'); }); });
halcyondude/annotations-panel
src/module.ts
///<reference path="../node_modules/grafana-sdk-mocks/app/headers/common.d.ts" /> import _ from 'lodash'; import {PanelCtrl} from 'app/plugins/sdk'; import moment from 'moment'; import './css/annolist.css'; class AnnoListCtrl extends PanelCtrl { static templateUrl = 'partials/module.html'; static scrollable = true; found: any[] = []; timeInfo?: string; // TODO shoudl be defined in Types queryUserId?: number; queryUser?: string; queryTagValue?: string; static panelDefaults = { limit: 10, tags: [], onlyFromThisDashboard: false, showTags: true, showUser: true, showTime: true, navigateBefore: '10m', navigateAfter: '10m', navigateToPanel: true, }; /** @ngInject */ constructor( $scope, $injector, private $rootScope, private backendSrv, private timeSrv, private $location ) { super($scope, $injector); _.defaults(this.panel, AnnoListCtrl.panelDefaults); $scope.moment = moment; this.events.on('refresh', this.onRefresh.bind(this)); this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); } onInitEditMode() { this.editorTabIndex = 1; this.addEditorTab('Options', 'public/plugins/ryantxu-annolist-panel/partials/editor.html'); } onRefresh() { const promises: Array<Promise<any>> = []; promises.push(this.getAnnotationSearch()); return Promise.all(promises).then(this.renderingCompleted.bind(this)); } getAnnotationSearch(): Promise<any> { // http://docs.grafana.org/http_api/annotations/ // https://github.com/grafana/grafana/blob/master/public/app/core/services/backend_srv.ts // https://github.com/grafana/grafana/blob/master/public/app/features/annotations/annotations_srv.ts const params: any = { tags: this.panel.tags, limit: this.panel.limit, type: 'annotation', // Skip the Annotations that are really alerts. (Use the alerts panel!) }; if (this.panel.onlyFromThisDashboard) { params.dashboardId = this.dashboard.id; } let timeInfo = ''; if (this.panel.onlyInTimeRange) { const range = this.timeSrv.timeRange(); params.from = range.from.valueOf(); params.to = range.to.valueOf(); } else { timeInfo = 'All Time'; } this.timeInfo = timeInfo; if (this.queryUserId !== undefined) { params.userId = this.queryUserId; this.timeInfo += ' ' + this.queryUser; } if (this.queryTagValue) { if (params.tags) { params.tags.push(this.queryTagValue); } else { params.tags = [this.queryTagValue]; } this.timeInfo += ' ' + this.queryTagValue; } return this.backendSrv.get('/api/annotations', params).then(result => { this.found = result; }); } _timeOffset(time: number, offset: string, subtract = false) { let incr = 5; let unit = 'm'; const parts = /^(\d+)(\w)/.exec(offset); if (parts && parts.length === 3) { incr = parseInt(parts[1], 10); unit = parts[2]; } const t = moment.utc(time); if (subtract) { incr *= -1; } t.add(incr, unit); return t; } selectAnno(anno: any, evt?: any) { if (evt) { evt.stopPropagation(); evt.preventDefault(); } const range = { from: this._timeOffset(anno.time, this.panel.navigateBefore, true), to: this._timeOffset(anno.time, this.panel.navigateAfter, false), }; // Link to the panel on the same dashboard if (this.dashboard.id === anno.dasboardId) { this.timeSrv.setTime(range); if (this.panel.navigateToPanel) { this.$location.search('panelId', anno.panelId); this.$location.search('fullscreen', true); } return; } if (anno.dashboardId === 0) { this.$rootScope.appEvent('alert-warning', [ 'Invalid Annotation Dashboard', 'Annotation on dashboard: 0 (new?)', ]); return; } this.backendSrv.get('/api/search', {dashboardIds: anno.dashboardId}).then(res => { if (res && res.length === 1 && res[0].id === anno.dashboardId) { const dash = res[0]; let path = dash.url; if (!path) { // before v5. path = '/dashboard/' + dash.uri; } const params: any = { from: range.from.valueOf().toString(), to: range.to.valueOf().toString(), }; if (this.panel.navigateToPanel) { params.panelId = anno.panelId; params.fullscreen = true; } const orgId = this.$location.search().orgId; if (orgId) { params.orgId = orgId; } console.log('SEARCH', path, params); this.$location.path(path).search(params); } else { console.log('Unable to find dashboard...', anno); this.$rootScope.appEvent('alert-warning', ['Unknown Dashboard: ' + anno.dashboardId]); } }); } queryAnnotationUser(anno: any, evt?: any) { if (evt) { evt.stopPropagation(); evt.preventDefault(); } this.queryUserId = anno.userId; this.queryUser = anno.login; console.log('Query User', anno, this); this.refresh(); } queryAnnotationTag(anno: any, tag: string, evt?: any) { if (evt) { evt.stopPropagation(); evt.preventDefault(); } this.queryTagValue = tag; console.log('Query Tag', tag, anno, this); this.refresh(); } } export {AnnoListCtrl, AnnoListCtrl as PanelCtrl};
dfreire/df0005
test/browser-tests/index.ts
<gh_stars>0 import add from '../../src/sample'; import TranslationSheets from '../../src/index.ts'; import { expect } from 'chai'; describe('TranslationSheets', () => { it('should run a simple TypeScript test', () => { expect(true).to.be.true; }); it('should be an object', () => { expect(TranslationSheets).to.eql({}); }); it('should return sum', () => { const sum: number = add(1, 1); expect(sum).to.eql(2); }); });
dfreire/df0005
src/index.tsx
import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('main') ); // var horizon = Horizon(); // horizon.onReady(function() { // document.querySelector('h1').innerHTML = 'App works!' // }); // horizon.connect();
dfreire/df0005
src/model.ts
<filename>src/model.ts interface Language { id: string, } interface Board { id: string, name: string, emails: string[], } interface Card { id: string, boardId: string, } interface Translation { id: string, cardId: string, languageId: string, text: string, notes: string, }
dfreire/df0005
config/typings/tsd.d.ts
/// <reference path="assertion-error/assertion-error.d.ts" /> /// <reference path="bluebird/bluebird.d.ts" /> /// <reference path="chai/chai.d.ts" /> /// <reference path="express-serve-static-core/express-serve-static-core.d.ts" /> /// <reference path="express/express.d.ts" /> /// <reference path="gulp/gulp.d.ts" /> /// <reference path="istanbul/istanbul.d.ts" /> /// <reference path="karma/karma.d.ts" /> /// <reference path="log4js/log4js.d.ts" /> /// <reference path="mime/mime.d.ts" /> /// <reference path="mocha/mocha.d.ts" /> /// <reference path="node/node.d.ts" /> /// <reference path="orchestrator/orchestrator.d.ts" /> /// <reference path="q/Q.d.ts" /> /// <reference path="serve-static/serve-static.d.ts" /> /// <reference path="sinon/sinon.d.ts" /> /// <reference path="source-map/source-map.d.ts" /> /// <reference path="typescript/typescript.d.ts" /> /// <reference path="uglify-js/uglify-js.d.ts" /> /// <reference path="webpack/webpack.d.ts" /> /// <reference path="vinyl-buffer/vinyl-buffer.d.ts" />
mfine15/vscode-languageclient
lib/utils/processes.d.ts
import * as cp from 'child_process'; import ChildProcess = cp.ChildProcess; export declare function terminate(process: ChildProcess, cwd?: string): boolean;
mfine15/vscode-languageclient
lib/utils/electron.d.ts
<gh_stars>0 import * as cp from 'child_process'; export interface IForkOpts { cwd?: string; env?: any; encoding?: string; execArgv?: string[]; } export declare function fork(modulePath: string, args: string[], options: IForkOpts, callback: (error: any, cp: cp.ChildProcess | undefined) => void): void;
paullouismas/shifts-manager
src/bootstraps/i18n/index.ts
import Vue from 'vue'; import VueI18n from 'vue-i18n'; import { getUserLocale } from '@/helpers'; import english from './english'; Vue.use(VueI18n); const translations: VueI18n.LocaleMessages = { // English en: english, }; export default new VueI18n({ locale: getUserLocale(), // Locale from user will be injected on auth fallbackLocale: 'en', messages: translations, });
paullouismas/shifts-manager
src/store/auth/index.ts
<gh_stars>0 import firebase from 'firebase/app'; import { FirestoreWrapper, getUserLocale } from '@/helpers'; interface SignUp { displayName: string; email: string; password: string; } type LogIn = Pick<SignUp, 'email' | 'password'>; type UserSession = Pick<firebase.User, 'displayName' | 'email' | 'uid'> & { metadata: { language: string; }; }; export interface AuthState { currentUser: UserSession | null; } type AuthModule = import('vuex').Module<AuthState, Record<string, unknown>>; const module: AuthModule = { namespaced: true, state: { currentUser: null, }, getters: { currentUser: ({ currentUser }) => currentUser, }, actions: { async setUser({ commit }, user: firebase.User | null) { if (!user) { commit('SET_USER', null); return; } const { displayName, email, uid } = user; const doc = await FirestoreWrapper(uid) .user() .get(); commit('SET_USER', { displayName, email, uid, metadata: doc.data(), } as UserSession); }, async signup(context, { displayName, email, password }: SignUp): Promise<void> { const { user } = await firebase.auth().createUserWithEmailAndPassword(email, password); if (!user) { throw new Error('User not created'); } await user.updateProfile({ displayName }); await FirestoreWrapper(user.uid) .user() .set({ language: getUserLocale(), } as UserSession['metadata']); }, async login(context, { email, password }: LogIn): Promise<void> { await firebase.auth().signInWithEmailAndPassword(email, password); }, signout: () => firebase.auth().signOut(), }, mutations: { SET_USER(state, user: UserSession | null) { state.currentUser = user; }, }, }; export default module;
paullouismas/shifts-manager
src/bootstraps/styles.ts
import Vue from 'vue'; import Buefy from 'buefy'; // import 'bulmaswatch/darkly/_variables.scss'; // import 'bulma'; import 'buefy/dist/buefy.css'; // import 'bulmaswatch/darkly/_overrides.scss'; // import 'bulmaswatch/darkly/bulmaswatch.min.css'; Vue.use(Buefy, { defaultIconPack: 'fas', defaultIconComponent: 'font-awesome-icon', defaultProgrammaticPromise: true, });
paullouismas/shifts-manager
src/models/Workplace.ts
<reponame>paullouismas/shifts-manager<filename>src/models/Workplace.ts import { Entity } from './Entity'; export interface Workplace extends Entity { /** The workplace's name */ name: string; /** The workplace's address, if any */ address: string | null; /** The workplace's description, if any */ description: string | null; }
paullouismas/shifts-manager
src/main.ts
<filename>src/main.ts import Vue from 'vue'; // The base app import App from '@/App.vue'; // Bootstraps scripts import '@/bootstraps'; import vuetify from '@/bootstraps/vuetify'; import i18n from '@/bootstraps/i18n'; import router from './router'; import store from './store'; Vue.config.productionTip = false; new Vue({ router, store, vuetify, render: (h) => h(App), i18n, }).$mount('#app');
paullouismas/shifts-manager
src/config.ts
<gh_stars>0 export default { APP_NAME: 'Shifts Manager', };
paullouismas/shifts-manager
src/models/RetrievableEntity.ts
export type RetrievableEntity<E = Record<string, unknown>> = E & { /** The entity's id */ id: string; };