f4d19e22baf0da7cd9760f38e1572a42da213489
[appc.git] / appc-adapters / appc-chef-adapter / appc-chef-adapter-bundle / src / test / java / org / onap / appc / adapter / chef / impl / ChefAdapterImplJobPusherTest.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2018 Nokia. All rights reserved.
6  * =============================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.appc.adapter.chef.impl;
21
22 import static com.google.common.collect.Maps.immutableEntry;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
25 import static org.mockito.BDDMockito.given;
26
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.collect.ImmutableMap.Builder;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import org.apache.http.HttpStatus;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35 import org.mockito.InjectMocks;
36 import org.mockito.Mock;
37 import org.mockito.runners.MockitoJUnitRunner;
38 import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
39 import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
40 import org.onap.appc.adapter.chef.chefclient.api.ChefResponse;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
43
44 @RunWith(MockitoJUnitRunner.class)
45 public class ChefAdapterImplJobPusherTest {
46
47     private static final String CLIENT_PRIVATE_KEY_PATH = "/opt/onap/appc/chef/localhost/onap/testclient.pem";
48     private static final String RESULT_CODE_ATTR_KEY = "chefServerResult.code";
49     private static final String RESULT_MESSAGE_ATTR_KEY = "chefServerResult.message";
50     private static final String EXPECTED_RESPONSE_MSG = "jobs/{666}/";
51
52     private static final String USERNAME = "testclient";
53     private static final String SERVER_ADDRESS = "localhost";
54     private static final String ORGANIZATIONS = "onap";
55     private static final String ACTION_PARAM = "/pushy/jobs";
56     private static final String REQUEST_BODY_DATA = "requestBodyData";
57     private static final String JOB_ID = "jobID";
58
59     @Mock
60     private PrivateKeyChecker privateKeyChecker;
61     @Mock
62     private ChefApiClientFactory chefApiClientFactory;
63     @Mock
64     private ChefApiClient chefApiClient;
65
66     @InjectMocks
67     private ChefAdapterFactory chefAdapterFactory;
68     private SvcLogicContext svcLogicContext;
69
70     @Before
71     public void setUp() {
72         svcLogicContext = new SvcLogicContext();
73     }
74
75     @Test
76     public void pushJob_shouldSuccessfullyMakePostCall_andUpdateSvcLogicContext_whenReturnedStatusIsDifferentThan_201()
77         throws SvcLogicException {
78         assertSuccessfulPostCallForStatus(HttpStatus.SC_OK);
79         assertThat(svcLogicContext.getAttribute(JOB_ID)).isBlank();
80     }
81
82     @Test
83     public void pushJob_shouldSuccessfullyMakePostCall_andUpdateSvcLogicContext_withReturnedStatusIs_201()
84         throws SvcLogicException {
85         assertSuccessfulPostCallForStatus(HttpStatus.SC_CREATED);
86         assertThat(svcLogicContext.getAttribute(JOB_ID)).isEqualTo("666");
87     }
88
89     public void assertSuccessfulPostCallForStatus(int expectedHttpStatus) throws SvcLogicException {
90         // GIVEN
91         Map<String, String> params = givenInputParams(
92             immutableEntry("chefAction", ACTION_PARAM),
93             immutableEntry("pushRequest", REQUEST_BODY_DATA));
94         given(chefApiClientFactory.create("https://localhost/organizations/onap", ORGANIZATIONS, USERNAME,
95             CLIENT_PRIVATE_KEY_PATH)).willReturn(chefApiClient);
96         given(chefApiClient.post(ACTION_PARAM, REQUEST_BODY_DATA))
97             .willReturn(ChefResponse.create(expectedHttpStatus, EXPECTED_RESPONSE_MSG));
98
99         // WHEN
100         chefAdapterFactory.create().pushJob(params, svcLogicContext);
101
102         // THEN
103         assertThat(svcLogicContext.getStatus()).isEqualTo("success");
104         assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
105             .isEqualTo(Integer.toString(expectedHttpStatus));
106         assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY)).isEqualTo(EXPECTED_RESPONSE_MSG);
107     }
108
109     @Test
110     public void pushJob_shouldHandleAllOccurringExceptions_duringMethodExecution() {
111         // GIVEN
112         Map<String, String> params = givenInputParams();
113         String expectedErrorMessage = "Something went wrong";
114         given(chefApiClientFactory.create("https://localhost/organizations/onap", ORGANIZATIONS, USERNAME,
115             CLIENT_PRIVATE_KEY_PATH)).willThrow(new NullPointerException(expectedErrorMessage));
116
117         // WHEN // THEN
118         assertThatExceptionOfType(SvcLogicException.class)
119             .isThrownBy(() -> chefAdapterFactory.create().pushJob(params, svcLogicContext))
120             .withMessage("Chef Adapter error:" + expectedErrorMessage);
121
122         assertThat(svcLogicContext.getStatus()).isEqualTo("failure");
123         assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
124             .isEqualTo(Integer.toString(HttpStatus.SC_UNAUTHORIZED));
125         assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY)).isEqualTo(expectedErrorMessage);
126         assertThat(svcLogicContext.getAttribute(JOB_ID)).isBlank();
127     }
128
129     @Test
130     public void checkPushJob_shouldSetFailStatusAndMsgInContext_andThrowException_whenRetryTimesParamIsMissing() {
131         // GIVEN
132         Map<String, String> params = givenInputParams(
133             immutableEntry("retryInterval", "1"),
134             immutableEntry("jobid", "666"));
135
136         // WHEN // THEN
137         assertIfInputParamsAreValidated(params);
138     }
139
140     @Test
141     public void checkPushJob_shouldSetFailStatusAndMsgInContext_andThrowException_whenRetryIntervalParamIsMissing() {
142         // GIVEN
143         Map<String, String> params = givenInputParams(
144             immutableEntry("retryTimes", "4"),
145             immutableEntry("jobid", "666"));
146
147         // WHEN // THEN
148         assertIfInputParamsAreValidated(params);
149     }
150
151     @Test
152     public void checkPushJob_shouldSetFailStatusAndMsgInContext_andThrowException_whenJobIdParamIsMissing() {
153         // GIVEN
154         Map<String, String> params = givenInputParams(
155             immutableEntry("retryTimes", "4"),
156             immutableEntry("retryInterval", "1"));
157         assertIfInputParamsAreValidated(params);
158     }
159
160     public void assertIfInputParamsAreValidated(Map<String, String> params) {
161         // WHEN // THEN
162         assertThatExceptionOfType(SvcLogicException.class)
163             .isThrownBy(() -> chefAdapterFactory.create().checkPushJob(params, svcLogicContext))
164             .withMessage("Chef Adapter error:" + "Missing Mandatory param(s) retryTimes , retryInterval ");
165
166         assertThat(svcLogicContext.getStatus()).isEqualTo("failure");
167         assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
168             .isEqualTo(Integer.toString(HttpStatus.SC_UNAUTHORIZED));
169         assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY))
170             .isEqualTo("Missing Mandatory param(s) retryTimes , retryInterval ");
171     }
172
173     @Test
174     public void checkPushJob_shouldCheckJobStatusOnlyOnce_withoutAdditionalRetries_whenFirstReturnedJobStatusIs_Complete()
175         throws SvcLogicException {
176         String expectedHttpStatus = Integer.toString(HttpStatus.SC_OK);
177         String expectedMessage = "{status:complete}";
178
179         assertCheckJobStatusFor(
180             expectedHttpStatus,
181             expectedMessage,
182             ChefResponse.create(HttpStatus.SC_OK, "{status:complete}"),
183             ChefResponse.create(HttpStatus.SC_OK, "{status:running}"));
184     }
185
186     @Test
187     public void checkPushJob_shouldCheckJobStatusExpectedNumberOf_ThreeRetryTimes_whenEachReturnedStatusIs_Running()
188         throws SvcLogicException {
189         String expectedHttpStatus = Integer.toString(HttpStatus.SC_ACCEPTED);
190         String expectedMessage = "chef client runtime out";
191
192         assertCheckJobStatusFor(
193             expectedHttpStatus,
194             expectedMessage,
195             ChefResponse.create(HttpStatus.SC_OK, "{status:running}"),
196             ChefResponse.create(HttpStatus.SC_OK, "{status:running}"),
197             ChefResponse.create(HttpStatus.SC_OK, "{status:running}"));
198     }
199
200     @Test
201     public void checkPushJob_shouldCheckJobStatusOnlyOnce_withoutAdditionalRetries_whenFirstReturnedJobStatusIsNot_Running()
202         throws SvcLogicException {
203
204         String expectedHttpStatus = Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR);
205         String expectedMessage = "{status:unexpectedStatus}";
206
207         assertCheckJobStatusFor(
208             expectedHttpStatus,
209             expectedMessage,
210             ChefResponse.create(HttpStatus.SC_OK, "{status:unexpectedStatus}"),
211             ChefResponse.create(HttpStatus.SC_OK, "{status:running}"));
212     }
213
214     public void assertCheckJobStatusFor(String expectedHttpStatus, String expectedMessage, ChefResponse firstResponse,
215         ChefResponse... nextResponses) throws SvcLogicException {
216
217         // GIVEN
218         Map<String, String> params = givenInputParams(
219             immutableEntry("jobid", "666"),
220             immutableEntry("retryTimes", "3"),
221             immutableEntry("retryInterval", "1"));
222         given(chefApiClientFactory.create("https://localhost/organizations/onap", ORGANIZATIONS, USERNAME,
223             CLIENT_PRIVATE_KEY_PATH)).willReturn(chefApiClient);
224         given(chefApiClient.get(ACTION_PARAM + "/" + params.get("jobid")))
225             .willReturn(firstResponse, nextResponses);
226
227         // WHEN
228         chefAdapterFactory.create().checkPushJob(params, svcLogicContext);
229
230         // THEN
231         assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY))
232             .isEqualTo(expectedHttpStatus);
233         assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY)).isEqualTo(expectedMessage);
234     }
235
236     private Map<String, String> givenInputParams(Entry<String, String>... entries) {
237         Builder<String, String> paramsBuilder = ImmutableMap.builder();
238         paramsBuilder.put("username", USERNAME)
239             .put("serverAddress", SERVER_ADDRESS)
240             .put("organizations", ORGANIZATIONS);
241
242         for (Entry<String, String> entry : entries) {
243             paramsBuilder.put(entry);
244         }
245         return paramsBuilder.build();
246     }
247 }