aboutsummaryrefslogtreecommitdiffstats
path: root/dcae-analytics-dmaap/src/test/java/org/openecomp/dcae/apod/analytics/dmaap/service/BaseDMaaPMRComponentTest.java
blob: 4265c46fba094d68fa9fd78a8d940f4df325b5da (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
/*
 * ===============================LICENSE_START======================================
 *  dcae-analytics
 * ================================================================================
 *    Copyright © 2017 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.openecomp.dcae.apod.analytics.dmaap.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Optional;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import org.openecomp.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
import org.openecomp.dcae.apod.analytics.dmaap.BaseAnalyticsDMaaPUnitTest;
import org.openecomp.dcae.apod.analytics.dmaap.domain.config.DMaaPMRPublisherConfig;
import org.openecomp.dcae.apod.analytics.dmaap.domain.config.DMaaPMRSubscriberConfig;
import org.openecomp.dcae.apod.analytics.dmaap.domain.response.DMaaPMRSubscriberResponse;
import org.openecomp.dcae.apod.analytics.dmaap.service.publisher.DMaaPMRPublisherQueue;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isA;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * @author Manjesh Gowda. Creation Date: 11/4/2016.
 */
public class BaseDMaaPMRComponentTest extends BaseAnalyticsDMaaPUnitTest {

    @Test
    public void testGetAuthHeaderWithGoodValues() {
        String expectedEncodedString = "Basic bTAwNTAyQHRjYS5hZi5kY2FlLmNvbTpUZTUwMjFhYmM=";
        Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader("USER", "PASSWORD");
        assertTrue(" Authentication Header has value ", actualOutput.isPresent());
//        assertEquals(" Authentication Header has value ", expectedEncodedString, actualOutput.get());
    }

    @Test
    public void testGetAuthHeaderWithNullValues() {
        Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader(null, null);
        assertFalse(" Authentication Header has value ", actualOutput.isPresent());
    }

    @Test
    public void testGetAuthHeaderWithUserNullValue() {
        Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader("USER", null);
        assertFalse(" Authentication Header has value ", actualOutput.isPresent());
    }

    @Test
    public void testGetAuthHeaderWithPasswordNullValue() {
        Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader(null, "PASSWORD");
        assertFalse(" Authentication Header has value ", actualOutput.isPresent());
    }

    @Test
    public void testCreatePublishURIWithGoodValues() {
        URI actualURI = BaseDMaaPMRComponent.createPublisherURI(getPublisherConfig());
        String test = actualURI.toString();
        assertEquals("Generated Publisher URL is correct",
                "https://testHostName:8080/events/testTopicName", actualURI.toString());
    }

    @Test(expected = DCAEAnalyticsRuntimeException.class)
    public void testCreatePublishURIWithURISyntaxException() {
        DMaaPMRPublisherConfig badPublisherConfig = new DMaaPMRPublisherConfig
                .Builder(" dav /gh. ss/ asd ", "///@$%#-htps:<>!##")
                .setPortNumber(0)
                .setProtocol("https").build();

      BaseDMaaPMRComponent.createPublisherURI(badPublisherConfig);
    }

    @Test
    public void testCreateSubscribeURIWithGoodValues() {
        URI actualURI = BaseDMaaPMRComponent.createSubscriberURI(
                getSubscriberConfig("test-consumer-group", "test-consumer-id"));
        assertEquals("Generated Subscriber URL is correct",
                "https://testHostName:8080/events/testTopicName/" +
                        "test-consumer-id/test-consumer-group?timeout=2000&limit=20",
                actualURI.toString());
    }

    @Test(expected = DCAEAnalyticsRuntimeException.class)
    public void testCreateSubscribeURIWithURISyntaxException() {
        DMaaPMRSubscriberConfig badSubscriberConfig = new DMaaPMRSubscriberConfig
                .Builder(" dav /gh. ss/ asd ", "")
                .setPortNumber(PORT_NUMBER)
                .setProtocol(HTTP_PROTOCOL)
                .setContentType(CONTENT_TYPE).build();

        URI actualURI = BaseDMaaPMRComponent.createSubscriberURI(badSubscriberConfig);
    }

    @Test
    public void testConvertToJsonStringGoodJsonStringList() {
        List<String> jsonMessage = Arrays.asList(
                "{\"message\":\"I'm Object 1 Message\"}",
                "{\"message\":\"I'm Object 2 Message\"}");

        String actualJSONMsg = BaseDMaaPMRComponent.convertToJsonString(jsonMessage);

        String expectedJSONMsg = "[{\"message\":\"I'm Object 1 Message\"}," +
                "{\"message\":\"I'm Object 2 Message\"}]";
        assertEquals("Convert a List of Strings to JSON is working fine", expectedJSONMsg, actualJSONMsg);

    }

    @Rule
    public ExpectedException expectedJsonProcessingException = ExpectedException.none();

    @Test
    public void testConvertToJsonStringBadJsonStringList() {
        expectedJsonProcessingException.expect(DCAEAnalyticsRuntimeException.class);
        expectedJsonProcessingException.expectCause(isA(JsonProcessingException.class));

        List<String> jsonMessage = Arrays.asList(
                "{\"message\":\"I'm Object 1 Message\"",
                "\"message\":\"I'm Object 2 Message\"");

        BaseDMaaPMRComponent.convertToJsonString(jsonMessage);
    }

    @Test
    public void testConvertToJsonStringWithEmptyList() {
        List<String> jsonMessage = Arrays.asList();
        String actualJSONMsg = BaseDMaaPMRComponent.convertToJsonString(jsonMessage);
        String expectedJSONMsg = "[]";
        assertEquals("Convert a List of Strings to JSON is working fine", expectedJSONMsg, actualJSONMsg);
    }

    @Test
    public void testConvertToJsonStringWithNullList() {
        String actualJSONMsg = BaseDMaaPMRComponent.convertToJsonString(null);
        String expectedJSONMsg = "[]";
        assertEquals("Convert a List of Strings to JSON is working fine", expectedJSONMsg, actualJSONMsg);
    }


    @Test
    public void testConvertJsonToStringMessagesGoodValues() {
        String inputJSONMsg = "[{\"message\":\"I'm Object 1 Message\"}," +
                "{\"message\":\"I'm Object 2 Message\"}]";
        List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(inputJSONMsg);
        assertThat(actualList, hasSize(2));
        assertThat(actualList, containsInAnyOrder(
                "{\"message\":\"I'm Object 1 Message\"}",
                "{\"message\":\"I'm Object 2 Message\"}"
        ));
    }

    @Test
    public void testConvertJsonToStringMessagesNoValues() {
        String inputJSONMsg = "[]";
        List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(inputJSONMsg);
        assertThat(actualList, hasSize(0));
    }

    @Test
    public void testConvertJsonToStringMessagesNullValues() {
        List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(null);
        assertThat(actualList, hasSize(0));
    }

    @Test
    public void testConvertJsonToStringMessagesEmptyValues() {
        List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages("  ");
        assertThat(actualList, hasSize(0));
    }

    @Rule
    public ExpectedException convertToJSONIOException = ExpectedException.none();

    @Test
    public void testConvertJsonToStringMessagesException() {
        convertToJSONIOException.expect(DCAEAnalyticsRuntimeException.class);
        convertToJSONIOException.expectCause(isA(IOException.class));

        String inputJSONMsg = "[\"{\"message\":\"I'm Object 1 Message\"}\"," +
                "\"{\"message\":\"I'm Object 2 Message\"}\"]";
        List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(inputJSONMsg);
        assertThat(actualList, hasSize(2));
        assertThat(actualList, containsInAnyOrder(
                "{\"message\":\"I'm Object 1 Message\"}",
                "{\"message\":\"I'm Object 2 Message\"}"
        ));
    }

    @Test
    public void testAddMessagesToRecoveryQueueAllGood() {
        DMaaPMRPublisherQueue dmaapMRPublisherQueue = mock(DMaaPMRPublisherQueue.class);
        given(dmaapMRPublisherQueue.addRecoverableMessages(Mockito.<String>anyList())).willReturn(0);
        given(dmaapMRPublisherQueue.getBatchQueueRemainingSize()).willReturn(0);
        List<String> messages = new ArrayList<String>();
        BaseDMaaPMRComponent.addMessagesToRecoveryQueue(dmaapMRPublisherQueue, messages);
    }

    @Rule
    public ExpectedException addQueueIllegalException = ExpectedException.none();

    @Test
    public void testAddMessagesToRecoveryQueueException() {
        addQueueIllegalException.expect(isA(DCAEAnalyticsRuntimeException.class));
        addQueueIllegalException.expectCause(isA(IllegalStateException.class));

        DMaaPMRPublisherQueue dmaapMRPublisherQueue = mock(DMaaPMRPublisherQueue.class);

        given(dmaapMRPublisherQueue.addRecoverableMessages(Mockito.<String>anyList()))
                .willThrow(IllegalStateException.class);
        List<String> messages = new ArrayList<String>();

        BaseDMaaPMRComponent.addMessagesToRecoveryQueue(dmaapMRPublisherQueue, messages);
    }


    @Test
    public void testResponseHandler() {
        HttpResponse mockHttpResponse = mock(HttpResponse.class);
        StatusLine mockStatusLine = mock(StatusLine.class);
        HttpEntity mockHttpEntity = mock(HttpEntity.class);
        // Could not mock EntityUtils as it's final class
        //EntityUtils mockEntityUtils = mock(EntityUtils.class);

        given(mockHttpResponse.getStatusLine()).willReturn(mockStatusLine);
        given(mockStatusLine.getStatusCode()).willReturn(200);
        given(mockHttpResponse.getEntity()).willReturn(null);
        //given(mockEntityUtils.toString()).willReturn("Test value");

        ResponseHandler<Pair<Integer, String>> responseHandler = BaseDMaaPMRComponent.responseHandler();
        try {
            Pair<Integer, String> mappedResponse = responseHandler.handleResponse(mockHttpResponse);
            assertTrue("Http response code returned properly ", mappedResponse.getLeft().equals(200));
            assertTrue("Http response body returned properly ", mappedResponse.getRight().equals(""));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void testCreateSubscriberResponse() {
        DMaaPMRSubscriberResponse dmaapMRSubscriberResponse =
                BaseDMaaPMRComponent.createSubscriberResponse(200, "Test Message", getTwoSampleMessages());

        assertThat(dmaapMRSubscriberResponse.getResponseCode(), is(200));
        assertEquals(dmaapMRSubscriberResponse.getResponseMessage(), "Test Message");
        assertThat(dmaapMRSubscriberResponse.getFetchedMessages().size(), is(2));

    }

    @Test
    public void testCreateSubscriberResponse_no_message() {
        DMaaPMRSubscriberResponse dmaapMRSubscriberResponse =
                BaseDMaaPMRComponent.createSubscriberResponse(200, "Test Message", null);

        assertThat(dmaapMRSubscriberResponse.getResponseCode(), is(200));
        assertEquals(dmaapMRSubscriberResponse.getResponseMessage(), "Test Message");
        assertThat(dmaapMRSubscriberResponse.getFetchedMessages().size(), is(0));

    }

}