param-bame-value component spec changes
[appc/cdt.git] / src / app / vnfs / build-artifacts / template-holder / param-name-value / param-name-value.component.spec.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
5 ===================================================================
6 Copyright (C) 2018 IBM.
7 ===================================================================
8
9 Unless otherwise specified, all software contained herein is licensed
10 under the Apache License, Version 2.0 (the License);
11 you may not use this software except in compliance with the License.
12 You may obtain a copy of the License at
13
14     http://www.apache.org/licenses/LICENSE-2.0
15
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
21
22 ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 ============LICENSE_END============================================
24 */
25
26 /* tslint:disable:no-unused-variable */
27 import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
28 import { By, BrowserModule } from '@angular/platform-browser';
29 import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
30 import { Component, OnInit, ViewChild, Input } from '@angular/core';
31 import { HttpUtilService } from '../../../../shared/services/httpUtil/http-util.service';
32 import { MappingEditorService } from '../../../../shared/services/mapping-editor.service';
33 import { ArtifactRequest } from '../../../../shared/models/index';
34 import { ActivatedRoute, Router } from "@angular/router";
35 import { saveAs } from "file-saver";
36 import { NotificationService } from '../../../../shared/services/notification.service';
37 import { NotificationsService } from "angular2-notifications"
38 import { ParamShareService } from '../../../../shared/services/paramShare.service';
39 import { DialogService } from "ng2-bootstrap-modal";
40 import { ConfirmComponent } from '../../../../shared/confirmModal/confirm.component';
41 import { BuildDesignComponent } from '../../build-artifacts.component';
42 import { environment } from '../../../../../environments/environment';
43 import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'
44 import { FormsModule } from '@angular/forms';
45 import { RouterTestingModule } from '@angular/router/testing';
46 import { HomeComponent } from '../../../../home/home/home.component';
47 import { LogoutComponent } from '../../../../shared/components/logout/logout.component';
48 import { HelpComponent } from '../../../../shared/components/help/help/help.component';
49 import { AboutUsComponent } from '../../../../about-us/aboutus.component';
50 import { TestComponent } from '../../../../test/test.component';
51 import { HttpModule } from '@angular/http';
52 import { AceEditorComponent } from 'ng2-ace-editor';
53 import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
54 import { SimpleNotificationsModule } from 'angular2-notifications';
55 import { GoldenConfigurationMappingComponent } from './param-name-value.component';
56 import { Observable } from 'rxjs/Observable';
57 import { NgProgress } from 'ngx-progressbar';
58 import { BaseRequestOptions, Response, ResponseOptions, Http } from '@angular/http';
59 import { MockBackend, MockConnection } from '@angular/http/testing';
60 import { NgxSpinnerService } from 'ngx-spinner';
61 import { UtilityService } from '../../../../shared/services/utilityService/utility.service';
62 import { APIService } from "../../../../shared/services/cdt.apicall";
63
64
65 describe('GoldenConfigurationMappingComponent', () => {
66     let component: GoldenConfigurationMappingComponent;
67     let fixture: ComponentFixture<GoldenConfigurationMappingComponent>;
68     let buildDesignComponent: BuildDesignComponent;
69     let paramShareService: ParamShareService;
70     let dialogService: DialogService;
71     let notificationService: NotificationService;
72     let httpUtil: HttpUtilService;
73     let mappingEditorService: MappingEditorService;
74     let activeRoutes: ActivatedRoute;
75     let router: Router;
76     let nService: NotificationsService
77     const routes = [
78         {
79             path: 'home',
80             component: HomeComponent
81         }, {
82             path: 'vnfs',
83             loadChildren: '../../../../vnfs/vnfs.module#VnfsModule'
84         }, {
85             path: 'test',
86             component: TestComponent
87         },
88         {
89             path: 'help',
90             component: HelpComponent
91         }, {
92             path: 'aboutUs',
93             component: AboutUsComponent
94         }, {
95             path: 'logout',
96             component: LogoutComponent
97         }, {
98             path: '',
99             redirectTo: '/home',
100             pathMatch: 'full'
101         }
102     ];
103
104     beforeEach(() => {
105         TestBed.configureTestingModule({
106             imports: [FormsModule, BrowserModule, RouterTestingModule.withRoutes(routes), HttpModule, Ng2Bs3ModalModule, SimpleNotificationsModule.forRoot()],
107             declarations: [GoldenConfigurationMappingComponent, HomeComponent, TestComponent, HelpComponent, AboutUsComponent, LogoutComponent, AceEditorComponent],
108             providers: [APIService, UtilityService, BuildDesignComponent, NgProgress, ParamShareService, DialogService, NotificationService, MockBackend,
109                 HttpUtilService, MappingEditorService, NotificationsService, NgxSpinnerService,
110                 BaseRequestOptions,
111                 {
112                     provide: Http,
113                     useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
114                         return new Http(backend, defaultOptions);
115                     },
116                     deps: [MockBackend, BaseRequestOptions],
117                 }
118
119             ],
120             schemas: [NO_ERRORS_SCHEMA],
121         })
122
123     });
124
125     beforeEach(async(() => {
126         TestBed.compileComponents()
127
128     }));
129
130     it('validate if uploaded file should be only json', () => {
131         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
132         component = fixture.componentInstance;
133         expect(component.validateUploadedFile('xls')).toBe(false);
134         expect(component.validateUploadedFile('json')).toBe(true);
135         expect(component.validateUploadedFile('xml')).toBe(false);
136     });
137
138
139
140     it('validate initialisation of variables in ngOnit() function', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
141         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
142         component = fixture.componentInstance;
143         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" }
144         mappingEditorService.fromScreen = 'MappingScreen';
145         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>";
146         expect(component.ngOnInit());
147         expect(component.ngAfterViewInit());
148
149         component.paramsContent = JSON.stringify({
150             "sync_auto-pop_name1": "10.0.1.34",
151             "sync_auto-pop_address1": "",
152             "node0_tacplus_server_name2": "192.34.45.5"
153         });
154         mappingEditorService.selectedObj({
155             action: "Configure",
156             vnf: "testVnf",
157             vnfc: "",
158             protocol: "CHEF",
159             param_artifact: "param_artifact",
160             pd_artifact: "pd_artifact",
161             template_artifact: "template_artifact"
162         });
163
164         expect(component.ngOnInit());
165
166         expect(component.ngAfterViewInit());
167
168         expect(component.action).toEqual('Configure');
169         expect(component.vnfType).toEqual('testVnf');
170         expect(component.vnfcType).toEqual('');
171         expect(component.protocol).toEqual('CHEF');
172
173         // 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" }
174         // expect(component.ngOnInit());
175         // expect(component.vnfcType).toEqual('testVnfc');
176
177
178     }));
179
180     it('check if variables are empty when reference data object is empty', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
181         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
182         component = fixture.componentInstance;
183         mappingEditorService.latestAction = undefined;
184         component.ngOnInit();
185         expect(component.ngAfterViewInit());
186         expect(component.action).toEqual('');
187         expect(component.vnfType).toEqual('');
188         expect(component.vnfcType).toEqual('');
189         expect(component.artifactName).toEqual('');
190
191     }));
192
193     it('test whether onparamchanges function is able to set the cache correctly for param name values', () => {
194         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
195         component = fixture.componentInstance;
196         var data = JSON.stringify({
197             "sync_auto-pop_name1": "10.0.1.34",
198             "sync_auto-pop_address1": "",
199             "node0_tacplus_server_name2": "192.34.45.5"
200         });
201         component.onParamChanges(data);
202         expect(localStorage["paramsContent"]).toBe(data);
203     })
204
205
206     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) => {
207         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
208         component = fixture.componentInstance;
209         var mockData = {
210             "output": {
211                 "data": {
212                     "block": "{\"userID\":null,\"designInfo\":null,\"statusInfo\":null,\"artifactInfo\":[{\"artifact-content\":\"[{\\\"node0_tacplus_server_name1\\\":\\\"199.37.184.211\\\",\\\"node0_tacplus_server_source_address1\\\":\\\"135.144.3.125\\\",\\\"node0_tacplus_server_name2\\\":\\\"199.37.184.242\\\"}]\"}]}",
213                     "requestId": "497085412083"
214                 },
215                 "status": {
216                     "code": "400",
217                     "message": "success"
218                 }
219             }
220         };
221
222         let response = new ResponseOptions({
223             body: JSON.stringify(mockData)
224         });
225         const baseResponse = new Response(response);
226         mockBackend.connections.subscribe(
227             (c: MockConnection) => c.mockRespond(baseResponse)
228         );
229
230         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" }
231
232         mappingEditorService.fromScreen = 'MappingScreen';
233         component.action = 'Configure';
234         component.refObj = mappingEditorService.latestAction;
235         component.scopeName = "testVnf";
236         component.vnfType = "testVnf";
237         component.userId = "abc";
238         component.item.action = "Configure";
239         mappingEditorService.identifier = "id1";
240         component.retrieveNameValueFromAppc();
241         expect(localStorage["localStorage['paramsContent']"]).not.toBe(null);
242
243     }));
244
245     it('test sync from param value function', inject([ParamShareService], (paramShareService: ParamShareService) => {
246         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
247         component = fixture.componentInstance;
248         localStorage['paramsContent'] = JSON.stringify({
249             "node0_tacplus_server_name1": "199.37.184.211", "node0_tacplus_server_source_address1": "135.144.3.125", "node0_tacplus_server_name2": "199.37.184.242"
250         });
251         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] }];
252         paramShareService.setSessionParamData([pdData]);
253         component.syncParam();
254     }));
255
256     // fileChange method
257     it('Should validatte fileChange method if file type is json', async(() => {
258         let reader = new FileReader();
259         let obj = { "e": " " };
260         let data = JSON.stringify(obj);
261         let file = new File([data], "foo.json", { type: "text/json" });
262         let input = { files: [file] };
263
264         component.fileParamChange(input);
265
266         component.readFile(input.files[0], reader, (res) => {
267             let jsonObject = JSON.parse(res);
268             expect(component.selectedUploadType).toEqual('Mapping Data');
269             expect(component.artifactRequest.paramsContent).toEqual(JSON.stringify(jsonObject, null, 1));
270         });
271     }));
272
273
274     it('Should validatte fileChange method if file type is not json', () => {
275         let spy = spyOn(NotificationsService.prototype, 'error');
276         let file = new File(["testing"], "foo.txt", { type: "text/txt" });
277         let input = { files: [file] };
278
279         component.fileParamChange(input);
280
281         expect(spy).toHaveBeenCalled();
282     });
283
284     it('Should validatte fileChange method if file is false', () => {
285         let spy = spyOn(NotificationsService.prototype, 'error');
286         let input = { files: [] };
287
288         component.fileParamChange(input);
289
290         expect(spy).toHaveBeenCalled();
291     });
292 });