Fixed defects in test screen & updated test cases
Fixed few defects raised by ST in test screen and also updated test
cases to improve coverage. Also,changed code to match onap standards,
and rectfied grep code violations.
Issue-ID: APPC-730
Change-Id: I0286c38eb4f76dc8c0253a4ccab721b3ccfeff9d
Signed-off-by: sj108s <sj108s@us.att.com>
diff --git a/.gitignore b/.gitignore
index 226efa3..067819b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,3 +25,4 @@
dist/
target/
.settings/
+coverage/
diff --git a/src/app/about-us/aboutus.component.html b/src/app/about-us/aboutus.component.html
index bfc6f9a..1d8134b 100644
--- a/src/app/about-us/aboutus.component.html
+++ b/src/app/about-us/aboutus.component.html
@@ -28,7 +28,7 @@
<div class="card-header" style="font-size: 20px">CONTACT DETAILS</div>
<div class="mdl-card__title">
<div class="text-center">
- Contact us @: <a href="mailto:DL-APPCDEVELOPMENTTEAM@att.com?Subject=1710CDTContactus">APPC
+ Contact us @: <a href="#">APPC
DEVELOPMENT TEAM </a>
</div>
</div>
diff --git a/src/app/about-us/aboutus.component.spec.ts b/src/app/about-us/aboutus.component.spec.ts
index e5541eb..175f8d1 100644
--- a/src/app/about-us/aboutus.component.spec.ts
+++ b/src/app/about-us/aboutus.component.spec.ts
@@ -20,19 +20,42 @@
ECOMP is a trademark and service mark of AT&T Intellectual Property.
============LICENSE_END============================================
*/
+import { async, ComponentFixture, TestBed, inject, tick, fakeAsync } from '@angular/core/testing';
+import { Http, HttpModule, ConnectionBackend, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
+import { MockBackend } from '@angular/http/testing';
+import { ModalDismissReasons, NgbModule } from '@ng-bootstrap/ng-bootstrap';
+import { Observable } from 'rxjs/Observable';
+import 'rxjs/add/observable/from';
+import 'rxjs/add/observable/empty';
+import 'rxjs/add/observable/of';
-/* tslint:disable:no-unused-variable */
-import {async, ComponentFixture, TestBed} from '@angular/core/testing';
+import { AboutUsComponent } from './aboutus.component';
-import {AboutUsComponent} from './aboutus.component';
+class MockService {
+ doStuff() {
+ return this;
+ }
+}
describe('ContacUsComponent', () => {
let component: AboutUsComponent;
let fixture: ComponentFixture<AboutUsComponent>;
-
+
beforeEach(async(() => {
+ let http = new MockService();
+
TestBed.configureTestingModule({
- declarations: [AboutUsComponent]
+ declarations: [AboutUsComponent],
+ imports: [HttpModule, NgbModule.forRoot()],
+ providers: [NgbModule, {
+ provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
+ return new Http(backend, defaultOptions);
+ }, deps: [MockBackend, BaseRequestOptions]
+ },
+ { provide: MockBackend, useClass: MockBackend },
+ { provide: BaseRequestOptions, useClass: BaseRequestOptions },
+ {provide: Http, useValue: http}]
+
})
.compileComponents();
}));
@@ -46,4 +69,27 @@
it('should create', () => {
expect(component).toBeTruthy();
});
+
+ it('test', inject([Http], (http: Http) => {
+ let spy = spyOn(http, 'get').and.returnValue(Observable.of('some value'))
+
+ component.versionLogFile();
+
+ expect(http).toBeTruthy();
+ expect(spy).toHaveBeenCalled()
+
+ }));
+
+ it('should open modal', inject([NgbModule],(ngbModule: NgbModule) => {
+ let content = 'test';
+ component.open(content);
+ }));
+
+ it('should download log file', () => {
+ var blob = new Blob(['test'], {
+ type: 'text/plain;charset=utf-8'
+ });
+
+ component.downloadLogFile();
+ });
});
diff --git a/src/app/about-us/aboutus.component.ts b/src/app/about-us/aboutus.component.ts
index 360855e..1c237e8 100644
--- a/src/app/about-us/aboutus.component.ts
+++ b/src/app/about-us/aboutus.component.ts
@@ -49,10 +49,8 @@
}
versionLogFile() {
- this.http.get('app/shared/components/about-us/versionLog.txt')
+ this.http.get('app/about-us/versionLog.txt')
.subscribe(res => this.data = res.text());
- console.log('json data ', this.data);
-
}
open(content) {
diff --git a/src/app/about-us/appVersion.json b/src/app/about-us/appVersion.json
index d4fc816..5972822 100644
--- a/src/app/about-us/appVersion.json
+++ b/src/app/about-us/appVersion.json
@@ -1,4 +1,4 @@
{
- "versionNo": "2.0.6",
+ "versionNo": "2.0.7",
"releaseName": "1806"
}
\ No newline at end of file
diff --git a/src/app/about-us/versionLog.txt b/src/app/about-us/versionLog.txt
index fea7248..af9808a 100644
--- a/src/app/about-us/versionLog.txt
+++ b/src/app/about-us/versionLog.txt
@@ -1,94 +1,99 @@
+Version 2.0.7
+===========================================================
+1. Fixed issues raised by ST in test screen.
+2. Added few test cases to increase code coverage.
+
Version 2.0.6
===========================================================
-1. Fixed issues raised by ST in test screen. (sj108s)
-2. Added test spec file (sj108s)
+1. Fixed issues raised by ST in test screen.
+2. Added test spec file
Version 2.0.5
===========================================================
-1. Changed the location of Assign new Template Identifier.(Author-ug0221)
-2. Fixed an issue with retaining the selected value in the dropdown for Template Id's.(Author-ug0221)
-3. Added Artifact Name to the Filter box.(Author-ug0221)
-4. Added empty value validations on create new VNF pop up box.(Author-ug0221)
+1. Changed the location of Assign new Template Identifier.
+2. Fixed an issue with retaining the selected value in the dropdown for Template Id's.
+3. Added Artifact Name to the Filter box.
+4. Added empty value validations on create new VNF pop up box.
Version 2.0.4
===========================================================
-1. Added test cases to golden configuration spec file(sj108s)
-2. Fixed defect in test screen regarding request id while polling using getTestResponse() method (sj108s)
-3. Added validation to template configuration tab for accepting only xml and json files (sj108s)
-4. Added validation to param values tab to accept only json files (sj108s)
+1. Added test cases to golden configuration spec file
+2. Fixed defect in test screen regarding request id while polling using getTestResponse method
+3. Added validation to template configuration tab for accepting only xml and json files
+4. Added validation to param values tab to accept only json files
Version 2.0.3
===========================================================
1. Fixed E2E defect 430809 in 1802 : Space is not getting ignored in param configure artifact
- generated by CDT tool if VNF name / vnfc - type has spaces (sj108s)
+ generated by CDT tool if VNF name / vnfc - type has spaces
Version 2.0.2
===========================================================
-1. Added Licence Info to Reference Data Screen.(ug0221)
-2. Added Config ScaleOut Action and Template Identifiers to the Reference screen.(ug0221)
-3. resolved a defect where the configscale out file uploaded doesnt populate the template is dropdown.(ug0221)
+1. Added Licence Info to Reference Data Screen.
+2. Added Config ScaleOut Action and Template Identifiers to the Reference screen.
+3. resolved a defect where the configscale out file uploaded doesnt populate the template is dropdown.
Version 2.0.1
===========================================================
-1. Added Licence Info to golden config/ My VNF and other modules for ONAP- Only Reference Page remaining.(sj108s)
-2. Added Test screen to the main menu.(sj108s)
-3. Created HTML for Test Screen and integrated ts code.(sj108s)
+1. Added Licence Info to golden config/ My VNF and other modules for ONAP- Only Reference Page remaining.
+2. Added Test screen to the main menu.
+3. Created HTML for Test Screen and integrated ts code.
Version 2.0.0
===========================================================
-1. 18/06 Major release.(ak583p)
+1. 18/06 Major release.
Version 1.1.1
===========================================================
-1. Defect 416768 Block Name should not be merged. Do not allow a merge with a value that double quotes around it, possibly a space and a colon at the end.(Author-ma926a)
-2. Populating PD using name/value pairs when Uploading key file.(Author-ma926a)
+1. Defect 416768 Block Name should not be merged. Do not allow a merge with a value that double quotes around it, possibly a space and a colon at the end.
+2. Populating PD using name/value pairs when Uploading key file.
Version 1.1.0
===========================================================
-1. Added functionality for entering names in template through modal.(Author-sj108s)
-2. Enabled test screen and added basic test functionality.(Author-sj108s)
+1. Added functionality for entering names in template through modal.
+2. Enabled test screen and added basic test functionality.
Version 1.0.9
===========================================================
-1. Allow user to upload of Key Data Files multiple times.(Author-ma926a)
+1. Allow user to upload of Key Data Files multiple times.
2. Removing INSTAR and its properties using key file.
Version 1.0.8
===========================================================
-1. Changed the color code for merge successful/ unsuccessful messages.(Author sj108s)
+1. Changed the color code for merge successful/ unsuccessful messages.
Version 1.0.7
===========================================================
-1. Fixed defect in reference screen where previous vm actions where not getting replaced on uploading the new ones.(Author sj108s)
+1. Fixed defect in reference screen where previous vm actions where not getting replaced on uploading the new ones.
Version 1.0.6
===========================================================
-1. Fixed defect 396019- Added functionality for syncing template from parameters.(Author sj108s)
+1. Fixed defect 396019- Added functionality for syncing template from parameters.
Version 1.0.5
===========================================================
-1. Fixed protocol field while uploading reference artifact file for OpenStack Actions.(Author sj108s)
+1. Fixed protocol field while uploading reference artifact file for OpenStack Actions.
Version 1.0.4
===========================================================
-1. Fixed defect: Changed artifact-list to [] and vnfc-type to null in case of reference artifact generated for OpenStack Actions.(Author sj108s)
+1. Fixed defect: Changed artifact-list to [] and vnfc-type to null in case of reference artifact generated for OpenStack Actions.
Version 1.0.3
===========================================================
-1. Fix for Defect#399542 Merge from Params should not Merge the commented section of the base template ( CDT Version : 1.2.1). (Author-ma926a)
-2. Fix for Defect#402786 While changing back to Manual from other sources, other fields is not return to previous. (Author-ma926a)
-3. With some minor ST issues on PD source, ruletype manipulation. (Author-ma926a)
+1. Fix for Defect#399542 Merge from Params should not Merge the commented section of the base template ( CDT Version : 1.2.1).
+2. Fix for Defect#402786 While changing back to Manual from other sources, other fields is not return to previous.
+3. With some minor ST issues on PD source, ruletype manipulation.
Version 1.0.2
===========================================================
-1. Added functionality for hiding template and PD tabs on selection of OpenStack Actions in reference screen(Author sj108s)
+1. Added functionality for hiding template and PD tabs on selection of OpenStack Actions in reference screen
2. Fixed ST defect raised by Ed, wherein the user autoretrieves refrence data with multiple actions from myvnfs,
comes to reference screen, and navigates to template and pd pages and comes back to reference page, the data for the
- multiple actions are saving and retrieving correctly now.(Author sj108s)
+ multiple actions are saving and retrieving correctly now.
Version 1.0.1
===========================================================
-Story#330094 - Fixed the defects and left over tasks from this story.(Author-ma926a)
+Story#330094 - Fixed the defects and left over tasks from this story.
1. Source Manual/INSTAR/A&AI selection handled properly.
2. Disabling INSTAR to avoid manual selection of INSTAR.
3. "" empty quates in PD file when we select empty value in dropdowns.
diff --git a/src/app/app.component.spec.ts b/src/app/app.component.spec.ts
index 9eedbcb..378ab8e 100644
--- a/src/app/app.component.spec.ts
+++ b/src/app/app.component.spec.ts
@@ -9,7 +9,7 @@
you may not use this software except in compliance with the License.
You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,8 +21,6 @@
============LICENSE_END============================================
*/
-/* tslint:disable:no-unused-variable */
-
import {async, TestBed} from '@angular/core/testing';
import {AppComponent} from './app.component';
import {NO_ERRORS_SCHEMA} from '@angular/core';
@@ -54,8 +52,10 @@
it(`should have as title 'app works!'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
- const app = fixture.debugElement.componentInstance;
+ const app = fixture.componentInstance;
+ app.ngOnInit();
expect(app.title).toEqual('app works!');
+ app.ngOnDestroy();
}));
});
diff --git a/src/app/shared/components/navigation/navigation.component.spec.ts b/src/app/shared/components/navigation/navigation.component.spec.ts
index c5a436b..9516e3d 100644
--- a/src/app/shared/components/navigation/navigation.component.spec.ts
+++ b/src/app/shared/components/navigation/navigation.component.spec.ts
@@ -21,11 +21,27 @@
============LICENSE_END============================================
*/
+import { async, ComponentFixture, TestBed, fakeAsync, tick, inject } from '@angular/core/testing';
+import { RouterTestingModule } from "@angular/router/testing";
+import { Router, ActivatedRoute } from "@angular/router";
+import { Observable } from 'rxjs/Observable';
+import 'rxjs/add/observable/empty';
+import {DialogService} from 'ng2-bootstrap-modal';
+import {FormsModule} from '@angular/forms';
+import {HttpModule} from '@angular/http';
+import {HttpUtilService} from '../../../shared/services/httpUtil/http-util.service';
+import {MappingEditorService} from '../../..//shared/services/mapping-editor.service';
+import {NO_ERRORS_SCHEMA} from '@angular/core';
+import {NgModule} from '@angular/core';
+import {NgProgress} from 'ngx-progressbar';
+import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
+import {NotificationService} from '../../../shared/services/notification.service';
+import {ParamShareService} from '../../..//shared/services/paramShare.service';
+import {SharedModule} from '../../../shared/shared.module';
+import {environment} from '../../../../environments/environment';
-/* tslint:disable:no-unused-variable */
-import {async, ComponentFixture, TestBed} from '@angular/core/testing';
-
-import {NavigationComponent} from './navigation.component';
+import { NavigationComponent } from './navigation.component';
+import { EmitterService } from '../../services/emitter.service';
describe('NavigationComponent', () => {
let component: NavigationComponent;
@@ -33,7 +49,9 @@
beforeEach(async(() => {
TestBed.configureTestingModule({
- declarations: [NavigationComponent]
+ declarations: [NavigationComponent],
+ imports: [RouterTestingModule.withRoutes([]),FormsModule, RouterTestingModule, HttpModule, NgbModule.forRoot()],
+ providers: []
})
.compileComponents();
}));
@@ -47,4 +65,67 @@
it('should create', () => {
expect(component).toBeTruthy();
});
+
+ it('should set userLoggedIn on ngOnInit', () => {
+ component.userId = 'testingId';
+
+ component.ngOnInit();
+ });
+
+ it('should validate on ngOnChanges', () => {
+ let spy = spyOn(EmitterService, 'get').and.callFake( ({}) => {
+ return Observable.empty();
+ });
+ component.id = 'userLogin';
+
+ component.ngOnChanges();
+
+ expect(spy).toHaveBeenCalled();
+ });
+
+ it('should go to /vnfs/list if url = vnfs and userId is not null or undefined', inject([Router],(router: Router) => {
+ let navigateSpy = spyOn(router, 'navigate');
+ localStorage['userId'] = 'testingId';
+ let testUrl = 'vnfs';
+
+ component.gotoDetail(testUrl);
+ }));
+
+ it('should go to /vnfs if url = vnfs and userId is null or undefined', inject([Router],(router: Router) => {
+ let navigateSpy = spyOn(router, 'navigate');
+ localStorage['userId'] = '';
+ let testUrl = 'vnfs';
+
+ component.gotoDetail(testUrl);
+ }));
+
+ it('should go to passed url if url != vnfs', inject([Router],(router: Router) => {
+ let navigateSpy = spyOn(router, 'navigate');
+ let testUrl = 'test';
+
+ component.gotoDetail(testUrl);
+ }));
+
+ it('should logout', inject([Router],(router: Router) => {
+ let navigateSpy = spyOn(router, 'navigate');
+
+ component.logout();
+ }));
+ it('should ngOnChanges', () => {
+ component.id="uday"
+ component.ngOnChanges()
+ expect(component.userLoggedIn).toBeFalsy();
+ });
+ it('should ngOnInit()', () => {
+ localStorage['userId']="uday"
+ component.ngOnInit()
+ expect(component.userLoggedIn).toBeTruthy();
+ });
+ it('should gotoDetail(url)', () => {
+ component.gotoDetail('vnfs')
+ });
+ it('should logout()', () => {
+ component.logout()
+ expect(component.userLoggedIn).toBeFalsy();
+ });
});
diff --git a/src/app/shared/directives/collapse.component.spec.ts b/src/app/shared/directives/collapse.component.spec.ts
new file mode 100644
index 0000000..0d234d7
--- /dev/null
+++ b/src/app/shared/directives/collapse.component.spec.ts
@@ -0,0 +1,31 @@
+import { Collapse } from './collapse.component';
+import { ElementRef } from '@angular/core';
+
+
+describe('CollapseComponent', () => {
+ let directive;
+
+ beforeEach(() => {
+ directive = new Collapse();
+ });
+
+ it('should create an instance', () => {
+ expect(directive).toBeTruthy();
+ });
+
+ describe('should toggle', () => {
+ it('should call hide() if isExpanded is true', () => {
+ directive.isExpanded = true;
+
+ directive.toggle();
+ });
+
+ it('should call show() if isExpanded is false', () => {
+ directive.isExpanded = false;
+
+ directive.toggle();
+ });
+
+
+ });
+});
\ No newline at end of file
diff --git a/src/app/shared/directives/drop-down-toggle.directive.spec.ts b/src/app/shared/directives/drop-down-toggle.directive.spec.ts
index b08d334..81b08c8 100644
--- a/src/app/shared/directives/drop-down-toggle.directive.spec.ts
+++ b/src/app/shared/directives/drop-down-toggle.directive.spec.ts
@@ -21,16 +21,26 @@
============LICENSE_END============================================
*/
-
-/* tslint:disable:no-unused-variable */
-
-import {DropDownToggleDirective} from './drop-down-toggle.directive';
-import {ElementRef} from '@angular/core';
+import { TestBed } from '@angular/core/testing';
+import { DropDownToggleDirective } from './drop-down-toggle.directive';
+import { ElementRef } from '@angular/core';
describe('DropDownToggleDirective', () => {
+ let directive;
+ beforeEach(() => {
+ TestBed.configureTestingModule({
+ declarations: [DropDownToggleDirective]
+ });
+ });
+
+ beforeEach(() => {
+ directive = new DropDownToggleDirective(new ElementRef(''));
+ });
+
it('should create an instance', () => {
- const directive = new DropDownToggleDirective(new ElementRef(''));
- expect(directive).toBeTruthy();
+ let el: HTMLElement;
+ directive.type = 'dropdown';
+ expect(directive).toBeTruthy();
});
});
diff --git a/src/app/shared/directives/dropdown.spec.ts b/src/app/shared/directives/dropdown.spec.ts
index 2dbebd2..1aedfa5 100644
--- a/src/app/shared/directives/dropdown.spec.ts
+++ b/src/app/shared/directives/dropdown.spec.ts
@@ -24,15 +24,22 @@
/* tslint:disable:no-unused-variable */
-import {Dropdown} from './dropdown';
-import {ElementRef} from '@angular/core';
+import { Dropdown } from './dropdown';
+import { ElementRef } from '@angular/core';
describe('DropDown', () => {
+ let directive;
+
+ beforeEach(() => {
+ directive = new Dropdown(new ElementRef('<dropdown></dropdown>'));
+ });
it('should create an instance', () => {
- const directive = new Dropdown(new ElementRef('<dropdown></dropdown>'));
expect(directive).toBeTruthy();
});
-
+ it('should test open method', () => {
+ let elementRef: ElementRef;
+ console.log(directive);
+ });
});
diff --git a/src/app/shared/directives/dropdownnotclosablezone.spec.ts b/src/app/shared/directives/dropdownnotclosablezone.spec.ts
new file mode 100644
index 0000000..e397f83
--- /dev/null
+++ b/src/app/shared/directives/dropdownnotclosablezone.spec.ts
@@ -0,0 +1,52 @@
+/*
+============LICENSE_START==========================================
+===================================================================
+Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+===================================================================
+
+Unless otherwise specified, all software contained herein is licensed
+under the Apache License, Version 2.0 (the License);
+you may not use this software except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+ECOMP is a trademark and service mark of AT&T Intellectual Property.
+============LICENSE_END============================================
+*/
+
+import { TestBed } from '@angular/core/testing';
+import { DropdownNotClosableZone } from './dropdownnotclosablezone';
+import { ElementRef } from '@angular/core';
+
+
+describe('DropdownNotClosableZone', () => {
+ let directive;
+ beforeEach(() => {
+ TestBed.configureTestingModule({
+ declarations: [DropdownNotClosableZone]
+ });
+ });
+
+ beforeEach(() => {
+ directive = new DropdownNotClosableZone(new ElementRef('<dropdown-not-closable-zone></dropdown-not-closable-zone>'));
+ });
+
+ it('should create an instance', () => {
+
+ expect(directive).toBeTruthy();
+ });
+
+ it('should test contain method', () => {
+ let el: HTMLElement;
+ let dropdownNotClosabledZone = false;
+
+
+ });
+});
diff --git a/src/app/shared/directives/dropdownopen.spec.ts b/src/app/shared/directives/dropdownopen.spec.ts
new file mode 100644
index 0000000..b7a7aa6
--- /dev/null
+++ b/src/app/shared/directives/dropdownopen.spec.ts
@@ -0,0 +1,51 @@
+import { DropdownOpen } from './dropdownopen';
+import { Dropdown } from './dropdown';
+import { ElementRef, Host, HostListener } from '@angular/core';
+import { async, TestBed, inject } from '@angular/core/testing';
+
+
+describe('DropdownOpen', () => {
+ let directive;
+ let dropdown = new Dropdown(new ElementRef(''));
+
+ beforeEach(() => {
+ directive = new DropdownOpen(dropdown, new ElementRef(''));
+ });
+
+ it('should create an instance', () => {
+ expect(directive).toBeTruthy();
+ });
+
+ describe('should validate on Host click event', () => {
+ it('should validate openDropdown method if activateOnFocus, openedByFocus are true', () => {
+ let event = new Event('click');
+ let dispatchEvent = window.dispatchEvent(event);
+ dropdown.activateOnFocus = true;
+ directive.openedByFocus = true;
+
+ directive.openDropdown();
+ });
+
+ it('should validate openDropdown method if dropdown.isOpened(), dropdown.toggleClick false', () => {
+ });
+ });
+
+ it('should validate on Host keydown event', () => {
+ let spy = spyOn(directive, 'openDropdown')
+ var event = new KeyboardEvent("keydown");
+
+ Object.defineProperty(event, "keyCode", {"value" : 40})
+
+ directive.dropdownKeydown(event);
+
+ expect(spy).toHaveBeenCalled()
+ });
+
+ it('should validate on Host focus event', () => {
+
+ dropdown.activateOnFocus = false;
+
+ directive.onFocus();
+
+ });
+});
\ No newline at end of file
diff --git a/src/app/shared/modules/tidy-table/order-by.pipe.spec.ts b/src/app/shared/modules/tidy-table/order-by.pipe.spec.ts
index 82c57a1..5746fe9 100644
--- a/src/app/shared/modules/tidy-table/order-by.pipe.spec.ts
+++ b/src/app/shared/modules/tidy-table/order-by.pipe.spec.ts
@@ -20,10 +20,6 @@
ECOMP is a trademark and service mark of AT&T Intellectual Property.
============LICENSE_END============================================
*/
-
-
-/* tslint:disable:no-unused-variable */
-
import {OrderBy} from './order-by.pipe';
describe('OrderByPipe', () => {
@@ -31,4 +27,36 @@
const pipe = new OrderBy();
expect(pipe).toBeTruthy();
});
+
+ it('ascending sorting', () => {
+ const pipe = new OrderBy();
+
+ let data =[
+ {'vnf-type':'vnf1','vnfc-type':'vnfc1','artifact-name':'artf1'},
+ {'vnf-type':'vnf2','vnfc-type':'vnfc2','artifact-name':'artf2'}
+
+ ]
+ expect(pipe.transform(data,"vnf-type",true)[0]['vnf-type']).toBe('vnf1');
+
+ });
+ it('descending sorting', () => {
+ const pipe = new OrderBy();
+
+ let data =[
+ {'vnf-type':'vnf1','vnfc-type':'vnfc1','artifact-name':'artf1'},
+ {'vnf-type':'vnf2','vnfc-type':'vnfc2','artifact-name':'artf2'}
+
+ ]
+ expect(pipe.transform(data,"vnf-type",false)[0]['vnf-type']).toBe('vnf2');
+ });
+ it('descending sorting', () => {
+ const pipe = new OrderBy();
+
+ let data =[
+ {'vnf-type':undefined,'vnfc-type':'vnfc1','artifact-name':'artf1'},
+ {'vnf-type':'vnf2','vnfc-type':'vnfc2','artifact-name':'artf2'}
+
+ ]
+ expect(pipe.transform(data,"vnf-type",false)[0]['vnf-type']).toBe('vnf2');
+ });
});
diff --git a/src/app/shared/modules/tidy-table/table-filter.pipe.spec.ts b/src/app/shared/modules/tidy-table/table-filter.pipe.spec.ts
index d8fe6c7..5d73a14 100644
--- a/src/app/shared/modules/tidy-table/table-filter.pipe.spec.ts
+++ b/src/app/shared/modules/tidy-table/table-filter.pipe.spec.ts
@@ -31,4 +31,15 @@
const pipe = new TableFilterPipe();
expect(pipe).toBeTruthy();
});
+ it('filter table based on input ', () => {
+ const pipe = new TableFilterPipe();
+
+ let data =[
+ {'vnf-type':'vnf1','vnfc-type':'vnfc1','artifact-name':'artf1'},
+ {'vnf-type':'vnf2','vnfc-type':'vnfc2','artifact-name':'artf2'}
+
+ ]
+ let filter = ['vnf-type', 'vnfc-type', 'artifact-name'];
+ expect(pipe.transform(data,'vnf1',filter).length).toBe(1);
+ });
});
diff --git a/src/app/shared/pipes/vm-filtering.pipe.spec.ts b/src/app/shared/pipes/vm-filtering.pipe.spec.ts
new file mode 100644
index 0000000..523abfb
--- /dev/null
+++ b/src/app/shared/pipes/vm-filtering.pipe.spec.ts
@@ -0,0 +1,49 @@
+/*
+============LICENSE_START==========================================
+===================================================================
+Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+===================================================================
+
+Unless otherwise specified, all software contained herein is licensed
+under the Apache License, Version 2.0 (the License);
+you may not use this software except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+ECOMP is a trademark and service mark of AT&T Intellectual Property.
+============LICENSE_END============================================ */
+import {VmFilteringPipe} from './vm-filtering.pipe';
+
+describe('VmFilteringPipe', () => {
+ it('create an instance', () => {
+ const pipe = new VmFilteringPipe();
+ expect(pipe).toBeTruthy();
+ });
+ it('should return configscaleout values if template id matches',()=>{
+ const pipe = new VmFilteringPipe();
+
+ let objArray = [
+ {action:"Configure","template-id":2,"type":"con"},
+ {action:"ConfigScaleout","template-id":1,"type":"conScale"}
+ ]
+ expect(pipe.transform(objArray,"ConfigScaleOut",1)[0].type).toBe("conScale")
+
+ });
+ it('should return configure calues',()=>{
+ const pipe = new VmFilteringPipe();
+
+ let objArray = [
+ {action:"Configure","template-id":2,"type":"con"},
+ {action:"ConfigScaleout","template-id":1,"type":"conScale"}
+ ]
+ expect(pipe.transform(objArray,"ConfigScaleOut",2)[0].type).toBe("con")
+
+ });
+});
diff --git a/src/app/shared/pipes/vm-filtering.pipe.ts b/src/app/shared/pipes/vm-filtering.pipe.ts
new file mode 100644
index 0000000..c20397b
--- /dev/null
+++ b/src/app/shared/pipes/vm-filtering.pipe.ts
@@ -0,0 +1,42 @@
+/*
+============LICENSE_START==========================================
+===================================================================
+Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+===================================================================
+
+Unless otherwise specified, all software contained herein is licensed
+under the Apache License, Version 2.0 (the License);
+you may not use this software except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+ECOMP is a trademark and service mark of AT&T Intellectual Property.
+============LICENSE_END============================================ */
+import {Pipe, PipeTransform} from '@angular/core';
+
+@Pipe({name: 'vmFiltering', pure: false})
+export class VmFilteringPipe implements PipeTransform {
+
+ transform(value: any, action: any, templateId): any {
+
+ if (action == 'ConfigScaleOut') {
+ let x = value.filter(obj => {
+ //return value
+ return obj['template-id'] == templateId;
+ });
+
+ return x;
+ } else {
+ return value;
+
+ }
+ }
+
+}
diff --git a/src/app/shared/services/emitter.service.spec.ts b/src/app/shared/services/emitter.service.spec.ts
index f12154f..6521311 100644
--- a/src/app/shared/services/emitter.service.spec.ts
+++ b/src/app/shared/services/emitter.service.spec.ts
@@ -21,9 +21,6 @@
============LICENSE_END============================================
*/
-
-/* tslint:disable:no-unused-variable */
-
import {inject, TestBed} from '@angular/core/testing';
import {EmitterService} from './emitter.service';
@@ -37,4 +34,10 @@
it('should ...', inject([EmitterService], (service: EmitterService) => {
expect(service).toBeTruthy();
}));
+
+ it('should test static get method', () => {
+ let id = 'login';
+
+ EmitterService.get(id);
+ })
});
diff --git a/src/app/shared/services/mapping-editor.service.ts b/src/app/shared/services/mapping-editor.service.ts
index 00ef211..fe70722 100644
--- a/src/app/shared/services/mapping-editor.service.ts
+++ b/src/app/shared/services/mapping-editor.service.ts
@@ -39,7 +39,6 @@
paramContent: string = '{}';
KEY_EXPRESSION: string = '\\${\\(.+?\\)}';//new RegExp('${.+?}'); // \${.+?}
- //SYNC_KEY_EXPRESSION: string = '\\${\\)}';
KEY_START: string = '${(';
KEY_MID: string = ')=(';
KEY_END: string = ')}';
@@ -89,19 +88,16 @@
changeNav(object) {
this._navItem = object;
- // this._observer.next(object);
this.referenceNameObjects = object;
}
changeNavAppData(object) {
this._navItem = object;
- // this._observer.next(object);
this.appDataObject = object;
}
changeNavDownloadData(object) {
this._navItem = object;
- // this._observer.next(object);
this.downloadDataObject = object;
}
@@ -127,7 +123,7 @@
public setParamContent(paramContent: string): void {
this.paramContent = paramContent;
- // localStorage["paramContent"]=paramContent;
+
}
public initialise(editor: any, editorContent: string, modal: any): void {
@@ -144,15 +140,6 @@
public initialiseCommands(modal): void {
- /* this.editor.commands.addCommand({
- name: 'annotateCommand',
- bindKey: { win: 'ENTER', mac: 'ENTER' },
- exec: (editor: any) => {
- this.handleAnnotation(modal);
- }
- });*/
-
-
this.editor.commands.addCommand({
name: 'keyCompletionCommand',
bindKey: {win: 'Ctrl-s', mac: 'Command-s'},
@@ -165,7 +152,7 @@
name: 'autoAnnotateCommand',
bindKey: {win: 'Ctrl-2', mac: 'Command-2'},
exec: (editor: any) => {
- this.autoAnnotateDataForParams(this.fileType);
+ this.autoAnnotateDataForParams();
}
});
@@ -200,9 +187,8 @@
return toAdd;
}
- public autoAnnotateDataForParams(fileType: any): boolean {
+ public autoAnnotateDataForParams(): boolean {
this.paramContent = localStorage['paramsContent'];
- //console.log("Param content=="+ this.paramContent)
var mergeStatus: boolean = false;
if (this.paramContent) {
var paramJson: JSON = JSON.parse(this.paramContent);
@@ -230,51 +216,6 @@
return mergeStatus;
}
- /* syncTemplateNames() {
- if (this.paramContent != '{}') {
- var paramJson: JSON = JSON.parse(this.paramContent);
- for (var prop in paramJson) {
- let value: string = paramJson[prop]
- if (value) {
- var occurances = this.editor.findAll(value, { regExp: false });
- var ranges = this.editor.getSelection().getAllRanges();
- if (ranges) {
- for (var r = 0; r < ranges.length; r++) {
- let selectedRange: any = ranges[r];
- let selectedWord: string = this.editor.session.getTextRange(selectedRange);
- let prefixSuffixselectedWord: string = this.editor.session.getTextRange(this.getStartBeforeAfterSelection(selectedRange, 1, 1));
- if (selectedWord && this.checkApplied(selectedRange)) {
- let replaceWord: any = this.KEY_START + selectedWord + this.KEY_MID + prop + this.KEY_END;
- this.editor.session.replace(selectedRange, replaceWord);
- }
- }
- }
- }
- }
- for (var prop in paramJson) {
- var occurances = this.editor.findAll(prop, { regExp: false });
- var ranges = this.editor.getSelection().getAllRanges();
- if (ranges) {
- for (var r = 0; r < ranges.length; r++) {
- let selectedRange: any = ranges[r];
- let selectedWord: string = this.editor.session.getTextRange(selectedRange);
- if (selectedWord && this.checkApplied(selectedRange)) {
- let replaceWord: any = '(' + paramJson[prop] + this.KEY_MID + selectedWord + ')';
- this.editor.session.replace(selectedRange, replaceWord);
- }
- }
- }
- else {
- this.replaceNamesWithBlankValues();
- }
- }
- }
- else {
- this.replaceNamesWithBlankValues()
- }
- }*/
-
-
checkComments(selectedRange: any) {
var tempStartColumn = selectedRange.start.column;
var result = false;
@@ -394,35 +335,14 @@
this.refreshEditor();
}
- /* public handleAnnotation(modal): void {
- let selectedWord: string = this.editor.session.getTextRange(this.editor.selectionRange);
- this.setSelectedWord(selectedWord);
- modal.open();
-
- /* let selectedWord: string = this.editor.session.getTextRange(this.editor.selectionRange);
- if (selectedWord) {
- if (selectedWord.startsWith('${(')) {
- var replaceWord = selectedWord.substring(3, selectedWord.indexOf(')=('));
- this.editor.session.replace(this.editor.session.selection.getRange(), replaceWord);
- } else {
- let mappingKey = this.getKeysForValues(selectedWord);
- var replaceWord = '${(' + selectedWord + ')=()}';
- this.editor.session.replace(this.editor.session.selection.getRange(), replaceWord);
- }
- }
- this.refreshEditor();
- }*/
-
public checkMethodCall(modal): void {
-//this.handleAnnotation(modal)
+ //this.handleAnnotation(modal)
}
public refreshEditor(): void {
if (this.editor) {
- // this.replaceNamesWithBlankValues();
var occurances = this.editor.findAll(this.KEY_EXPRESSION, {regExp: true});
- //console.log("Occurances from save" + occurances)
var ranges = this.editor.getSelection().getAllRanges();
if (ranges) {
this.refreshParams(ranges);
@@ -435,8 +355,7 @@
}
this.refreshMarker();
}
- // console.log("Param data from refresh editor=="+this.paramData)
-
+
}
replaceNamesWithBlankValues() {
@@ -446,23 +365,19 @@
if (ranges) {
for (var r = 0; r < ranges.length; r++) {
let selectedRange: any = ranges[r];
- // console.log("Selected range == " + selectedRange)
let selectedWord: string = this.editor.session.getTextRange(selectedRange);
let specialKeys = (selectedWord.substring(2, selectedWord.length - 1)).match(this.checkSpecialCharsReg);
- // console.log("Selected word == " + selectedWord.length)
- //if (!selectedWord.startsWith('<') || !selectedWord.startsWith('{')) {
if (selectedWord && this.checkAppliedForNamesOnly(selectedRange) && !specialKeys) {
let replaceWord: any = this.KEY_START + '' + this.KEY_MID + selectedWord.substring(2, selectedWord.length - 1) + this.KEY_END;
this.editor.session.replace(selectedRange, replaceWord);
}
- // }
+
}
}
}
}
public refreshParams(ranges: any): void {
- // console.log("This param content==="+ this.paramContent);
var paramData = [];
if (this.paramContent === undefined) this.paramContent = '{}';
if (this.editor && ranges) {
@@ -470,17 +385,12 @@
this.hasErrorCode = false;
for (var r = 0; r < ranges.length; r++) {
let keyValue: string = this.editor.session.getTextRange(ranges[r]);
- //console.log("keyValues==="+keyValue)
if (keyValue && keyValue.startsWith(this.KEY_START) && keyValue.endsWith(this.KEY_END) && keyValue.includes(this.KEY_MID)) {
let key: string = keyValue.substring(keyValue.indexOf(this.KEY_MID) + this.KEY_MID_LENGTH, keyValue.indexOf(this.KEY_END));
let value: string = keyValue.substring(this.KEY_START_LENGTH, keyValue.indexOf(this.KEY_MID));
let specialKeys = key.match(this.checkSpecialCharsReg);
- //console.log("Special keys=="+specialKeys)
- //console.log("Keys=="+key+",values=="+value);
if (specialKeys && specialKeys.length) {
- // this.paramData = [];
- // this.hasErrorCode = true;
- // break;
+
} else {
if (this.fromScreen === 'TemplateScreen') {
if (key) {
@@ -506,7 +416,6 @@
}
}
}
- // console.log("Param data=="+ JSON.stringify(paramData))
this.paramData = paramData;
this.paramContent = JSON.stringify(paramJson);
diff --git a/src/app/shared/services/utilityService/utility.service.spec.ts b/src/app/shared/services/utilityService/utility.service.spec.ts
index c11927a..85b4818 100644
--- a/src/app/shared/services/utilityService/utility.service.spec.ts
+++ b/src/app/shared/services/utilityService/utility.service.spec.ts
@@ -21,9 +21,6 @@
============LICENSE_END============================================
*/
-
-/* tslint:disable:no-unused-variable */
-
import {inject, TestBed} from '@angular/core/testing';
import {UtilityService} from './utility.service';
import {NotificationsService} from 'angular2-notifications';
@@ -39,11 +36,16 @@
expect(service).toBeTruthy();
}));
+ it('should generate random id', inject([UtilityService],(service: UtilityService) => {
+ let ret = service.randomId();
+
+ expect(ret).not.toBeNull();
+ }));
it('should apply slashes for a string...', inject([UtilityService], (service: UtilityService) => {
- let text = {'vnf-host-ip-address': '135.21.166.36'};
+ let text = {'vnf-host-ip-address': 'testidaddress'};
- expect(service.appendSlashes(JSON.stringify(text))).toEqual('{\\"vnf-host-ip-address\\":\\"135.21.166.36\\"}');
+ expect(service.appendSlashes(JSON.stringify(text))).toEqual('{\\"vnf-host-ip-address\\":\\"testidaddress\\"}');
}));
diff --git a/src/app/test/test.component.html b/src/app/test/test.component.html
index ad6ff7f..3519007 100644
--- a/src/app/test/test.component.html
+++ b/src/app/test/test.component.html
@@ -32,16 +32,6 @@
<input class="form-control" type="text" disabled value="{{action}}" />
</div>
- <!-- <div class="col-lg-3 col-sm-6 col-md-3 col-xs-12">
- <label>Vnf Type:</label>
- <input class="form-control" type="text" disabled value="{{vnfType}}" />
-
- </div>
- <div class="col-lg-3 col-sm-6 col-md-3 col-xs-12">
- <label>Vnfc Type:</label>
- <input class="form-control" type="text" disabled value="{{vnfcType}}" />
-
- </div>-->
<div class="col-lg-3 col-sm-6 col-md-4 col-xs-12">
<label>Vnf Id:</label>
<input class="form-control" type="text" [(ngModel)]="this.actionIdentifiers['vnf-id']" />
@@ -54,11 +44,6 @@
</div>
- <!-- <div class="col-lg-3 col-sm-6 col-md-3 col-xs-12">
- <label>VF-Module-Id(optional):</label>
- <input class="form-control" disabled type="text" value="{{this.actionIdentifiers['vmodule-id']}}" />
-
- </div>-->
<div class="col-12">
<div class="input-group">
@@ -113,14 +98,9 @@
<div class="col-md-12">
<div class="row justify-content-center" style="padding-top:0.3cm">
-
- <!-- <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" type="button" (click)="clearLog()">Abort Test</button> -->
-
<button style="margin-left:6%;" [disabled]="!enableTestButton" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary" type="submit" (click)="testVnf()">Execute Test
</button>
- <!-- <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" type="button" (click)="abortTest()">Abort Test</button> -->
- <!--button class="btn btn-primary" type="submit"> Save Revised Name/Value Pair to APPC</button-->
-
+
</div>
</div>
@@ -130,8 +110,7 @@
</div>
<div style="padding-left:60%;padding-bottom:0.5cm">
- <!-- <a href="javascript:void(0)" style="color:darkblue; text-decoration: double; font-size: 15px;" (click)="download()">Download Raw Request/Response.</a>-->
- <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary" type="button" (click)="download()">Download Raw Request/Response
+ <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary" type="button" [disabled]="!enableDownload" (click)="download()">Download Raw Request/Response
</button>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" type="button" [disabled]="!enableAbort" (click)="abortTest()">Abort Test
</button>
diff --git a/src/app/test/test.component.spec.ts b/src/app/test/test.component.spec.ts
index 8d96554..e07ff93 100644
--- a/src/app/test/test.component.spec.ts
+++ b/src/app/test/test.component.spec.ts
@@ -21,9 +21,6 @@
============LICENSE_END============================================
*/
-/* tslint:disable:no-unused-variable */
-
-// Modules
import { async, ComponentFixture, TestBed,inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
@@ -31,23 +28,32 @@
import { RouterTestingModule } from '@angular/router/testing';
import { SimpleNotificationsModule } from 'angular2-notifications';
import { Http, Response, Headers, RequestOptions, HttpModule } from '@angular/http';
+import { Observable } from 'rxjs/Observable';
+import { Subscription } from 'rxjs/Subscription';
+import 'rxjs/add/observable/from';
+import 'rxjs/add/observable/empty';
+import 'rxjs/add/observable/throw';
-// Component
import { TestComponent } from './test.component';
-
-// Services
import { NotificationService } from '../shared/services/notification.service';
import { ParamShareService } from '.././shared/services/paramShare.service';
import { MappingEditorService } from '../shared/services/mapping-editor.service';
import { HttpUtilService } from '../shared/services/httpUtil/http-util.service';
import { UtilityService } from '../shared/services/utilityService/utility.service';
+import { environment } from '../.././environments/environment';
import { NgProgress } from 'ngx-progressbar';
-import {NgProgressModule} from 'ngx-progressbar';
+import { NgProgressModule } from 'ngx-progressbar';
+
+class MockService {
+ doStuff() {
+ return this;
+ }
+}
describe( 'TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
-
+ let http = new MockService();
beforeEach(async(() => {
TestBed.configureTestingModule({
@@ -60,12 +66,13 @@
NgProgressModule
],
providers: [
- NotificationService,
+ NotificationService,
ParamShareService,
MappingEditorService,
HttpUtilService,
UtilityService,
- NgProgress
+ NgProgress,
+ {provide: Http, useValue: http}
]
})
.compileComponents();
@@ -77,82 +84,300 @@
fixture.detectChanges();
});
- it( 'should create', () => {
- expect(component).toBeTruthy();
- });
+ it('should ...', inject([HttpUtilService], (service: HttpUtilService) => {
+ let spy = spyOn(service, 'post').and.returnValue(Observable.empty());
+ fixture.detectChanges(); // onInit()
- // it('test', () => {
- // expect(2).toEqual(1)
- // });
+ component.pollTestStatus();
+
+ expect(service).toBeTruthy();
+ expect(spy).toHaveBeenCalled();
+ expect(spy.calls.any()).toBe(true, 'test');
+ }));
+
+ // Test download Method
+ describe('Test download Method', () => {
+ it('Should have download method', () => {
+ expect(component.download).toBeDefined();
+ });
+ it('test if apiRequest if true', inject( [SimpleNotificationsModule], (service: SimpleNotificationsModule) => {
+ component.apiRequest = '{"input":{"common-header":{"timestamp":"2018-03-05T07:41:14.329Z","api-ver":"2.00","originator-id":"CDT","request-id":"1520235674330","sub-request-id":"1520235674330","flags":{"mode":"NORMAL","force":"TRUE","ttl":3600}},"action":"ConfigModify","action-identifiers":{"vnf-id":"testVnf","vserver-id":"test"},"payload":""';
+ component.apiResponse = '';
+ component.action = 'ConfigModify';
+ component.actionIdentifiers['vnf-id'] = 'testVnf';
+ let fileName = 'test_' + component.action + '_' + component.actionIdentifiers['vnf-id'] + '_request';
+ let theJSON = component.apiRequest;
+ var blob = new Blob([theJSON], {
+ type: 'text/json'
+ });
- // it('test preparfilename', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
- // // fixture = TestBed.createComponent(TestComponent);
- // // component = fixture.componentInstance;
- // mappingEditorService.latestAction=undefined
+ component.download();
- // expect(component.prepareFileName()).toBe(undefined);
- // }));
+ expect(service instanceof SimpleNotificationsModule).toBeTruthy();
+ expect(component.apiRequest).not.toBe('');
+ expect(fileName).not.toBe('');
+ expect(fileName).not.toBeNull();
+ expect(fileName).toContain('test_');
+ expect(fileName).toContain('_request');
+ expect(typeof (blob)).toBe('object');
+ }));
- it('Should have download method', () => {
- expect(component.download).toBeDefined();
+ it('test method if apiResponse is true', () => {
+ component.apiResponse = '{"input":{"common-header":{"timestamp":"2018-03-05T07:41:14.329Z","api-ver":"2.00","originator-id":"CDT","request-id":"1520235674330","sub-request-id":"1520235674330","flags":{"mode":"NORMAL","force":"TRUE","ttl":3600}},"action":"ConfigModify","action-identifiers":{"vnf-id":"testvnf","vserver-id":"test"},"payload":""';
+ component.apiRequest = '';
+ component.action = 'ConfigModify';
+ component.actionIdentifiers['vnf-id'] = 'testvnf';
+ let fileName = 'test_' + component.action + '_' + component.actionIdentifiers['vnf-id'] + '_response';
+ let theJSON = component.apiRequest;
+ var blob = new Blob([theJSON], {
+ type: 'text/json'
+ });
+
+ component.download();
+
+ expect(component.apiResponse).not.toBe('');
+ expect(fileName).not.toBe('');
+ expect(fileName).not.toBeNull();
+ expect(fileName).toContain('test_');
+ expect(fileName).toContain('_response');
+ expect(typeof (blob)).toBe('object');
+
+ });
});
// Test abortTest Method
- it('Should have abortTest method', () => {
- expect(component.abortTest).toBeDefined();
+ describe('Test abortTest Method', () => {
+ it('Should have abortTest method', () => {
+ expect(component.abortTest).toBeDefined();
+ });
+
+ it('Test abortTest Method', () => {
+ const temp = component.abortTest();
+ expect(component.enableBrowse).toBeTruthy();
+ expect(component.enableTestButton).toBeTruthy();
+ expect(component.enablePollButton).toBeTruthy();
+ });
});
- it('Test abortTest Method', () => {
- const temp = component.abortTest();
- expect(component.enableBrowse).toBeTruthy();
- expect(component.enableTestButton).toBeTruthy();
+ // Test excelBrowseOption Method
+ describe('Test excelBrowseOption Method', () => {
+ it('test excelBrowseOption', () => {
+ spyOn(component, 'excelBrowseOption');
+ let button = fixture.debugElement.query(By.css('#excelInputFile ~ button.browse'));
+ button.nativeElement.click();
+ expect(component.excelBrowseOption).toHaveBeenCalled()
+ });
});
- it('Should have excelBrowseOption method', () => {
- expect(component.excelBrowseOption).toBeDefined();
+ // Test Upload Method
+ describe('Test Upload Method', () => {
+ it('Should have upload method', () => {
+ expect(component.upload).toBeDefined();
+ });
+
+ it('should execute if file extension is XLS, XLSX', () => {
+ let fileExtension = 'XLS';
+ let event = { isTrusted: true, type: "change", target: {files: [{name:'foo.XLS', size: 500001}]} }
+ let reader = new FileReader();
+ spyOn(reader, 'onload');
+
+ component.upload(event);
+
+ expect(reader instanceof FileReader).toBeTruthy();
+ expect(reader.onload).toHaveBeenCalled();
+ expect(component.enableTestButton).toBeTruthy();
+ console.log('aaa',component.enableTestButton, component.uploadFileName);
+ });
+
+ it('should return an error if file extension is not XLS, XLSX', () => {
+ spyOn(component, 'upload');
+ let ele = fixture.debugElement.query(By.css('#filesparam'));
+ const target = { files: ['']};
+ component.uploadFileName = 'test.doc';
+ let fileExtension = 'DOC';
+ component.upload('change');
+
+ expect(target.files.length).toEqual(1)
+ expect(fileExtension).not.toBe('XLS');
+ expect(fileExtension).not.toBe('XLSX');
+ });
});
- it('Should have upload method', () => {
- expect(component.upload).toBeDefined();
+ // Test processUploadedFile Method
+ describe('Test processUploadedFile Method', () => {
+ it('should return valid payload', () => {
+ let data = [
+ {"TagName":"action","Value":"ConfigModify"},
+ {"List Name":"action-identifiers","TagName":"vserver-id","Value":"test"},
+ {"List Name":"payload","List Name_1":"request-parameters","TagName":"vnf-name","Value":"testVnf"},
+ {"List Name":"payload","List Name_1":"request-parameters","List Name_2":"[vm]","List Name_3":"vnfc","TagName":"vnfc-name","Value":"testVnfcName"},
+ {"List Name":"payload","List Name_1":"configuration-parameters","TagName":"testConfigParam","Value":"testConfigValue"}
+ ]
+
+ let payload = component.processUploadedFile(data);
+ });
});
- it('Should have constructTestPayload method', () => {
- expect(component.constructTestPayload).toBeDefined();
+ // Test uploadedFileResult Method
+ describe('Test uploadedFileResult', () => {
+ it('should return success message', inject([SimpleNotificationsModule],(service: SimpleNotificationsModule) => {
+ component.action = 'ConfigModify';
+ component.actionIdentifiers['vnf-id'] = 'testvnf';
+
+ component.uploadedFileResult();
+
+ expect(service instanceof SimpleNotificationsModule).toBeTruthy();
+ }));
+
+ it('should return error message', inject([SimpleNotificationsModule], (service: SimpleNotificationsModule) => {
+ component.action = '';
+ component.actionIdentifiers['vnf-id'] = '';
+
+ component.uploadedFileResult();
+
+ expect(service instanceof SimpleNotificationsModule).toBeTruthy();
+ }));
});
- it('Should have constructRequest method', () => {
- expect(component.constructRequest).toBeDefined();
+ // Test constructTestPayload Method
+ describe('Test constructTestPayload Method', () => {
+ //3rd , 4th columnd, tag name , tag value
+ it('Should have constructTestPayload method', () => {
+ expect(component.constructTestPayload).toBeDefined();
+ });
+
+ it('test if listName2, listName3 are undefined', () => {
+ let temp = component.constructTestPayload(undefined, undefined, 'vnfc-type', 'testvnfc');
+ expect(component.subPayload['vnfc-type']).toEqual('testvnfc')
+ });
+
+ it('test if lastName2 is not undefined', () => {
+ let temp = component.constructTestPayload(['vm'], undefined, 'vnfc-type', 'testvnfc');
+ expect(typeof(component.vmJson)).toEqual('object');
+ expect(typeof(component.vnfcJson)).toEqual('object');
+ expect(component.vmJson['vnfc-type']).toBe('testvnfc');
+ expect(component.flag).toBe(0);
+ });
+
+ it('test if lastNmae2, lastName3 are not undefined', () => {
+ let temp = component.constructTestPayload(['vm'], 'vnfc', 'vnfc-type', 'testvnfc');
+ expect(component.vnfcJson['vnfc-type']).toEqual('testvnfc');
+ expect(component.vmJson['vnfc']['vnfc-type']).toEqual('testvnfc');
+ expect(component.flag).toBe(1);
+ })
});
- it('Should have testVnf method', () => {
- expect(component.testVnf).toBeDefined();
+ // Test constructRequest Method
+ describe('Test constructRequest Method', () => {
+ it('Should have constructRequest method', () => {
+ expect(component.constructRequest).toBeDefined();
+ });
+
+ it('test method', () => {
+ let temp = component.constructRequest();
+ });
});
- it('Should have pollTestStatus method', () => {
- expect(component.pollTestStatus).toBeDefined();
+ // Test testVnf Method
+ describe('Test testVnf Method', () => {
+ it('Should have testVnf method', () => {
+ expect(component.testVnf).toBeDefined();
+ });
+
+ it('should return response on success', inject([HttpUtilService, NgProgress], (httpUtilService: HttpUtilService, ngProgress: NgProgress) => {
+ let spy = spyOn(httpUtilService, 'post').and.callFake( ({}) => {
+ return Observable.empty();
+ });
+ component.action = 'ConfigModify';
+
+ component.testVnf();
+ expect(component.enableBrowse).toBeFalsy()
+ expect(component.enableTestButton).toBeFalsy();
+ expect(component.enablePollButton).toBeFalsy();
+ expect(spy).toHaveBeenCalled();
+ }));
+
+ it('should return an error if fails', inject([HttpUtilService],( httpUtilService: HttpUtilService) => {
+ let error = 'Error in connecting to APPC Server';
+ let spy = spyOn(httpUtilService, 'post').and.returnValue(Observable.throw(error));
+ component.action = 'ConfigModify';
+
+ component.testVnf();
+
+ expect(spy).toHaveBeenCalled();
+ expect(component.enableBrowse).toBeTruthy();
+ expect(component.enableTestButton).toBeTruthy();
+ expect(component.enablePollButton).toBeTruthy();
+ expect(component.enableCounterDiv).toBeFalsy();
+ }));
+
+ it('test setTimeout', inject([NgProgress], (ngProgress: NgProgress) => {
+ let spy = spyOn(ngProgress, 'done');
+ component.action = 'ConfigModify';
+
+ component.testVnf();
+
+ }));
});
+ // Test pollTestStatus Method
+ describe('Test pollTestStatus Method', () => {
+ it('Should have pollTestStatus method', () => {
+ expect(component.pollTestStatus).toBeDefined();
+ });
+ it('test method', () => {
+ let temp = component.pollTestStatus();
+ let requestId = new Date().getTime().toString();
+ let actionIdentifiers = 123456;
+ });
+
+ it('should call fake server', inject([HttpUtilService], (httpUtilService: HttpUtilService) => {
+ let spy = spyOn(httpUtilService, 'post').and.callFake(({}) => {
+ return Observable.empty();
+ });
+
+ component.pollTestStatus();
+
+ expect(spy).toHaveBeenCalled();
+ }));
+
+ it('should return an error if fails', inject([HttpUtilService], (httpUtilService: HttpUtilService) => {
+ let error = 'Error Connecting to APPC server';
+ let spy = spyOn(httpUtilService, 'post').and.callFake( ({}) => {
+ return Observable.throw(error);
+ });
+ component.requestId = null;
+ component.actionIdentifiers['vnf-id'] = false;
+
+ component.pollTestStatus();
+
+ expect(spy).toHaveBeenCalled();
+ }));
+ });
+
// Test getUrlEndPoint Method
- it('Should have getUrlEndPoint method', () => {
- expect(component.getUrlEndPoint).toBeDefined();
- });
+ describe('Test getUrlEndPoint Method', () => {
+ it('Should have getUrlEndPoint method', () => {
+ expect(component.getUrlEndPoint).toBeDefined();
+ });
- it('getUrlEndPoint Should return value', () => {
- expect(component.getUrlEndPoint('configmodify')).toEqual('config-modify');
- expect(component.getUrlEndPoint('configbackup')).toEqual('config-backup');
- expect(component.getUrlEndPoint('configrestore')).toEqual('config-restore');
- expect(component.getUrlEndPoint('healthcheck')).toEqual('health-check');
- expect(component.getUrlEndPoint('quiescetraffic')).toEqual('quiesce-traffic');
- expect(component.getUrlEndPoint('resumetraffic')).toEqual('resume-traffic');
- expect(component.getUrlEndPoint('startapplication')).toEqual('start-application');
- expect(component.getUrlEndPoint('stopapplication')).toEqual('stop-application');
- expect(component.getUrlEndPoint('upgradebackout')).toEqual('upgrade-backout');
- expect(component.getUrlEndPoint('upgradepostcheck')).toEqual('upgrade-post-check');
- expect(component.getUrlEndPoint('upgradeprecheck')).toEqual('upgrade-pre-check');
- expect(component.getUrlEndPoint('upgradesoftware')).toEqual('upgrade-software');
- expect(component.getUrlEndPoint('DeFaultCASE')).toEqual('defaultcase');
+ it('getUrlEndPoint Should return value', () => {
+ expect(component.getUrlEndPoint('configmodify')).toEqual('config-modify');
+ expect(component.getUrlEndPoint('configbackup')).toEqual('config-backup');
+ expect(component.getUrlEndPoint('configrestore')).toEqual('config-restore');
+ expect(component.getUrlEndPoint('healthcheck')).toEqual('health-check');
+ expect(component.getUrlEndPoint('quiescetraffic')).toEqual('quiesce-traffic');
+ expect(component.getUrlEndPoint('resumetraffic')).toEqual('resume-traffic');
+ expect(component.getUrlEndPoint('startapplication')).toEqual('start-application');
+ expect(component.getUrlEndPoint('stopapplication')).toEqual('stop-application');
+ expect(component.getUrlEndPoint('upgradebackout')).toEqual('upgrade-backout');
+ expect(component.getUrlEndPoint('upgradepostcheck')).toEqual('upgrade-post-check');
+ expect(component.getUrlEndPoint('upgradeprecheck')).toEqual('upgrade-pre-check');
+ expect(component.getUrlEndPoint('upgradesoftware')).toEqual('upgrade-software');
+ expect(component.getUrlEndPoint('DeFaultCASE')).toEqual('defaultcase');
+ });
});
-})
+})
\ No newline at end of file
diff --git a/src/app/test/test.component.ts b/src/app/test/test.component.ts
index 1874904..411b057 100644
--- a/src/app/test/test.component.ts
+++ b/src/app/test/test.component.ts
@@ -101,6 +101,7 @@
public enablePollButton: boolean = true;
public pollCounter = 0;
public enableCounterDiv: boolean = false;
+ public enableDownload: boolean = false;
constructor(private location: Location, private activeRoutes: ActivatedRoute, private notificationService: NotificationService, private nService: NotificationsService, private router: Router, private paramShareService: ParamShareService, private mappingEditorService: MappingEditorService, private httpUtil: HttpUtilService,
private utiltiy: UtilityService, private ngProgress: NgProgress) {
@@ -112,20 +113,6 @@
}
- prepareFileName(): any {
- let fileNameObject: any = this.mappingEditorService.latestAction;
- return fileNameObject;
- }
-
- /*public download() {
- let stringData: any;
- stringData = JSON.stringify(this.paramShareService.getSessionParamData());
- let paramsKeyValueFromEditor: JSON;
- paramsKeyValueFromEditor = JSON.parse(stringData);
- let fileName = 'param_' + this.action + '_' + this.type + '_' + "0.0.1" + 'V';
- this.JSONToCSVConvertor([paramsKeyValueFromEditor], fileName, true);
-
- }*/
public download() {
if (this.apiRequest) {
@@ -166,40 +153,6 @@
}
- /*JSONToCSVConvertor(JSONData, fileName, ShowLabel) {
- //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
- var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
-
- var CSV = '';
-
- //This condition will generate the Label/Header
- if (ShowLabel) {
- var testRow = "";
- for (var index in arrData[0]) {
-
- CSV += arrData[0][index].name + '\t' + arrData[0][index].value + '\t' + arrData[0][index].source + '\r\n';
- }
- }
-
- if (CSV == '') {
- alert("Invalid data");
- return;
- }
-
- //Initialize file format you want csv or xls
- var uri = 'data:application/vnd.ms-excel,' + encodeURI(CSV);
-
- var link = document.createElement("a");
- link.href = uri;
-
- link.download = fileName + ".xls";
-
- //this part will append the anchor tag and remove it after automatic click
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }*/
-
excelBrowseOption() {
$('#excelInputFile').trigger('click');
}
@@ -209,7 +162,7 @@
/* wire up file reader */
$('#filesparam').trigger('click');
const target: DataTransfer = <DataTransfer>(evt.target);
-
+ this.pollCounter = 0;
this.uploadFileName = evt.target.files[0].name;
var fileExtension = this.uploadFileName.substr(this.uploadFileName.lastIndexOf('.') + 1);
@@ -241,9 +194,9 @@
this.showStatusResponseDiv = false;
this.errorResponse = '';
this.statusResponse = '';
-
+ this.enableDownload=true;
let arrData = (<AOA>(XLSX.utils.sheet_to_json(ws, { blankrows: false })));
- this.nService.success('Success', 'SpreadSheet uploaded successfully');
+
console.log('Array data ==' + arrData[0]);
@@ -254,50 +207,14 @@
this.payload = {};
this.oldListName1 = '';
this.actionIdentifiers = {};
- for (var i = 0; i < arrData.length; i++) {
- var element = arrData[i];
- if (element['TagName'] === 'action') {
- this.action = element['Value'];
- }
- if (element['List Name'] === 'action-identifiers') {
- this.vnfId = element['Value'];
- var key = element['TagName'];
- var value = element['Value'];
- if (key && value) {
- this.actionIdentifiers[key] = value;
-
- }
- }
-
- if (element['List Name'] === 'payload') {
- var listName1 = element['List Name_1'];
- var listName2 = element['List Name_2'];
- var listName3 = element['List Name_3'];
- var key = element['TagName'];
- var value = element['Value'];
- if (listName1) {
- if (this.oldListName1 == '' || (listName1 === this.oldListName1)) {
- this.constructTestPayload(listName2, listName3, key, value);
- this.payload[listName1] = this.subPayload;
- }
- else {
- this.subPayload = {};
- this.constructTestPayload(listName2, listName3, key, value);
- this.payload[listName1] = this.subPayload;
- }
- this.oldListName1 = listName1;
- }
- else {
- this.payload[key] = value;
- }
- }
- }
-
- //console.log("VM JSON===" + JSON.stringify(this.vmPayload))
- // console.log('VM payload===' + JSON.stringify(this.payload));
- };
+ // Refactor
+ this.payload = this.processUploadedFile(arrData);
+ this.uploadedFileResult();
+ };
reader.readAsBinaryString(target.files[0]);
+
+
}
else {
this.nService.error('Error', 'Incorrect spreadsheet uploaded');
@@ -313,9 +230,82 @@
this.apiRequest = '';
this.apiResponse = '';
this.enableCounterDiv = false;
+ this.enableAbort = false;
+ this.enableTestButton = false;
+ this.enableDownload = false;
}
}
+processUploadedFile(arrData) {
+ let tempPayload = {};
+ for (var i = 0; i < arrData.length; i++) {
+ var element = arrData[i];
+ if (element['TagName'] === 'action') {
+ this.action = element['Value'];
+ }
+ if (element['List Name'] === 'action-identifiers') {
+ this.vnfId = element['Value'];
+ var key = element['TagName'];
+ var value = element['Value'];
+ if (key && value) {
+ this.actionIdentifiers[key] = value;
+
+ }
+ }
+
+ if (element['List Name'] === 'payload') {
+ var listName1 = element['List Name_1'];
+ var listName2 = element['List Name_2'];
+ var listName3 = element['List Name_3'];
+ var key = element['TagName'];
+ var value = element['Value'];
+ if (listName1) {
+ if (this.oldListName1 == '' || (listName1 === this.oldListName1)) {
+ this.constructTestPayload(listName2, listName3, key, value);
+ tempPayload[listName1] = this.subPayload;
+ }
+ else {
+ this.subPayload = {};
+ this.constructTestPayload(listName2, listName3, key, value);
+ tempPayload[listName1] = this.subPayload;
+ }
+ this.oldListName1 = listName1;
+ }
+ else {
+ tempPayload[key] = value;
+ }
+ }
+ }
+
+ return tempPayload;
+ }
+
+ uploadedFileResult() {
+ if (this.action && this.actionIdentifiers['vnf-id']) {
+ this.nService.success('Success', 'SpreadSheet uploaded successfully');
+ }
+ else {
+ this.flag = 1;
+ this.oldListName1 = '';
+ this.vmJson = {};
+ this.vnfcJson = {};
+ this.subPayload = {};
+ this.vmPayload = [];
+ this.payload = {};
+ this.action = '';
+ this.actionIdentifiers = {};
+ this.apiRequest = '';
+ this.apiResponse = '';
+ this.enableCounterDiv = false;
+ this.enableAbort = false;
+ this.enableTestButton = false;
+ this.enableDownload = false;
+ this.nService.error("Error", "Please check the contents of the file uploaded")
+ }
+ }
+
+
+
constructTestPayload(listName2, listName3, key, value) {
if (listName2 == undefined && listName3 == undefined) {
this.subPayload[key] = value;
@@ -373,9 +363,6 @@
}
testVnf() {
- //let payload = '{"request-parameters":{"vnf-host-ip-address":"' + this.host + '"},"configuration-parameters":"' + JSON.stringify(this.formattedNameValuePairs) + '"}"';
- //let payload = '{"request-parameters":{"host-ip-address:"' + this.host + '",port-number:"'+port+'"}}';
-
this.enableBrowse = false;
this.enableTestButton = false;
this.enablePollButton = false;
@@ -412,9 +399,7 @@
pollTestStatus() {
if (this.requestId && this.actionIdentifiers['vnf-id']) {
- // console.log("payload==" + JSON.stringify(this.payload))
let timeStamp = new Date().toISOString();
- // console.log("timestamp==" + timeStamp)
let reqId = new Date().getTime().toString();
let data = {
'input': {
@@ -435,20 +420,17 @@
'payload': '{"request-id":' + this.requestId + '}'
}
};
- //this.ngProgress.start();
this.httpUtil.post(
{
url: environment.checkTestStatus, data: data
})
.subscribe(resp => {
- // console.log('Response==' + JSON.stringify(resp));
this.statusResponse = JSON.stringify(resp);
var status = ''
var statusReason = ''
this.enableCounterDiv = true;
this.pollCounter++;
- //this.statusResponse=JSON.parse(this.statusResponse)
if (resp.output) var timeStamp = resp.output['common-header'].timestamp;
if (resp.output.payload) {
var payload = resp.output.payload.replace(/\\/g, "")
@@ -466,7 +448,7 @@
this.outputTimeStamp = timeStamp;
this.status = status;
this.statusReason = statusReason;
- if (status.toUpperCase() === 'SUCCESS') {
+ if (status.toUpperCase() === 'SUCCESS' || status.toUpperCase() === 'SUCCESSFUL') {
this.subscribe.unsubscribe();
this.enablePollButton = true;
}
@@ -479,7 +461,7 @@
this.showStatusResponseDiv = false;
}
- // this.ngProgress.done();
+
},
error => {
this.statusResponse = null;
@@ -493,9 +475,7 @@
else {
this.nService.error("Error", "Please enter vnf Id & request Id");
}
- // setTimeout(() => {
- // this.ngProgress.done();
- // }, 3500);
+
}
getUrlEndPoint(action) {
diff --git a/src/app/vnfs/build-artifacts/parameter-definitions/parameter-definition.service.spec.ts b/src/app/vnfs/build-artifacts/parameter-definitions/parameter-definition.service.spec.ts
index 8a9c112..a629bcf 100644
--- a/src/app/vnfs/build-artifacts/parameter-definitions/parameter-definition.service.spec.ts
+++ b/src/app/vnfs/build-artifacts/parameter-definitions/parameter-definition.service.spec.ts
@@ -100,15 +100,35 @@
}));
- // it('processKeyFile...', inject([ParameterDefinitionService, ParamShareService], (service: ParameterDefinitionService, paramShareService: ParamShareService)=> {
- // let keyFile = "PARAMVALUE|SOURCE|RULETYPE|KEY1|VALUE1|KEY2|VALUE2|KEY3|VALUE3\nvalue1|INSTAR|interface_ip_address|UniqueKeyName1|addressfqdn123|UniqueKeyValue|m001ssc001p1n001v001|FieldKeyName|ipaddress_v4\nvalue2|INSTAR|interface_ip_address|UniqueKeyName2|addressfqdnAsgar1|UniqueKeyValue|m001ssc001p1n001v002|FieldKeyName|ipaddress_v4";
- // let expectedPD = [{"name":"name1","type":null,"description":null,"required":null,"default":null,"source":"Manual","rule-type":null,
- // "request-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"response-keys":[{"key-name":null
- // ,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"ruleTypeValues":[null]}];
- // localStorage['paramsContent'] = "{ \"name1\":\"value1\",\"name2\":\"value2\"}";
- // paramShareService.setSessionParamData(expectedPD)
- // expect(service.processKeyFile("testfile.txt", keyFile)).toEqual(expectedPD);
+ it('processKeyFile...', inject([ParameterDefinitionService, ParamShareService], (service: ParameterDefinitionService, paramShareService: ParamShareService)=> {
+ let keyFile = "PARAMVALUE|SOURCE|RULETYPE|KEY1|VALUE1|KEY2|VALUE2|KEY3|VALUE3\nvalue1|INSTAR|interface_ip_address|UniqueKeyName1|addressfqdn123|UniqueKeyValue|m001ssc001p1n001v001|FieldKeyName|ipaddress_v4\nvalue2|INSTAR|interface_ip_address|UniqueKeyName2|addressfqdnAsgar1|UniqueKeyValue|m001ssc001p1n001v002|FieldKeyName|ipaddress_v4";
+ let expectedPD = [{"name":"name1","type":null,"description":null,"required":null,"default":null,"source":"Manual","rule-type":null,
+ "request-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"response-keys":[{"key-name":null
+ ,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"ruleTypeValues":[null]}];
+ localStorage['paramsContent'] = "{ \"name1\":\"value1\",\"name2\":\"value2\"}";
+ paramShareService.setSessionParamData(expectedPD)
+ expect(service.processKeyFile("testfile.txt", keyFile)).toEqual(expectedPD);
- // }));
+ }));
+
+ it('destroy...', inject([ParameterDefinitionService, ParamShareService, MappingEditorService], (service: ParameterDefinitionService, paramShareService: ParamShareService, mappingEditorService: MappingEditorService)=> {
+ mappingEditorService.referenceNameObjects = {"action":"Configure","action-level":"vnf","scope":{"vnf-type":"ticktack","vnfc-type":""},"template":"Y","vm":[],"device-protocol":"CHEF","user-name":"","port-number":"","artifact-list":[{"artifact-name":"template_Configure_ticktack_0.0.1V.json","artifact-type":"config_template"},{"artifact-name":"pd_Configure_ticktack_0.0.1V.yaml","artifact-type":"parameter_definitions"}],"scopeType":"vnf-type"};
+
+ let displayParamObjects = [{"name":"name1","type":null,"description":null,"required":null,"default":null,"source":"Manual","rule-type":null,
+ "request-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"response-keys":[{"key-name":null
+ ,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"ruleTypeValues":[null]}];
+ localStorage['paramsContent'] = "{ \"name1\":\"value1\",\"name2\":\"value2\"}";
+
+ let expectedPDdata = "---\nkind: \"Property Definition\"\nversion: V1\nvnf-parameter-list:\n- name: name1\n type: null\n description: null\n required: null\n default: null\n source: Manual\n rule-type: null\n request-keys: null\n response-keys: null\n";
+ let expectedAppData = {"input":{"design-request":{"request-id":"115599612197","action":"uploadArtifact","payload":{"userID": "test Usr","vnf-type" : "undefined","action" : "undefined","artifact-name" : "undefined","artifact-type" : "APPC-CONFIG","artifact-version" : "0.0.1","artifact-contents" : "---\nkind: \"Property Definition\"\nversion: V1\nvnf-parameter-list:\n- name: name1\n type: null\n description: null\n required: null\n default: null\n source: Manual\n rule-type: null\n request-keys: null\n response-keys: null\n"}}}};
+ service.appDataObject = {pd:""};
+ service.downloadDataObject = {pd:{pdData:"", pdFileName:""}};
+ service.destroy(displayParamObjects);
+ expect(mappingEditorService.downloadDataObject.pd.pdData).toEqual(expectedPDdata);
+ //expect(mappingEditorService.appDataObject.pd).toEqual(expectedAppData);
+
+
+ }));
+
});
diff --git a/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.html b/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.html
index ed0fbd3..cb02db9 100644
--- a/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.html
+++ b/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.html
@@ -23,8 +23,7 @@
-->
<simple-notifications [options]="options"></simple-notifications>
-<ng-progress [positionUsing]="'marginLeft'" [minimum]="0.15" [maximum]="1" [speed]="200" [showSpinner]="false" [direction]="'leftToRightIncreased'" [color]="'#6ab344'"
- [trickleSpeed]="250" [thick]="true" [ease]="'linear'"></ng-progress>
+<ng-progress [positionUsing]="'marginLeft'" [minimum]="0.15" [maximum]="1" [speed]="200" [showSpinner]="false" [direction]="'leftToRightIncreased'" [color]="'#6ab344'" [trickleSpeed]="250" [thick]="true" [ease]="'linear'"></ng-progress>
<div class="card" style=" margin-bottom: 23px;">
<img class="card-img-top" data-src="holder.js/100%x180/" alt="">
<div class="card-block" style="border-top: 5px solid #6ab344;border-top-right-radius: 7px;border-top-left-radius: 7px;">
@@ -43,7 +42,7 @@
<label>Protocol</label><input class="form-control" type="text" disabled value="{{protocol}}" />
</div>
<div *ngIf="(action === 'ConfigScaleOut')" class="col-lg-3 col-sm-6 col-md-3 col-xs-12">
- <label>templateIdentifier</label><input class="form-control" type="text" disabled value="{{identifier}}" />
+ <label>Template Identifier</label><input class="form-control" type="text" disabled value="{{identifier}}" />
</div>
</div>
</div>
@@ -55,18 +54,15 @@
<div class="input-group">
<input id="inputFile1" class="file" hidden #myInput1 type='file' (change)="fileChange(myInput1, 'pdfile')">
<input [(ngModel)]="myPdFileName" type="text" class="input-lg" disabled placeholder="Upload parameters from PC" style="width:85%;">
- <button [disabled]="(undefined == mappingEditorService.latestAction)" (click)="browsePdFile($event)" class="browse mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary input-lg"
- type="button"> UPLOAD PD FILE
+ <button [disabled]="(undefined == mappingEditorService.latestAction)" (click)="browsePdFile($event)" class="browse mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary input-lg" type="button"> UPLOAD PD FILE
</button>
</div>
</div>
<div class="col-12">
<div class="input-group">
<input id="inputFile2" class="file" hidden #myInput2 type='file' (change)="fileChange(myInput2, 'keyfile')">
- <input [(ngModel)]="myKeyFileName" type="text" class="input-lg" disabled placeholder="Upload key file from PC. You can upload a key file only if you have some parameters."
- style="width:85%;">
- <button [disabled]="(!(undefined !== displayParamObjects && displayParamObjects.length>0))" (click)="browseKeyFile($event)" class="browse mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary input-lg"
- type="button">UPLOAD KEY FILE
+ <input [(ngModel)]="myKeyFileName" type="text" class="input-lg" disabled placeholder="Upload key file from PC. You can upload a key file only if you have some parameters." style="width:85%;">
+ <button [disabled]="(!(undefined !== displayParamObjects && displayParamObjects.length>0))" (click)="browseKeyFile($event)" class="browse mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary input-lg" type="button">UPLOAD KEY FILE
</button>
</div>
</div>
@@ -148,8 +144,7 @@
</td>
<td class="mdl-data-table__cell--non-numeric">
- <select (ngModelChange)="ruleTypeChanged($event,obj)" class="form-control" id="id4" [(ngModel)]="obj['rule-type']" #objRuleType="ngModel" name="objRuleType{{i}}"
- list="ruleTypes">
+ <select (ngModelChange)="ruleTypeChanged($event,obj)" class="form-control" id="id4" [(ngModel)]="obj['rule-type']" #objRuleType="ngModel" name="objRuleType{{i}}" list="ruleTypes">
<option *ngFor="let rTyp of obj.ruleTypeValues;" [value]="rTyp"
[selected]="rTyp === obj.rule-type">
{{rTyp}}
@@ -158,8 +153,7 @@
</td>
<td>
- <select *ngIf="obj.showFilterFields" (ngModelChange)="filetrByFieldChanged($event,obj)" class="form-control" id="id4" [(ngModel)]="obj['response-keys'][3]['key-value']"
- #objfilterByField="ngModel" name="filterByField{{i}}" list="ruleTypes">
+ <select *ngIf="obj.showFilterFields" (ngModelChange)="filetrByFieldChanged($event,obj)" class="form-control" id="id4" [(ngModel)]="obj['response-keys'][3]['key-value']" #objfilterByField="ngModel" name="filterByField{{i}}" list="ruleTypes">
<option *ngFor="let fTyp of filterByFieldvalues;" [value]="fTyp"
[selected]="fTyp === obj['response-keys'][3]['key-value']">
{{fTyp}}
@@ -167,8 +161,8 @@
</select>
</td>
<td>
- <input *ngIf="obj.showFilterFields" [disabled]="!(obj.enableFilterByValue)" type="text" [value]="obj['response-keys'][4]['key-value']" class="form-control"
- id="id4" [(ngModel)]="obj['response-keys'][4]['key-value']" #objfilterByValue="ngModel" name="objfilterByValue{{i}}" list="ruleTypes">
+ <input *ngIf="obj.showFilterFields" [disabled]="!(obj.enableFilterByValue)" type="text" [value]="obj['response-keys'][4]['key-value']" class="form-control" id="id4" [(ngModel)]="obj['response-keys'][4]['key-value']" #objfilterByValue="ngModel" name="objfilterByValue{{i}}"
+ list="ruleTypes">
</td>
<td class="mdl-data-table__cell--non-numeric">{{obj['response-keys'][0]['key-name']}}
diff --git a/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.spec.ts b/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.spec.ts
index 2668f2b..0d220c8 100644
--- a/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.spec.ts
+++ b/src/app/vnfs/build-artifacts/parameter-definitions/parameter.component.spec.ts
@@ -119,21 +119,6 @@
expect(component.ngAfterViewInit()).toEqual("TEST PD INFORMATION");
}));
-/*
- it('should read file key file content...', () => {
- let input = {"__zone_symbol__changefalse":[{"type":"eventTask","state":"running","source":"HTMLInputElement.addEventListener:change","zone":"angular","runCount":2}]};
- expect(component.fileChange(input, 'keyfile'));
- });
-
-let content = new Blob(["PARAMVALUE|SOURCE|RULETYPE|KEY1|VALUE1|KEY2|VALUE2|KEY3|VALUE3\nvalue1|INSTAR|interface_ip_address|UniqueKeyName1|addressfqdn123|UniqueKeyValue|m001ssc001p1n001v001|FieldKeyName|ipaddress_v4\nvalue2|INSTAR|interface_ip_address|UniqueKeyName2|addressfqdnAsgar1|UniqueKeyValue|m001ssc001p1n001v002|FieldKeyName|ipaddress_v4"]
-{includes:()});
-let file = new File(content, "test.txt");
- it('should read file PD file content...', () => {
- let input = {"__zone_symbol__changefalse":[{"type":"eventTask","state":"running","source":"HTMLInputElement.addEventListener:change","zone":"angular","runCount":2}]};
-
- expect(component.fileChange(input, 'pdfile'));
- });
- */
it('should set the ruletypes for source A&AI...', inject([MappingEditorService, ParamShareService], (mappingEditorService: MappingEditorService, paramShareService:ParamShareService) => {
let obj = {"name":"name1","type":"ipv4-address","description":"xxx","required":"true","default":null,"source":"A&AI","rule-type":null,"request-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"response-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"ruleTypeValues":[null]}
diff --git a/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.html b/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.html
index 150d5ad..3b1199b 100644
--- a/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.html
+++ b/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.html
@@ -22,8 +22,7 @@
-->
<simple-notifications [options]="options"></simple-notifications>
-<ng-progress [positionUsing]="'marginLeft'" [minimum]="0.15" [maximum]="1" [speed]="200" [showSpinner]="false" [direction]="'leftToRightIncreased'" [color]="'#6ab344'"
- [trickleSpeed]="250" [thick]="true" [ease]="'linear'"></ng-progress>
+<ng-progress [positionUsing]="'marginLeft'" [minimum]="0.15" [maximum]="1" [speed]="200" [showSpinner]="false" [direction]="'leftToRightIncreased'" [color]="'#6ab344'" [trickleSpeed]="250" [thick]="true" [ease]="'linear'"></ng-progress>
<tabs>
<tab [tabTitle]="'Template Configuration'">
@@ -69,6 +68,9 @@
<div class="col-lg-3 col-sm-6 col-md-3 col-xs-12">
<label>Protocol</label><input class="form-control" type="text" disabled value="{{protocol}}" />
</div>
+ <div *ngIf="(action === 'ConfigScaleOut')" class="col-lg-3 col-sm-6 col-md-3 col-xs-12">
+ <label>Template Identifier</label><input class="form-control" type="text" disabled value="{{identifier}}" />
+ </div>
</div>
</div>
</div>
@@ -83,8 +85,7 @@
</div>
</div>
- <input type="file" id="filesparam" style="visibility:hidden;" class="form-control-file" (change)="fileParamChange(myInputParam)" #myInputParam placeholder="Upload file..."
- />
+ <input type="file" id="filesparam" style="visibility:hidden;" class="form-control-file" (change)="fileParamChange(myInputParam)" #myInputParam placeholder="Upload file..." />
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-12 text-right">
<button type="button" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary" (click)="retrieveNameValueFromAppc()">Retrieve Name/Value from APPC
@@ -95,24 +96,13 @@
</div>
</div>
<hr>
- <!--Commenting out 1712 changes here-->
- <!--<div class="col-md-12" [hidden]="!showMappingDownloadDiv"><label>Download Name/Value pair as : </label>
- <select class="form-control col-md-3" [(ngModel)]="mapppingDownloadType" (ngModelChange)="onDownloadParameter()">
- <option value="">Select</option>
- <option value="Json">JSON</option>
- <option value="Xls">XLS</option>
- </select>
-</div>-->
-
+
<div class="col-md-12"></div>
<div><label for="textAreaGeneratedTemplate">
<div class="mdl-card__title-text">Param Name Value List</div>
<div><font size="1">(Please click anywhere on the editor to see the synced name value pairs)</font></div>
</label>
- <!-- <ace-editor [(text)]="this.artifactRequest.paramsContent" [theme]="'chrome'" [mode]="'velocity'" (textChanged)="onParamChanges($event)" [options]="{maxLines: 'Infinity', fontSize: '13pt'}"
- style="min-height: 500px; width: fit-content;"></ace-editor> -->
- <ace-editor [(text)]="this.artifactRequest.paramsContent" #templateeditor [theme]="'chrome'" [mode]="'velocity'" (textChanged)="onParamChanges($event)"
- [options]="{maxLines: 'Infinity', fontSize: '13pt' }" style="min-height: 500px; width: 100%"></ace-editor>
+ <ace-editor [(text)]="this.artifactRequest.paramsContent" #templateeditor [theme]="'chrome'" [mode]="'velocity'" (textChanged)="onParamChanges($event)" [options]="{maxLines: 'Infinity', fontSize: '13pt' }" style="min-height: 500px; width: 100%"></ace-editor>
</div>
</tab>
diff --git a/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.spec.ts b/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.spec.ts
new file mode 100644
index 0000000..991ff45
--- /dev/null
+++ b/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.spec.ts
@@ -0,0 +1,242 @@
+/*
+============LICENSE_START==========================================
+===================================================================
+Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+===================================================================
+
+Unless otherwise specified, all software contained herein is licensed
+under the Apache License, Version 2.0 (the License);
+you may not use this software except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+ECOMP is a trademark and service mark of AT&T Intellectual Property.
+============LICENSE_END============================================
+*/
+
+import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
+import { By, BrowserModule } from '@angular/platform-browser';
+import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
+import { Component, OnInit, ViewChild, Input } from '@angular/core';
+import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
+import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
+import { ArtifactRequest } from '../../../../shared/models/index';
+import { ActivatedRoute, Router } from "@angular/router";
+import { saveAs } from "file-saver";
+import { NotificationService } from '../../../../shared/services/notification.service';
+import { NotificationsService } from "angular2-notifications"
+import { ParamShareService } from '../../../../shared/services/paramShare.service';
+import { DialogService } from "ng2-bootstrap-modal";
+import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
+import { BuildDesignComponent } from '../../build-artifacts.component';
+import { environment } from '../../../../../environments/environment';
+import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'
+import { FormsModule } from '@angular/forms';
+import { RouterTestingModule } from '@angular/router/testing';
+import { HomeComponent } from '../../../../home/home/home.component';
+import { LogoutComponent } from '../../../../shared/components/logout/logout.component';
+import { HelpComponent } from '../../../../shared/components/help/help/help.component';
+import { AboutUsComponent } from '../../../../about-us/aboutus.component';
+import { TestComponent } from '../../../../test/test.component';
+import { HttpModule } from '@angular/http';
+import { AceEditorComponent } from 'ng2-ace-editor';
+import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
+import { SimpleNotificationsModule } from 'angular2-notifications';
+import { GoldenConfigurationMappingComponent } from './param-name-value.component';
+import { Observable } from 'rxjs/Observable';
+import { NgProgress } from 'ngx-progressbar';
+import { BaseRequestOptions, Response, ResponseOptions, Http } from '@angular/http';
+import { MockBackend, MockConnection } from '@angular/http/testing';
+
+
+describe('GoldenConfigurationMappingComponent', () => {
+ let component: GoldenConfigurationMappingComponent;
+ let fixture: ComponentFixture<GoldenConfigurationMappingComponent>;
+ let buildDesignComponent: BuildDesignComponent;
+ let paramShareService: ParamShareService;
+ let dialogService: DialogService;
+ let notificationService: NotificationService;
+ let httpUtil: HttpUtilService;
+ let mappingEditorService: MappingEditorService;
+ let activeRoutes: ActivatedRoute;
+ let router: Router;
+ let nService: NotificationsService
+ const routes = [
+ {
+ path: 'home',
+ component: HomeComponent
+ }, {
+ path: 'vnfs',
+ loadChildren: '../../../../vnfs/vnfs.module#VnfsModule'
+ }, {
+ path: 'test',
+ component: TestComponent
+ },
+ {
+ path: 'help',
+ component: HelpComponent
+ }, {
+ path: 'aboutUs',
+ component: AboutUsComponent
+ }, {
+ path: 'logout',
+ component: LogoutComponent
+ }, {
+ path: '',
+ redirectTo: '/home',
+ pathMatch: 'full'
+ }
+ ];
+
+ beforeEach(() => {
+ TestBed.configureTestingModule({
+ imports: [FormsModule, BrowserModule, RouterTestingModule.withRoutes(routes), HttpModule, Ng2Bs3ModalModule, SimpleNotificationsModule.forRoot()],
+ declarations: [GoldenConfigurationMappingComponent, HomeComponent, TestComponent, HelpComponent, AboutUsComponent, LogoutComponent, AceEditorComponent],
+ providers: [BuildDesignComponent, NgProgress, ParamShareService, DialogService, NotificationService,MockBackend,
+ HttpUtilService, MappingEditorService, NotificationsService,
+ BaseRequestOptions,
+ {
+ provide: Http,
+ useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
+ return new Http(backend, defaultOptions);
+ },
+ deps: [MockBackend, BaseRequestOptions],
+ }
+
+ ],
+ schemas: [NO_ERRORS_SCHEMA],
+ })
+
+ });
+
+ beforeEach(async(() => {
+ TestBed.compileComponents()
+
+ }));
+
+ it('validate if uploaded file should be only json', () => {
+ fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
+ component = fixture.componentInstance;
+ expect(component.validateUploadedFile('xls')).toBe(false);
+ expect(component.validateUploadedFile('json')).toBe(true);
+ expect(component.validateUploadedFile('xml')).toBe(false);
+ });
+
+
+
+ it('validate initialisation of variables in ngOnit() function', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" }
+ mappingEditorService.fromScreen = 'MappingScreen';
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>";
+ expect(component.ngOnInit());
+ expect(component.ngAfterViewInit());
+
+ component.paramsContent = JSON.stringify({
+ "sync_auto-pop_name1": "testIp1",
+ "sync_auto-pop_address1": "",
+ "node0_tacplus_server_name2": "testIp2"
+ });
+ expect(component.ngOnInit());
+
+ expect(component.ngAfterViewInit());
+
+ expect(component.action).toEqual('Configure');
+ expect(component.vnfType).toEqual('testVnf');
+ expect(component.vnfcType).toEqual('');
+ expect(component.protocol).toEqual('CHEF');
+
+ expect(component.artifactName).toEqual('template_Configure_test_0.0.1V.json');
+
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "testVnfc" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" }
+ expect(component.ngOnInit());
+ expect(component.vnfcType).toEqual('testVnfc');
+
+
+ }));
+
+ it('check if variables are empty when reference data object is empty', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = undefined;
+ component.ngOnInit();
+ expect(component.ngAfterViewInit());
+ expect(component.action).toEqual('');
+ expect(component.vnfType).toEqual('');
+ expect(component.vnfcType).toEqual('');
+ expect(component.artifactName).toEqual('');
+
+ }));
+
+ it('test whether onparamchanges function is able to set the cache correctly for param name values', () => {
+ fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
+ component = fixture.componentInstance;
+ var data = JSON.stringify({
+ "sync_auto-pop_name1": "testIp1",
+ "sync_auto-pop_address1": "",
+ "node0_tacplus_server_name2": "testIp2"
+ });
+ component.onParamChanges(data);
+ expect(localStorage["paramsContent"]).toBe(data);
+ })
+
+
+ it('retrieveNameValue function should return response on success and set the localstorage data for param', inject([HttpUtilService, NgProgress, MappingEditorService, MockBackend], (httpUtilService: HttpUtilService, mappingEditorService: MappingEditorService, ngProgress: NgProgress, mockBackend: MockBackend) => {
+ fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
+ component = fixture.componentInstance;
+ var mockData = {
+ "output": {
+ "data": {
+ "block": "{\"userID\":null,\"designInfo\":null,\"statusInfo\":null,\"artifactInfo\":[{\"artifact-content\":\"[{\\\"node0_tacplus_server_name1\\\":\\\"testIp1\\\",\\\"node0_tacplus_server_source_address1\\\":\\\"testIp2\\\",\\\"node0_tacplus_server_name2\\\":\\\"testIp3\\\"}]\"}]}",
+ "requestId": "497085412083"
+ },
+ "status": {
+ "code": "400",
+ "message": "success"
+ }
+ }
+ };
+
+ let response = new ResponseOptions({
+ body: JSON.stringify(mockData)
+ });
+ const baseResponse = new Response(response);
+ mockBackend.connections.subscribe(
+ (c: MockConnection) => c.mockRespond(baseResponse)
+ );
+
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" }
+
+ mappingEditorService.fromScreen = 'MappingScreen';
+ component.action = 'Configure';
+ component.refObj = mappingEditorService.latestAction;
+ component.scopeName = "testVnf";
+ component.vnfType = "testVnf";
+ component.userId = "abc";
+ component.item.action = "Configure";
+ component.retrieveNameValueFromAppc();
+ expect(localStorage["localStorage['paramsContent']"]).not.toBe(null);
+
+ }));
+
+ it('test sync from param value function', inject([ParamShareService], (paramShareService: ParamShareService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
+ component = fixture.componentInstance;
+ localStorage['paramsContent'] = JSON.stringify({
+ "node0_tacplus_server_name1": "testIp1", "node0_tacplus_server_source_address1": "testIp2", "node0_tacplus_server_name2": "testIp3"
+ });
+ var pdData = [{ "name": "sync_auto-pop_name1", "type": null, "description": null, "required": null, "default": null, "source": "A&AI", "rule-type": "vnfc-oam-ipv4-address-list", "request-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "response-keys": [{ "key-name": "unique-key-name", "key-value": "parent-name" }, { "key-name": "unique-key-value", "key-value": "vnfc" }, { "key-name": "field-key-name", "key-value": "ipaddress-v4-oam-vip" }, { "key-name": null, "key-value": "vm-number" }, { "key-name": null, "key-value": "test" }], "ruleTypeValues": [null, "vnf-name", "vm-name-list", "vnfc-name-list", "vnf-oam-ipv4-address", "vnfc-oam-ipv4-address-list"], "showFilterFields": true, "enableFilterByValue": true }, { "name": "sync_auto-pop_address1", "type": null, "description": null, "required": null, "default": null, "source": "A&AI", "rule-type": "vm-name-list", "request-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "response-keys": [{ "key-name": "unique-key-name", "key-value": "parent-name" }, { "key-name": "unique-key-value", "key-value": "vserver" }, { "key-name": "field-key-name", "key-value": "vserver-name" }, { "key-name": null, "key-value": "vnfc-function-code" }, { "key-name": null, "key-value": null }], "ruleTypeValues": [null, "vnf-name", "vm-name-list", "vnfc-name-list", "vnf-oam-ipv4-address", "vnfc-oam-ipv4-address-list"], "showFilterFields": true, "enableFilterByValue": true }, { "name": "node0_tacplus_server_name2", "type": null, "description": null, "required": null, "default": null, "source": "Manual", "rule-type": null, "request-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "response-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "ruleTypeValues": [null] }];
+ paramShareService.setSessionParamData([pdData]);
+ component.syncParam();
+ }));
+
+
+});
\ No newline at end of file
diff --git a/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.ts b/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.ts
index 9ea95ec..a3c5a8e 100644
--- a/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.ts
+++ b/src/app/vnfs/build-artifacts/template-holder/param-name-value/param-name-value.component.ts
@@ -40,17 +40,6 @@
import { NgProgress } from 'ngx-progressbar';
import * as XLSX from 'xlsx';
-type AOA = Array<Array<any>>;
-
-function s2ab(s: string): ArrayBuffer {
- const buf = new ArrayBuffer(s.length);
- const view = new Uint8Array(buf);
- for (let i = 0; i !== s.length; ++i) {
- view[i] = s.charCodeAt(i) & 0xFF;
- }
- return buf;
-}
-
declare var $: any;
@Component({
@@ -62,7 +51,7 @@
enableMappingSave: boolean = false;
aceText: string = '';
fileName: string = '';
- actionType: any;
+ actionType: any='';
modal: any;
configMappingEditorContent: any;
fileType: any = '';
@@ -80,11 +69,13 @@
enableDownload: boolean = false;
showMappingDownloadDiv: boolean = false;
mapppingDownloadType: any;
- action: any;
- artifactName: any;
+ action: any='';
+ artifactName: any='';
enableMerge: boolean = false;
apiToken = localStorage['apiToken'];
userId = localStorage['userId'];
+ identifier: any;
+
public uploadTypes = [
{
value: 'Mapping Data',
@@ -107,20 +98,9 @@
@ContentChildren(Tab) tabs: QueryList<Tab>;
public subscription: any;
public item: any = {};
-
- public Actions = [
- { action: 'ConfigBackup', value: 'ConfigBackup' },
- { action: 'ConfigModify', value: 'ConfigModify' },
- { action: 'ConfigRestore', value: 'ConfigRestore' },
- { action: 'Configure', value: 'Configure' },
- { action: 'GetRunningConfig', value: 'GetRunningConfig' },
- { action: 'HealthCheck', value: 'HealthCheck' },
- { action: 'StartApplication', value: 'StartApplication' },
- { action: 'StopApplication', value: 'StopApplication' }
- ];
- vnfType: any;
- vnfcType: any;
- protocol: any;
+ vnfType: any='';
+ vnfcType: any='';
+ protocol: any='';
refObj: any;
public paramsContent = localStorage['paramsContent'];
@@ -175,13 +155,12 @@
this.activeRoutes.url.subscribe(UrlSegment => {
this.actionType = UrlSegment[0].path;
});
- if (this.actionType === 'configureTemplate') {
- this.mappingEditorService.fromScreen = 'TemplateScreen';
- }
+
if (this.actionType === 'myTemplates') {
this.mappingEditorService.fromScreen = 'MappingScreen';
}
this.mappingEditorService.paramData = [];
+ this.identifier = this.mappingEditorService.identifier;
}
@@ -192,11 +171,7 @@
}
//========================== End of browseOption() Method============================================
- selectedNavItem(item: any) {
- this.item = item;
- }
-
- //========================== End of selectedNavItem() Method============================================
+
ngOnDestroy() {
this.prepareFileName();
}
@@ -221,73 +196,13 @@
}
}
else {
- this.Actions = [];
this.enableMappingBrowse = false;
}
}
//========================== End of ngAfterViewInit() Method============================================
- upload(evt: any) {
- /* wire up file reader */
- if (evt.target.files[0]) {
- const target: DataTransfer = <DataTransfer>(evt.target);
- this.myfileName = evt.target.files[0].name;
- var fileExtension = this.myfileName.substr(this.myfileName.lastIndexOf('.') + 1);
- if (fileExtension.toUpperCase() === 'xls'.toUpperCase()) {
- if (target.files.length != 1) {
- throw new Error('Cannot upload multiple files on the entry');
- }
- const reader = new FileReader();
- reader.onload = (e: any) => {
- /* read workbook */
- const bstr = e.target.result;
- const wb = XLSX.read(bstr, { type: 'binary' });
- /* grab first sheet */
- const wsname = wb.SheetNames[0];
- const ws = wb.Sheets[wsname];
- /* save data */
- let arrData = (<AOA>(XLSX.utils.sheet_to_json(ws, { header: 1 })));
- var jsonStr = arrData.toString();
- var JsonArr = jsonStr.split(',');
- var finalStr = '{\r\n';
- for (var i = 0; i < JsonArr.length; i = i + 2) {
- var key = JsonArr[i];
- var value = JsonArr[i + 1];
- finalStr = finalStr + key + ':' + value + ',\r\n';
- }
- finalStr = finalStr.substring(0, finalStr.length - 3) + '\r\n}';
- this.artifactRequest.paramsContent = finalStr;
- this.initialData = finalStr;
- this.enableMappingSave = true;
- };
- reader.readAsBinaryString(target.files[0]);
- if ('Mapping Data' === this.selectedUploadType) {
- this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
- this.mappingEditorService.setParamContent(this.artifactRequest.paramsContent);
- }
- }
- else {
- let reader = new FileReader();
- this.readFile(evt.target.files[0], reader, (result) => {
- if ('Mapping Data' === this.selectedUploadType) {
- var jsonObject = JSON.parse(result);
- this.artifactRequest.paramsContent = JSON.stringify(jsonObject, null, 1);
- this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
- this.mappingEditorService.setParamContent(this.artifactRequest.paramsContent);
- }
- this.initialData = result;
- this.enableMappingSave = true;
- });
- }
- }
- else {
- this.notificationService.notifyErrorMessage('Failed to reading file..');
- }
- this.myInputParam.nativeElement.value = '';
- }
-
- //========================== End of upload() Method============================================
- //uncommenting for 1710
+
+
public fileParamChange(input) {
if (input.files && input.files[0]) {
this.enableMappingSave = true;
@@ -349,75 +264,7 @@
}
//========================== End of onParamChanges() Method============================================
- onDownloadParameter() {
- let refObj = this.refObj;
- if (refObj) {
- // refObj = refObj[refObj.length - 1];
- let paramsKeyValueFromEditor: JSON;
- this.initialData = this.artifactRequest.paramsContent;
- paramsKeyValueFromEditor = JSON.parse(this.artifactRequest.paramsContent);
- let theJSON = JSON.stringify(paramsKeyValueFromEditor, null, '\t');
- var blob = new Blob([theJSON], {
- type: 'text/json'
- });
- this.showVersionDiv = true;
- let fileName: any;
- fileName = this.updateFileName(refObj.action, this.scopeName, this.versionNo);
- saveAs(blob, fileName);
- }
- else {
- this.nService.error('Error', 'Please enter Action and VNF type in Reference Data screen');
-
- }
- }
-
- //========================== End of onDownloadParameter() Method============================================
- JSONToCSVConvertor(JSONData, fileName, ShowLabel) {
- //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
- var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
- var CSV = '';
- //This condition will generate the Label/Header
- if (ShowLabel) {
- var testRow = '';
- for (var index in arrData[0]) {
- CSV += index + '\t' + arrData[0][index] + '\r\n';
- }
- }
- if (CSV == '') {
- return;
- }
- //Initialize file format you want csv or xls
- var uri = 'data:application/vnd.ms-excel,' + encodeURI(CSV);
- var link = document.createElement('a');
- link.href = uri;
- link.download = fileName + '.xls';
- //this part will append the anchor tag and remove it after automatic click
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
-
- //========================== End of JSONToCSVConvertor() Method============================================
- updateFileNameForXls(action: any, scopeName: any, versionNo: any) {
- let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V';
- return fileName;
- }
-
- //========================== End of updateFileNameForXls() Method============================================
- appendSlashes(artifactData) {
- let x = artifactData.replace(new RegExp(',"', 'g'), ',\"');
- let y = x.replace(new RegExp('":', 'g'), '\":');
- let z = y.replace(new RegExp('{"', 'g'), '{\"');
- let t = z.replace(new RegExp(':"', 'g'), ':\"');
- let m = t.replace(new RegExp('",', 'g'), '\",');
- let n = y.replace(new RegExp('"}', 'g'), '\"}');
- let nw = n.replace(new RegExp('{"', 'g'), '{\"');
- let nw1 = nw.replace(new RegExp(':"', 'g'), ':\"');
- let nw2 = nw1.replace(new RegExp('",', 'g'), '\",');
- return nw2;
- }
-
- //========================== End of appendSlashes() Method============================================
+
updateFileName(action: any, scopeName: any, versionNo: any) {
let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
this.downloadedFileName = fileName;
@@ -431,55 +278,14 @@
}
//========================== End of prepareFileName() Method============================================
- openModel(toShow: any, message: any, title: any) {
- this.message = message;
- this.title = title;
- $('#modalButton').trigger('click');
- }
-
- //========================== End of openModel() Method============================================
- checkSave(selectedAction): void {
- if (this.actionType === 'updateTemplate') {
- if (!this.buildDesignComponent.isReferenceFound(selectedAction, this.mappingEditorService.getReferenceList())) {
- this.nService.error('Error', 'Reference Data not found. Please add Reference Data for Action:' + selectedAction);
- }
- }
- if (this.initialData != this.artifactRequest.paramsContent) {
- this.showConfirm(this.initialData);
- }
- else {
- this.initialAction = this.item.action;
- }
- }
-
- //========================== End of checkSave() Method============================================
- showConfirm(initialData) {
- let disposable = this.dialogService.addDialog(ConfirmComponent, {
- title: 'Confirm title',
- message: 'Confirm message'
- })
- .subscribe((isConfirmed) => {
- //We get dialog result
- if (isConfirmed) {
- this.artifactRequest.paramsContent = initialData;
- this.initialAction = this.item.action;
- }
- else {
- this.item.action = this.initialAction;
- }
- });
- }
-
- //========================== End of showConfirm() Method============================================
+
retrieveNameValueFromAppc() {
let refObj = this.refObj;
if (refObj && refObj != undefined) {
- // console.log("REF OBJECT IN RETRIVE"+JSON.stringify(refObj));
this.enableMerge = true;
var scopeName = this.scopeName.replace(/ /g, '').replace(new RegExp('/', "g"), '_').replace(/ /g, '');
let fileName = this.updateFileName(this.item.action, scopeName, this.versionNo);
let payload = '{"userID": "' + this.userId + '", "action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
- // console.log("payload OBJECT IN RETRIVE"+JSON.stringify(payload));
let input = {
'input': {
'design-request': {
@@ -531,70 +337,8 @@
}
//========================== End of retrieveNameValueFromAppc() Method============================================
- saveNameValueToAppc() {
- let refObj = this.refObj;
- if (refObj && refObj != undefined) {
- // refObj = refObj[refObj.length - 1];
- let paramsKeyValueFromEditor = JSON.parse(this.artifactRequest.paramsContent);
- let action = this.item.action;
- let fileName = this.updateFileName(refObj.action, this.scopeName, this.versionNo);
- let vnfType = this.vnfType;
- let Json = [paramsKeyValueFromEditor];
- let slashedPayload = this.appendSlashes(JSON.stringify(Json));
- let newPayload =
- {
- 'userID': this.userId,
- 'vnf-type': this.vnfType,
- 'action': action,
- 'artifact-name': fileName,
- 'artifact-type': 'APPC-CONFIG',
- 'artifact-version': this.versionNo,
- 'artifact-contents': slashedPayload
- };
- let data =
- {
- 'input': {
- 'design-request': {
- 'request-id': this.apiToken,
- 'action': 'uploadArtifact',
- 'payload': JSON.stringify(newPayload)
- }
- }
- };
- this
- .httpUtil
- .post(
- { url: environment.getDesigns, data: data })
- .subscribe(resp => {
- if (resp.output.status.code === '400' && resp.output.status.message === 'success') {
- this.nService.success('Success', 'Name/value pairs saved successfully to APPC');
- }
- if (resp.output.status.code === '401') {
- this.nService.error('Error', resp.output.status.message);
- }
- },
- error => this.nService.error('Error', 'Could not save name value pairs. Error in connecting APPC Server'));
- }
- setTimeout(() => {
- this.ngProgress.done();
- }, 3500);
- }
-
- //========================== End of saveNameValueToAppc() Method============================================
+
formatNameValuePairs(namevaluePairs: string) {
- //var string = namevaluePairs.substring(2, namevaluePairs.length - 2);
- /* var stringArr = string.split(",");
- var newStringArr = [];
- var resultStr = "{\r\n\"";
- for (var index in stringArr) {
- newStringArr[index] = stringArr[index] + ",\r\n";
- }
- for (var index in newStringArr) {
- resultStr = resultStr + newStringArr[index];
- }
- resultStr = resultStr.substring(0, resultStr.length - 3) + "\"\r\n}"
- return resultStr;*/
-
var string = namevaluePairs.substring(1, namevaluePairs.length - 1);
var stringArr = string.split(',');
var newStringArr = [];
@@ -619,7 +363,6 @@
var pdDataArrayForSession = [];
try {
paramNameValues = JSON.parse(paramNameValuesStr);
- console.log('Param Name values array==' + JSON.stringify(paramNameValues));
if (paramNameValues && paramNameValues != undefined) {
for (var index in paramNameValues) {
var json = {
@@ -688,7 +431,7 @@
'ruleTypeValues': arr2item.ruleTypeValues
};
pdDataArrayForSession.splice(i, 1, json);
- // console.log("Result array index ==" + JSON.stringify(resultArr[i]))
+
}
});
diff --git a/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.html b/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.html
index c1fb030..335b595 100644
--- a/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.html
+++ b/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.html
@@ -21,8 +21,7 @@
============LICENSE_END============================================
-->
<simple-notifications [options]="options"></simple-notifications>
-<ng-progress [positionUsing]="'marginLeft'" [minimum]="0.15" [maximum]="1" [speed]="200" [showSpinner]="false" [direction]="'leftToRightIncreased'" [color]="'#6ab344'"
- [trickleSpeed]="250" [thick]="true" [ease]="'linear'"></ng-progress>
+<ng-progress [positionUsing]="'marginLeft'" [minimum]="0.15" [maximum]="1" [speed]="200" [showSpinner]="false" [direction]="'leftToRightIncreased'" [color]="'#6ab344'" [trickleSpeed]="250" [thick]="true" [ease]="'linear'"></ng-progress>
<div>
<div>
<div class="card" style="margin-bottom: 23px;">
@@ -43,7 +42,7 @@
<label>Protocol</label><input class="form-control" type="text" disabled value="{{protocol}}" />
</div>
<div *ngIf="(action === 'ConfigScaleOut')" class="col-lg-3 col-sm-6 col-md-3 col-xs-12">
- <label>templateIdentifier</label><input class="form-control" type="text" disabled value="{{identifier}}" />
+ <label>Template Identifier</label><input class="form-control" type="text" disabled value="{{identifier}}" />
</div>
</div>
</div>
@@ -53,8 +52,7 @@
<div class="input-group">
<input id="inputFile" class="file" #myInput type='file' (change)='fileChange(myInput)'>
<input [(ngModel)]="fileName" type="text" class="input-lg" disabled placeholder="Upload template from PC" style="width:80%">
- <button (click)="browseOption($event)" [disabled]="!enableBrowse" class="browse mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary input-lg"
- type="button">Upload Template File
+ <button (click)="browseOption($event)" [disabled]="!enableBrowse" class="browse mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--primary input-lg" type="button">Upload Template File
</button>
</div>
</div>
@@ -73,10 +71,7 @@
<div><label for="textAreaGeneratedTemplate">
<div class="mdl-card__title-text">File Editor</div>
</label>
- <!-- <ace-editor [(text)]="configMappingEditorContent" #templateeditor [theme]="'chrome'" [mode]="'velocity'" [options]="{maxLines: 'Infinity', fontSize: '13pt'}"
- style="min-height: 500px; width: fit-content;scroll-snap-coordinate: 3%"></ace-editor> -->
- <ace-editor [(text)]="configMappingEditorContent" #templateeditor [theme]="'chrome'" [mode]="'velocity'" [options]="{maxLines: 'Infinity', fontSize: '13pt' }"
- style="min-height: 500px; width: 100%"></ace-editor>
+ <ace-editor [(text)]="configMappingEditorContent" #templateeditor [theme]="'chrome'" [mode]="'velocity'" [options]="{maxLines: 'Infinity', fontSize: '13pt' }" style="min-height: 500px; width: 100%"></ace-editor>
</div>
<app-modal [title]="'Confirmation'" [isShow]="false" [message]="'Template is saved and ready for creating parameter definition'" #modalComponent>
</app-modal>
diff --git a/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.spec.ts b/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.spec.ts
index f26e5fd..d2412a0 100644
--- a/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.spec.ts
+++ b/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.spec.ts
@@ -21,12 +21,11 @@
============LICENSE_END============================================
*/
-/* tslint:disable:no-unused-variable */
+
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { By, BrowserModule } from '@angular/platform-browser';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { Component, OnInit, ViewChild, Input } from '@angular/core';
-//import { ModalComponent } from '../../modal/modal.component';
import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
import { ArtifactRequest } from '../../../../shared/models/index';
@@ -36,8 +35,8 @@
import { NotificationsService } from "angular2-notifications"
import { ParamShareService } from '../../../../shared/services/paramShare.service';
import { DialogService } from "ng2-bootstrap-modal";
-import {ConfirmComponent} from '../../../../shared/confirmModal/confirm.component';
-import {BuildDesignComponent} from '../../build-artifacts.component';
+import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
+import { BuildDesignComponent } from '../../build-artifacts.component';
import { environment } from '../../../../../environments/environment';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'
import { FormsModule } from '@angular/forms';
@@ -53,6 +52,8 @@
import { SimpleNotificationsModule } from 'angular2-notifications';
import { GoldenConfigurationComponent } from './template-configuration.component';
import { NgProgress } from 'ngx-progressbar';
+import { BaseRequestOptions, Response, ResponseOptions, Http } from '@angular/http';
+import { MockBackend, MockConnection } from '@angular/http/testing';
describe('GoldenConfigurationComponent', () => {
let component: GoldenConfigurationComponent;
@@ -97,7 +98,17 @@
TestBed.configureTestingModule({
imports: [FormsModule, BrowserModule, RouterTestingModule.withRoutes(routes), HttpModule, Ng2Bs3ModalModule, SimpleNotificationsModule.forRoot()],
declarations: [GoldenConfigurationComponent, HomeComponent, TestComponent, HelpComponent, AboutUsComponent, LogoutComponent, AceEditorComponent],
- providers: [BuildDesignComponent, NgProgress, ParamShareService, DialogService, NotificationService, HttpUtilService, MappingEditorService, NotificationsService],
+ providers: [BuildDesignComponent, NgProgress, ParamShareService, DialogService, NotificationService, MockBackend,
+ BaseRequestOptions,
+ {
+ provide: Http,
+ useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
+ return new Http(backend, defaultOptions);
+ },
+ deps: [MockBackend, BaseRequestOptions],
+ },
+
+ HttpUtilService, MappingEditorService, NotificationsService],
schemas: [NO_ERRORS_SCHEMA],
})
@@ -132,28 +143,28 @@
expect(component.artifactName).toEqual('template_Configure_test_0.0.1V.json');
- mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "testVnfc" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" }
- expect(component.ngOnInit());
- expect(component.vnfcType).toEqual('testVnfc');
-
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "testVnfc" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" }
+ expect(component.ngOnInit());
+ expect(component.vnfcType).toEqual('testVnfc');
+
}));
it('check if variables are empty when reference data object is empty', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
fixture = TestBed.createComponent(GoldenConfigurationComponent);
component = fixture.componentInstance;
- mappingEditorService.latestAction = { "action": "", "scope": { "vnf-type": "", "vnfc-type": "" }, "vm": [], "protocol": "", "download-dg-reference": "", "user-name": "", "port-number": "", "artifact-list": [], "deviceTemplate": "", "scopeType": "" };
-
+ // mappingEditorService.latestAction = { "action": "", "scope": { "vnf-type": "", "vnfc-type": "" }, "vm": [], "protocol": "", "download-dg-reference": "", "user-name": "", "port-number": "", "artifact-list": [], "deviceTemplate": "", "scopeType": "" };
+ mappingEditorService.latestAction = undefined;
expect(component.ngAfterViewInit());
expect(component.action).toEqual('');
expect(component.vnfType).toEqual('');
expect(component.vnfcType).toEqual('');
expect(component.protocol).toEqual('');
expect(component.artifactName).toEqual('');
-
+
}));
- it('check if correct notification is fired while initialising if reference data object is undefined',()=>{
+ it('check if correct notification is fired while initialising if reference data object is undefined', () => {
fixture = TestBed.createComponent(GoldenConfigurationComponent);
component = fixture.componentInstance;
expect(component.ngAfterViewInit());
@@ -161,39 +172,205 @@
expect(component.enableBrowse).toBe(false)
});
- it('test sync template when template data, param data and pd data are available', inject([MappingEditorService, ParamShareService], (mappingEditorService: MappingEditorService, paramShareService:ParamShareService) => {
+ it('test sync template when template data, param data and pd data are available', inject([MappingEditorService, ParamShareService], (mappingEditorService: MappingEditorService, paramShareService: ParamShareService) => {
fixture = TestBed.createComponent(GoldenConfigurationComponent);
component = fixture.componentInstance;
mappingEditorService.fromScreen === 'MappingScreen'
- component.configMappingEditorContent="<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"
mappingEditorService.initialise(component.templateeditor.getEditor(), component.configMappingEditorContent, component.modal);
-
- var pdData=[{"name":"sync_auto-pop_name1","type":null,"description":null,"required":null,"default":null,"source":"A&AI","rule-type":"vnfc-oam-ipv4-address-list","request-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"response-keys":[{"key-name":"unique-key-name","key-value":"parent-name"},{"key-name":"unique-key-value","key-value":"vnfc"},{"key-name":"field-key-name","key-value":"ipaddress-v4-oam-vip"},{"key-name":null,"key-value":"vm-number"},{"key-name":null,"key-value":"test"}],"ruleTypeValues":[null,"vnf-name","vm-name-list","vnfc-name-list","vnf-oam-ipv4-address","vnfc-oam-ipv4-address-list"],"showFilterFields":true,"enableFilterByValue":true},{"name":"sync_auto-pop_address1","type":null,"description":null,"required":null,"default":null,"source":"A&AI","rule-type":"vm-name-list","request-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"response-keys":[{"key-name":"unique-key-name","key-value":"parent-name"},{"key-name":"unique-key-value","key-value":"vserver"},{"key-name":"field-key-name","key-value":"vserver-name"},{"key-name":null,"key-value":"vnfc-function-code"},{"key-name":null,"key-value":null}],"ruleTypeValues":[null,"vnf-name","vm-name-list","vnfc-name-list","vnf-oam-ipv4-address","vnfc-oam-ipv4-address-list"],"showFilterFields":true,"enableFilterByValue":true},{"name":"node0_tacplus_server_name2","type":null,"description":null,"required":null,"default":null,"source":"Manual","rule-type":null,"request-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"response-keys":[{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null},{"key-name":null,"key-value":null}],"ruleTypeValues":[null]}];
+
+ var pdData = [{ "name": "sync_auto-pop_name1", "type": null, "description": null, "required": null, "default": null, "source": "A&AI", "rule-type": "vnfc-oam-ipv4-address-list", "request-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "response-keys": [{ "key-name": "unique-key-name", "key-value": "parent-name" }, { "key-name": "unique-key-value", "key-value": "vnfc" }, { "key-name": "field-key-name", "key-value": "ipaddress-v4-oam-vip" }, { "key-name": null, "key-value": "vm-number" }, { "key-name": null, "key-value": "test" }], "ruleTypeValues": [null, "vnf-name", "vm-name-list", "vnfc-name-list", "vnf-oam-ipv4-address", "vnfc-oam-ipv4-address-list"], "showFilterFields": true, "enableFilterByValue": true }, { "name": "sync_auto-pop_address1", "type": null, "description": null, "required": null, "default": null, "source": "A&AI", "rule-type": "vm-name-list", "request-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "response-keys": [{ "key-name": "unique-key-name", "key-value": "parent-name" }, { "key-name": "unique-key-value", "key-value": "vserver" }, { "key-name": "field-key-name", "key-value": "vserver-name" }, { "key-name": null, "key-value": "vnfc-function-code" }, { "key-name": null, "key-value": null }], "ruleTypeValues": [null, "vnf-name", "vm-name-list", "vnfc-name-list", "vnf-oam-ipv4-address", "vnfc-oam-ipv4-address-list"], "showFilterFields": true, "enableFilterByValue": true }, { "name": "node0_tacplus_server_name2", "type": null, "description": null, "required": null, "default": null, "source": "Manual", "rule-type": null, "request-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "response-keys": [{ "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }, { "key-name": null, "key-value": null }], "ruleTypeValues": [null] }];
paramShareService.setSessionParamData([pdData]);
- localStorage["paramsContent"]={
- "sync_auto-pop_name1":"10.0.1.34",
- "sync_auto-pop_address1":"",
- "node0_tacplus_server_name2":"192.34.45.5"
- };
+ localStorage["paramsContent"] = {
+ "sync_auto-pop_name1": "testIp1",
+ "sync_auto-pop_address1": "",
+ "node0_tacplus_server_name2": "testIp2"
+ };
expect(component.syncTemplate());
-
-
+
+
}));
- it('test sync template when template data, param data and pd data are not available', inject([MappingEditorService, ParamShareService], (mappingEditorService: MappingEditorService, paramShareService:ParamShareService) => {
+ it('test sync template when template data, param data and pd data are not available', inject([MappingEditorService, ParamShareService], (mappingEditorService: MappingEditorService, paramShareService: ParamShareService) => {
fixture = TestBed.createComponent(GoldenConfigurationComponent);
component = fixture.componentInstance;
mappingEditorService.fromScreen === 'MappingScreen'
- component.configMappingEditorContent="<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"
mappingEditorService.initialise(component.templateeditor.getEditor(), component.configMappingEditorContent, component.modal);
-
- var pdData=[];
+
+ var pdData = [];
paramShareService.setSessionParamData([pdData]);
- localStorage["paramsContent"]={};
+ localStorage["paramsContent"] = {};
expect(component.syncTemplate());
-
-
+
+
}));
+ it('test whether proper param data and template data are getting set in the appDataObject', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" };
+ component.ngOnInit();
+ component.ngAfterViewInit();
+ component.appDataObject = { reference: {}, template: { templateData: {}, nameValueData: {} }, pd: {} };
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"
+ mappingEditorService.initialise(component.templateeditor.getEditor(), component.configMappingEditorContent, component.modal);
+ localStorage["paramsContent"] = JSON.stringify({ "sync_auto-pop_name1": "testIp1", "sync_auto-pop_address1": "", "node0_tacplus_server_name2": "testIp2" });
+
+ component.userId = "testuser";
+ component.apiToken = "87264736473";
+ component.prepareAppData();
+ var paramData = { "input": ({ "design-request": ({ "request-id": '87264736473', "action": 'uploadArtifact', "payload": '{"userID":"testuser","vnf-type":"testVnf","action":"Configure","artifact-name":"param_Configure_testVnf_0.0.1V.json","artifact-type":"APPC-CONFIG","artifact-version":"0.0.1","artifact-contents":"[{\"sync_auto-pop_name1\":\"10.0.1.34\",\"sync_auto-pop_address1\":\"\",\"node0_tacplus_server_name2\":\"192.34.45.5\"}]"}' }) }) };
+ var templateData = { input: ({ "design-request": ({ "request-id": '87264736473', "action": 'uploadArtifact', "payload": '{"userID":"testuser","vnf-type":"testVnf","action":"Configure","artifact-name":"template_Configure_test_0.0.1V.json","artifact-type":"APPC-CONFIG","artifact-version":"0.0.1","artifact-contents":"<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n<version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"}' }) }) };
+ expect(component.appDataObject.template.nameValueData["payload"]).toBe(JSON.stringify(paramData["payload"]));
+ expect(component.appDataObject.template.templateData["payload"]).toBe(JSON.stringify(templateData["payload"]));
+ }));
+
+
+ it('test whether proper param data is getting set in the downloadDataObject', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" };
+ component.ngOnInit();
+ component.ngAfterViewInit();
+ component.downloadDataObject = {
+ reference: {},
+ template: { templateData: {}, nameValueData: {}, templateFileName: '', nameValueFileName: '' },
+ pd: { pdData: '', pdFileName: '' }
+ };
+ localStorage["paramsContent"] = JSON.stringify({ "sync_auto-pop_name1": "testIp1", "sync_auto-pop_address1": "", "node0_tacplus_server_name2": "testIp2" });
+
+ component.onDownloadParameter();
+ var nameValueData = {
+ "sync_auto-pop_name1": "testIp1",
+ "sync_auto-pop_address1": "",
+ "node0_tacplus_server_name2": "testIp2"
+ };
+ expect(component.downloadDataObject.template.nameValueData).toBe(JSON.stringify(nameValueData, null, "\t"));
+ expect(component.downloadDataObject.template.nameValueFileName).toBe("param_Configure_testVnf_0.0.1V.json");
+ }));
+
+ it('test whether proper template data is getting set in the downloadDataObject', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" };
+ component.ngOnInit();
+ component.ngAfterViewInit();
+ component.downloadDataObject = {
+ reference: {},
+ template: { templateData: {}, nameValueData: {}, templateFileName: '', nameValueFileName: '' },
+ pd: { pdData: '', pdFileName: '' }
+ };
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"
+ component.fileType = "text/xml"
+ component.onDownloadTemplate('Template');
+
+ component.fileType = "text/plain"
+ component.onDownloadTemplate('Template');
+ component.fileType = "text/json"
+ component.onDownloadTemplate('Template');
+ component.tempretrieveFlag = true;
+ component.fileNameForTempSave = "Configure_testVnf_0.0.1V.json"
+ component.onDownloadTemplate('Template');
+ expect(component.downloadDataObject.template.templateData).toBe(component.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}'));
+ }));
+
+
+ it('test merge status for golden config template and uploaded parameter data', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" };
+ component.ngOnInit();
+ component.ngAfterViewInit();
+ component.downloadDataObject = {
+ reference: {},
+ template: { templateData: {}, nameValueData: {}, templateFileName: '', nameValueFileName: '' },
+ pd: { pdData: '', pdFileName: '' }
+ };
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \r\n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\r\n <version>15.1X49-D50.3</version>\r\n <groups>\r\n <name>node0</name>\r\n <system>\r\n <tacplus-server>\r\n <name>testIp1</name>\r\n <source-address>135.144.3.125</source-address>\r\n </tacplus-server>\r\n <tacplus-server>\r\n <name>199.37.184.242</name>\r\n <source-address>testIp2</source-address>\r\n </tacplus-server>\r\n </system> \r\n </groups>\r\n </configuration>";
+ mappingEditorService.initialise(component.templateeditor.getEditor(), component.configMappingEditorContent, component.modal);
+ localStorage["paramsContent"] = JSON.stringify({
+ "node0_tacplus_server_name1": "testIp1",
+ "node0_tacplus_server_source_address1": "675453432",
+ "node0_tacplus_server_name2": "testIp2"
+ });
+ component.mergeParams();
+ expect(component.mergeStatus).toBe(true);
+
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\n <version>15.1X49-D50.3</version>\n <groups>\n <name>node0</name>\n <system>\n <tacplus-server>\n <name>${sync_auto-pop_name1}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n <tacplus-server>\n <name>${node0_tacplus_server_name2}</name>\n <source-address>${sync_auto-pop_address1}</source-address>\n </tacplus-server>\n </system> \n </groups>\n </configuration>"
+ mappingEditorService.initialise(component.templateeditor.getEditor(), component.configMappingEditorContent, component.modal);
+ component.mergeParams();
+ expect(component.mergeStatus).toBe(false);
+
+ }));
+
+ it('test handleAnnotation method', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" };
+ component.ngOnInit();
+ component.ngAfterViewInit();
+
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \r\n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\r\n <version>15.1X49-D50.3</version>\r\n <groups>\r\n <name>node0</name>\r\n <system>\r\n <tacplus-server>\r\n <name>199.37.184.211</name>\r\n <source-address>675453432</source-address>\r\n </tacplus-server>\r\n <tacplus-server>\r\n <name>199.37.184.242</name>\r\n <source-address>675453432</source-address>\r\n </tacplus-server>\r\n </system> \r\n </groups>\r\n </configuration>";
+ mappingEditorService.initialise(component.templateeditor.getEditor(), component.configMappingEditorContent, component.modal);
+ component.selectedWord = "node0";
+ expect(component.handleAnnotation(component.modal));
+ }));
+
+ it('test handleAnnotation method', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
+ fixture = TestBed.createComponent(GoldenConfigurationComponent);
+ component = fixture.componentInstance;
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" };
+ component.ngOnInit();
+ component.ngAfterViewInit();
+
+ component.configMappingEditorContent = "<configuration xmlns=\"http://xml.juniper.net/xnm/1.1/xnm\" \r\n xmlns:a=\"http://xml.juniper.net/junos/15.1X49/junos\" >\r\n <version>15.1X49-D50.3</version>\r\n <groups>\r\n <name>node0</name>\r\n <system>\r\n <tacplus-server>\r\n <name>{(node1)=(name1)}</name>\r\n <source-address>675453432</source-address>\r\n </tacplus-server>\r\n <tacplus-server>\r\n <name>199.37.184.242</name>\r\n <source-address>675453432</source-address>\r\n </tacplus-server>\r\n </system> \r\n </groups>\r\n </configuration>";
+ mappingEditorService.initialise(component.templateeditor.getEditor(), component.configMappingEditorContent, component.modal);
+ component.selectedWord = "node0";
+ component.tempName = "name0";
+ component.submitNameValues()
+ expect(component.replaceWord).toContain("{(node0)=(name0)}");
+ component.selectedWord = "{(node1)=(name1)}";
+ component.submitNameValues();
+ component.tempName = false;
+ component.submitNameValues();
+ }));
+
+ it('retrieveTemplateFromAppc function should return response on success and set the configMappingEditorContent object', inject([HttpUtilService, NgProgress, MappingEditorService, MockBackend], (httpUtilService: HttpUtilService, mappingEditorService: MappingEditorService, ngProgress: NgProgress, mockBackend: MockBackend) => {
+ fixture = TestBed.createComponent(GoldenConfigurationComponent);
+ component = fixture.componentInstance;
+ var mockData = {
+ "output": {
+ "data": {
+ "block": "{\"userID\":null,\"designInfo\":null,\"statusInfo\":null,\"artifactInfo\":[{\"artifact-content\":\" <configuration xmlns=\\\"http://xml.juniper.net/xnm/1.1/xnm\\\" \\n xmlns:a=\\\"http://xml.juniper.net/junos/15.1X49/junos\\\" >\\n <version>15.1X49-D50.3</version>\\n <groups>\\n <name>node0</name>\\n <system>\\n <tacplus-server>\\n <name>${sync_auto-pop_name1}</name>\\n <source-address>${sync_auto-pop_address1}</source-address>\\n </tacplus-server>\\n <tacplus-server>\\n <name>${node0_tacplus_server_name2}</name>\\n <source-address>${sync_auto-pop_address1}</source-address>\\n </tacplus-server>\\n </system> \\n </groups>\\n </configuration>\"}]}",
+ "requestId": "497085412083"
+ },
+ "status": {
+ "code": "400",
+ "message": "success"
+ }
+ }
+ }
+ let response = new ResponseOptions({
+ body: JSON.stringify(mockData)
+ });
+ const baseResponse = new Response(response);
+ mockBackend.connections.subscribe(
+ (c: MockConnection) => c.mockRespond(baseResponse)
+ );
+
+ mappingEditorService.latestAction = { "action": "Configure", "action-level": "vnf", "scope": { "vnf-type": "testVnf", "vnfc-type": "" }, "template": "Y", "vm": [], "device-protocol": "CHEF", "user-name": "", "port-number": "", "artifact-list": [{ "artifact-name": "template_Configure_test_0.0.1V.json", "artifact-type": "config_template" }, { "artifact-name": "pd_Configure_test_0.0.1V.yaml", "artifact-type": "parameter_definitions" }], "scopeType": "vnf-type" }
+
+ mappingEditorService.fromScreen = 'MappingScreen';
+ component.action = 'Configure';
+ component.refObj = mappingEditorService.latestAction;
+ component.scopeName = "testVnf";
+ component.vnfType = "testVnf";
+ component.userId = "abc";
+ component.item.action = "Configure";
+ component.retrieveTemplateFromAppc();
+ expect(component.configMappingEditorContent).not.toBe(null);
+
+ }));
});
diff --git a/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.ts b/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.ts
index 8514e24..1d1bc4f 100644
--- a/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.ts
+++ b/src/app/vnfs/build-artifacts/template-holder/template-configuration/template-configuration.component.ts
@@ -22,7 +22,6 @@
*/
import { Component, Input, OnInit, ViewChild } from '@angular/core';
-//import { ModalComponent } from '../../modal/modal.component';
import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
import { ArtifactRequest } from '../../../../shared/models/index';
@@ -45,7 +44,6 @@
@Input() configMappingEditorContent: string;
@Input() isMappingComp: boolean;
@ViewChild('myInput') myInputVariable: any;
- // @ViewChild(ModalComponent) modalComponent: ModalComponent;
@ViewChild('myModal') modal: ModalComponent;
aceText: string = ""
fileName: string = ""
@@ -96,6 +94,7 @@
clickToClose: true,
maxLength: 200
}
+ public replaceWord;
public enableDownloadButtons: boolean = false;
constructor(private buildDesignComponent: BuildDesignComponent, private paramShareService: ParamShareService, private dialogService: DialogService, private notificationService: NotificationService, private httpUtil: HttpUtilService, private mappingEditorService: MappingEditorService, private activeRoutes: ActivatedRoute, private router: Router, private nService: NotificationsService, private ngProgress: NgProgress) {
this.artifactRequest.action = '';
@@ -131,13 +130,13 @@
enableValidateTemplate: boolean = false;;
public selectedUploadType: string = this.uploadTypes[0].value;
identifier: any;
- //this.mappingeditorservice.referenceNameObjects = object;PLEASE USE THIS OBJECT TO GET TEMPALLDATA
- //====================================================
+ public tempRetrievalResponse:any;
+ public mergeStatus:boolean=false;
+
+ //======================================Start of ngOnInit() Method============================================
ngOnInit() {
var refObj = this.refObj = this.prepareFileName();
- // console.log("Ref object: " + JSON.stringify(refObj))
if (refObj && refObj != undefined) {
- // refObj = refObj[refObj.length - 1];
this.item = refObj;
this.vnfType = this.item.scope["vnf-type"];
@@ -160,17 +159,11 @@
this.activeRoutes.url.subscribe(UrlSegment => {
this.actionType = UrlSegment[0].path
})
- /*if (this.actionType === 'createTemplate') {
- this.mappingEditorService.fromScreen = 'TemplateScreen';
- }
- if (this.actionType === 'updateTemplate') {*/
this.mappingEditorService.fromScreen = 'MappingScreen';
- // }
this.identifier = this.mappingEditorService.identifier;
}
//========================== End of ngOnInit() Method============================================
ngOnDestroy() {
- //console.log("Reference object =="+ JSON.stringify(this.refObj));
if (this.refObj && this.refObj != undefined) {
if (this.configMappingEditorContent && this.configMappingEditorContent != undefined) {
this.saveTemplate();
@@ -200,13 +193,6 @@
}
let self = this;
this.templateEditor = self.templateeditor.getEditor();
- /* this.templateeditor.getEditor().commands.addCommand({
- name: 'annotateCommand',
- bindKey: { win: 'Ctrl-4', mac: 'Command-4' },
- exec: function (editor) {
- self.mappingEditorService.checkMethodCall(this.modal);
- }
- });*/
this.templateeditor.getEditor().commands.addCommand({
name: 'annotateCommand',
bindKey: { win: 'ENTER', mac: 'ENTER' },
@@ -218,10 +204,6 @@
this.configMappingEditorContent = this.mappingEditorService.getTemplateMappingDataFromStore();
this.fileType = sessionStorage.getItem('fileType');
}
- /* else if (this.mappingEditorService.fromScreen === 'TemplateScreen') {
- this.configMappingEditorContent = this.mappingEditorService.getTemplateDataFromStore();
- this.fileType = sessionStorage.getItem('fileType');
- }*/
if (this.configMappingEditorContent) {
this.artifactRequest.templateContent = this.configMappingEditorContent;
this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
@@ -246,18 +228,6 @@
$("#inputFile").trigger('click');
}
//========================== End of browseOption() Method============================================
- /* openFile(event) {
- let input = event.target;
- this.fileName = event.currentTarget.value.replace(/C:\\fakepath\\/i, '');
- for (let index = 0; index < input.files.length; index++) {
- let reader = new FileReader();
- reader.onload = () => {
- this.configMappingEditorContent = reader.result;
- }
- reader.readAsText(input.files[index]);
- };
- }
- //========================== End of openFile() Method============================================*/
//save to GUI
public saveTemplate() {
this.saveToGuiCacheFlag = 'true';
@@ -286,46 +256,9 @@
if (this.fileType === '') {
sessionStorage.setItem('fileType', '');
}
- // paramArr = this.mappingEditorService.paramData;
- // this.paramShareService.setTemplateData(paramArr)
- }
+ }
}
//========================== End of saveTemplate() Method============================================
- /* clearHighlight() {
- this.mappingEditorService.removeTheSelectedMarkers();
- }
- //========================== End of clearHighlight() Method============================================*/
- /*validateTemplate() {
- var fileExtensionArr = this.fileType.split("/");
- let data = {
- "input": {
- "design-request": {
- "request-id": this.apiToken,
- "action": "validateTemplate",
- "data-type": fileExtensionArr[1].toUpperCase(),
- "payload": this.configMappingEditorContent
- }
- }
- };
- let url = environment.validateTemplate;
- this
- .httpUtil
- .post(
- { url: url, data: data })
- .subscribe(resp => {
- if (resp.output.status.code === '400' && resp.output.status.message === "success") {
- this.uploadValidationSuccess = true;
- this.nService.success("Success", "Template Validated succesfully");
- return true;
- }
- else if (resp.output.status.code === '401') {
- this.nService.error("Error", resp.output.status.message);
- return false;
- }
- },
- error => this.nService.error("Error", "Unable to validate the uploaded template. Error in connecting APPC Server"));
- }
- //========================== End of validateTemplate() Method============================================*/
retrieveTemplateFromAppc() {
let refObj = this.refObj;
if (refObj && refObj != undefined) {
@@ -341,7 +274,6 @@
}
}
};
- // console.log("Retrieve artifact payload=="+ payload);
let artifactContent: any;
this.ngProgress.start();
this.httpUtil.post({
@@ -350,6 +282,7 @@
}).subscribe(resp => {
if (resp.output.status.code === '400' && resp.output.status.message === "success") {
this.nService.success("Success", "Template retrieved successfully from APPC");
+ this.tempRetrievalResponse=resp;
let result = JSON.parse(resp.output.data.block).artifactInfo[0];
result = result['artifact-content'];
if ('Generated Template' === this.selectedUploadType) {
@@ -371,16 +304,7 @@
}
this.ngProgress.done();
},
- /* (error) => {
- // this.showUploadErrorStatus = true;
- // this.nService.error('Status','Error Connecting to the APPC Network')
- //this.notificationService.notifyErrorMessage('Configuration Template file successfully uploaded..')
- //this.uploadStatusError = true;
- //window.scrollTo(0, 0)
- // this. nService.error('Status','Error Connecting to the APPC Network')
- this.openModel(true, "Could not retrieve latest template for given action""Error in connecting to APPC database")
- });*/
- error => this.nService.error("Error", "Error in connecting to APPC Server"));
+ error => this.nService.error("Error", "Error in connecting to APPC Server"));
setTimeout(() => {
this.ngProgress.done();
}, 3500);
@@ -389,14 +313,8 @@
//========================== End of retrieveTemplateFromAppc() Method============================================
prepareAppData() {
let refObj = this.refObj;
- //console.log("Reference object =="+ JSON.stringify(refObj));
if (refObj && refObj != undefined) {
- // refObj = refObj[refObj.length - 1];
let paramsKeyValueFromEditor: JSON;
- /* if (this.fileExtension.toUpperCase() === "XML")
- paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
- else*/
- // paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
try {
paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
}
@@ -432,7 +350,7 @@
}
}
}
- this.appDataObject.template.nameValueData = data;
+ this.appDataObject.template.nameValueData = data;
}
if (this.configMappingEditorContent) {
let actualContent = this.configMappingEditorContent;
@@ -452,7 +370,6 @@
fileName = this.fileNameForTempSave;
}
else {
- // fileName = this.updateDownloadTemplateFileName(refObj.action, this.scopeName, versionandFileType);
fileName = this.artifactName;
}
let vnfType = this.vnfType;
@@ -464,7 +381,6 @@
"artifact-name": fileName,
"artifact-type": "APPC-CONFIG",
"artifact-version": this.templateVersionNo,
- //"artifact-contents": this.configMappingEditorContent
"artifact-contents": this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
}
@@ -485,51 +401,6 @@
}
}
//========================== End of prepareAppData() Method============================================
- /*retrieveNameValueFromAppc() {
- let refObj: any = this.prepareFileName();
- if (refObj && refObj != undefined) {
- let fileName = this.updateParamFileName(this.item.action, this.scopeName, this.templateVersionNo);
- let payload = '{"userID": "' + this.userId + '","action": "' + this.item.action + '", "vnf-type" : "' + this.vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
- let input = {
- "input": {
- "design-request": {
- "request-id": this.apiToken,
- "action": "getArtifact",
- "payload": payload
- }
- }
- };
-
- let artifactContent: any;
- this.httpUtil.post({
- // url:"https://mtanjv9apdb51.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
- url: environment.getDesigns,
- data: input
- }).subscribe(resp => {
- if (resp.output.status.code === '400' && resp.output.status.message === "success") {
- this.openModel(true, 'Name/value pairs retrieved successfully from APPC', 'Success');
- let result = JSON.parse(resp.output.data.block).artifactInfo[0];
- result = JSON.parse(result['artifact-content']);
- var jsonString = JSON.stringify(result[0]);
- var string = jsonString.substring(1, jsonString.length - 1);
- var stringArr = string.split(",");
- var newStringArr = [];
- var resultStr = "{\r\n"
- for (var index in stringArr) {
- newStringArr[index] = stringArr[index] + ",\r\n";
- }
- for (var index in newStringArr) {
- resultStr = resultStr + newStringArr[index];
- }
- resultStr = resultStr.substring(0, resultStr.length - 3) + "\r\n}"
- this.configMappingEditorContent = resultStr;
-
- }
- },
- error => this.openModel(true, "Could not retrieve the name value pairs. Error in connecting to APPC Server", "ERROR"));
- }
- }*/
- //========================== End of retrieveNameValueFromAppc() Method============================================
prepareFileName(): any {
let fileNameObject: any = this.mappingEditorService.latestAction;
this.appDataObject = this.mappingEditorService.appDataObject;
@@ -541,14 +412,8 @@
onDownloadParameter() {
let refObj = this.refObj;
if (refObj) {
- // refObj = refObj[refObj.length - 1];
let paramsKeyValueFromEditor: JSON;
- if (this.fileExtension.toUpperCase() === "XML")
- paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
- else
- paramsKeyValueFromEditor = this.mappingEditorService.generateParams(this.templateeditor.getEditor(), this.artifactRequest.templateContent);
-
- try {
+ try {
paramsKeyValueFromEditor = JSON.parse(localStorage["paramsContent"]);
}
catch (error) {
@@ -571,37 +436,6 @@
}
//========================== End of onDownloadParameter() Method============================================
- /* JSONToCSVConvertor(JSONData, fileName, ShowLabel) {
- //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
- var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
- var CSV = '';
- //This condition will generate the Label/Header
- if (ShowLabel) {
- var testRow = "";
- for (var index in arrData[0]) {
- CSV += index + '\t' + arrData[0][index] + '\r\n';
- }
- }
- if (CSV == '') {
- return;
- }
- //Initialize file format you want csv or xls
- var uri = 'data:application/vnd.ms-excel,' + encodeURI(CSV);
- var link = document.createElement("a");
- link.href = uri;
- link.download = fileName + ".xls";
- //this part will append the anchor tag and remove it after automatic click
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
- //========================== End of JSONToCSVConvertor() Method============================================
- updateParamFileNameForXls(action: any, scopeName: any, versionNo: any) {
- let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V';
- this.downloadedParamFileName = fileName;
- return fileName;
- }
- //========================== End of updateParamFileNameForXls() Method============================================*/
updateParamFileName(action: any, scopeName: any, versionNo: any) {
let fileName = 'param_' + action + '_' + scopeName + '_' + versionNo + 'V.json';
this.downloadedParamFileName = fileName;
@@ -614,9 +448,7 @@
var config_template_fileName: any
let refObj = this.refObj;
let versionandFileType: string;
- this.mappingEditorService.generateTemplate(this.templateEditor);
- if (artifact == 'Template' && this.artifactRequest && this.configMappingEditorContent && refObj) {
- // refObj = refObj[refObj.length - 1];
+ if (artifact == 'Template' && this.artifactRequest && this.configMappingEditorContent && refObj) {
this.showTemplateVersionDiv = true;
if (this.fileType === "text/xml") {
textToSaveAsBlob = new Blob([this.configMappingEditorContent], {
@@ -645,30 +477,15 @@
});
}
else {
- // config_template_fileName = this.updateDownloadTemplateFileName(refObj.action, this.scopeName, versionandFileType);
config_template_fileName = this.artifactName;
}
- // saveAs(textToSaveAsBlob, config_template_fileName);
this.mappingEditorService.initialise(this.templateeditor.getEditor(), actualContent, this.modal);
- //this.downloadDataObject.template.templateData = this.configMappingEditorContent;
this.downloadDataObject.template.templateData = this.configMappingEditorContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}');
this.downloadDataObject.template.templateFileName = config_template_fileName;
}
}
//========================== End of onDownloadTemplate() Method============================================
- updateDownloadTemplateFileName(action: any, scopeName: any, versionandFileType: any) {
- let fileName = 'template_' + action + '_' + scopeName + '_' + versionandFileType;
- this.downloadedTemplateFileName = fileName;
- return fileName;
- }
- //========================== End of updateDownloadTemplateFileName() Method============================================
- /* openModel(toShow: any, message: any, title: any) {
- //this.modalComponent.isShow = toShow;
- //this.modalComponent.message = message;
- //this.modalComponent.title = title;
- }
- //========================== End of openModel() Method============================================*/
fileChange(input) {
let self = this;
@@ -676,17 +493,11 @@
this.enableValidateTemplate = true;
if (refObj && refObj != undefined) {
- // refObj = refObj[refObj.length - 1];
if (input.files && input.files[0]) {
- console.log("input files0" + JSON.stringify(input.files[0]))
this.myfileName = input.files[0].name;
this.fileName = input.files[0].name;
this.fileType = input.files[0].type;
- // var fileExtension = this.myfileName.substr(this.myfileName.lastIndexOf('.') + 1);
-
let reader = new FileReader();
- // if(this.validateUploadedFile(fileExtension))
- //{
this.readFile(input.files[0], reader, (result) => {
if (this.fileType === 'text/xml') {
sessionStorage.setItem('fileType', 'text/xml');
@@ -703,7 +514,6 @@
if ('Generated Template' === this.selectedUploadType) {
this.configMappingEditorContent = result
this.artifactRequest.templateContent = this.configMappingEditorContent;
- console.log("editor content==" + JSON.stringify(this.configMappingEditorContent))
this.notificationService.notifySuccessMessage('Configuration Template file successfully uploaded..');
if (this.artifactRequest.templateContent) {
this.mappingEditorService.initialise(this.templateeditor.getEditor(), this.artifactRequest.templateContent, this.modal);
@@ -714,12 +524,7 @@
this.saveTemplate();
});
- // }
- // else{
- // this.nService.error("Error", "Incorrect File Format")
- //this.configMappingEditorContent=''
- //}
- }
+ }
else {
this.nService.error("Error", "Failed to read file");
}
@@ -776,22 +581,13 @@
this.saveTemplate();
var templateData = this.mappingEditorService.paramData; //template data array
- // this.paramShareService.setTemplateData(templateData);
-
- //console.log("Template Name value pairs ===" + JSON.stringify(templateData))
var pdData = this.paramShareService.getSessionParamData(); //PD data array
- console.log("PD name value pairs===" + JSON.stringify(pdData))
-
-
var paramsContent = localStorage["paramsContent"];
- console.log("Param content before==" + paramsContent);
-
+
if (paramsContent && paramsContent != undefined) {
try {
var paramTabData = JSON.parse(paramsContent);
- //console.log("Param content after==" + paramsContent);
- //console.log("Param tab data after==" + JSON.stringify(paramTabData))
- }
+ }
catch (error) {
console.log("error is : " + error)
}
@@ -812,7 +608,6 @@
templateData.forEach(function (item) {
resultParamObj[item.paramName] = item.paramValue;
});
- // console.log("pARAM Result array before is " + JSON.stringify(resultParamObj))
if (paramTabData && paramTabData != undefined) {
templateData.forEach(function (item) {
for (var index in paramTabData) {
@@ -836,9 +631,6 @@
}
localStorage["paramsContent"] = JSON.stringify(resultParamObj);
- //console.log("param content after==" +JSON.stringify(resultParamObj));
-
- //removing duplicate elements from the array
templateData = Array.from(new Set(templateData.map((itemInArray) => itemInArray.paramName)))
//reformatting arr1 to match with PD
@@ -883,9 +675,6 @@
})
});
}
- //console.log("Result array before is " + JSON.stringify(resultArr))
- // console.log("Length before is: " + resultArr.length)
-
if (pdData && pdData != undefined) {
for (var i = 0; i < resultArr.length; i++) {
@@ -905,8 +694,7 @@
"ruleTypeValues": arr2item.ruleTypeValues
};
resultArr.splice(i, 1, json)
- // console.log("Result array index ==" + JSON.stringify(resultArr[i]))
- }
+ }
});
@@ -914,8 +702,6 @@
}
this.paramShareService.setSessionParamData(resultArr);
- //console.log("Result array after is " + JSON.stringify(resultArr))
- //console.log("Length after is: " + resultArr.length)
this.mappingEditorService.paramData = [];
//navigate to PD page after sync
this
@@ -925,8 +711,8 @@
//========================== End of syncTemplate() Method============================================
mergeParams() {
- var mergeStatus: boolean = this.mappingEditorService.autoAnnotateDataForParams(this.fileType);
- if (mergeStatus) {
+ this.mergeStatus = this.mappingEditorService.autoAnnotateDataForParams();
+ if (this.mergeStatus) {
this.nService.success("Success", "Merge Successful");
}
else {
@@ -937,30 +723,24 @@
//========================== End of mergeParams() Method============================================
public handleAnnotation(modal) {
- let selectedWord: string = this.templateeditor.getEditor().session.getTextRange(this.templateeditor.getEditor().selectionRange);
- this.selectedWord = selectedWord;
+ this.selectedWord = this.templateeditor.getEditor().session.getTextRange(this.templateeditor.getEditor().selectionRange);
modal.open();
}
//========================== End of handleAnnotations() Method============================================
public submitNameValues() {
- /*var editor = this.templateeditor.getEditor()
- this.editor = editor;
- this.editor.session = editor.session;
- this.editor.selection.session.$backMarkers = {};
- this.editorContent = this.artifactRequest.templateContent;
- this.editor.$blockScrolling = Infinity;
- this.editor.$blockSelectEnabled = false;*/
if (this.tempName) {
this.checkNameEntered = true;
if (this.selectedWord) {
if (this.selectedWord.startsWith('${(')) {
- var replaceWord: any = this.selectedWord.substring(3, this.selectedWord.indexOf(')=(')) + this.tempName;
+ var replaceWord: any =this.replaceWord = this.selectedWord.substring(3, this.selectedWord.indexOf(')=(')) + this.tempName;
this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
+
} else {
let mappingKey = this.mappingEditorService.getKeysForValues(this.selectedWord);
- var replaceWord: any = '${(' + this.selectedWord + ')=(' + this.tempName + ')}';
+ var replaceWord: any = this.replaceWord='${(' + this.selectedWord + ')=(' + this.tempName + ')}';
this.templateeditor.getEditor().session.replace(this.templateeditor.getEditor().session.selection.getRange(), replaceWord);
+
}
}
this.mappingEditorService.refreshEditor();
diff --git a/src/environments/environment.dev3.ts b/src/environments/environment.dev3.ts
index 38deafd..8167549 100644
--- a/src/environments/environment.dev3.ts
+++ b/src/environments/environment.dev3.ts
@@ -28,10 +28,6 @@
export const environment = {
production: false,
getDesigns: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:dbservice',
- //getDesigns: "http://localhost:9090/" + "https://mtanjv9apbc51.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
-
- //getDesigns:"http://localhost:8443/restconf/operations/design-services:dbservice",
- // validateTemplate:"https://"+window.location.hostname+":8443/restconf/operations/design-services:validator"
validateTemplate: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:validator',
testConfigure: 'https://' + window.location.hostname + ':8443/restconf/operations/appc-provider-lcm:configure'
};
diff --git a/src/environments/environment.dev4.ts b/src/environments/environment.dev4.ts
index 38deafd..8167549 100644
--- a/src/environments/environment.dev4.ts
+++ b/src/environments/environment.dev4.ts
@@ -28,10 +28,6 @@
export const environment = {
production: false,
getDesigns: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:dbservice',
- //getDesigns: "http://localhost:9090/" + "https://mtanjv9apbc51.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
-
- //getDesigns:"http://localhost:8443/restconf/operations/design-services:dbservice",
- // validateTemplate:"https://"+window.location.hostname+":8443/restconf/operations/design-services:validator"
validateTemplate: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:validator',
testConfigure: 'https://' + window.location.hostname + ':8443/restconf/operations/appc-provider-lcm:configure'
};
diff --git a/src/environments/environment.prod.ts b/src/environments/environment.prod.ts
index d0c6462..472f51b 100644
--- a/src/environments/environment.prod.ts
+++ b/src/environments/environment.prod.ts
@@ -28,10 +28,6 @@
export const environment = {
production: true,
getDesigns: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:dbservice',
- //getDesigns: "http://localhost:9090/" + "https://mtanjv9apbc51.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
-
- //getDesigns:"http://localhost:8443/restconf/operations/design-services:dbservice",
- // validateTemplate:"https://"+window.location.hostname+":8443/restconf/operations/design-services:validator"
validateTemplate: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:validator',
testConfigure: 'https://' + window.location.hostname + ':8443/restconf/operations/appc-provider-lcm:configure'
};
diff --git a/src/environments/environment.ts b/src/environments/environment.ts
index 37d7598..0804645 100644
--- a/src/environments/environment.ts
+++ b/src/environments/environment.ts
@@ -30,31 +30,10 @@
production: false,
//Environment for PROD
- // getDesigns: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:dbservice',
- // validateTemplate: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:validator',
- // testVnf: 'https://' + window.location.hostname + ':8443/restconf/operations/appc-provider-lcm:',
- // checkTestStatus: 'https://' + window.location.hostname + ':8443/restconf/operations/appc-provider-lcm:action-status'
+ getDesigns: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:dbservice',
+ validateTemplate: 'https://' + window.location.hostname + ':8443/restconf/operations/design-services:validator',
+ testVnf: 'https://' + window.location.hostname + ':8443/restconf/operations/appc-provider-lcm:',
+ checkTestStatus: 'https://' + window.location.hostname + ':8443/restconf/operations/appc-provider-lcm:action-status'
- // Evn for Dev3 should always be commented
- //
- // getDesigns: "https://mtanjv9apbc53.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
- // validateTemplate: "https://mtanjv9apbc53.aic.cip.att.com:8443/restconf/operations/design-services:validator",
- // testVnf: "https://mtanjv9apbc53.aic.cip.att.com:8443/restconf/operations/appc-provider-lcm:",
- // checkTestStatus: "https://mtanjv9apbc53.aic.cip.att.com:8443/restconf/operations/appc-provider-lcm:action-status"
-
-
- // Evn for Dev1 should always be commented
-
- getDesigns: "https://mtanjv9apbc51.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
- validateTemplate: "https://mtanjv9apbc51.aic.cip.att.com:8443/restconf/operations/design-services:validator",
- testVnf: "https://mtanjv9apbc51.aic.cip.att.com:8443/restconf/operations/appc-provider-lcm:",
- checkTestStatus: "https://mtanjv9apbc51.aic.cip.att.com:8443/restconf/operations/appc-provider-lcm:action-status"
-
- // Evn for Dev6 should always be commented
-
- // getDesigns: "https://mtanjv9apdb53.aic.cip.att.com:8443/restconf/operations/design-services:dbservice",
- // validateTemplate: "https://mtanjv9apdb53.aic.cip.att.com:8443/restconf/operations/design-services:validator",
- // testVnf: "https://mtanjv9apdb53.aic.cip.att.com:8443/restconf/operations/appc-provider-lcm:",
- // checkTestStatus: "https://mtanjv9apdb53.aic.cip.att.com:8443/restconf/operations/appc-provider-lcm:action-status"
};