08f9c644407cd331beeace7cbb7c5c5e55166b71
[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
63
64 describe('GoldenConfigurationMappingComponent', () => {
65     let component: GoldenConfigurationMappingComponent;
66     let fixture: ComponentFixture<GoldenConfigurationMappingComponent>;
67     let buildDesignComponent: BuildDesignComponent;
68     let paramShareService: ParamShareService;
69     let dialogService: DialogService;
70     let notificationService: NotificationService;
71     let httpUtil: HttpUtilService;
72     let mappingEditorService: MappingEditorService;
73     let activeRoutes: ActivatedRoute;
74     let router: Router;
75     let nService: NotificationsService
76     const routes = [
77         {
78             path: 'home',
79             component: HomeComponent
80         }, {
81             path: 'vnfs',
82             loadChildren: '../../../../vnfs/vnfs.module#VnfsModule'
83         }, {
84             path: 'test',
85             component: TestComponent
86         },
87         {
88             path: 'help',
89             component: HelpComponent
90         }, {
91             path: 'aboutUs',
92             component: AboutUsComponent
93         }, {
94             path: 'logout',
95             component: LogoutComponent
96         }, {
97             path: '',
98             redirectTo: '/home',
99             pathMatch: 'full'
100         }
101     ];
102
103     beforeEach(() => {
104         TestBed.configureTestingModule({
105             imports: [FormsModule, BrowserModule, RouterTestingModule.withRoutes(routes), HttpModule, Ng2Bs3ModalModule, SimpleNotificationsModule.forRoot()],
106             declarations: [GoldenConfigurationMappingComponent, HomeComponent, TestComponent, HelpComponent, AboutUsComponent, LogoutComponent, AceEditorComponent],
107             providers: [UtilityService, BuildDesignComponent, NgProgress, ParamShareService, DialogService, NotificationService, MockBackend,
108                 HttpUtilService, MappingEditorService, NotificationsService, NgxSpinnerService,
109                 BaseRequestOptions,
110                 {
111                     provide: Http,
112                     useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
113                         return new Http(backend, defaultOptions);
114                     },
115                     deps: [MockBackend, BaseRequestOptions],
116                 }
117
118             ],
119             schemas: [NO_ERRORS_SCHEMA],
120         })
121
122     });
123
124     beforeEach(async(() => {
125         TestBed.compileComponents()
126
127     }));
128
129     it('validate if uploaded file should be only json', () => {
130         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
131         component = fixture.componentInstance;
132         expect(component.validateUploadedFile('xls')).toBe(false);
133         expect(component.validateUploadedFile('json')).toBe(true);
134         expect(component.validateUploadedFile('xml')).toBe(false);
135     });
136
137
138
139     it('validate initialisation of variables in ngOnit() function', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
140         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
141         component = fixture.componentInstance;
142         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" }
143         mappingEditorService.fromScreen = 'MappingScreen';
144         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>";
145         expect(component.ngOnInit());
146         expect(component.ngAfterViewInit());
147
148         component.paramsContent = JSON.stringify({
149             "sync_auto-pop_name1": "10.0.1.34",
150             "sync_auto-pop_address1": "",
151             "node0_tacplus_server_name2": "192.34.45.5"
152         });
153         expect(component.ngOnInit());
154
155         expect(component.ngAfterViewInit());
156
157         expect(component.action).toEqual('Configure');
158         expect(component.vnfType).toEqual('testVnf');
159         expect(component.vnfcType).toEqual('');
160         expect(component.protocol).toEqual('CHEF');
161
162         expect(component.artifactName).toEqual('template_Configure_test_0.0.1V.json');
163
164         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" }
165         expect(component.ngOnInit());
166         expect(component.vnfcType).toEqual('testVnfc');
167
168
169     }));
170
171     it('check if variables are empty when reference data object is empty', inject([MappingEditorService], (mappingEditorService: MappingEditorService) => {
172         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
173         component = fixture.componentInstance;
174         mappingEditorService.latestAction = undefined;
175         component.ngOnInit();
176         expect(component.ngAfterViewInit());
177         expect(component.action).toEqual('');
178         expect(component.vnfType).toEqual('');
179         expect(component.vnfcType).toEqual('');
180         expect(component.artifactName).toEqual('');
181
182     }));
183
184     it('test whether onparamchanges function is able to set the cache correctly for param name values', () => {
185         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
186         component = fixture.componentInstance;
187         var data = JSON.stringify({
188             "sync_auto-pop_name1": "10.0.1.34",
189             "sync_auto-pop_address1": "",
190             "node0_tacplus_server_name2": "192.34.45.5"
191         });
192         component.onParamChanges(data);
193         expect(localStorage["paramsContent"]).toBe(data);
194     })
195
196
197     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) => {
198         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
199         component = fixture.componentInstance;
200         var mockData = {
201             "output": {
202                 "data": {
203                     "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\\\"}]\"}]}",
204                     "requestId": "497085412083"
205                 },
206                 "status": {
207                     "code": "400",
208                     "message": "success"
209                 }
210             }
211         };
212
213         let response = new ResponseOptions({
214             body: JSON.stringify(mockData)
215         });
216         const baseResponse = new Response(response);
217         mockBackend.connections.subscribe(
218             (c: MockConnection) => c.mockRespond(baseResponse)
219         );
220
221         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" }
222
223         mappingEditorService.fromScreen = 'MappingScreen';
224         component.action = 'Configure';
225         component.refObj = mappingEditorService.latestAction;
226         component.scopeName = "testVnf";
227         component.vnfType = "testVnf";
228         component.userId = "abc";
229         component.item.action = "Configure";
230         mappingEditorService.identifier = "id1";
231         component.retrieveNameValueFromAppc();
232         expect(localStorage["localStorage['paramsContent']"]).not.toBe(null);
233
234     }));
235
236     it('test sync from param value function', inject([ParamShareService], (paramShareService: ParamShareService) => {
237         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
238         component = fixture.componentInstance;
239         localStorage['paramsContent'] = JSON.stringify({
240             "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"
241         });
242         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] }];
243         paramShareService.setSessionParamData([pdData]);
244         component.syncParam();
245     }));
246
247     // fileChange method
248     it('Should validatte fileChange method if file type is json', async(() => {
249         let reader = new FileReader();
250         let obj = { "e": " " };
251         let data = JSON.stringify(obj);
252         let file = new File([data], "foo.json", { type: "text/json" });
253         let input = { files: [file] };
254
255         component.fileParamChange(input);
256
257         component.readFile(input.files[0], reader, (res) => {
258             let jsonObject = JSON.parse(res);
259             expect(component.selectedUploadType).toEqual('Mapping Data');
260             expect(component.artifactRequest.paramsContent).toEqual(JSON.stringify(jsonObject, null, 1));
261         });
262     }));
263
264
265     it('Should validatte fileChange method if file type is not json', () => {
266         let spy = spyOn(NotificationsService.prototype, 'error');
267         let file = new File(["testing"], "foo.txt", { type: "text/txt" });
268         let input = { files: [file] };
269
270         component.fileParamChange(input);
271
272         expect(spy).toHaveBeenCalled();
273     });
274
275     it('Should validatte fileChange method if file is false', () => {
276         let spy = spyOn(NotificationsService.prototype, 'error');
277         let input = { files: [] };
278
279         component.fileParamChange(input);
280
281         expect(spy).toHaveBeenCalled();
282     });
283
284     it('should validate of the file name creation for configscaleout is correct', () => {
285         fixture = TestBed.createComponent(GoldenConfigurationMappingComponent);
286         component = fixture.componentInstance;
287
288         let fileName;
289         let expectedFileName = "param_Configure_testVnfType_0.0.1V_id1.json";
290         expect(expectedFileName).toBe(fileName);
291     });
292 });