summaryrefslogtreecommitdiffstats
path: root/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/ChefAdapterImplJobPusherTest.java
blob: f4d19e22baf0da7cd9760f38e1572a42da213489 (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
/*
 * ============LICENSE_START=======================================================
 * ONAP : APPC
 * ================================================================================
 * Copyright (C) 2018 Nokia. 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.appc.adapter.chef.impl;

import static com.google.common.collect.Maps.immutableEntry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
import org.onap.appc.adapter.chef.chefclient.api.ChefResponse;
import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;

@RunWith(MockitoJUnitRunner.class)
public class ChefAdapterImplJobPusherTest {

    private static final String CLIENT_PRIVATE_KEY_PATH = "/opt/onap/appc/chef/localhost/onap/testclient.pem";
    private static final String RESULT_CODE_ATTR_KEY = "chefServerResult.code";
    private static final String RESULT_MESSAGE_ATTR_KEY = "chefServerResult.message";
    private static final String EXPECTED_RESPONSE_MSG = "jobs/{666}/";

    private static final String USERNAME = "testclient";
    private static final String SERVER_ADDRESS = "localhost";
    private static final String ORGANIZATIONS = "onap";
    private static final String ACTION_PARAM = "/pushy/jobs";
    private static final String REQUEST_BODY_DATA = "requestBodyData";
    private static final String JOB_ID = "jobID";

    @Mock
    private PrivateKeyChecker privateKeyChecker;
    @Mock
    private ChefApiClientFactory chefApiClientFactory;
    @Mock
    private ChefApiClient chefApiClient;

    @InjectMocks
    private ChefAdapterFactory chefAdapterFactory;
    private SvcLogicContext svcLogicContext;

    @Before
    public void setUp() {
        svcLogicContext = new SvcLogicContext();
    }

    @Test
    public void pushJob_shouldSuccessfullyMakePostCall_andUpdateSvcLogicContext_whenReturnedStatusIsDifferentThan_201()
        throws SvcLogicException {
        assertSuccessfulPostCallForStatus(HttpStatus.SC_OK);
        assertThat(svcLogicContext.getAttribute(JOB_ID)).isBlank();
    }

    @Test
    public void pushJob_shouldSuccessfullyMakePostCall_andUpdateSvcLogicContext_withReturnedStatusIs_201()
        throws SvcLogicException {
        assertSuccessfulPostCallForStatus(HttpStatus.SC_CREATED);
        assertThat(svcLogicContext.getAttribute(JOB_ID)).isEqualTo("666");
    }

    public void assertSuccessfulPostCallForStatus(int expectedHttpStatus) throws SvcLogicException {
        // GIVEN
        Map<String, String> params = givenInputParams(
            immutableEntry("chefAction", ACTION_PARAM),
            immutableEntry("pushRequest", REQUEST_BODY_DATA));
        given(chefApiClientFactory.create("https://localhost/organizations/onap", ORGANIZATIONS, USERNAME,
            CLIENT_PRIVATE_KEY_PATH)).willReturn(chefApiClient);
        given(chefApiClient.post(ACTION_PARAM, REQUEST_BODY_DATA))
            .willReturn(ChefResponse.create(expectedHttpStatus, EXPECTED_RESPONSE_MSG));

        // WHEN
        chefAdapterFactory.create().pushJob(params, svcLogicContext);

        // THEN
        assertThat(svcLogicContext.getStatus()).isEqualTo("success");
        assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
            .isEqualTo(Integer.toString(expectedHttpStatus));
        assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY)).isEqualTo(EXPECTED_RESPONSE_MSG);
    }

    @Test
    public void pushJob_shouldHandleAllOccurringExceptions_duringMethodExecution() {
        // GIVEN
        Map<String, String> params = givenInputParams();
        String expectedErrorMessage = "Something went wrong";
        given(chefApiClientFactory.create("https://localhost/organizations/onap", ORGANIZATIONS, USERNAME,
            CLIENT_PRIVATE_KEY_PATH)).willThrow(new NullPointerException(expectedErrorMessage));

        // WHEN // THEN
        assertThatExceptionOfType(SvcLogicException.class)
            .isThrownBy(() -> chefAdapterFactory.create().pushJob(params, svcLogicContext))
            .withMessage("Chef Adapter error:" + expectedErrorMessage);

        assertThat(svcLogicContext.getStatus()).isEqualTo("failure");
        assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
            .isEqualTo(Integer.toString(HttpStatus.SC_UNAUTHORIZED));
        assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY)).isEqualTo(expectedErrorMessage);
        assertThat(svcLogicContext.getAttribute(JOB_ID)).isBlank();
    }

    @Test
    public void checkPushJob_shouldSetFailStatusAndMsgInContext_andThrowException_whenRetryTimesParamIsMissing() {
        // GIVEN
        Map<String, String> params = givenInputParams(
            immutableEntry("retryInterval", "1"),
            immutableEntry("jobid", "666"));

        // WHEN // THEN
        assertIfInputParamsAreValidated(params);
    }

    @Test
    public void checkPushJob_shouldSetFailStatusAndMsgInContext_andThrowException_whenRetryIntervalParamIsMissing() {
        // GIVEN
        Map<String, String> params = givenInputParams(
            immutableEntry("retryTimes", "4"),
            immutableEntry("jobid", "666"));

        // WHEN // THEN
        assertIfInputParamsAreValidated(params);
    }

    @Test
    public void checkPushJob_shouldSetFailStatusAndMsgInContext_andThrowException_whenJobIdParamIsMissing() {
        // GIVEN
        Map<String, String> params = givenInputParams(
            immutableEntry("retryTimes", "4"),
            immutableEntry("retryInterval", "1"));
        assertIfInputParamsAreValidated(params);
    }

    public void assertIfInputParamsAreValidated(Map<String, String> params) {
        // WHEN // THEN
        assertThatExceptionOfType(SvcLogicException.class)
            .isThrownBy(() -> chefAdapterFactory.create().checkPushJob(params, svcLogicContext))
            .withMessage("Chef Adapter error:" + "Missing Mandatory param(s) retryTimes , retryInterval ");

        assertThat(svcLogicContext.getStatus()).isEqualTo("failure");
        assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
            .isEqualTo(Integer.toString(HttpStatus.SC_UNAUTHORIZED));
        assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY))
            .isEqualTo("Missing Mandatory param(s) retryTimes , retryInterval ");
    }

    @Test
    public void checkPushJob_shouldCheckJobStatusOnlyOnce_withoutAdditionalRetries_whenFirstReturnedJobStatusIs_Complete()
        throws SvcLogicException {
        String expectedHttpStatus = Integer.toString(HttpStatus.SC_OK);
        String expectedMessage = "{status:complete}";

        assertCheckJobStatusFor(
            expectedHttpStatus,
            expectedMessage,
            ChefResponse.create(HttpStatus.SC_OK, "{status:complete}"),
            ChefResponse.create(HttpStatus.SC_OK, "{status:running}"));
    }

    @Test
    public void checkPushJob_shouldCheckJobStatusExpectedNumberOf_ThreeRetryTimes_whenEachReturnedStatusIs_Running()
        throws SvcLogicException {
        String expectedHttpStatus = Integer.toString(HttpStatus.SC_ACCEPTED);
        String expectedMessage = "chef client runtime out";

        assertCheckJobStatusFor(
            expectedHttpStatus,
            expectedMessage,
            ChefResponse.create(HttpStatus.SC_OK, "{status:running}"),
            ChefResponse.create(HttpStatus.SC_OK, "{status:running}"),
            ChefResponse.create(HttpStatus.SC_OK, "{status:running}"));
    }

    @Test
    public void checkPushJob_shouldCheckJobStatusOnlyOnce_withoutAdditionalRetries_whenFirstReturnedJobStatusIsNot_Running()
        throws SvcLogicException {

        String expectedHttpStatus = Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        String expectedMessage = "{status:unexpectedStatus}";

        assertCheckJobStatusFor(
            expectedHttpStatus,
            expectedMessage,
            ChefResponse.create(HttpStatus.SC_OK, "{status:unexpectedStatus}"),
            ChefResponse.create(HttpStatus.SC_OK, "{status:running}"));
    }

    public void assertCheckJobStatusFor(String expectedHttpStatus, String expectedMessage, ChefResponse firstResponse,
        ChefResponse... nextResponses) throws SvcLogicException {

        // GIVEN
        Map<String, String> params = givenInputParams(
            immutableEntry("jobid", "666"),
            immutableEntry("retryTimes", "3"),
            immutableEntry("retryInterval", "1"));
        given(chefApiClientFactory.create("https://localhost/organizations/onap", ORGANIZATIONS, USERNAME,
            CLIENT_PRIVATE_KEY_PATH)).willReturn(chefApiClient);
        given(chefApiClient.get(ACTION_PARAM + "/" + params.get("jobid")))
            .willReturn(firstResponse, nextResponses);

        // WHEN
        chefAdapterFactory.create().checkPushJob(params, svcLogicContext);

        // THEN
        assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
            .isEqualTo(expectedHttpStatus);
        assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY)).isEqualTo(expectedMessage);
    }

    private Map<String, String> givenInputParams(Entry<String, String>... entries) {
        Builder<String, String> paramsBuilder = ImmutableMap.builder();
        paramsBuilder.put("username", USERNAME)
            .put("serverAddress", SERVER_ADDRESS)
            .put("organizations", ORGANIZATIONS);

        for (Entry<String, String> entry : entries) {
            paramsBuilder.put(entry);
        }
        return paramsBuilder.build();
    }
}