http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/sensors/sensor-storm-settings/sensor-storm-settings.component.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/sensors/sensor-storm-settings/sensor-storm-settings.component.spec.ts b/metron-interface/metron-config/src/app/sensors/sensor-storm-settings/sensor-storm-settings.component.spec.ts index 02f1fd9..6549b4b 100644 --- a/metron-interface/metron-config/src/app/sensors/sensor-storm-settings/sensor-storm-settings.component.spec.ts +++ b/metron-interface/metron-config/src/app/sensors/sensor-storm-settings/sensor-storm-settings.component.spec.ts @@ -16,153 +16,161 @@ * limitations under the License. */ -import {async, TestBed, ComponentFixture} from '@angular/core/testing'; -import {SensorStormSettingsComponent} from './sensor-storm-settings.component'; -import {SharedModule} from '../../shared/shared.module'; -import {SimpleChanges, SimpleChange} from '@angular/core'; -import {SensorParserConfig} from '../../model/sensor-parser-config'; -import {SensorStormSettingsModule} from './sensor-storm-settings.module'; -import '../../rxjs-operators'; +import { async, TestBed, ComponentFixture } from '@angular/core/testing'; +import { SensorStormSettingsComponent } from './sensor-storm-settings.component'; +import { SharedModule } from '../../shared/shared.module'; +import { SimpleChanges, SimpleChange } from '@angular/core'; +import { SensorParserConfig } from '../../model/sensor-parser-config'; +import { SensorStormSettingsModule } from './sensor-storm-settings.module'; describe('Component: SensorStormSettingsComponent', () => { - - let fixture: ComponentFixture<SensorStormSettingsComponent>; - let component: SensorStormSettingsComponent; - let sensorParserConfig: SensorParserConfig = new SensorParserConfig(); - sensorParserConfig.sensorTopic = 'bro'; - sensorParserConfig.parserClassName = 'org.apache.metron.parsers.bro.BasicBroParser'; - sensorParserConfig.parserConfig = {}; - sensorParserConfig.numWorkers = 2; - sensorParserConfig.numAckers = 2; - sensorParserConfig.spoutParallelism = 2; - sensorParserConfig.spoutNumTasks = 2; - sensorParserConfig.parserParallelism = 2; - sensorParserConfig.parserNumTasks = 2; - sensorParserConfig.errorWriterParallelism = 2; - sensorParserConfig.errorWriterNumTasks = 2; - sensorParserConfig.spoutConfig = {'spoutConfigProp': 'spoutConfigValue1'}; - sensorParserConfig.stormConfig = {'stormConfigProp': 'stormConfigValue1'}; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [SharedModule, SensorStormSettingsModule], - }); - - fixture = TestBed.createComponent(SensorStormSettingsComponent); - component = fixture.componentInstance; - })); - - it('should create an instance', () => { - expect(component).toBeDefined(); - }); - - it('should create an instance', () => { - spyOn(component, 'init'); - let changes: SimpleChanges = {'showStormSettings': new SimpleChange(false, true)}; - - component.ngOnChanges(changes); - expect(component.init).toHaveBeenCalled(); - - changes = {'showStormSettings': new SimpleChange(true, false)}; - component.ngOnChanges(changes); - expect(component.init['calls'].count()).toEqual(1); - - fixture.destroy(); + let fixture: ComponentFixture<SensorStormSettingsComponent>; + let component: SensorStormSettingsComponent; + let sensorParserConfig: SensorParserConfig = new SensorParserConfig(); + sensorParserConfig.sensorTopic = 'bro'; + sensorParserConfig.parserClassName = + 'org.apache.metron.parsers.bro.BasicBroParser'; + sensorParserConfig.parserConfig = {}; + sensorParserConfig.numWorkers = 2; + sensorParserConfig.numAckers = 2; + sensorParserConfig.spoutParallelism = 2; + sensorParserConfig.spoutNumTasks = 2; + sensorParserConfig.parserParallelism = 2; + sensorParserConfig.parserNumTasks = 2; + sensorParserConfig.errorWriterParallelism = 2; + sensorParserConfig.errorWriterNumTasks = 2; + sensorParserConfig.spoutConfig = { spoutConfigProp: 'spoutConfigValue1' }; + sensorParserConfig.stormConfig = { stormConfigProp: 'stormConfigValue1' }; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [SharedModule, SensorStormSettingsModule] }); - it('should initialise the fields', () => { - - component.init(); - expect(component.newSensorParserConfig).toEqual(new SensorParserConfig()); - - component.sensorParserConfig = sensorParserConfig; - component.init(); - expect(component.newSensorParserConfig).toEqual(sensorParserConfig); - expect(component.newSpoutConfig).toEqual('{\n\t"spoutConfigProp": "spoutConfigValue1"\n}'); - expect(component.newStormConfig).toEqual('{\n\t"stormConfigProp": "stormConfigValue1"\n}'); - - fixture.destroy(); + fixture = TestBed.createComponent(SensorStormSettingsComponent); + component = fixture.componentInstance; + })); + + it('should create an instance', () => { + expect(component).toBeDefined(); + }); + + it('should create an instance', () => { + spyOn(component, 'init'); + let changes: SimpleChanges = { + showStormSettings: new SimpleChange(false, true, true) + }; + + component.ngOnChanges(changes); + expect(component.init).toHaveBeenCalled(); + + changes = { showStormSettings: new SimpleChange(true, false, false) }; + component.ngOnChanges(changes); + expect(component.init['calls'].count()).toEqual(1); + + fixture.destroy(); + }); + + it('should initialise the fields', () => { + component.init(); + expect(component.newSensorParserConfig).toEqual(new SensorParserConfig()); + + component.sensorParserConfig = sensorParserConfig; + component.init(); + expect(component.newSensorParserConfig).toEqual(sensorParserConfig); + expect(component.newSpoutConfig).toEqual( + '{\n\t"spoutConfigProp": "spoutConfigValue1"\n}' + ); + expect(component.newStormConfig).toEqual( + '{\n\t"stormConfigProp": "stormConfigValue1"\n}' + ); + + fixture.destroy(); + }); + + it('should save the fields', () => { + spyOn(component.hideStormSettings, 'emit'); + spyOn(component.onStormSettingsChanged, 'emit'); + component.sensorParserConfig = sensorParserConfig; + component.init(); + component.newSensorParserConfig.numWorkers = 3; + component.newSensorParserConfig.numAckers = 3; + component.newSensorParserConfig.spoutParallelism = 3; + component.newSensorParserConfig.spoutNumTasks = 3; + component.newSensorParserConfig.parserParallelism = 3; + component.newSensorParserConfig.parserNumTasks = 3; + component.newSensorParserConfig.errorWriterParallelism = 3; + component.newSensorParserConfig.errorWriterNumTasks = 3; + component.newSpoutConfig = '{"spoutConfigProp": "spoutConfigValue2"}'; + component.newStormConfig = '{"stormConfigProp": "stormConfigValue2"}'; + component.onSave(); + expect(component.sensorParserConfig.numWorkers).toEqual(3); + expect(component.sensorParserConfig.numAckers).toEqual(3); + expect(component.sensorParserConfig.spoutParallelism).toEqual(3); + expect(component.sensorParserConfig.spoutNumTasks).toEqual(3); + expect(component.sensorParserConfig.parserParallelism).toEqual(3); + expect(component.sensorParserConfig.parserNumTasks).toEqual(3); + expect(component.sensorParserConfig.errorWriterParallelism).toEqual(3); + expect(component.sensorParserConfig.errorWriterNumTasks).toEqual(3); + expect(component.sensorParserConfig.spoutConfig).toEqual({ + spoutConfigProp: 'spoutConfigValue2' }); - - it('should save the fields', () => { - spyOn(component.hideStormSettings, 'emit'); - spyOn(component.onStormSettingsChanged, 'emit'); - component.sensorParserConfig = sensorParserConfig; - component.init(); - component.newSensorParserConfig.numWorkers = 3; - component.newSensorParserConfig.numAckers = 3; - component.newSensorParserConfig.spoutParallelism = 3; - component.newSensorParserConfig.spoutNumTasks = 3; - component.newSensorParserConfig.parserParallelism = 3; - component.newSensorParserConfig.parserNumTasks = 3; - component.newSensorParserConfig.errorWriterParallelism = 3; - component.newSensorParserConfig.errorWriterNumTasks = 3; - component.newSpoutConfig = '{"spoutConfigProp": "spoutConfigValue2"}'; - component.newStormConfig = '{"stormConfigProp": "stormConfigValue2"}'; - component.onSave(); - expect(component.sensorParserConfig.numWorkers).toEqual(3); - expect(component.sensorParserConfig.numAckers).toEqual(3); - expect(component.sensorParserConfig.spoutParallelism).toEqual(3); - expect(component.sensorParserConfig.spoutNumTasks).toEqual(3); - expect(component.sensorParserConfig.parserParallelism).toEqual(3); - expect(component.sensorParserConfig.parserNumTasks).toEqual(3); - expect(component.sensorParserConfig.errorWriterParallelism).toEqual(3); - expect(component.sensorParserConfig.errorWriterNumTasks).toEqual(3); - expect(component.sensorParserConfig.spoutConfig).toEqual({'spoutConfigProp': 'spoutConfigValue2'}); - expect(component.sensorParserConfig.stormConfig).toEqual({'stormConfigProp': 'stormConfigValue2'}); - expect(component.hideStormSettings.emit).toHaveBeenCalled(); - expect(component.onStormSettingsChanged.emit).toHaveBeenCalled(); - }); - - it('hasSpoutConfigChanged should properly detect changes', () => { - let sensorParserConfigWithSpoutConfig = new SensorParserConfig(); - sensorParserConfigWithSpoutConfig.spoutConfig = {}; - component.sensorParserConfig = sensorParserConfigWithSpoutConfig; - component.newSpoutConfig = '{}'; - expect(component.hasSpoutConfigChanged()).toEqual(false); - - sensorParserConfigWithSpoutConfig.spoutConfig = {'field': 'value'}; - component.sensorParserConfig = sensorParserConfigWithSpoutConfig; - component.newSpoutConfig = '{ "field" : "value" }'; - expect(component.hasSpoutConfigChanged()).toEqual(false); - - sensorParserConfigWithSpoutConfig.spoutConfig = {'field': 'value'}; - component.sensorParserConfig = sensorParserConfigWithSpoutConfig; - component.newSpoutConfig = '{"field": "value2"}'; - expect(component.hasSpoutConfigChanged()).toEqual(true); - - component.newSpoutConfig = '{"field": "value2", }'; - expect(component.hasSpoutConfigChanged()).toEqual(true); - }); - - it('hasStormConfigChanged should properly detect changes', () => { - let sensorParserConfigWithStormConfig = new SensorParserConfig(); - sensorParserConfigWithStormConfig.stormConfig = {}; - component.sensorParserConfig = sensorParserConfigWithStormConfig; - component.newStormConfig = '{}'; - expect(component.hasStormConfigChanged()).toEqual(false); - - sensorParserConfigWithStormConfig.stormConfig = {'field': 'value'}; - component.sensorParserConfig = sensorParserConfigWithStormConfig; - component.newStormConfig = '{ "field" : "value" }'; - expect(component.hasStormConfigChanged()).toEqual(false); - - sensorParserConfigWithStormConfig.stormConfig = {'field': 'value'}; - component.sensorParserConfig = sensorParserConfigWithStormConfig; - component.newStormConfig = '{"field": "value2"}'; - expect(component.hasStormConfigChanged()).toEqual(true); - - component.newSpoutConfig = '{"field": "value2", }'; - expect(component.hasStormConfigChanged()).toEqual(true); - }); - - it('should hide panel', () => { - spyOn(component.hideStormSettings, 'emit'); - - component.onCancel(); - - expect(component.hideStormSettings.emit).toHaveBeenCalled(); - - fixture.destroy(); + expect(component.sensorParserConfig.stormConfig).toEqual({ + stormConfigProp: 'stormConfigValue2' }); + expect(component.hideStormSettings.emit).toHaveBeenCalled(); + expect(component.onStormSettingsChanged.emit).toHaveBeenCalled(); + }); + + it('hasSpoutConfigChanged should properly detect changes', () => { + let sensorParserConfigWithSpoutConfig = new SensorParserConfig(); + sensorParserConfigWithSpoutConfig.spoutConfig = {}; + component.sensorParserConfig = sensorParserConfigWithSpoutConfig; + component.newSpoutConfig = '{}'; + expect(component.hasSpoutConfigChanged()).toEqual(false); + + sensorParserConfigWithSpoutConfig.spoutConfig = { field: 'value' }; + component.sensorParserConfig = sensorParserConfigWithSpoutConfig; + component.newSpoutConfig = '{ "field" : "value" }'; + expect(component.hasSpoutConfigChanged()).toEqual(false); + + sensorParserConfigWithSpoutConfig.spoutConfig = { field: 'value' }; + component.sensorParserConfig = sensorParserConfigWithSpoutConfig; + component.newSpoutConfig = '{"field": "value2"}'; + expect(component.hasSpoutConfigChanged()).toEqual(true); + + component.newSpoutConfig = '{"field": "value2", }'; + expect(component.hasSpoutConfigChanged()).toEqual(true); + }); + + it('hasStormConfigChanged should properly detect changes', () => { + let sensorParserConfigWithStormConfig = new SensorParserConfig(); + sensorParserConfigWithStormConfig.stormConfig = {}; + component.sensorParserConfig = sensorParserConfigWithStormConfig; + component.newStormConfig = '{}'; + expect(component.hasStormConfigChanged()).toEqual(false); + + sensorParserConfigWithStormConfig.stormConfig = { field: 'value' }; + component.sensorParserConfig = sensorParserConfigWithStormConfig; + component.newStormConfig = '{ "field" : "value" }'; + expect(component.hasStormConfigChanged()).toEqual(false); + + sensorParserConfigWithStormConfig.stormConfig = { field: 'value' }; + component.sensorParserConfig = sensorParserConfigWithStormConfig; + component.newStormConfig = '{"field": "value2"}'; + expect(component.hasStormConfigChanged()).toEqual(true); + + component.newSpoutConfig = '{"field": "value2", }'; + expect(component.hasStormConfigChanged()).toEqual(true); + }); + + it('should hide panel', () => { + spyOn(component.hideStormSettings, 'emit'); + + component.onCancel(); + + expect(component.hideStormSettings.emit).toHaveBeenCalled(); + + fixture.destroy(); + }); });
http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/sensors/sensor-threat-triage/sensor-threat-triage.component.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/sensors/sensor-threat-triage/sensor-threat-triage.component.spec.ts b/metron-interface/metron-config/src/app/sensors/sensor-threat-triage/sensor-threat-triage.component.spec.ts index b9e595e..43e8e6b 100644 --- a/metron-interface/metron-config/src/app/sensors/sensor-threat-triage/sensor-threat-triage.component.spec.ts +++ b/metron-interface/metron-config/src/app/sensors/sensor-threat-triage/sensor-threat-triage.component.spec.ts @@ -15,16 +15,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {SimpleChange, SimpleChanges} from '@angular/core'; -import {Http} from '@angular/http'; -import {async, TestBed, ComponentFixture} from '@angular/core/testing'; -import {SensorThreatTriageComponent, SortOrderOption, ThreatTriageFilter} from './sensor-threat-triage.component'; -import {SensorEnrichmentConfig, ThreatIntelConfig} from '../../model/sensor-enrichment-config'; -import {RiskLevelRule} from '../../model/risk-level-rule'; -import {SensorEnrichmentConfigService} from '../../service/sensor-enrichment-config.service'; -import {Observable} from 'rxjs/Observable'; -import '../../rxjs-operators'; -import {SensorThreatTriageModule} from './sensor-threat-triage.module'; +import { SimpleChange, SimpleChanges } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { async, TestBed, ComponentFixture } from '@angular/core/testing'; +import { + SensorThreatTriageComponent, + SortOrderOption, + ThreatTriageFilter +} from './sensor-threat-triage.component'; +import { + SensorEnrichmentConfig, + ThreatIntelConfig +} from '../../model/sensor-enrichment-config'; +import { RiskLevelRule } from '../../model/risk-level-rule'; +import { SensorEnrichmentConfigService } from '../../service/sensor-enrichment-config.service'; +import { Observable } from 'rxjs'; +import { SensorThreatTriageModule } from './sensor-threat-triage.module'; class MockSensorEnrichmentConfigService { public getAvailableThreatTriageAggregators(): Observable<string[]> { @@ -36,7 +42,6 @@ class MockSensorEnrichmentConfigService { } describe('Component: SensorThreatTriageComponent', () => { - let component: SensorThreatTriageComponent; let fixture: ComponentFixture<SensorThreatTriageComponent>; let sensorEnrichmentConfigService: SensorEnrichmentConfigService; @@ -45,15 +50,21 @@ describe('Component: SensorThreatTriageComponent', () => { TestBed.configureTestingModule({ imports: [SensorThreatTriageModule], providers: [ - {provide: Http}, - {provide: SensorEnrichmentConfigService, useClass: MockSensorEnrichmentConfigService}, + { provide: HttpClient }, + { + provide: SensorEnrichmentConfigService, + useClass: MockSensorEnrichmentConfigService + } ] - }).compileComponents() - .then(() => { - fixture = TestBed.createComponent(SensorThreatTriageComponent); - component = fixture.componentInstance; - sensorEnrichmentConfigService = fixture.debugElement.injector.get(SensorEnrichmentConfigService); - }); + }) + .compileComponents() + .then(() => { + fixture = TestBed.createComponent(SensorThreatTriageComponent); + component = fixture.componentInstance; + sensorEnrichmentConfigService = fixture.debugElement.injector.get( + SensorEnrichmentConfigService + ); + }); })); it('should create an instance', () => { @@ -63,12 +74,14 @@ describe('Component: SensorThreatTriageComponent', () => { it('should create an instance', async(() => { spyOn(component, 'init'); - let changes: SimpleChanges = {'showThreatTriage': new SimpleChange(false, true)}; + let changes: SimpleChanges = { + showThreatTriage: new SimpleChange(false, true, true) + }; component.ngOnChanges(changes); expect(component.init).toHaveBeenCalled(); - changes = {'showStellar': new SimpleChange(true, false)}; + changes = { showStellar: new SimpleChange(true, false, false) }; component.ngOnChanges(changes); expect(component.init['calls'].count()).toEqual(1); @@ -89,22 +102,25 @@ describe('Component: SensorThreatTriageComponent', () => { it('should get color', async(() => { let sensorEnrichmentConfig = new SensorEnrichmentConfig(); - sensorEnrichmentConfig.threatIntel = Object.assign(new ThreatIntelConfig(), { - 'triageConfig': { - 'riskLevelRules': { - 'ruleA': 15, - 'ruleB': 95, - 'ruleC': 50 - }, - 'aggregator': 'MAX', - 'aggregationConfig': {} + sensorEnrichmentConfig.threatIntel = Object.assign( + new ThreatIntelConfig(), + { + triageConfig: { + riskLevelRules: { + ruleA: 15, + ruleB: 95, + ruleC: 50 + }, + aggregator: 'MAX', + aggregationConfig: {} + } } - }); + ); component.sensorEnrichmentConfig = sensorEnrichmentConfig; - let ruleA = {name: 'ruleA', rule: 'rule A', score: 15, comment: ''}; - let ruleB = {name: 'ruleB', rule: 'rule B', score: 95, comment: ''}; - let ruleC = {name: 'ruleC', rule: 'rule C', score: 50, comment: ''}; + let ruleA = { name: 'ruleA', rule: 'rule A', score: 15, comment: '' }; + let ruleB = { name: 'ruleB', rule: 'rule B', score: 95, comment: '' }; + let ruleC = { name: 'ruleC', rule: 'rule C', score: 50, comment: '' }; expect(component.getRuleColor(ruleA)).toEqual('khaki'); expect(component.getRuleColor(ruleB)).toEqual('red'); @@ -114,26 +130,30 @@ describe('Component: SensorThreatTriageComponent', () => { })); it('should edit rules', async(() => { - let ruleA = {name: 'ruleA', rule: 'rule A', score: 15, comment: ''}; - let ruleB = {name: 'ruleB', rule: 'rule B', score: 95, comment: ''}; - let ruleC = {name: 'ruleC', rule: 'rule C', score: 50, comment: ''}; - let ruleD = {name: 'ruleD', rule: 'rule D', score: 85, comment: ''}; - let ruleE = {name: 'ruleE', rule: 'rule E', score: 5, comment: ''}; - let ruleF = {name: 'ruleF', rule: 'rule F', score: 21, comment: ''}; - let ruleG = {name: 'ruleG', rule: 'rule G', score: 100, comment: ''}; + let ruleA = { name: 'ruleA', rule: 'rule A', score: 15, comment: '' }; + let ruleB = { name: 'ruleB', rule: 'rule B', score: 95, comment: '' }; + let ruleC = { name: 'ruleC', rule: 'rule C', score: 50, comment: '' }; + let ruleD = { name: 'ruleD', rule: 'rule D', score: 85, comment: '' }; + let ruleE = { name: 'ruleE', rule: 'rule E', score: 5, comment: '' }; + let ruleF = { name: 'ruleF', rule: 'rule F', score: 21, comment: '' }; + let ruleG = { name: 'ruleG', rule: 'rule G', score: 100, comment: '' }; let sensorEnrichmentConfig = new SensorEnrichmentConfig(); - sensorEnrichmentConfig.threatIntel = Object.assign(new ThreatIntelConfig(), { - 'triageConfig': { - 'riskLevelRules': [ruleA, ruleB, ruleC, ruleD, ruleE], - 'aggregator': 'MAX', - 'aggregationConfig': {} + sensorEnrichmentConfig.threatIntel = Object.assign( + new ThreatIntelConfig(), + { + triageConfig: { + riskLevelRules: [ruleA, ruleB, ruleC, ruleD, ruleE], + aggregator: 'MAX', + aggregationConfig: {} + } } - }); + ); component.sensorEnrichmentConfig = sensorEnrichmentConfig; - - let changes: SimpleChanges = {'showThreatTriage': new SimpleChange(false, true)}; + let changes: SimpleChanges = { + showThreatTriage: new SimpleChange(false, true, true) + }; component.ngOnChanges(changes); // sorted by score high to low @@ -170,7 +190,14 @@ describe('Component: SensorThreatTriageComponent', () => { component.currentRiskLevelRule = ruleF; expect(component.showTextEditor).toEqual(true); component.onSubmitTextEditor(ruleF); - expect(component.visibleRules).toEqual([ruleE, ruleA, ruleF, ruleC, ruleD, ruleB]); + expect(component.visibleRules).toEqual([ + ruleE, + ruleA, + ruleF, + ruleC, + ruleD, + ruleB + ]); expect(component.lowAlerts).toEqual(2); expect(component.mediumAlerts).toEqual(2); expect(component.highAlerts).toEqual(2); @@ -206,6 +233,4 @@ describe('Component: SensorThreatTriageComponent', () => { fixture.destroy(); })); - - }); http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/authentication.service.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/authentication.service.spec.ts b/metron-interface/metron-config/src/app/service/authentication.service.spec.ts index 7f9b296..dedb69c 100644 --- a/metron-interface/metron-config/src/app/service/authentication.service.spec.ts +++ b/metron-interface/metron-config/src/app/service/authentication.service.spec.ts @@ -15,176 +15,138 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Router} from '@angular/router'; -import {async, inject, TestBed} from '@angular/core/testing'; -import {MockBackend, MockConnection} from '@angular/http/testing'; -import {HttpModule, XHRBackend, Response, ResponseOptions, Http} from '@angular/http'; -import '../rxjs-operators'; -import {Observable} from 'rxjs/Observable'; -import {AuthenticationService} from './authentication.service'; -import {APP_CONFIG, METRON_REST_CONFIG} from '../app.config'; -import {IAppConfig} from '../app.config.interface'; +import { Router } from '@angular/router'; +import { TestBed } from '@angular/core/testing'; +import { HttpErrorResponse } from '@angular/common/http'; +import { + HttpClientTestingModule, + HttpTestingController +} from '@angular/common/http/testing'; +import { AuthenticationService } from './authentication.service'; +import { APP_CONFIG, METRON_REST_CONFIG } from '../app.config'; class MockRouter { - - navigateByUrl(url: string) { - - } + navigateByUrl(url: string) {} } describe('AuthenticationService', () => { + let authenticationService: AuthenticationService; + let mockBackend: HttpTestingController; + let router: MockRouter; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [ + AuthenticationService, + { provide: Router, useClass: MockRouter }, + { provide: APP_CONFIG, useValue: METRON_REST_CONFIG } + ] + }); + authenticationService = TestBed.get(AuthenticationService); + mockBackend = TestBed.get(HttpTestingController); + router = TestBed.get(Router); + }); + + afterEach(() => { + mockBackend.verify(); + }); + + describe('when service functions', () => { + it('init', () => { + authenticationService.init(); + authenticationService.onLoginEvent.getValue(); + + const req = mockBackend.match('/api/v1/user'); + req[1].flush('user'); + expect(req[1].request.method).toBe('GET'); + expect(authenticationService.onLoginEvent.getValue()).toEqual(true); + }); + + it('login', () => { + let errorObj = new HttpErrorResponse({ + status: 404, + statusText: 'Not Found' + }); + spyOn(router, 'navigateByUrl'); + + authenticationService.login('test', 'test', error => {}); + let errorSpy = jasmine.createSpy('error'); + authenticationService.login('test', 'test', errorSpy); + + const req = mockBackend.match('/api/v1/user'); + req[1].flush('test'); + expect(req[1].request.method).toBe('GET'); + + expect(router.navigateByUrl).toHaveBeenCalledWith('/sensors'); + expect(authenticationService.onLoginEvent.getValue()).toEqual(true); + req[2].flush('Error', errorObj); + expect(req[2].request.method).toBe('GET'); + expect(errorSpy).toHaveBeenCalled(); + }); - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [HttpModule], - providers: [ - AuthenticationService, - {provide: XHRBackend, useClass: MockBackend}, - {provide: Router, useClass: MockRouter}, - {provide: APP_CONFIG, useValue: METRON_REST_CONFIG} - ] - }) - .compileComponents(); - })); - - describe('when service functions', () => { - it('can instantiate service when inject service', - inject([AuthenticationService], (service: AuthenticationService) => { - expect(service instanceof AuthenticationService).toBe(true); - })); + it('logout', () => { + spyOn(router, 'navigateByUrl'); + spyOn(authenticationService.onLoginEvent, 'next'); + authenticationService.logout(); + const req = mockBackend.match('/logout'); + const req2 = mockBackend.expectOne('/api/v1/user'); + req.map(r => r.flush('')); + expect(req[0].request.method).toBe('POST'); + + expect(router.navigateByUrl).toHaveBeenCalledWith('/login'); + expect(authenticationService.onLoginEvent.getValue()).toEqual(false); + }); + + it('checkAuthentication', () => { + let isAuthenticated = false; + spyOn(router, 'navigateByUrl'); + spyOn(authenticationService, 'isAuthenticated').and.callFake(function() { + return isAuthenticated; + }); + + authenticationService.checkAuthentication(); + expect(router.navigateByUrl).toHaveBeenCalledWith('/login'); + isAuthenticated = true; + authenticationService.checkAuthentication(); + expect(router.navigateByUrl['calls'].count()).toEqual(1); + const req = mockBackend.expectOne('/api/v1/user'); }); - describe('when service functions', () => { - let authenticationService: AuthenticationService; - let mockBackend: MockBackend; - let userResponse: Response; - let userName = 'test'; - let router: MockRouter; - - beforeEach(inject([Http, XHRBackend, Router, AuthenticationService, APP_CONFIG], - (http: Http, be: MockBackend, mRouter: MockRouter, service: AuthenticationService, config: IAppConfig) => { - mockBackend = be; - router = mRouter; - authenticationService = service; - userResponse = new Response(new ResponseOptions({status: 200, body: userName})); - })); - - it('init', async(inject([], () => { - let userResponsesuccess = true; - spyOn(authenticationService.onLoginEvent, 'emit'); - spyOn(authenticationService, 'getCurrentUser').and.callFake(function() { - if (userResponsesuccess) { - return Observable.create(observer => { - observer.next(userResponse); - observer.complete(); - }); - } - - return Observable.throw('Error'); - }); - - authenticationService.init(); - expect(authenticationService.onLoginEvent.emit).toHaveBeenCalledWith(true); - - userResponsesuccess = false; - authenticationService.init(); - expect(authenticationService.onLoginEvent.emit['calls'].count()).toEqual(2); - - }))); - - it('login', async(inject([], () => { - let responseMessageSuccess = true; - mockBackend.connections.subscribe((c: MockConnection) => { - if (responseMessageSuccess) { - c.mockRespond(userResponse); - } else { - c.mockError(new Error('login failed')); - } - }); - - spyOn(router, 'navigateByUrl'); - spyOn(authenticationService.onLoginEvent, 'emit'); - authenticationService.login('test', 'test', error => { - }); - - expect(router.navigateByUrl).toHaveBeenCalledWith('/sensors'); - expect(authenticationService.onLoginEvent.emit).toHaveBeenCalled(); - - responseMessageSuccess = false; - let errorSpy = jasmine.createSpy('error'); - authenticationService.login('test', 'test', errorSpy); - expect(errorSpy).toHaveBeenCalledWith(new Error('login failed')); - - }))); - - it('logout', async(inject([], () => { - let responseMessageSuccess = true; - mockBackend.connections.subscribe((c: MockConnection) => { - if (responseMessageSuccess) { - c.mockRespond(userResponse); - } else { - c.mockError(new Error('login failed')); - } - }); - - spyOn(router, 'navigateByUrl'); - spyOn(authenticationService.onLoginEvent, 'emit'); - authenticationService.logout(); - - expect(router.navigateByUrl).toHaveBeenCalledWith('/login'); - expect(authenticationService.onLoginEvent.emit).toHaveBeenCalled(); - - responseMessageSuccess = false; - spyOn(console, 'log'); - authenticationService.logout(); - expect(console.log).toHaveBeenCalled(); - - }))); - - it('checkAuthentication', async(inject([], () => { - let isAuthenticated = false; - spyOn(router, 'navigateByUrl'); - spyOn(authenticationService, 'isAuthenticated').and.callFake(function() { - return isAuthenticated; - }); - - authenticationService.checkAuthentication(); - expect(router.navigateByUrl).toHaveBeenCalledWith('/login'); - - isAuthenticated = true; - authenticationService.checkAuthentication(); - expect(router.navigateByUrl['calls'].count()).toEqual(1); - }))); - - it('getCurrentUser', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => userResponse); - authenticationService.getCurrentUser(null).subscribe( - result => { - expect(result).toEqual(''); - }, error => console.log(error)); - }))); - - it('isAuthenticationChecked', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(userResponse)); - - expect(authenticationService.isAuthenticationChecked()).toEqual(false); - - authenticationService.login('test', 'test', null); - expect(authenticationService.isAuthenticationChecked()).toEqual(true); - - }))); - - it('isAuthenticated', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(userResponse)); + it('getCurrentUser', () => { + authenticationService.getCurrentUser().subscribe( + result => { + expect(result).toEqual(''); + }, + error => console.log(error) + ); + const req = mockBackend.match('/api/v1/user'); + req.map(r => { + expect(r.request.method).toBe('GET'); + r.flush(''); + }); + }); - expect(authenticationService.isAuthenticated()).toEqual(false); + it('isAuthenticationChecked', () => { + expect(authenticationService.isAuthenticationChecked()).toEqual(false); - authenticationService.login('test', 'test', null); - expect(authenticationService.isAuthenticated()).toEqual(true); + authenticationService.login('test', 'test', null); + const req = mockBackend.match('/api/v1/user'); + req[1].flush('user'); - }))); + expect(authenticationService.isAuthenticationChecked()).toEqual(true); }); + it('isAuthenticated', () => { + expect(authenticationService.isAuthenticated()).toEqual(false); + + authenticationService.login('test', 'test', null); + authenticationService.login('test', 'test', null); + const req = mockBackend.match('/api/v1/user'); + req[1].flush('user'); + expect(authenticationService.isAuthenticated()).toEqual(true); + }); + }); }); http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/authentication.service.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/authentication.service.ts b/metron-interface/metron-config/src/app/service/authentication.service.ts index 5fd50f3..3c4d880 100644 --- a/metron-interface/metron-config/src/app/service/authentication.service.ts +++ b/metron-interface/metron-config/src/app/service/authentication.service.ts @@ -15,61 +15,71 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Injectable, EventEmitter, Inject} from '@angular/core'; -import {Http, Headers, RequestOptions, Response} from '@angular/http'; -import {Router} from '@angular/router'; -import {Observable} from 'rxjs/Observable'; -import {IAppConfig} from '../app.config.interface'; -import {APP_CONFIG} from '../app.config'; +import { Injectable, Inject } from '@angular/core'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; +import { Router } from '@angular/router'; +import { BehaviorSubject } from 'rxjs'; +import { IAppConfig } from '../app.config.interface'; +import { APP_CONFIG } from '../app.config'; @Injectable() export class AuthenticationService { - - private static USER_NOT_VERIFIED: string = 'USER-NOT-VERIFIED'; + private static USER_NOT_VERIFIED = 'USER-NOT-VERIFIED'; private currentUser: string = AuthenticationService.USER_NOT_VERIFIED; loginUrl: string = this.config.apiEndpoint + '/user'; - logoutUrl: string = '/logout'; - defaultHeaders = {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}; - onLoginEvent: EventEmitter<boolean> = new EventEmitter<boolean>(); + logoutUrl = '/logout'; + onLoginEvent: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); - constructor(private http: Http, private router: Router, @Inject(APP_CONFIG) private config: IAppConfig) { + constructor( + private http: HttpClient, + private router: Router, + @Inject(APP_CONFIG) private config: IAppConfig + ) { this.init(); } public init() { - this.getCurrentUser(new RequestOptions({headers: new Headers(this.defaultHeaders)})).subscribe((response: Response) => { - this.currentUser = response.text(); + this.getCurrentUser({ responseType: 'text' }).subscribe( + response => { + this.currentUser = response.toString(); if (this.currentUser) { - this.onLoginEvent.emit(true); + this.onLoginEvent.next(true); } - }, error => { - this.onLoginEvent.emit(false); - }); + }, + error => { + this.onLoginEvent.next(false); + } + ); } public login(username: string, password: string, onError): void { - let loginHeaders: Headers = new Headers(this.defaultHeaders); - loginHeaders.append('authorization', 'Basic ' + btoa(username + ':' + password)); - let loginOptions: RequestOptions = new RequestOptions({headers: loginHeaders}); - this.getCurrentUser(loginOptions).subscribe((response: Response) => { - this.currentUser = response.text(); + let credentials = btoa(username + ':' + password); + this.getCurrentUser({ + headers: new HttpHeaders({ Authorization: `Basic ${credentials}` }), + responseType: 'text' + }).subscribe( + response => { + this.currentUser = response.toString(); this.router.navigateByUrl('/sensors'); - this.onLoginEvent.emit(true); + this.onLoginEvent.next(true); }, error => { onError(error); - }); + } + ); } public logout(): void { - this.http.post(this.logoutUrl, {}, new RequestOptions({headers: new Headers(this.defaultHeaders)})).subscribe(response => { + this.http.post(this.logoutUrl, {}).subscribe( + response => { this.currentUser = AuthenticationService.USER_NOT_VERIFIED; - this.onLoginEvent.emit(false); + this.onLoginEvent.next(false); this.router.navigateByUrl('/login'); }, error => { console.log(error); - }); + } + ); } public checkAuthentication() { @@ -78,7 +88,7 @@ export class AuthenticationService { } } - public getCurrentUser(options: RequestOptions): Observable<Response> { + public getCurrentUser(options?: {}) { return this.http.get(this.loginUrl, options); } @@ -87,6 +97,9 @@ export class AuthenticationService { } public isAuthenticated(): boolean { - return this.currentUser !== AuthenticationService.USER_NOT_VERIFIED && this.currentUser != null; + return ( + this.currentUser !== AuthenticationService.USER_NOT_VERIFIED && + this.currentUser != null + ); } } http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/global-config.service.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/global-config.service.spec.ts b/metron-interface/metron-config/src/app/service/global-config.service.spec.ts index f53c3f3..9ad3b13 100644 --- a/metron-interface/metron-config/src/app/service/global-config.service.spec.ts +++ b/metron-interface/metron-config/src/app/service/global-config.service.spec.ts @@ -15,85 +15,66 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {async, inject, TestBed} from '@angular/core/testing'; -import {MockBackend, MockConnection} from '@angular/http/testing'; -import {HttpModule, XHRBackend, Response, ResponseOptions, Http} from '@angular/http'; -import '../rxjs-operators'; -import {APP_CONFIG, METRON_REST_CONFIG} from '../app.config'; -import {IAppConfig} from '../app.config.interface'; -import {GlobalConfigService} from './global-config.service'; +import { TestBed } from '@angular/core/testing'; +import { APP_CONFIG, METRON_REST_CONFIG } from '../app.config'; +import { GlobalConfigService } from './global-config.service'; +import { + HttpTestingController, + HttpClientTestingModule +} from '@angular/common/http/testing'; describe('GlobalConfigService', () => { + let mockBackend: HttpTestingController; + let globalConfigService: GlobalConfigService; - beforeEach(async(() => { + beforeEach(() => { TestBed.configureTestingModule({ - imports: [HttpModule], + imports: [HttpClientTestingModule], providers: [ GlobalConfigService, - {provide: XHRBackend, useClass: MockBackend}, - {provide: APP_CONFIG, useValue: METRON_REST_CONFIG} + { provide: APP_CONFIG, useValue: METRON_REST_CONFIG } ] - }) - .compileComponents(); - })); - - it('can instantiate service when inject service', - inject([GlobalConfigService], (service: GlobalConfigService) => { - expect(service instanceof GlobalConfigService).toBe(true); - })); - - it('can instantiate service with "new"', inject([Http, APP_CONFIG], (http: Http, config: IAppConfig) => { - expect(http).not.toBeNull('http should be provided'); - let service = new GlobalConfigService(http, config); - expect(service instanceof GlobalConfigService).toBe(true, 'new service should be ok'); - })); - + }); + mockBackend = TestBed.get(HttpTestingController); + globalConfigService = TestBed.get(GlobalConfigService); + }); - it('can provide the mockBackend as XHRBackend', - inject([XHRBackend], (backend: MockBackend) => { - expect(backend).not.toBeNull('backend should be provided'); - })); + afterEach(() => { + mockBackend.verify(); + }); describe('when service functions', () => { - let globalConfigService: GlobalConfigService; - let mockBackend: MockBackend; - let globalConfig = {'field': 'value'}; - let globalConfigResponse: Response; - let deleteResponse: Response; - - beforeEach(inject([Http, XHRBackend, APP_CONFIG], (http: Http, be: MockBackend, config: IAppConfig) => { - mockBackend = be; - globalConfigService = new GlobalConfigService(http, config); - globalConfigResponse = new Response(new ResponseOptions({status: 200, body: globalConfig})); - })); - - it('post', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(globalConfigResponse)); + let globalConfig = { field: 'value' }; + it('post', () => { globalConfigService.post(globalConfig).subscribe( - result => { - expect(result).toEqual(globalConfig); - }, error => console.log(error)); - }))); + result => { + expect(result).toEqual(globalConfig); + }, + error => console.log(error) + ); - it('get', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(globalConfigResponse)); + const req = mockBackend.expectOne('/api/v1/global/config'); + expect(req.request.method).toBe('POST'); + req.flush(globalConfig); + }); + it('get', () => { globalConfigService.get().subscribe( result => { expect(result).toEqual(globalConfig); - }, error => console.log(error)); - }))); - - it('deleteSensorParserConfigs', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(deleteResponse)); - + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/global/config'); + expect(req.request.method).toBe('GET'); + req.flush(globalConfig); + }); + + it('deleteSensorParserConfigs', () => { globalConfigService.delete().subscribe(result => { expect(result.status).toEqual(200); }); - }))); + }); }); - }); - - http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/global-config.service.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/global-config.service.ts b/metron-interface/metron-config/src/app/service/global-config.service.ts index 1ed4325..84bd014 100644 --- a/metron-interface/metron-config/src/app/service/global-config.service.ts +++ b/metron-interface/metron-config/src/app/service/global-config.service.ts @@ -16,8 +16,10 @@ * limitations under the License. */ import {Injectable, Inject} from '@angular/core'; -import {Http, Headers, RequestOptions, Response, ResponseOptions} from '@angular/http'; -import {Observable} from 'rxjs/Observable'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; +import { Response, ResponseOptions } from '@angular/http'; +import {Observable} from 'rxjs'; +import { map, catchError } from 'rxjs/operators'; import {HttpUtil} from '../util/httpUtil'; import {IAppConfig} from '../app.config.interface'; import {APP_CONFIG} from '../app.config'; @@ -25,13 +27,10 @@ import {APP_CONFIG} from '../app.config'; @Injectable() export class GlobalConfigService { url = this.config.apiEndpoint + '/global/config'; - defaultHeaders = {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}; - private globalConfig = { + private globalConfig = {}; - }; - - constructor(private http: Http, @Inject(APP_CONFIG) private config: IAppConfig) { + constructor(private http: HttpClient, @Inject(APP_CONFIG) private config: IAppConfig) { this.globalConfig['solr.collection'] = 'metron'; this.globalConfig['storm.indexingWorkers'] = 1; this.globalConfig['storm.indexingExecutors'] = 2; @@ -51,15 +50,15 @@ export class GlobalConfigService { } public post(globalConfig: {}): Observable<{}> { - return this.http.post(this.url, globalConfig, new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + return this.http.post(this.url, globalConfig).pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError)); } public get(): Observable<{}> { - return this.http.get(this.url , new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + return this.http.get(this.url).pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError)); } public delete(): Observable<Response> { http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/grok-validation.service.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/grok-validation.service.spec.ts b/metron-interface/metron-config/src/app/service/grok-validation.service.spec.ts index da45a80..d66b0aa 100644 --- a/metron-interface/metron-config/src/app/service/grok-validation.service.spec.ts +++ b/metron-interface/metron-config/src/app/service/grok-validation.service.spec.ts @@ -15,92 +15,80 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {async, inject, TestBed} from '@angular/core/testing'; -import {MockBackend, MockConnection} from '@angular/http/testing'; -import {GrokValidationService} from './grok-validation.service'; -import {GrokValidation} from '../model/grok-validation'; -import {HttpModule, XHRBackend, Response, ResponseOptions, Http} from '@angular/http'; -import '../rxjs-operators'; -import {APP_CONFIG, METRON_REST_CONFIG} from '../app.config'; -import {IAppConfig} from '../app.config.interface'; +import { async, inject, TestBed } from '@angular/core/testing'; +import { GrokValidationService } from './grok-validation.service'; +import { GrokValidation } from '../model/grok-validation'; +import { APP_CONFIG, METRON_REST_CONFIG } from '../app.config'; +import { + HttpClientTestingModule, + HttpTestingController +} from '@angular/common/http/testing'; describe('GrokValidationService', () => { + let grokValidationService: GrokValidationService; + let mockBackend: HttpTestingController; - beforeEach(async(() => { + beforeEach(() => { TestBed.configureTestingModule({ - imports: [HttpModule], + imports: [HttpClientTestingModule], providers: [ GrokValidationService, - {provide: XHRBackend, useClass: MockBackend}, - {provide: APP_CONFIG, useValue: METRON_REST_CONFIG} + { provide: APP_CONFIG, useValue: METRON_REST_CONFIG } ] - }) - .compileComponents(); - })); - - it('can instantiate service when inject service', - inject([GrokValidationService], (service: GrokValidationService) => { - expect(service instanceof GrokValidationService).toBe(true); - })); - - it('can instantiate service with "new"', inject([Http, APP_CONFIG], (http: Http, config: IAppConfig) => { - expect(http).not.toBeNull('http should be provided'); - let service = new GrokValidationService(http, config); - expect(service instanceof GrokValidationService).toBe(true, 'new service should be ok'); - })); - + }); + grokValidationService = TestBed.get(GrokValidationService); + mockBackend = TestBed.get(HttpTestingController); + }); - it('can provide the mockBackend as XHRBackend', - inject([XHRBackend], (backend: MockBackend) => { - expect(backend).not.toBeNull('backend should be provided'); - })); + afterEach(() => { + mockBackend.verify(); + }); describe('when service functions', () => { - let grokValidationService: GrokValidationService; - let mockBackend: MockBackend; let grokValidation = new GrokValidation(); grokValidation.statement = 'statement'; grokValidation.sampleData = 'sampleData'; - grokValidation.results = {'results': 'results'}; + grokValidation.results = { results: 'results' }; let grokList = ['pattern']; let grokStatement = 'grok statement'; - let grokValidationResponse: Response; - let grokListResponse: Response; - let grokGetStatementResponse: Response; - beforeEach(inject([Http, XHRBackend, APP_CONFIG], (http: Http, be: MockBackend, config: IAppConfig) => { - mockBackend = be; - grokValidationService = new GrokValidationService(http, config); - grokValidationResponse = new Response(new ResponseOptions({status: 200, body: grokValidation})); - grokListResponse = new Response(new ResponseOptions({status: 200, body: grokList})); - grokGetStatementResponse = new Response(new ResponseOptions({status: 200, body: grokStatement})); - })); + it('validate', () => { + grokValidationService.validate(grokValidation).subscribe( + result => { + expect(result).toEqual(grokValidation); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/grok/validate'); + expect(req.request.method).toBe('POST'); + req.flush(grokValidation); + } + ); - it('validate', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(grokValidationResponse)); - - grokValidationService.validate(grokValidation).subscribe( - result => { - expect(result).toEqual(grokValidation); - }, error => console.log(error)); - }))); - - it('list', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(grokListResponse)); - grokValidationService.list().subscribe( - results => { - expect(results).toEqual(grokList); - }, error => console.log(error)); - }))); + it('list', () => { + grokValidationService.list().subscribe( + results => { + expect(results).toEqual(grokList); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/grok/list'); + expect(req.request.method).toBe('GET'); + req.flush(grokList); + } + ); - it('getStatement', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(grokGetStatementResponse)); - grokValidationService.getStatement('/path').subscribe( + it('getStatement', () => { + grokValidationService.getStatement('/path').subscribe( results => { expect(results).toEqual(grokStatement); - }, error => console.log(error)); - }))); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/grok/get/statement?path=/path'); + expect(req.request.method).toBe('GET'); + req.flush(grokStatement); + } + ); }); - - }); http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/grok-validation.service.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/grok-validation.service.ts b/metron-interface/metron-config/src/app/service/grok-validation.service.ts index bcdce82..7da8798 100644 --- a/metron-interface/metron-config/src/app/service/grok-validation.service.ts +++ b/metron-interface/metron-config/src/app/service/grok-validation.service.ts @@ -15,42 +15,45 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Injectable, Inject} from '@angular/core'; -import {Http, Headers, RequestOptions, URLSearchParams} from '@angular/http'; -import {Observable} from 'rxjs/Observable'; -import {GrokValidation} from '../model/grok-validation'; -import {HttpUtil} from '../util/httpUtil'; -import {IAppConfig} from '../app.config.interface'; -import {APP_CONFIG} from '../app.config'; +import { Injectable, Inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { map, catchError } from 'rxjs/operators'; +import { GrokValidation } from '../model/grok-validation'; +import { HttpUtil } from '../util/httpUtil'; +import { IAppConfig } from '../app.config.interface'; +import { APP_CONFIG } from '../app.config'; @Injectable() export class GrokValidationService { url = this.config.apiEndpoint + '/grok'; - defaultHeaders = {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}; - constructor(private http: Http, @Inject(APP_CONFIG) private config: IAppConfig) { - - } + constructor( + private http: HttpClient, + @Inject(APP_CONFIG) private config: IAppConfig + ) {} public validate(grokValidation: GrokValidation): Observable<GrokValidation> { - return this.http.post(this.url + '/validate', JSON.stringify(grokValidation), - new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + return this.http + .post(this.url + '/validate', JSON.stringify(grokValidation)) + .pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError) + ); } public list(): Observable<string[]> { - return this.http.get(this.url + '/list', new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + return this.http.get(this.url + '/list').pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError) + ); } - public getStatement(path: string): Observable<string> { - let params: URLSearchParams = new URLSearchParams(); - params.set('path', path); - return this.http.get(this.url + '/get/statement', new RequestOptions({headers: new Headers(this.defaultHeaders), search: params})) - .map(HttpUtil.extractString) - .catch(HttpUtil.handleError); + public getStatement(path: string): Observable<Object> { + const options: HttpParams = new HttpParams().set('path', path); + return this.http.get(this.url + '/get/statement', { params: options }).pipe( + map(HttpUtil.extractString), + catchError(HttpUtil.handleError) + ); } - } http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/hdfs.service.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/hdfs.service.spec.ts b/metron-interface/metron-config/src/app/service/hdfs.service.spec.ts index 16196ab..251d392 100644 --- a/metron-interface/metron-config/src/app/service/hdfs.service.spec.ts +++ b/metron-interface/metron-config/src/app/service/hdfs.service.spec.ts @@ -15,96 +15,81 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {async, inject, TestBed} from '@angular/core/testing'; -import {MockBackend, MockConnection} from '@angular/http/testing'; -import {HttpModule, XHRBackend, Response, ResponseOptions, Http} from '@angular/http'; -import '../rxjs-operators'; -import {APP_CONFIG, METRON_REST_CONFIG} from '../app.config'; -import {IAppConfig} from '../app.config.interface'; -import {HdfsService} from './hdfs.service'; + +import { TestBed } from '@angular/core/testing'; +import { APP_CONFIG, METRON_REST_CONFIG } from '../app.config'; +import { HdfsService } from './hdfs.service'; +import { + HttpTestingController, + HttpClientTestingModule +} from '@angular/common/http/testing'; describe('HdfsService', () => { + let hdfsService: HdfsService; + let mockBackend: HttpTestingController; - beforeEach(async(() => { + beforeEach(() => { TestBed.configureTestingModule({ - imports: [HttpModule], + imports: [HttpClientTestingModule], providers: [ HdfsService, - {provide: XHRBackend, useClass: MockBackend}, - {provide: APP_CONFIG, useValue: METRON_REST_CONFIG} + { provide: APP_CONFIG, useValue: METRON_REST_CONFIG } ] - }) - .compileComponents(); - })); - - it('can instantiate service when inject service', - inject([HdfsService], (service: HdfsService) => { - expect(service instanceof HdfsService).toBe(true); - })); - - it('can instantiate service with "new"', inject([Http, APP_CONFIG], (http: Http, config: IAppConfig) => { - expect(http).not.toBeNull('http should be provided'); - let service = new HdfsService(http, config); - expect(service instanceof HdfsService).toBe(true, 'new service should be ok'); - })); - - - it('can provide the mockBackend as XHRBackend', - inject([XHRBackend], (backend: MockBackend) => { - expect(backend).not.toBeNull('backend should be provided'); - })); + }); + hdfsService = TestBed.get(HdfsService); + mockBackend = TestBed.get(HttpTestingController); + }); describe('when service functions', () => { - let hdfsService: HdfsService; - let mockBackend: MockBackend; let fileList = ['file1', 'file2']; let contents = 'file contents'; - let listResponse: Response; - let readResponse: Response; - let postResponse: Response; - let deleteResponse: Response; - beforeEach(inject([Http, XHRBackend, APP_CONFIG], (http: Http, be: MockBackend, config: IAppConfig) => { - mockBackend = be; - hdfsService = new HdfsService(http, config); - listResponse = new Response(new ResponseOptions({status: 200, body: fileList})); - readResponse = new Response(new ResponseOptions({status: 200, body: contents})); - postResponse = new Response(new ResponseOptions({status: 200})); - deleteResponse = new Response(new ResponseOptions({status: 200})); - })); - - it('list', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(listResponse)); - hdfsService.list('/path').subscribe( - result => { - expect(result).toEqual(fileList); - }, error => console.log(error)); - }))); + it('list', () => { + hdfsService.list('/path').subscribe( + result => { + expect(result).toEqual(fileList); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/hdfs/list?path=/path'); + expect(req.request.method).toBe('GET'); + req.flush(fileList); + }); - it('read', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(readResponse)); - hdfsService.read('/path').subscribe( - result => { - expect(result).toEqual(contents); - }, error => console.log(error)); - }))); + it('read', () => { + hdfsService.read('/path').subscribe( + result => { + expect(result).toEqual(contents); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/hdfs?path=/path'); + expect(req.request.method).toBe('GET'); + req.flush(contents); + }); - it('post', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(postResponse)); - hdfsService.post('/path', contents).subscribe( + it('post', () => { + hdfsService.post('/path', contents).subscribe( result => { expect(result.status).toEqual(200); - }, error => console.log(error)); - }))); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/hdfs?path=/path'); + expect(req.request.method).toBe('POST'); + req.flush({ status: 200 }); + }); - it('deleteFile', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(deleteResponse)); - hdfsService.deleteFile('/path').subscribe( + it('deleteFile', () => { + hdfsService.deleteFile('/path').subscribe( result => { expect(result.status).toEqual(200); - }, error => console.log(error)); - }))); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/hdfs?path=/path'); + expect(req.request.method).toBe('DELETE'); + req.flush({ status: 200 }); + }); }); - - }); http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/hdfs.service.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/hdfs.service.ts b/metron-interface/metron-config/src/app/service/hdfs.service.ts index 4e4b808..fdeb001 100644 --- a/metron-interface/metron-config/src/app/service/hdfs.service.ts +++ b/metron-interface/metron-config/src/app/service/hdfs.service.ts @@ -15,49 +15,50 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Injectable, Inject} from '@angular/core'; -import {Http, Headers, RequestOptions, Response, URLSearchParams} from '@angular/http'; -import {Observable} from 'rxjs/Observable'; -import {HttpUtil} from '../util/httpUtil'; -import {IAppConfig} from '../app.config.interface'; -import {APP_CONFIG} from '../app.config'; +import { Injectable, Inject } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { map, catchError } from 'rxjs/operators'; +import { HttpUtil } from '../util/httpUtil'; +import { IAppConfig } from '../app.config.interface'; +import { APP_CONFIG } from '../app.config'; @Injectable() export class HdfsService { url = this.config.apiEndpoint + '/hdfs'; - defaultHeaders = {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}; - constructor(private http: Http, @Inject(APP_CONFIG) private config: IAppConfig) { - } + constructor( + private http: HttpClient, + @Inject(APP_CONFIG) private config: IAppConfig + ) {} public list(path: string): Observable<string[]> { - let params: URLSearchParams = new URLSearchParams(); - params.set('path', path); - return this.http.get(this.url + '/list', new RequestOptions({headers: new Headers(this.defaultHeaders), search: params})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + const options: HttpParams = new HttpParams().set('path', path); + return this.http.get(this.url + '/list', { params: options }).pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError) + ); } - public read(path: string): Observable<string> { - let params: URLSearchParams = new URLSearchParams(); - params.set('path', path); - return this.http.get(this.url , new RequestOptions({headers: new Headers(this.defaultHeaders), search: params})) - .map(HttpUtil.extractString) - .catch(HttpUtil.handleError); + public read(path: string): Observable<Object> { + const options: HttpParams = new HttpParams().set('path', path); + return this.http.get(this.url, { params: options }).pipe( + map(HttpUtil.extractString), + catchError(HttpUtil.handleError) + ); } - public post(path: string, contents: string): Observable<Response> { - let params: URLSearchParams = new URLSearchParams(); - params.set('path', path); - return this.http.post(this.url, contents, new RequestOptions({headers: new Headers(this.defaultHeaders), search: params})) - .catch(HttpUtil.handleError); + public post(path: string, contents: string): any { + const options: HttpParams = new HttpParams().set('path', path); + return this.http + .post(this.url, contents, { params: options }) + .pipe(catchError(HttpUtil.handleError)); } - public deleteFile(path: string): Observable<Response> { - let params: URLSearchParams = new URLSearchParams(); - params.set('path', path); - return this.http.delete(this.url, new RequestOptions({headers: new Headers(this.defaultHeaders), search: params})) - .catch(HttpUtil.handleError); + public deleteFile(path: string): any { + const options: HttpParams = new HttpParams().set('path', path); + return this.http + .delete(this.url, { params: options }) + .pipe(catchError(HttpUtil.handleError)); } - } http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/kafka.service.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/kafka.service.spec.ts b/metron-interface/metron-config/src/app/service/kafka.service.spec.ts index e6f1d7f..12f0c12 100644 --- a/metron-interface/metron-config/src/app/service/kafka.service.spec.ts +++ b/metron-interface/metron-config/src/app/service/kafka.service.spec.ts @@ -15,100 +15,89 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {async, inject, TestBed} from '@angular/core/testing'; -import {MockBackend, MockConnection} from '@angular/http/testing'; -import {KafkaService} from './kafka.service'; -import {KafkaTopic} from '../model/kafka-topic'; -import {HttpModule, XHRBackend, Response, ResponseOptions, Http} from '@angular/http'; -import '../rxjs-operators'; -import {APP_CONFIG, METRON_REST_CONFIG} from '../app.config'; -import {IAppConfig} from '../app.config.interface'; +import { TestBed } from '@angular/core/testing'; +import { KafkaService } from './kafka.service'; +import { KafkaTopic } from '../model/kafka-topic'; +import { APP_CONFIG, METRON_REST_CONFIG } from '../app.config'; +import { + HttpClientTestingModule, + HttpTestingController +} from '@angular/common/http/testing'; describe('KafkaService', () => { + let mockBackend: HttpTestingController; + let kafkaService: KafkaService; - beforeEach(async(() => { + beforeEach(() => { TestBed.configureTestingModule({ - imports: [HttpModule], + imports: [HttpClientTestingModule], providers: [ KafkaService, - {provide: XHRBackend, useClass: MockBackend}, - {provide: APP_CONFIG, useValue: METRON_REST_CONFIG} + { provide: APP_CONFIG, useValue: METRON_REST_CONFIG } ] - }) - .compileComponents(); - })); - - it('can instantiate service when inject service', - inject([KafkaService], (service: KafkaService) => { - expect(service instanceof KafkaService).toBe(true); - })); - - it('can instantiate service with "new"', inject([Http, APP_CONFIG], (http: Http, config: IAppConfig) => { - expect(http).not.toBeNull('http should be provided'); - let service = new KafkaService(http, config); - expect(service instanceof KafkaService).toBe(true, 'new service should be ok'); - })); + }); + mockBackend = TestBed.get(HttpTestingController); + kafkaService = TestBed.get(KafkaService); + }); - it('can provide the mockBackend as XHRBackend', - inject([XHRBackend], (backend: MockBackend) => { - expect(backend).not.toBeNull('backend should be provided'); - })); + afterEach(() => { + mockBackend.verify(); + }); describe('when service functions', () => { - let kafkaService: KafkaService; - let mockBackend: MockBackend; let kafkaTopic = new KafkaTopic(); kafkaTopic.name = 'bro'; kafkaTopic.numPartitions = 1; kafkaTopic.replicationFactor = 1; let sampleMessage = 'sample message'; - let kafkaResponse: Response; - let kafkaListResponse: Response; - let sampleMessageResponse: Response; - - beforeEach(inject([Http, XHRBackend, APP_CONFIG], (http: Http, be: MockBackend, config: IAppConfig) => { - mockBackend = be; - kafkaService = new KafkaService(http, config); - kafkaResponse = new Response(new ResponseOptions({status: 200, body: kafkaTopic})); - kafkaListResponse = new Response(new ResponseOptions({status: 200, body: [kafkaTopic]})); - sampleMessageResponse = new Response(new ResponseOptions({status: 200, body: sampleMessage})); - })); - - it('post', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(kafkaResponse)); + it('post', () => { kafkaService.post(kafkaTopic).subscribe( result => { expect(result).toEqual(kafkaTopic); - }, error => console.log(error)); - }))); - - it('get', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(kafkaResponse)); - + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/kafka/topic'); + expect(req.request.method).toBe('POST'); + req.flush(kafkaTopic); + }); + + it('get', () => { kafkaService.get('bro').subscribe( result => { expect(result).toEqual(kafkaTopic); - }, error => console.log(error)); - }))); - - it('list', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(kafkaListResponse)); - + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/kafka/topic/bro'); + expect(req.request.method).toBe('GET'); + req.flush(kafkaTopic); + }); + + it('list', () => { kafkaService.list().subscribe( result => { expect(result).toEqual([kafkaTopic]); - }, error => console.log(error)); - }))); - - it('sample', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(sampleMessageResponse)); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/kafka/topic'); + expect(req.request.method).toBe('GET'); + req.flush([kafkaTopic]); + }); + + it('sample', () => { kafkaService.sample('bro').subscribe( result => { expect(result).toEqual(sampleMessage); - }, error => console.log(error)); - }))); + }, + error => console.log(error) + ); + + const req = mockBackend.expectOne('/api/v1/kafka/topic/bro/sample'); + expect(req.request.method).toBe('GET'); + req.flush(sampleMessage); + }); }); - }); - http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/kafka.service.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/kafka.service.ts b/metron-interface/metron-config/src/app/service/kafka.service.ts index ac02366..f39f364 100644 --- a/metron-interface/metron-config/src/app/service/kafka.service.ts +++ b/metron-interface/metron-config/src/app/service/kafka.service.ts @@ -15,45 +15,50 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {Injectable, Inject} from '@angular/core'; -import {Http, Headers, RequestOptions} from '@angular/http'; -import {Observable} from 'rxjs/Observable'; -import {KafkaTopic} from '../model/kafka-topic'; -import {HttpUtil} from '../util/httpUtil'; -import {IAppConfig} from '../app.config.interface'; -import {APP_CONFIG} from '../app.config'; +import { Injectable, Inject } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { map, catchError } from 'rxjs/operators'; +import { KafkaTopic } from '../model/kafka-topic'; +import { HttpUtil } from '../util/httpUtil'; +import { IAppConfig } from '../app.config.interface'; +import { APP_CONFIG } from '../app.config'; +import { RestError } from '../model/rest-error'; @Injectable() export class KafkaService { url = this.config.apiEndpoint + '/kafka/topic'; - defaultHeaders = {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}; - constructor(private http: Http, @Inject(APP_CONFIG) private config: IAppConfig) { - - } + constructor( + private http: HttpClient, + @Inject(APP_CONFIG) private config: IAppConfig + ) {} public post(kafkaTopic: KafkaTopic): Observable<KafkaTopic> { - return this.http.post(this.url, JSON.stringify(kafkaTopic), new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + return this.http.post(this.url, JSON.stringify(kafkaTopic)).pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError) + ); } public get(name: string): Observable<KafkaTopic> { - return this.http.get(this.url + '/' + name, new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + return this.http.get(this.url + '/' + name).pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError) + ); } - public list(): Observable<string[]> { - return this.http.get(this.url, new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractData) - .catch(HttpUtil.handleError); + public list(): Observable<KafkaTopic[]> { + return this.http.get(this.url).pipe( + map(HttpUtil.extractData), + catchError(HttpUtil.handleError) + ); } - public sample(name: string): Observable<string> { - return this.http.get(this.url + '/' + name + '/sample', new RequestOptions({headers: new Headers(this.defaultHeaders)})) - .map(HttpUtil.extractString) - .catch(HttpUtil.handleError); + public sample(name: string): Observable<string | RestError> { + return this.http.get(this.url + '/' + name + '/sample').pipe( + map(HttpUtil.extractString), + catchError(HttpUtil.handleError) + ); } - } http://git-wip-us.apache.org/repos/asf/metron/blob/0c4c622b/metron-interface/metron-config/src/app/service/sensor-enrichment-config.service.spec.ts ---------------------------------------------------------------------- diff --git a/metron-interface/metron-config/src/app/service/sensor-enrichment-config.service.spec.ts b/metron-interface/metron-config/src/app/service/sensor-enrichment-config.service.spec.ts index 89863ee..e2cb131 100644 --- a/metron-interface/metron-config/src/app/service/sensor-enrichment-config.service.spec.ts +++ b/metron-interface/metron-config/src/app/service/sensor-enrichment-config.service.spec.ts @@ -15,130 +15,170 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import {async, inject, TestBed} from '@angular/core/testing'; -import {MockBackend, MockConnection} from '@angular/http/testing'; -import {SensorEnrichmentConfigService} from './sensor-enrichment-config.service'; -import {SensorEnrichmentConfig, EnrichmentConfig} from '../model/sensor-enrichment-config'; -import {HttpModule, XHRBackend, Response, ResponseOptions, Http} from '@angular/http'; -import '../rxjs-operators'; -import {METRON_REST_CONFIG, APP_CONFIG} from '../app.config'; -import {IAppConfig} from '../app.config.interface'; +import { TestBed } from '@angular/core/testing'; +import { SensorEnrichmentConfigService } from './sensor-enrichment-config.service'; +import { + SensorEnrichmentConfig, + EnrichmentConfig +} from '../model/sensor-enrichment-config'; +import { HttpResponse } from '@angular/common/http'; +import { METRON_REST_CONFIG, APP_CONFIG } from '../app.config'; +import { + HttpClientTestingModule, + HttpTestingController +} from '@angular/common/http/testing'; describe('SensorEnrichmentConfigService', () => { + let mockBackend: HttpTestingController; + let sensorEnrichmentConfigService: SensorEnrichmentConfigService; - beforeEach(async(() => { + beforeEach(() => { TestBed.configureTestingModule({ - imports: [HttpModule], + imports: [HttpClientTestingModule], providers: [ SensorEnrichmentConfigService, - {provide: XHRBackend, useClass: MockBackend}, - {provide: APP_CONFIG, useValue: METRON_REST_CONFIG} + { provide: APP_CONFIG, useValue: METRON_REST_CONFIG } ] - }) - .compileComponents(); - })); - - it('can instantiate service when inject service', - inject([SensorEnrichmentConfigService], (service: SensorEnrichmentConfigService) => { - expect(service instanceof SensorEnrichmentConfigService).toBe(true); - })); - - it('can instantiate service with "new"', inject([Http, APP_CONFIG], (http: Http, config: IAppConfig) => { - expect(http).not.toBeNull('http should be provided'); - let service = new SensorEnrichmentConfigService(http, config); - expect(service instanceof SensorEnrichmentConfigService).toBe(true, 'new service should be ok'); - })); - + }); + mockBackend = TestBed.get(HttpTestingController); + sensorEnrichmentConfigService = TestBed.get(SensorEnrichmentConfigService); + }); - it('can provide the mockBackend as XHRBackend', - inject([XHRBackend], (backend: MockBackend) => { - expect(backend).not.toBeNull('backend should be provided'); - })); + afterEach(() => { + mockBackend.verify(); + }); describe('when service functions', () => { - let sensorEnrichmentConfigService: SensorEnrichmentConfigService; - let mockBackend: MockBackend; let sensorEnrichmentConfig1 = new SensorEnrichmentConfig(); let enrichmentConfig1 = new EnrichmentConfig(); - enrichmentConfig1.fieldMap = {'geo': ['ip_dst_addr'], 'host': ['ip_dst_addr']}; + enrichmentConfig1.fieldMap = { + geo: ['ip_dst_addr'], + host: ['ip_dst_addr'] + }; sensorEnrichmentConfig1.enrichment.fieldMap = enrichmentConfig1; let sensorEnrichmentConfig2 = new SensorEnrichmentConfig(); let enrichmentConfig2 = new EnrichmentConfig(); - enrichmentConfig1.fieldMap = {'whois': ['ip_dst_addr'], 'host': ['ip_src_addr']}; + enrichmentConfig1.fieldMap = { + whois: ['ip_dst_addr'], + host: ['ip_src_addr'] + }; sensorEnrichmentConfig2.enrichment = enrichmentConfig2; let availableEnrichments: string[] = ['geo', 'host', 'whois']; - let availableThreatTriageAggregators: string[] = ['MAX', 'MIN', 'SUM', 'MEAN', 'POSITIVE_MEAN']; - let sensorEnrichmentConfigResponse: Response; - let sensorEnrichmentConfigsResponse: Response; - let availableEnrichmentsResponse: Response; - let availableThreatTriageAggregatorsResponse: Response; - let deleteResponse: Response; - - beforeEach(inject([Http, XHRBackend, APP_CONFIG], (http: Http, be: MockBackend, config: IAppConfig) => { - mockBackend = be; - sensorEnrichmentConfigService = new SensorEnrichmentConfigService(http, config); - sensorEnrichmentConfigResponse = new Response(new ResponseOptions({status: 200, body: sensorEnrichmentConfig1})); - sensorEnrichmentConfigsResponse = new Response(new ResponseOptions({status: 200, body: [sensorEnrichmentConfig1, - sensorEnrichmentConfig2]})); - availableEnrichmentsResponse = new Response(new ResponseOptions({status: 200, body: availableEnrichments})); - availableThreatTriageAggregatorsResponse = new Response(new ResponseOptions({status: 200, body: availableThreatTriageAggregators})); - deleteResponse = new Response(new ResponseOptions({status: 200})); - })); - - it('post', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(sensorEnrichmentConfigResponse)); + let availableThreatTriageAggregators: string[] = [ + 'MAX', + 'MIN', + 'SUM', + 'MEAN', + 'POSITIVE_MEAN' + ]; + let sensorEnrichmentConfigResponse: HttpResponse<{}>; + let sensorEnrichmentConfigsResponse: HttpResponse<{}>; + let availableEnrichmentsResponse: HttpResponse<{}>; + let availableThreatTriageAggregatorsResponse: HttpResponse<{}>; + let deleteResponse: HttpResponse<{}>; + + beforeEach(() => { + sensorEnrichmentConfigResponse = new HttpResponse({ + status: 200, + body: sensorEnrichmentConfig1 + }); + sensorEnrichmentConfigsResponse = new HttpResponse({ + status: 200, + body: [sensorEnrichmentConfig1, sensorEnrichmentConfig2] + }); + availableEnrichmentsResponse = new HttpResponse({ + status: 200, + body: availableEnrichments + }); + availableThreatTriageAggregatorsResponse = new HttpResponse({ + status: 200, + body: availableThreatTriageAggregators + }); + deleteResponse = new HttpResponse({ status: 200 }); + }); - sensorEnrichmentConfigService.post('bro', sensorEnrichmentConfig1).subscribe( + it('post', () => { + sensorEnrichmentConfigService + .post('bro', sensorEnrichmentConfig1) + .subscribe( result => { expect(result).toEqual(sensorEnrichmentConfig1); - }, error => console.log(error)); - }))); - - it('get', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(sensorEnrichmentConfigResponse)); - + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/sensor/enrichment/config/bro'); + expect(req.request.method).toBe('POST'); + req.flush(sensorEnrichmentConfig1); + }); + + it('get', () => { sensorEnrichmentConfigService.get('bro').subscribe( - result => { - expect(result).toEqual(sensorEnrichmentConfig1); - }, error => console.log(error)); - }))); - - it('getAll', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(sensorEnrichmentConfigsResponse)); - + result => { + expect(result).toEqual(sensorEnrichmentConfig1); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne('/api/v1/sensor/enrichment/config/bro'); + expect(req.request.method).toBe('GET'); + req.flush(sensorEnrichmentConfig1); + }); + + it('getAll', () => { sensorEnrichmentConfigService.getAll().subscribe( - results => { - expect(results).toEqual([sensorEnrichmentConfig1, sensorEnrichmentConfig2]); - }, error => console.log(error)); - }))); - - it('getAvailableEnrichments', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(availableEnrichmentsResponse)); - + results => { + expect(results).toEqual([ + sensorEnrichmentConfig1, + sensorEnrichmentConfig2 + ]); + }, + error => console.log(error) + ); + + const req = mockBackend.expectOne('/api/v1/sensor/enrichment/config'); + expect(req.request.method).toBe('GET'); + req.flush([sensorEnrichmentConfig1, sensorEnrichmentConfig2]); + }); + + it('getAvailableEnrichments', () => { sensorEnrichmentConfigService.getAvailableEnrichments().subscribe( - results => { - expect(results).toEqual(availableEnrichments); - }, error => console.log(error)); - }))); - - it('getAvailableThreatTriageAggregators', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(availableThreatTriageAggregatorsResponse)); - - sensorEnrichmentConfigService.getAvailableThreatTriageAggregators().subscribe( + results => { + expect(results).toEqual(availableEnrichments); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne( + '/api/v1/sensor/enrichment/config/list/available/enrichments' + ); + expect(req.request.method).toBe('GET'); + req.flush(availableEnrichments); + }); + + it('getAvailableThreatTriageAggregators', () => { + sensorEnrichmentConfigService + .getAvailableThreatTriageAggregators() + .subscribe( results => { expect(results).toEqual(availableThreatTriageAggregators); - }, error => console.log(error)); - }))); - - it('deleteSensorEnrichments', async(inject([], () => { - mockBackend.connections.subscribe((c: MockConnection) => c.mockRespond(deleteResponse)); - - sensorEnrichmentConfigService.deleteSensorEnrichments('bro').subscribe(result => { - expect(result.status).toEqual(200); - }); - }))); + }, + error => console.log(error) + ); + const req = mockBackend.expectOne( + '/api/v1/sensor/enrichment/config/list/available/threat/triage/aggregators' + ); + expect(req.request.method).toBe('GET'); + req.flush(availableThreatTriageAggregators); + }); + + it('deleteSensorEnrichments', () => { + sensorEnrichmentConfigService + .deleteSensorEnrichments('bro') + .subscribe(result => { + expect(result.status).toEqual(200); + }); + + const req = mockBackend.expectOne('/api/v1/sensor/enrichment/config/bro'); + expect(req.request.method).toBe('DELETE'); + req.flush(deleteResponse); + }); }); - }); - -