Add new actions DownloadNESw and ActivateNESw for CDT
[appc/cdt.git] / src / app / test / test.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 Intellectual Property. All rights reserved.
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 ============LICENSE_END============================================
22 */
23
24 /* tslint:disable:no-unused-variable */
25
26 // Modules
27 import { async, ComponentFixture, TestBed,inject } from '@angular/core/testing';
28 import { By } from '@angular/platform-browser';
29 import { DebugElement } from '@angular/core';
30 import { FormsModule, ReactiveFormsModule } from '@angular/forms';
31 import { RouterTestingModule } from '@angular/router/testing';
32 import { SimpleNotificationsModule } from 'angular2-notifications';
33 import { Http, Headers, HttpModule, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
34 import { MockBackend, MockConnection } from '@angular/http/testing';
35 import { Observable } from 'rxjs/Observable';
36 import { Subscription } from 'rxjs/Subscription';
37 import 'rxjs/add/observable/from';
38 import 'rxjs/add/observable/empty';
39 import 'rxjs/add/observable/throw';
40
41 // Component
42 import { TestComponent } from './test.component';
43
44 // Services
45 import { NotificationService } from '../shared/services/notification.service';
46 import { ParamShareService } from '.././shared/services/paramShare.service';
47 import { MappingEditorService } from '../shared/services/mapping-editor.service';
48 import { HttpUtilService } from '../shared/services/httpUtil/http-util.service';
49 import { UtilityService } from '../shared/services/utilityService/utility.service';
50 import { environment } from '../.././environments/environment';
51 import { NgProgress } from 'ngx-progressbar';
52 import { NgProgressModule } from 'ngx-progressbar';
53 import { NgxSpinnerModule } from 'ngx-spinner';
54
55 fdescribe( 'TestComponent', () => {
56     let component: TestComponent;
57     let fixture: ComponentFixture<TestComponent>;
58
59     beforeEach(async(() => {
60         TestBed.configureTestingModule({
61             declarations: [TestComponent],
62             imports: [
63             FormsModule,
64             RouterTestingModule,
65             SimpleNotificationsModule,
66             HttpModule,
67             NgProgressModule,
68             NgxSpinnerModule
69             ],
70             providers: [
71             NotificationService, 
72             ParamShareService,
73             MappingEditorService,
74             HttpUtilService,
75             UtilityService,
76             NgProgress,MockBackend, BaseRequestOptions,
77                 {
78                     provide: Http,
79                     useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
80                         return new Http(backend, defaultOptions);
81                     },
82                     deps: [MockBackend, BaseRequestOptions],
83                 }
84             ]
85         })
86         .compileComponents();
87     }));
88
89     beforeEach(() => {
90         fixture = TestBed.createComponent(TestComponent);
91         component = fixture.componentInstance;
92         fixture.detectChanges();
93     });
94
95     it('should ...', inject([HttpUtilService], (service: HttpUtilService) => {
96         fixture.detectChanges(); // onInit()
97
98         component.pollTestStatus();
99         
100         expect(service).toBeTruthy();
101     }));
102     
103     // Test download Method
104     describe('Test download Method', () => {
105         it('Should have download method', () => {
106             expect(component.download).toBeDefined();
107         });
108
109         it('test if apiRequest if true', inject( [SimpleNotificationsModule], (service: SimpleNotificationsModule) => {
110             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":"ibcx0001","vserver-id":"test"},"payload":""';
111             component.apiResponse = '';
112             component.action  = 'ConfigModify';
113             component.actionIdentifiers['vnf-id'] = 'ibcx0001';
114             let fileName = 'test_' + component.action + '_' + component.actionIdentifiers['vnf-id'] + '_request';
115             let theJSON = component.apiRequest; 
116             var blob = new Blob([theJSON], {
117                 type: 'text/json'
118             });
119
120             component.download();
121
122             expect(service instanceof SimpleNotificationsModule).toBeTruthy();
123             expect(component.apiRequest).not.toBe('');
124             expect(fileName).not.toBe('');
125             expect(fileName).not.toBeNull();
126             expect(fileName).toContain('test_');
127             expect(fileName).toContain('_request');
128             expect(typeof (blob)).toBe('object');
129
130         }));
131
132         it('test method if apiResponse is true', () => {
133             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":"ibcx0001","vserver-id":"test"},"payload":""';
134             component.apiRequest = '';
135             component.action  = 'ConfigModify';
136             component.actionIdentifiers['vnf-id'] = 'ibcx0001';
137             let fileName = 'test_' + component.action + '_' + component.actionIdentifiers['vnf-id'] + '_response';
138             let theJSON = component.apiRequest;
139             var blob = new Blob([theJSON], {
140                 type: 'text/json'
141             });
142
143             component.download();
144
145             expect(component.apiResponse).not.toBe('');
146             expect(fileName).not.toBe('');
147             expect(fileName).not.toBeNull();
148             expect(fileName).toContain('test_');
149             expect(fileName).toContain('_response');
150             expect(typeof (blob)).toBe('object');
151
152         });
153     });
154
155     // Test abortTest Method
156     describe('Test abortTest Method', () => {
157         it('Should have abortTest method', () => {
158             expect(component.abortTest).toBeDefined();
159         });
160
161         it('Test abortTest Method', () => {
162             component.abortTest();
163             expect(component.enableBrowse).toBeTruthy();
164             expect(component.enableTestButton).toBeTruthy();
165             expect(component.enablePollButton).toBeTruthy();
166         });
167     });
168
169     // Test excelBrowseOption Method
170     describe('Test excelBrowseOption Method', () => {
171         it('test excelBrowseOption', () => {
172             spyOn(component, 'excelBrowseOption');
173             let button = fixture.debugElement.query(By.css('#excelInputFile ~ button.browse'));
174             button.nativeElement.click();
175             expect(component.excelBrowseOption).toHaveBeenCalled()
176         });
177     });
178
179     // Test Upload Method
180     describe('Test Upload Method', () => {
181         it('Should have upload method', () => {
182             expect(component.upload).toBeDefined();
183         });
184
185         it('should execute if file extension is XLS, XLSX', () => {
186             let reader = new FileReader();
187             let file = new File(["testing"], "foo.XLS", {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
188             let fileExtension = 'XLS';
189             let event = { isTrusted: true, type: "change", target: {files: [file]} }
190
191             component.upload(event);
192
193             expect(reader instanceof FileReader).toBeTruthy();
194             expect(component.pollCounter).toBe(0)
195         });
196
197         it('should return an error if file extension is not XLS, XLSX', () => {
198             let reader = new FileReader();
199             let file = new File(["testing"], "foo.doc", {type: ""})
200             let fileExtension = 'doc';
201             let event = { isTrusted: true, type: "change", target: {files: [file]} }
202             
203             component.upload(event);
204
205             expect(reader instanceof FileReader).toBeTruthy();
206             expect(component.flag).toBe(1)
207         });
208
209         it('Should return an error is files length is not equal to 1', () => {
210             
211         });
212     });
213
214     // Test processUploadedFile Method
215     describe('Test processUploadedFile Method', () => {
216         it('should return valid payload', () => {
217             let data = [
218                 {"TagName":"action","Value":"ConfigModify"},
219                 {"List Name":"action-identifiers","TagName":"vserver-id","Value":"test"},
220                 {"List Name":"payload","List Name_1":"request-parameters","TagName":"vnf-name","Value":"ibcx0001"},
221                 {"List Name":"payload","List Name_1":"request-parameters","List Name_2":"[vm]","List Name_3":"vnfc","TagName":"vnfc-name","Value":"ibcx0001vm001ssc001"},
222                 {"List Name":"payload","List Name_1":"configuration-parameters","TagName":"CORE_NETWORK_DEFAULT_GATEWAY","Value":"192.168.30.44"}
223             ]
224
225             let payload = component.processUploadedFile(data);
226         });
227     });
228
229     // Test uploadedFileResult Method
230     describe('Test uploadedFileResult', () => {
231         it('should return success message', inject([SimpleNotificationsModule],(service: SimpleNotificationsModule) => {
232             component.action  = 'ConfigModify';
233             component.actionIdentifiers['vnf-id'] = 'ibcx0001';
234
235             component.uploadedFileResult();
236
237             expect(service instanceof SimpleNotificationsModule).toBeTruthy();
238         }));
239
240         it('should return error message', inject([SimpleNotificationsModule], (service: SimpleNotificationsModule) => {
241             component.action  = '';
242             component.actionIdentifiers['vnf-id'] = '';
243
244             component.uploadedFileResult();
245
246             expect(service instanceof SimpleNotificationsModule).toBeTruthy();
247         }));
248     });
249
250     // Test constructTestPayload Method 
251     describe('Test constructTestPayload Method', () => {
252         it('Should have constructTestPayload method', () => {
253             expect(component.constructTestPayload).toBeDefined();
254         });
255
256         it('test if listName2, listName3 are undefined', () => {
257             let temp = component.constructTestPayload(undefined, undefined, 'vnfc-type', 'vISBC - ssc');
258             expect(component.subPayload['vnfc-type']).toEqual('vISBC - ssc')
259         });
260
261         it('test if lastName2 is not undefined', () => {
262             let temp = component.constructTestPayload(['vm'], undefined, 'vnfc-type', 'vISBC - ssc');
263             expect(typeof(component.vmJson)).toEqual('object');
264             expect(typeof(component.vnfcJson)).toEqual('object');
265             expect(component.vmJson['vnfc-type']).toBe('vISBC - ssc');
266             expect(component.flag).toBe(0);
267         });
268
269         it('test if lastNmae2, lastName3 are not undefined', () => {
270             let temp = component.constructTestPayload(['vm'], 'vnfc', 'vnfc-type', 'vISBC - ssc');
271             expect(component.vnfcJson['vnfc-type']).toEqual('vISBC - ssc');
272             expect(component.vmJson['vnfc']['vnfc-type']).toEqual('vISBC - ssc');
273             expect(component.flag).toBe(1);
274         })
275     });
276
277     // Test constructRequest Method
278     describe('Test constructRequest Method', () => {
279         it('Should have constructRequest method', () => {
280             expect(component.constructRequest).toBeDefined();
281         });
282
283         it('test method', () => {
284             let temp = component.constructRequest();
285         });
286     });
287
288     // Test testVnf Method
289     describe('Test testVnf Method', () => {
290         it('Should have testVnf method', () => {
291             expect(component.testVnf).toBeDefined();
292         });
293
294         it('should return response on success', inject([MockBackend], (mockBackend: MockBackend) => {    
295             let mockData = 'testing';
296             let response = new ResponseOptions({
297                 body: JSON.stringify(mockData)
298             });
299             const baseResponse = new Response(response);
300             mockBackend.connections.subscribe(
301                 (c: MockConnection) => { 
302                     c.mockRespond(baseResponse)
303                 }
304             );
305
306             component.action  = 'ConfigModify';
307             
308             component.testVnf();
309         }));
310
311         it('should return an error if fails', inject([HttpUtilService],( httpUtilService: HttpUtilService) => {
312             let error = 'Error in connecting to APPC Server';
313             let spy = spyOn(httpUtilService, 'post').and.returnValue(Observable.throw(error));
314             component.action  = 'ConfigModify';
315             
316             component.testVnf();
317
318             expect(spy).toHaveBeenCalled();
319             expect(component.enableBrowse).toBeTruthy();
320             expect(component.enableTestButton).toBeTruthy();
321             expect(component.enablePollButton).toBeTruthy();
322             expect(component.enableCounterDiv).toBeFalsy();
323         }));
324
325         it('test setTimeout', inject([NgProgress], (ngProgress: NgProgress) => {
326             component.action  = 'ConfigModify';
327             
328             component.testVnf();
329         }));
330     });
331
332     // Test pollTestStatus Method
333     describe('Test pollTestStatus Method', () => {
334         it('Should have pollTestStatus method', () => {
335             expect(component.pollTestStatus).toBeDefined();
336         });
337
338         it('should call fake server', inject([MockBackend], (mockBackend: MockBackend) => {
339             component.requestId = new Date().getTime().toString();
340             component.actionIdentifiers['vnf-id'] = 123456;
341             let mockData = { "output": { "common-header": { "originator-id": "CDT", "sub-request-id": "653018029941", "timestamp": "2018-02-12T07:27:21.448Z", "api-ver": "2.00", "request-id": "653018029941", "flags": { "force": "TRUE", "mode": "NORMAL", "ttl": 3600 } }, "payload": "{\"status-reason\":\"FAILED\",\"status\":\"FAILED\"}", "status": { "message": "SUCCESS - request has been processed successfully", "code": 400 } } } ;
342             let response = new ResponseOptions({
343                 body: JSON.stringify(mockData)
344             });
345             const baseResponse = new Response(response);
346             mockBackend.connections.subscribe(
347                 (c: MockConnection) => c.mockRespond(baseResponse)
348             );
349             
350             component.pollTestStatus();
351         }));
352
353         it('should call fake server if status is success', inject([MockBackend], (mockBackend: MockBackend) => {
354             component.requestId = new Date().getTime().toString();
355             component.actionIdentifiers['vnf-id'] = 123456;
356             let mockData = { "output": { "common-header": { "originator-id": "CDT", "sub-request-id": "653018029941", "timestamp": "2018-02-12T07:27:21.448Z", "api-ver": "2.00", "request-id": "653018029941", "flags": { "force": "TRUE", "mode": "NORMAL", "ttl": 3600 } }, "payload": "{\"status-reason\":\"SUCCESS\",\"status\":\"SUCCESS\"}", "status": { "message": "SUCCESS - request has been processed successfully", "code": 400 } } } ;
357             let response = new ResponseOptions({
358                 body: JSON.stringify(mockData)
359             });
360             const baseResponse = new Response(response);
361             mockBackend.connections.subscribe(
362                 (c: MockConnection) => c.mockRespond(baseResponse)
363             );
364             
365             component.pollTestStatus();
366         }));
367
368         it('should execute else part if timeStamp && status && statusReason are false', inject([MockBackend], (mockBackend: MockBackend) => {
369             component.requestId = new Date().getTime().toString();
370             component.actionIdentifiers['vnf-id'] = 123456;
371             let mockData = { "output": { "common-header": { "originator-id": "CDT", "sub-request-id": "653018029941", "timestamp": "2018-02-12T07:27:21.448Z", "api-ver": "2.00", "request-id": "653018029941", "flags": { "force": "TRUE", "mode": "NORMAL", "ttl": 3600 } }, "payload": "{\"status-reason\":\"FAILED\",\"status\":\"\"}", "status": { "message": "SUCCESS - request has been processed successfully", "code": 400 } } } ;
372             let response = new ResponseOptions({
373                 body: JSON.stringify(mockData)
374             });
375             const baseResponse = new Response(response);
376             mockBackend.connections.subscribe(
377                 (c: MockConnection) => c.mockRespond(baseResponse)
378             );
379             
380             component.pollTestStatus();
381         }));
382
383          it('should check error condition on polling where timestamp and test status are not available', inject([MockBackend], (mockBackend: MockBackend) => {
384             component.requestId = new Date().getTime().toString();
385             component.actionIdentifiers['vnf-id'] = 123456;
386             //let mockData = { "output": { "common-header": { "originator-id": "CDT", "sub-request-id": "653018029941", "timestamp": "2018-02-12T07:27:21.448Z", "api-ver": "2.00", "request-id": "653018029941", "flags": { "force": "TRUE", "mode": "NORMAL", "ttl": 3600 } }, "payload": "{\"status-reason\":\"FAILED\",\"status\":\"\"}", "status": { "message": "SUCCESS - request has been processed successfully", "code": 400 } } } ;
387             let mockData={"output":{"common-header":{"timestamp":"2018-03-21T14:20:30.910Z","api-ver":"2.00","request-id":"1521642030910","flags":{"force":"TRUE","mode":"NORMAL","ttl":3600},"originator-id":"CDT","sub-request-id":"1521642030910"},"status":{"message":"INVALID INPUT PARAMETER - vserver-id","code":301}}};
388             let response = new ResponseOptions({
389                 body: JSON.stringify(mockData)
390             });
391             const baseResponse = new Response(response);
392             mockBackend.connections.subscribe(
393                 (c: MockConnection) => c.mockRespond(baseResponse)
394             );
395             
396             component.pollTestStatus();
397         }));
398
399         it('should return an error if fails', inject([MockBackend], (mockBackend: MockBackend) => {
400             let error = 'Error Connecting to APPC server';
401             component.requestId = new Date().getTime().toString();
402             component.actionIdentifiers['vnf-id'] = 123456;
403             let mockData = '';
404             let response = new ResponseOptions({
405                 body: JSON.stringify(mockData)
406             });
407             const baseResponse = new Response(response);
408             mockBackend.connections.subscribe(
409                 (c: MockConnection) => c.mockError(new Error(error))
410             );
411
412             component.pollTestStatus();
413         }));
414     });
415     
416     // Test getUrlEndPoint Method
417     describe('Test getUrlEndPoint Method', () => {
418         it('Should have getUrlEndPoint method', () => {
419             expect(component.getUrlEndPoint).toBeDefined();
420         });
421
422         it('getUrlEndPoint Should return value', () => {
423             expect(component.getUrlEndPoint('configmodify')).toEqual('configmodify');
424             expect(component.getUrlEndPoint('configbackup')).toEqual('configbackup');
425             expect(component.getUrlEndPoint('configrestore')).toEqual('configrestore');
426             expect(component.getUrlEndPoint('healthcheck')).toEqual('healthcheck');
427             expect(component.getUrlEndPoint('quiescetraffic')).toEqual('quiescetraffic');
428             expect(component.getUrlEndPoint('resumetraffic')).toEqual('resumetraffic');
429             expect(component.getUrlEndPoint('distributetraffic')).toEqual('distributetraffic');
430             expect(component.getUrlEndPoint('distributetrafficcheck')).toEqual('distributetrafficcheck');
431             expect(component.getUrlEndPoint('startapplication')).toEqual('startapplication');
432             expect(component.getUrlEndPoint('stopapplication')).toEqual('stopapplication');
433             expect(component.getUrlEndPoint('upgradebackout')).toEqual('upgradebackout');
434             expect(component.getUrlEndPoint('upgradepostcheck')).toEqual('upgradepostcheck');
435             expect(component.getUrlEndPoint('upgradeprecheck')).toEqual('upgradeprecheck');
436             expect(component.getUrlEndPoint('upgradesoftware')).toEqual('upgradesoftware');
437             expect(component.getUrlEndPoint('downloadnesw')).toEqual('downloadnesw');
438             expect(component.getUrlEndPoint('activatenesw')).toEqual('activatenesw');
439             expect(component.getUrlEndPoint('DeFaultCASE')).toEqual('de-fault-c-a-s-e');
440             expect(component.getUrlEndPoint('upgradebackup')).toEqual('upgradebackup');
441             expect(component.getUrlEndPoint('attachvolume')).toEqual('attachvolume');
442             expect(component.getUrlEndPoint('detachvolume')).toEqual('detachvolume');
443         });
444     });
445
446     describe('Test setValuesOnFileUploadFailure Method', () => {
447         it('Should have setValuesOnFileUploadFailure method', () => {
448             expect(component.setValuesOnFileUploadFailure).toBeDefined();
449         });
450
451         it('getUrlEndPoint setValuesOnFileUploadFailure set value', () => {
452             component.setValuesOnFileUploadFailure();
453             expect(component.flag).toEqual(1);
454             expect(component.oldListName1).toEqual('');
455             expect(component.vmJson).toEqual({});
456             expect(component.vnfcJson).toEqual({});
457             expect(component.subPayload).toEqual({});
458             expect(component.vmPayload).toEqual([]);
459             expect(component.payload).toEqual({});
460             expect(component.action).toEqual('');
461             expect(component.actionIdentifiers).toEqual({});
462             expect(component.apiRequest).toEqual('');
463             expect(component.apiResponse).toEqual('');
464             expect(component.enableCounterDiv).toEqual(false);
465             expect(component.enableAbort).toEqual(false);
466             expect(component.enableTestButton).toEqual(false);
467             expect(component.enableDownload).toEqual(false);
468
469         });
470     });
471 })