aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java
blob: 85faaab28dfe893a16a459e9d29da0de1050f771 (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
/*-
 * ============LICENSE_START=======================================================
 * VID
 * ================================================================================
 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.vid.job.command;

import static java.util.Collections.emptyList;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.onap.vid.job.Job.JobStatus.COMPLETED;
import static org.onap.vid.job.Job.JobStatus.COMPLETED_WITH_ERRORS;
import static org.onap.vid.job.Job.JobStatus.COMPLETED_WITH_NO_ACTION;
import static org.onap.vid.job.Job.JobStatus.FAILED;
import static org.onap.vid.job.Job.JobStatus.IN_PROGRESS;
import static org.onap.vid.job.Job.JobStatus.PAUSE;
import static org.onap.vid.job.Job.JobStatus.RESOURCE_IN_PROGRESS;
import static org.onap.vid.job.Job.JobStatus.STOPPED;
import static org.onap.vid.job.command.ResourceCommandKt.ACTION_PHASE;
import static org.onap.vid.job.command.ResourceCommandKt.INTERNAL_STATE;
import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.createGroup;
import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.createMember;
import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.createNetwork;
import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.createService;
import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.createVfModule;
import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.createVnf;
import static org.onap.vid.model.Action.Create;
import static org.onap.vid.model.Action.Delete;
import static org.onap.vid.model.Action.None;
import static org.onap.vid.model.Action.Resume;
import static org.onap.vid.model.Action.values;
import static org.onap.vid.utils.Logging.getMethodCallerName;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.ws.rs.ProcessingException;
import kotlin.Pair;
import org.jetbrains.annotations.NotNull;
import org.onap.vid.exceptions.AbortingException;
import org.onap.vid.exceptions.GenericUncheckedException;
import org.onap.vid.exceptions.TryAgainException;
import org.onap.vid.job.Job;
import org.onap.vid.job.JobAdapter;
import org.onap.vid.job.JobsBrokerService;
import org.onap.vid.job.NextCommand;
import org.onap.vid.job.impl.JobSharedData;
import org.onap.vid.model.Action;
import org.onap.vid.model.serviceInstantiation.BaseResource;
import org.onap.vid.model.serviceInstantiation.InstanceGroup;
import org.onap.vid.model.serviceInstantiation.InstanceGroupMember;
import org.onap.vid.model.serviceInstantiation.Network;
import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
import org.onap.vid.model.serviceInstantiation.VfModule;
import org.onap.vid.model.serviceInstantiation.Vnf;
import org.onap.vid.mso.RestMsoImplementation;
import org.onap.vid.mso.model.ModelInfo;
import org.springframework.http.HttpMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.togglz.core.manager.FeatureManager;

public class ResourceCommandTest {

    public static class MockCommand extends ResourceCommand {

        public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus) {
            this(mockState, mockPhase, mockedJobStatus, false);
        }

        public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean lateInit) {
            super(
                    mock(RestMsoImplementation.class, RETURNS_MOCKS),
                    mock(InProgressStatusService.class),
                    mock(MsoResultHandlerService.class, RETURNS_MOCKS),
                    mock(WatchChildrenJobsBL.class),
                    mock(JobsBrokerService.class, RETURNS_MOCKS),
                    mock(JobAdapter.class, RETURNS_MOCKS),
                    mock(FeatureManager.class));
            this.mockedJobStatus = mockedJobStatus;
            this.mockState = mockState;
            this.mockPhase = mockPhase;
            if (!lateInit) {
                init();
            }
            when(this.getWatchChildrenJobsBL().cumulateJobStatus(any(), any())).thenReturn(mockedJobStatus);
        }

        protected void init() {
            if (mockState == InternalState.INITIAL) {
                init(mock(JobSharedData.class), Collections.emptyMap());
            } else {
                init(mock(JobSharedData.class), ImmutableMap.of(INTERNAL_STATE, mockState.name(), ACTION_PHASE, mockPhase.name()));
            }
        }

        private final Job.JobStatus mockedJobStatus;
        private final InternalState mockState;
        private final Action mockPhase;


        @NotNull
        @Override
        public Job.JobStatus createChildren() {
            if (mockState == InternalState.CREATING_CHILDREN || (mockState == InternalState.INITIAL && mockPhase== Delete))
                return mockedJobStatus;
            throw (new RuntimeException("Not expected to call "+getMethodCallerName()));
        }

        protected Job.JobStatus mockedStatusOrThrow(InternalState expectedState) {
            if (mockState == expectedState)
                return mockedJobStatus;
            throw (new RuntimeException("Not expected to call "+getMethodCallerName()));
        }

        protected MsoRestCallPlan mockedPlanOrThrow(InternalState expectedState) {
            if (mockState == expectedState)
                return new MsoRestCallPlan(HttpMethod.POST, "path", Optional.empty(), Optional.empty(), "nothing");
            throw (new RuntimeException("Not expected to call "+getMethodCallerName()));
        }

        @NotNull
        @Override
        public MsoRestCallPlan planCreateMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId, String testApi) {
            return mockedPlanOrThrow(InternalState.CREATE_MYSELF);
        }

        @NotNull
        @Override
        public MsoRestCallPlan planDeleteMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId) {
            return mockedPlanOrThrow(InternalState.DELETE_MYSELF);
        }
    }

    public static class MockCommandTestingStateMachine extends MockCommand {

        private final JobSharedData sharedData;
        private final boolean isDescendantHasAction;

        public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf) {
            this(mockState, mockPhase, mockedJobStatus, mockedNeedToDeleteMySelf, false, true);
        }

        public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf, boolean isService, boolean isDescendantHasAction) {
            super(mockState, mockPhase, mockedJobStatus, true);
            this.mockedNeedToDeleteMySelf = mockedNeedToDeleteMySelf;
            this.isService = isService;
            this.sharedData = mock(JobSharedData.class, RETURNS_MOCKS);
            this.isDescendantHasAction = isDescendantHasAction;
            init();
        }

        protected final boolean mockedNeedToDeleteMySelf;
        private final boolean isService;

        @NotNull
        @Override
        public Job.JobStatus inProgress() {
            return mockedStatusOrThrow(InternalState.IN_PROGRESS);
        }

        @NotNull
        @Override
        public Job.JobStatus watchChildren() {
            return mockedStatusOrThrow(InternalState.WATCHING);
        }

        @Override
        public boolean isNeedToDeleteMyself() {
            return mockedNeedToDeleteMySelf;
        }

        @Override
        protected boolean isServiceCommand() {
            return isService;
        }

        @Override
        public JobSharedData getSharedData() {
            return sharedData;
        }

        @Override
        protected boolean isDescendantHasAction(@NotNull Action phase) {
            return isDescendantHasAction;
        }
    }

    @DataProvider
    public static Object[][] nextStateDeletePhaseProvider() {
        return new Object[][]{
                {InternalState.CREATING_CHILDREN, COMPLETED, InternalState.WATCHING},
                {InternalState.WATCHING, COMPLETED, InternalState.DELETE_MYSELF},
                {InternalState.WATCHING, IN_PROGRESS, InternalState.WATCHING},
                {InternalState.WATCHING, RESOURCE_IN_PROGRESS, InternalState.WATCHING},
                {InternalState.DELETE_MYSELF, COMPLETED, InternalState.IN_PROGRESS},
                {InternalState.IN_PROGRESS, COMPLETED, InternalState.TERMINAL},
                {InternalState.IN_PROGRESS, IN_PROGRESS, InternalState.IN_PROGRESS},
                {InternalState.IN_PROGRESS, RESOURCE_IN_PROGRESS, InternalState.IN_PROGRESS},
        };
    }

    @Test(dataProvider = "nextStateDeletePhaseProvider")
    public void whenCalcNextStateDeletePhase_expectedStateIsReturned(
            InternalState internalState, Job.JobStatus jobStatus, InternalState expectedState) {

        //there is no meaning to the constructor inputs here
        MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Delete, FAILED, true);
        assertEquals(expectedState, underTest.calcNextStateDeletePhase(jobStatus, internalState));
    }

    @Test
    public void whenNoNeedToDeleteMyself_internalStateMovesFromWatchingToTerminal() {
        MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Delete, COMPLETED, false);
        assertEquals(InternalState.TERMINAL, underTest.calcNextStateDeletePhase(COMPLETED, InternalState.WATCHING));
    }

    @DataProvider
    public static Object[][] testShallStopJobDataProvider() {
        return new Object[][]{
                {IN_PROGRESS, None, false, false},
                {COMPLETED_WITH_NO_ACTION, None, false, false},
                {COMPLETED, None, false, false},
                {FAILED, None, false, true},
                {COMPLETED_WITH_ERRORS, None, false, true},
                {COMPLETED_WITH_ERRORS, None, true, false},
                {FAILED, None, true, false},
                {FAILED, Delete, true, true},
                {FAILED, Create, true, true},
        };
    }


    @Test(dataProvider = "testShallStopJobDataProvider")
    public void testShallStopJob(Job.JobStatus jobStatus, Action action, boolean isService, boolean expectedResult) {
        //in this test, there is no meaning to constructor parameters besides isService
        MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Delete, COMPLETED, false, isService, true);

        BaseResource mockedRequest = mock(BaseResource.class);
        when(underTest.getSharedData().getRequest()).thenReturn(mockedRequest);
        when(mockedRequest.getAction()).thenReturn(action);

        assertEquals(expectedResult, underTest.shallStopJob(jobStatus));
    }

    public static class FakeResourceCreator {

        public static<T> Map<String, T> convertToMap(List<T> list) {
            if (list==null) {
                return null;
            }
            return list.stream().collect(Collectors.toMap(x-> UUID.randomUUID().toString(), x->x));
        }

        static ServiceInstantiation createService(List<Vnf> vnfs, List<Network> networks, List<InstanceGroup> vnfGroups) {
            return new ServiceInstantiation(mock(ModelInfo.class), null, null, null, null, null, null, null, null, null, null, null, null, null, null,
                    convertToMap(vnfs),
                    convertToMap(networks),
                    convertToMap(vnfGroups),
                    null,
                    null, false, 1, false,false,null, null, null, null, null, null, null, null);
        }

        public static ServiceInstantiation createServiceWith2InstancesInEachLevel(Action action) {
            return createService(
                    ImmutableList.of(
                            createVnf(ImmutableList.of(createVfModule(action), createVfModule(action)), action),
                            createVnf(ImmutableList.of(createVfModule(action), createVfModule(action)), action)),
                    ImmutableList.of(
                            createNetwork(action),
                            createNetwork(action)),
                    ImmutableList.of(
                            createGroup(ImmutableList.of(createMember(action), createMember(action)), action),
                            createGroup(ImmutableList.of(createMember(action), createMember(action)), action))
                    );
        }

        static InstanceGroup createGroup(List<InstanceGroupMember> groupMembers, Action action) {
            return new InstanceGroup(mock(ModelInfo.class), null, action.name(), false, null, convertToMap(groupMembers), null, null, null,
                null, null);
        }

        static InstanceGroupMember createMember(Action action) {
            return new InstanceGroupMember(null, action.toString(), null, null, null, null, null);
        }

        static Vnf createVnf(List<VfModule> vfModules, Action action) {
            Map<String, Map<String, VfModule>> vfModulesMap = new HashMap<>();
            vfModulesMap.put("abc",convertToMap(vfModules));

            return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, vfModulesMap, null, null, null,
                null, null);
        }

        static Vnf createVnf(Action action) {
            return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null,null, null, null, null,
                null, null);
        }

        static VfModule createVfModule(Action action) {
            return new VfModule(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null,
                false, false, null, null, null, null, null, null, null, null, null);
        }

        static Network createNetwork(Action action) {
            return new Network(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, null, null, null,
                null, null);
        }
    }

    @DataProvider
    public static Object[][] testIsDescendantHasActionDataProvider() {
        return new Object[][]{
                {"empty service", Create, false, createService(emptyList(), emptyList(), emptyList())},
                {"instance group with None", Create, false, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(emptyList(), None)))},
                {"instance group with Create", Create, true, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(emptyList(), Create)))},
                {"instance group None + member Delete", Delete, true, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Delete)), None)))},
                {"instance group None + member Create", Delete, false, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Create)), None)))},
                {"instance group None + member Create + member Delete", Delete, true,
                        createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Create), createMember(Delete)), None)))},
                {"vnf Create", Delete, false, createService(ImmutableList.of(createVnf(emptyList(), Create)), emptyList(),emptyList())},
                {"vnf Create", Create, true, createService(ImmutableList.of(createVnf(emptyList(), Create)), emptyList(),emptyList())},
                {"vnf Create null VfModules internal map", Create, false, createService(ImmutableList.of(createVnf(null, Delete)), emptyList(),emptyList())},
                {"vnf Delete with null VfModules", Create, false, createService(ImmutableList.of(createVnf(Delete)), emptyList(),emptyList())},
                {"vnf None + VfModule Create", Create, true, createService(ImmutableList.of(createVnf(ImmutableList.of(createVfModule(Create)), None)), emptyList(),emptyList())},
                {"vnf None + VfModule None", Create, false, createService(ImmutableList.of(createVnf(ImmutableList.of(createVfModule(None)), None)), emptyList(),emptyList())},
                {"network Create", Create, true, createService(emptyList(), ImmutableList.of(createNetwork(Create)), emptyList())},
                {"network Delete", Create, false, createService(emptyList(), ImmutableList.of(createNetwork(Delete)), emptyList())},
        };
    }

    @Test(dataProvider = "testIsDescendantHasActionDataProvider")
    public void testIsDescendantHasAction(String desc, Action action, boolean expectedResult, BaseResource request) {
        //in this test, there is no meaning to constructor parameters
        MockCommand underTest = new MockCommand(InternalState.WATCHING, Delete, COMPLETED);
        assertEquals(expectedResult, underTest.isDescendantHasAction(request, action));
    }

    @DataProvider
    public static Object[][] testCallDataProvider() {
        return new Object[][]{
                {"initial state with successful creating children" ,InternalState.INITIAL, COMPLETED, InternalState.WATCHING, RESOURCE_IN_PROGRESS},
                {"initial state with failed creating children", InternalState.INITIAL, FAILED, null, FAILED},
                {"watching state with children still in progress" ,InternalState.WATCHING, RESOURCE_IN_PROGRESS, InternalState.WATCHING, RESOURCE_IN_PROGRESS},
                {"watching state with children that completed with errors" ,InternalState.WATCHING, COMPLETED_WITH_ERRORS, null, COMPLETED_WITH_ERRORS},
                {"watching state with children that completed with no action" ,InternalState.WATCHING, COMPLETED_WITH_NO_ACTION, InternalState.DELETE_MYSELF, RESOURCE_IN_PROGRESS},
                {"watching state with children that has completed" ,InternalState.WATCHING, COMPLETED, InternalState.DELETE_MYSELF, RESOURCE_IN_PROGRESS},
                {"mso call state that failed" ,InternalState.DELETE_MYSELF, FAILED, null, FAILED},
                //TODO handle AAI get unique name state {"mso call state that still in progress" ,InternalState.DELETE_MYSELF, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED, false},
                {"mso call state that success" ,InternalState.DELETE_MYSELF, COMPLETED, InternalState.IN_PROGRESS, RESOURCE_IN_PROGRESS},
                {"in progress return in progress" ,InternalState.IN_PROGRESS, IN_PROGRESS, InternalState.IN_PROGRESS, RESOURCE_IN_PROGRESS},
                {"in progress return in pause" ,InternalState.IN_PROGRESS, PAUSE, InternalState.IN_PROGRESS, RESOURCE_IN_PROGRESS},
                {"in progress return in pause" ,InternalState.IN_PROGRESS, STOPPED, null, STOPPED},
                {"in progress return in pause" ,InternalState.IN_PROGRESS, FAILED, null, FAILED},
                {"in progress return in pause" ,InternalState.IN_PROGRESS, COMPLETED, null, COMPLETED},

        };
    }

    @Test(dataProvider = "testCallDataProvider")
    public void whenCallCommandWithDeletePhase_nextJobStatusAndInternalStateAreAsExpected(
            String description, InternalState internalState, Job.JobStatus currentStateResult,
            InternalState expectedNextState, Job.JobStatus expectedNextStatus) {

        MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(internalState, Delete, currentStateResult, true);
        NextCommand nextCommand = underTest.call();
        assertEquals(expectedNextStatus, nextCommand.getStatus());

        //expectedNextState == null means nextCommand has no real command
        if (expectedNextState!=null) {
            assertEquals(expectedNextState, (nextCommand.getCommand().getData().get(INTERNAL_STATE)));
            assertFalse(nextCommand.getStatus().isFinal());
        }
        else {
            assertNull(nextCommand.getCommand());
            assertTrue(nextCommand.getStatus().isFinal());
        }
    }

    @DataProvider
    public static Object[][] InProgressDataProvider() {
        return Stream.of(Job.JobStatus.values())
                .map(status -> new Object[] { status })
                .toArray(Object[][]::new);
    }

    @Test(dataProvider = "InProgressDataProvider")
    public void whenGetResultFromMso_InProgressReturnThem(Job.JobStatus mockedJobStatus) {
        Job.JobStatus expectedJobStatus = (mockedJobStatus== PAUSE) ? IN_PROGRESS : mockedJobStatus;
        MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Delete, mockedJobStatus);
        when(underTest.getInProgressStatusService().call(any(), any(), any())).thenReturn(mockedJobStatus);

        // we need to mock the request for pause after completion only when the status is completed
        if(mockedJobStatus == COMPLETED){
            BaseResource mockedBaseResource = mock(BaseResource.class);
            when(underTest.getSharedData().getRequest()).thenReturn(mockedBaseResource);
        }
        assertEquals(expectedJobStatus, underTest.inProgress());
    }

    @DataProvider
    public static Object[][] InProgressExceptionsDataProvider() {
        return new Object[][]{
                {new ProcessingException(""), IN_PROGRESS},
                {new InProgressStatusService.BadResponseFromMso(null), IN_PROGRESS},
                {new GenericUncheckedException(""), STOPPED }
        };
    }

    @Test(dataProvider = "InProgressExceptionsDataProvider")
    public void whenInProgressStatusServiceThrowException_InProgressReturnStatus(Exception exception, Job.JobStatus expectedJobStatus) {
        MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Delete, expectedJobStatus);
        when(underTest.getInProgressStatusService().call(any(), any(), any())).thenThrow(exception);
        assertEquals(expectedJobStatus, underTest.inProgress());
    }

    @DataProvider
    public static Object[][] testIsNeedToDeleteMySelfDataProvider() {
        return Stream.of(values())
                .map(status -> new Object[] { status })
                .toArray(Object[][]::new);
    }

    @Test(dataProvider = "testIsNeedToDeleteMySelfDataProvider")
    public void testIsNeedToDeleteMySelf(Action action) {
        boolean expectedResult = (action== Delete);
        MockCommand underTest = new MockCommand(InternalState.DELETE_MYSELF, Delete, IN_PROGRESS);
        BaseResource mockedBaseResource = mock(BaseResource.class);
        when(underTest.getSharedData().getRequest()).thenReturn(mockedBaseResource);
        when(mockedBaseResource.getAction()).thenReturn(action);
        assertEquals(expectedResult, underTest.isNeedToDeleteMyself());
    }

    @DataProvider
    public static Object[][] testWatchingDataProvider() {
        return new Object[][]{
                {"all children final, no failed child ", COMPLETED, COMPLETED},
                {"all children final, there is failed child ", COMPLETED_WITH_ERRORS, COMPLETED_WITH_ERRORS},
                {"not all children final", IN_PROGRESS, IN_PROGRESS},
        };
    }

    @Test(dataProvider = "testWatchingDataProvider")
    public void testWatching(String desc, Job.JobStatus childrenJobsStatus, Job.JobStatus expectedJobStatus) {
        MockCommand underTest = new MockCommand(InternalState.WATCHING, Delete, IN_PROGRESS);
        when(underTest.getWatchChildrenJobsBL().retrieveChildrenJobsStatus(any())).thenReturn(childrenJobsStatus);
        assertEquals(expectedJobStatus, underTest.watchChildren());
    }

    @DataProvider
    public static Object[][] testCalcInitialStateDataProvider() {
        return new Object[][]{
                {Delete, true, Delete, InternalState.CREATING_CHILDREN},
                {Delete, false, Delete, InternalState.DELETE_MYSELF},
                {Delete, false, Create, InternalState.TERMINAL},
                {Delete, true, Create, InternalState.CREATING_CHILDREN},
                {Create, true, Create, InternalState.CREATE_MYSELF},
                {Create, false, Create, InternalState.CREATE_MYSELF},
                {Create, false, Delete, InternalState.TERMINAL},
                {Create, true, Delete, InternalState.CREATING_CHILDREN},
                {Create, true, Resume, InternalState.RESUME_MYSELF},
                {Delete, false, Resume, InternalState.TERMINAL},
        };
    }

    @Test(dataProvider = "testCalcInitialStateDataProvider")
    public void testCalcInitialState(Action phase, boolean isDescendantHasAction, Action action, InternalState expectedState) {
        ResourceCommand underTest = mock(ResourceCommand.class);
        when(underTest.calcInitialState(any(), any())).thenCallRealMethod();
        when(underTest.isDescendantHasAction(eq(phase))).thenReturn(isDescendantHasAction);
        when(underTest.getActionType()).thenReturn(action);
        when(underTest.isNeedToDeleteMyself()).thenCallRealMethod();
        when(underTest.isNeedToCreateMyself()).thenCallRealMethod();
        when(underTest.isNeedToResumeMySelf()).thenCallRealMethod();

        Map<String, String> commandData = ImmutableMap.of(INTERNAL_STATE, InternalState.INITIAL.name());
        assertEquals(expectedState, underTest.calcInitialState(commandData, phase));
    }


    //throw exception when call to create children
    //create children is just example, it could be any other method that called by ResourceCommand.invokeCommand
    public static class MockCommandThrowExceptionOnCreateChildren extends MockCommandTestingStateMachine {

        private final RuntimeException exceptionToThrow;

        public MockCommandThrowExceptionOnCreateChildren(RuntimeException exceptionToThrow) {
            super(InternalState.CREATING_CHILDREN, Delete, COMPLETED, true);
            this.exceptionToThrow = exceptionToThrow;
            doAnswer(returnsFirstArg()).when(this.getWatchChildrenJobsBL()).cumulateJobStatus(any(), any());
        }

        @NotNull
        @Override
        public Job.JobStatus createChildren() {
            throw exceptionToThrow;
        }
    }

    @DataProvider
    public static Object[][] exceptionAndStateProvider() {
        return new Object[][]{
                {new TryAgainException(new Exception()), RESOURCE_IN_PROGRESS},
                {new AbortingException(new Exception()), FAILED},
        };
    }

    @Test(dataProvider = "exceptionAndStateProvider")
    public void whenKnownExceptionThrownInCommandInvocation_thenStateIsAsExpected(RuntimeException exception, Job.JobStatus expectedNextStatus) {
        MockCommandTestingStateMachine underTest = new MockCommandThrowExceptionOnCreateChildren(exception);
        NextCommand nextCommand = underTest.call();
        assertEquals(expectedNextStatus, nextCommand.getStatus());
    }

    @DataProvider
    public static Object[][] resourcePosition() {
        return new Object[][]{
            {1, 2, 3, ImmutableList.of(1,2,3)},
            {null, 1, 100, ImmutableList.of(101,1,100)},
            {null, null, null, ImmutableList.of(1,2,3)},
            {1,2,2, ImmutableList.of(1,2,2)}
        };
    }

    @Test(dataProvider = "resourcePosition")
    public void sortChildren_sortAccordingToPosition(Integer firstPosition, Integer secondPosition, Integer thirdPosition, List<Integer> expectedPositions){
        BaseResource mockedRequest1 = mock(BaseResource.class);
        when(mockedRequest1.getPosition()).thenReturn(firstPosition);
        BaseResource mockedRequest2 = mock(BaseResource.class);
        when(mockedRequest2.getPosition()).thenReturn(secondPosition);
        BaseResource mockedRequest3 = mock(BaseResource.class);
        when(mockedRequest3.getPosition()).thenReturn(thirdPosition);

        MockCommand underTest = new MockCommand(InternalState.CREATING_CHILDREN, Create, IN_PROGRESS);
        List<Pair<BaseResource, Integer>> sortedList = underTest.setPositionWhereIsMissing(ImmutableList.of(mockedRequest1, mockedRequest2, mockedRequest3));

        assertEquals(sortedList.get(0).getSecond(),expectedPositions.get(0));
        assertEquals(sortedList.get(1).getSecond(),expectedPositions.get(1));
        assertEquals(sortedList.get(2).getSecond(),expectedPositions.get(2));
    }
}