summaryrefslogtreecommitdiffstats
path: root/nokiav2/driver/src/test/java/org/onap/vfc/nfvo/driver/vnfm/svnfm/nokia/vnfm/TestJobManager.java
blob: 79dcac31747c3f92183b1559f1891d2d2fc18fb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/*
 * Copyright 2016-2017, Nokia Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file 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.
 */
package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm;

import com.google.common.collect.Lists;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.nokia.cbam.lcm.v32.model.*;
import io.reactivex.Observable;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.onap.vnfmdriver.model.JobDetailInfo;
import org.onap.vnfmdriver.model.JobResponseInfo;
import org.onap.vnfmdriver.model.JobStatus;
import org.springframework.test.util.ReflectionTestUtils;
import org.threeten.bp.OffsetDateTime;

import static junit.framework.TestCase.*;
import static org.mockito.Mockito.*;
import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.SEPARATOR;
import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.JobManager.extractOnapJobId;
import static org.onap.vnfmdriver.model.JobStatus.*;

public class TestJobManager extends TestBase {

    @Mock
    private HttpServletResponse httpResponse;

    private JobManager jobManager;
    private List<VnfInfo> vnfs = new ArrayList<>();

    @Before
    public void initMocks() throws Exception {
        ReflectionTestUtils.setField(JobManager.class, "logger", logger);
        when(vnfApi.vnfsGet(NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(vnfs));
        when(selfRegistrationManagerForVfc.isReady()).thenReturn(true);
        jobManager = new JobManager(cbamRestApiProviderForVfc, selfRegistrationManagerForVfc);
    }

    /**
     * Only the _ can be used as separator
     * . / % & handled specially in URLs
     * - used in CBAM for separation
     */
    @Test
    public void testSeparator() {
        assertEquals("_", SEPARATOR);
    }

    /**
     * The operation result must contain the ONAP job identifier under the jobId field
     */
    @Test
    public void testJobIdExtractionFromOperationResult() {
        assertEquals("1234", extractOnapJobId(new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"1234\"}}")));
        try {
            extractOnapJobId(new JsonParser().parse("{ }"));
            fail();
        } catch (NoSuchElementException e) {
            assertEquals("The operation result {} does not contain the mandatory additionalParams structure", e.getMessage());
        }
        try {
            extractOnapJobId(new JsonParser().parse("{ \"additionalParams\" : { } }"));
            fail();
        } catch (NoSuchElementException e) {
            assertEquals("The operation result {\"additionalParams\":{}} does not contain the mandatory jobId in the additionalParams structure", e.getMessage());
        }
    }

    /**
     * If the VNF does not exists but the job manager still runs the VNF manipulation process the job is reported to be running
     */
    @Test
    public void testJobForNonExistingVnfReportedRunningIfJobIsOngoing() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        //when
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, STARTED, "50", "Operation started");
    }

    /**
     * If the VNF does not exists and the internal job is not running the job is reported to be finished
     */
    @Test
    public void testJobForExistingVnfReportedRunningIfJobIsFinished() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        jobManager.jobFinished(jobId);
        //when
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, JobStatus.FINISHED, "100", "Operation finished");
        assertEquals(false, jobManager.isPreparingForShutDown());
    }

    /**
     * Spawning jobs after preparing for shutdown results in error
     */
    @Test
    public void testNoMoreJobsAreAllowedAfterPrepareForShutdown() throws Exception {
        jobManager.prepareForShutdown();
        //when
        try {
            jobManager.spawnJob(JOB_ID, httpResponse);
            fail();
        } catch (Exception e) {
            verify(logger).error("The service is preparing to shut down");
        }
        assertEquals(true, jobManager.isPreparingForShutDown());
    }

    /**
     * Verify if the jobId has valid format
     */
    @Test
    public void testJobIdValidation() throws Exception {
        try {
            //when
            jobManager.getJob(VNFM_ID, "bad");
            //verify
            fail();
        } catch (IllegalArgumentException e) {
            assertEquals("The jobId should be in the <vnfId>_<UUID> format, but was bad", e.getMessage());
        }
        try {
            //when
            jobManager.getJob(VNFM_ID, "vnfId_");
            //verify
            fail();
        } catch (IllegalArgumentException e) {
            assertEquals("The UUID in the jobId (vnfId_) can not be empty", e.getMessage());
        }
        try {
            //when
            jobManager.getJob(VNFM_ID, "_UUID");
            //verify
            fail();
        } catch (IllegalArgumentException e) {
            assertEquals("The vnfId in the jobId (_UUID) can not be empty", e.getMessage());
        }
    }

    /**
     * If the VNF exists but no operation execution is present with given internalJobId, than the state of the
     * job is ongoing if the internal job is ongoing
     */
    @Test
    public void testExistingVnfWithNotYetStartedOperation() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, STARTED, "50", "Operation started");
        assertTrue(jobManager.hasOngoingJobs());
    }

    /**
     * If the VNF exists but no operation execution is present with given internalJobId, than the state of the
     * job is failed if the internal job is finished (the operation on CBAM was not able to start)
     */
    @Test
    public void testExistingVnfWithNotUnableToStartOperation() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        jobManager.jobFinished(jobId);
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, ERROR, "100", "Operation failed due to The requested operation was not able to start on CBAM");
        assertFalse(jobManager.hasOngoingJobs());
    }

    /**
     * If the VNF exists but and the operation execution is present with given internalJobId, than the state of the
     * job is ongoing if the operation is ongoing
     */
    @Test
    public void testExistingVnfWithStartedOperation() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        OperationExecution operation = new OperationExecution();
        operation.setId(UUID.randomUUID().toString());
        operation.setStartTime(OffsetDateTime.now());
        operation.setStatus(OperationStatus.STARTED);
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(operation);
        JsonElement operationParams = new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}");
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operation.getId(), NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(operationParams));
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, STARTED, "50", "Operation started");
        assertTrue(jobManager.hasOngoingJobs());
    }

    /**
     * If the VNF does not exists till the time the job queries the status of the operation
     */
    @Test
    public void testTerminatedVnf() throws Exception {
        //ddd
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        List<Integer> vnfQueryCallCounter = new ArrayList<>();
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenAnswer(new Answer<Observable<VnfInfo>>() {
            @Override
            public Observable<VnfInfo> answer(InvocationOnMock invocation) throws Throwable {
                vnfs.clear();
                return buildObservable(detailedVnf);
            }
        });

        jobManager.jobFinished(jobId);

        OperationExecution operation = new OperationExecution();
        operation.setId(UUID.randomUUID().toString());
        operation.setStartTime(OffsetDateTime.now());
        operation.setStatus(OperationStatus.FINISHED);
        operation.setOperationType(OperationType.TERMINATE);
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(operation);

        JsonElement operationParams = new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}");
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operation.getId(), NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(operationParams));
        //when
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, FINISHED, "100", "Operation finished");
    }

    /**
     * If the VNF exists but and the operation execution is present with given internalJobId, than the state of the
     * job is error if the operation is failed
     */
    @Test
    public void testExistingVnfWithFailedOperation() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        List<Integer> vnfCounter = new ArrayList<>();
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        OperationExecution operation = new OperationExecution();
        operation.setId(UUID.randomUUID().toString());
        operation.setStartTime(OffsetDateTime.now());
        operation.setStatus(OperationStatus.FAILED);
        ProblemDetails errorDetails = new ProblemDetails();
        errorDetails.setTitle("Title");
        errorDetails.setDetail("detail");
        operation.setError(errorDetails);
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(operation);
        JsonElement operationParams = new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}");
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operation.getId(), NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(operationParams));
        //when
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, ERROR, "100", "Operation failed due to Title: detail");
        assertTrue(jobManager.hasOngoingJobs());
    }

    private void assertResult(String jobId, JobDetailInfo job, JobStatus status, String progress, String descriptor) {
        assertEquals(jobId, job.getJobId());
        assertEquals(status, job.getResponseDescriptor().getStatus());
        assertEquals(progress, job.getResponseDescriptor().getProgress());
        assertNull(job.getResponseDescriptor().getErrorCode());
        boolean finalState = JobStatus.ERROR.equals(status) || JobStatus.FINISHED.equals(status);
        if (finalState) {
            assertEquals(2, job.getResponseDescriptor().getResponseHistoryList().size());
            JobResponseInfo startEvent = job.getResponseDescriptor().getResponseHistoryList().get(0);
            JobResponseInfo endEvent = job.getResponseDescriptor().getResponseHistoryList().get(1);
            assertNull(startEvent.getErrorCode());
            assertEquals("50", startEvent.getProgress());
            assertEquals(JobStatus.STARTED.name(), startEvent.getStatus());
            assertEquals("1", startEvent.getResponseId());
            assertEquals("Operation started", startEvent.getStatusDescription());

            assertNull(endEvent.getErrorCode());
            assertEquals("100", endEvent.getProgress());
            assertEquals(job.getResponseDescriptor().getStatus().name(), endEvent.getStatus());
            assertEquals("2", endEvent.getResponseId());
            assertEquals(descriptor, endEvent.getStatusDescription());
        } else {
            assertEquals(1, job.getResponseDescriptor().getResponseHistoryList().size());
            assertNull(job.getResponseDescriptor().getResponseHistoryList().get(0).getErrorCode());
            assertEquals(progress, job.getResponseDescriptor().getResponseHistoryList().get(0).getProgress());
            assertEquals(job.getResponseDescriptor().getStatus().name(), job.getResponseDescriptor().getResponseHistoryList().get(0).getStatus());
            assertEquals("1", job.getResponseDescriptor().getResponseHistoryList().get(0).getResponseId());
            assertEquals(descriptor, job.getResponseDescriptor().getResponseHistoryList().get(0).getStatusDescription());
        }
        assertEquals(Integer.toString(job.getResponseDescriptor().getResponseHistoryList().size()), job.getResponseDescriptor().getResponseId());
        assertEquals(descriptor, job.getResponseDescriptor().getStatusDescription());
    }

    /**
     * If the VNF exists but and the operation execution is present with given internalJobId, than the state of the
     * job is finished if the operation is finished, but is not a termination
     */
    @Test
    public void testExistingVnfWithFinishedOperation() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        OperationExecution operation = new OperationExecution();
        operation.setId(UUID.randomUUID().toString());
        operation.setStartTime(OffsetDateTime.now());
        operation.setStatus(OperationStatus.FINISHED);
        operation.setOperationType(OperationType.SCALE);
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(operation);
        JsonElement operationParams = new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}");
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operation.getId(), NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(operationParams));
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, JobStatus.FINISHED, "100", "Operation finished");
        assertTrue(jobManager.hasOngoingJobs());
    }

    /**
     * If the VNF exists but and the operation execution is present with given internalJobId, than the state of the
     * job is ongoing if the termination operation is finished. In ONAP terminology the termination includes
     * delete, so the ONAP operation is ongoing since the VNF is not yet deleted
     */
    @Test
    public void testExistingVnfWithFinishedTerminationOperation() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        OperationExecution operation = new OperationExecution();
        operation.setId(UUID.randomUUID().toString());
        operation.setStartTime(OffsetDateTime.now());
        operation.setStatus(OperationStatus.FINISHED);
        operation.setOperationType(OperationType.TERMINATE);
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(operation);
        JsonElement operationParams = new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}");
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operation.getId(), NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(operationParams));
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, STARTED, "50", "Operation started");
        //when
        jobManager.jobFinished(jobId);
        job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertResult(jobId, job, ERROR, "100", "Operation failed due to unable to delete VNF");
        assertFalse(jobManager.hasOngoingJobs());

    }

    /**
     * Failuire to retrieve operation parameters (CBAM REST API fail) is logged and propagated
     */
    @Test
    public void failuresDuringOperationExecutionRetrievalIsLoggedAndPropagated() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        OperationExecution operation = new OperationExecution();
        operation.setId(UUID.randomUUID().toString());
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(operation);
        RuntimeException expectedException = new RuntimeException();
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(operation.getId(), NOKIA_LCM_API_VERSION)).thenThrow(expectedException);
        //verify
        try {
            JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
            fail();
        } catch (RuntimeException e) {
            assertEquals(expectedException, e.getCause());
            verify(logger).error("Unable to retrieve operation parameters of operation with " + operation.getId() + " identifier", expectedException);
        }
        assertTrue(jobManager.hasOngoingJobs());
    }

    /**
     * Failure to retrieve VNF (CBAM REST API fail) is logged and propagated
     */
    @Test
    public void failuresDuringVnfRetrievalIsLoggedAndPropagated() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        RuntimeException expectedException = new RuntimeException();
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenThrow(expectedException);
        //verify
        try {
            JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
            fail();
        } catch (RuntimeException e) {
            assertEquals(expectedException, e.getCause());
            verify(logger).error("Unable to retrieve VNF with myVnfId identifier", expectedException);
        }
        assertTrue(jobManager.hasOngoingJobs());
    }

    /**
     * When searching for the ONAP job by iterating the operation executions. The newest jobs
     * are inspected first (performance optimalization)
     */
    @Test
    public void testNewestOperationAreInspectedFirst() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        OperationExecution olderOperation = new OperationExecution();
        olderOperation.setId(UUID.randomUUID().toString());
        olderOperation.setStartTime(OffsetDateTime.now());
        olderOperation.setStatus(OperationStatus.FINISHED);
        olderOperation.setOperationType(OperationType.TERMINATE);
        OperationExecution newerOperation = new OperationExecution();
        newerOperation.setId(UUID.randomUUID().toString());
        newerOperation.setStartTime(OffsetDateTime.now().plusDays(1));
        newerOperation.setStatus(OperationStatus.FINISHED);
        newerOperation.setOperationType(OperationType.TERMINATE);
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(olderOperation);
        detailedVnf.getOperationExecutions().add(newerOperation);
        JsonElement operationParams = new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}");
        List<String> queriedOperaionsInOrder = new ArrayList<>();
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(Mockito.anyString(), Mockito.eq(NOKIA_LCM_API_VERSION)))
                .then(new Answer<Observable<Object>>() {
                    @Override
                    public Observable<Object> answer(InvocationOnMock invocationOnMock) throws Throwable {
                        queriedOperaionsInOrder.add(invocationOnMock.getArguments()[0].toString());
                        if (invocationOnMock.getArguments()[0].equals(olderOperation.getId())) {
                            return buildObservable(new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}"));
                        } else {
                            return buildObservable(new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + "nonMatching" + "\"}}"));
                        }
                    }
                });
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertEquals(Lists.newArrayList(newerOperation.getId(), olderOperation.getId()), queriedOperaionsInOrder);
        assertTrue(jobManager.hasOngoingJobs());
    }

    /**
     * the modify attribute job is skipped, since it is not explicitly triggered by any external job
     */
    @Test
    public void testModifyAttributesOperationExecutionIsSkipped() throws Exception {
        String jobId = jobManager.spawnJob(VNF_ID, httpResponse);
        VnfInfo vnf = new VnfInfo();
        vnf.setId(VNF_ID);
        vnfs.add(vnf);
        VnfInfo detailedVnf = new VnfInfo();
        detailedVnf.setId(VNF_ID);
        when(vnfApi.vnfsVnfInstanceIdGet(VNF_ID, NOKIA_LCM_API_VERSION)).thenReturn(buildObservable(detailedVnf));
        OperationExecution olderOperation = new OperationExecution();
        olderOperation.setId(UUID.randomUUID().toString());
        olderOperation.setStartTime(OffsetDateTime.now());
        olderOperation.setStatus(OperationStatus.FINISHED);
        olderOperation.setOperationType(OperationType.TERMINATE);
        OperationExecution newerOperation = new OperationExecution();
        newerOperation.setId(UUID.randomUUID().toString());
        newerOperation.setStartTime(OffsetDateTime.now().plusDays(1));
        newerOperation.setStatus(OperationStatus.FINISHED);
        newerOperation.setOperationType(OperationType.MODIFY_INFO);
        detailedVnf.setOperationExecutions(new ArrayList<>());
        detailedVnf.getOperationExecutions().add(olderOperation);
        detailedVnf.getOperationExecutions().add(newerOperation);
        JsonElement operationParams = new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}");
        List<String> queriedOperaionsInOrder = new ArrayList<>();
        when(operationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(Mockito.anyString(), Mockito.eq(NOKIA_LCM_API_VERSION)))
                .then(new Answer<Observable<Object>>() {
                    @Override
                    public Observable<Object> answer(InvocationOnMock invocationOnMock) throws Throwable {
                        queriedOperaionsInOrder.add(invocationOnMock.getArguments()[0].toString());
                        if (invocationOnMock.getArguments()[0].equals(olderOperation.getId())) {
                            return buildObservable(new JsonParser().parse("{ \"additionalParams\" : { \"jobId\" : \"" + jobId + "\"}}"));
                        } else {
                            throw new RuntimeException(); //this should be never reached
                        }
                    }
                });
        JobDetailInfo job = jobManager.getJob(VNFM_ID, jobId);
        //verify
        assertEquals(Lists.newArrayList(olderOperation.getId()), queriedOperaionsInOrder);
        assertTrue(jobManager.hasOngoingJobs());
    }

    /**
     * if the registration process has not finished it is prevented to spawn jobs
     */
    @Test
    public void noJobCanBeStartedIfRegistrationNotFinished() throws Exception {
        //given
        when(selfRegistrationManagerForVfc.isReady()).thenReturn(false);
        //when
        try {
            jobManager.spawnJob(VNF_ID, httpResponse);
            fail();
        } catch (RuntimeException e) {
            assertEquals("The service is not yet ready", e.getMessage());
        }
    }

    /**
     * Ongoing job are out waited during the the preparation for shutdown
     */
    @Test
    //need to wait for an asynchronous execution to finish
    //this is the most optimal way to do it
    @SuppressWarnings("squid:S2925")
    public void onGoingJobsAreOutwaitedDuringShutdown() throws Exception {
        String firstJobId = jobManager.spawnJob(VNF_ID, httpResponse);
        ExecutorService executorService = Executors.newCachedThreadPool();
        ArgumentCaptor<Integer> sleeps = ArgumentCaptor.forClass(Integer.class);
        doNothing().when(systemFunctions).sleep(sleeps.capture());
        //when prepare job manager for shutdown
        Future<?> shutDown = executorService.submit(() -> jobManager.prepareForShutdown());
        while (sleeps.getAllValues().size() == 0) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
            }
        }
        assertFalse(shutDown.isDone());
        jobManager.jobFinished(firstJobId);
        //verify
        shutDown.get();
        verify(systemFunctions, times(sleeps.getAllValues().size())).sleep(500L);
    }
}