4a3f321cfee353f6965f59d1be33b7c8b30027a5
[policy/models.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. 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
21 package org.onap.policy.controlloop.actorserviceprovider;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotEquals;
27 import static org.junit.Assert.assertNull;
28 import static org.junit.Assert.assertTrue;
29
30 import ch.qos.logback.classic.Logger;
31 import java.util.LinkedHashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.TreeMap;
35 import java.util.concurrent.atomic.AtomicInteger;
36 import lombok.Builder;
37 import lombok.Data;
38 import org.junit.AfterClass;
39 import org.junit.Before;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
42 import org.onap.policy.common.utils.coder.CoderException;
43 import org.onap.policy.common.utils.coder.StandardCoder;
44 import org.onap.policy.common.utils.test.log.logback.ExtractAppender;
45 import org.slf4j.LoggerFactory;
46
47 public class UtilTest {
48     private static final String MY_REQUEST = "my-request";
49     private static final String URL = "my-url";
50     private static final String OUT_URL = "OUT|REST|my-url";
51     private static final String IN_URL = "IN|REST|my-url";
52     protected static final String EXPECTED_EXCEPTION = "expected exception";
53
54     /**
55      * Used to attach an appender to the class' logger.
56      */
57     private static final Logger logger = (Logger) LoggerFactory.getLogger(Util.class);
58     private static final ExtractAppender appender = new ExtractAppender();
59
60     /**
61      * Initializes statics.
62      */
63     @BeforeClass
64     public static void setUpBeforeClass() {
65         appender.setContext(logger.getLoggerContext());
66         appender.start();
67
68         logger.addAppender(appender);
69     }
70
71     @AfterClass
72     public static void tearDownAfterClass() {
73         appender.stop();
74     }
75
76     @Before
77     public void setUp() {
78         appender.clearExtractions();
79     }
80
81     @Test
82     public void testIdent() {
83         Object object = new Object();
84         String result = Util.ident(object).toString();
85
86         assertNotEquals(object.toString(), result);
87         assertThat(result).startsWith("@");
88         assertTrue(result.length() > 1);
89     }
90
91     @Test
92     public void testLogRestRequest() throws CoderException {
93         // log structured data
94         appender.clearExtractions();
95         Util.logRestRequest(URL, new Abc(10, null, null));
96         List<String> output = appender.getExtracted();
97         assertEquals(1, output.size());
98
99         assertThat(output.get(0)).contains(OUT_URL).contains("{\n  \"intValue\": 10\n}");
100
101         // log a plain string
102         appender.clearExtractions();
103         Util.logRestRequest(URL, MY_REQUEST);
104         output = appender.getExtracted();
105         assertEquals(1, output.size());
106
107         assertThat(output.get(0)).contains(OUT_URL).contains(MY_REQUEST);
108
109         // exception from coder
110         StandardCoder coder = new StandardCoder() {
111             @Override
112             public String encode(Object object, boolean pretty) throws CoderException {
113                 throw new CoderException(EXPECTED_EXCEPTION);
114             }
115         };
116
117         appender.clearExtractions();
118         Util.logRestRequest(coder, URL, new Abc(11, null, null));
119         output = appender.getExtracted();
120         assertEquals(2, output.size());
121         assertThat(output.get(0)).contains("cannot pretty-print request");
122         assertThat(output.get(1)).contains(OUT_URL);
123     }
124
125     @Test
126     public void testLogRestResponse() throws CoderException {
127         // log structured data
128         appender.clearExtractions();
129         Util.logRestResponse(URL, new Abc(10, null, null));
130         List<String> output = appender.getExtracted();
131         assertEquals(1, output.size());
132
133         assertThat(output.get(0)).contains(IN_URL).contains("{\n  \"intValue\": 10\n}");
134
135         // log null response
136         appender.clearExtractions();
137         Util.logRestResponse(URL, null);
138         output = appender.getExtracted();
139         assertEquals(1, output.size());
140
141         assertThat(output.get(0)).contains(IN_URL).contains("null");
142
143         // log a plain string
144         appender.clearExtractions();
145         Util.logRestResponse(URL, MY_REQUEST);
146         output = appender.getExtracted();
147         assertEquals(1, output.size());
148
149         assertThat(output.get(0)).contains(IN_URL).contains(MY_REQUEST);
150
151         // exception from coder
152         StandardCoder coder = new StandardCoder() {
153             @Override
154             public String encode(Object object, boolean pretty) throws CoderException {
155                 throw new CoderException(EXPECTED_EXCEPTION);
156             }
157         };
158
159         appender.clearExtractions();
160         Util.logRestResponse(coder, URL, new Abc(11, null, null));
161         output = appender.getExtracted();
162         assertEquals(2, output.size());
163         assertThat(output.get(0)).contains("cannot pretty-print response");
164         assertThat(output.get(1)).contains(IN_URL);
165     }
166
167     @Test
168     public void testRunFunction() {
169         // no exception, no log
170         AtomicInteger count = new AtomicInteger();
171         Util.runFunction(() -> count.incrementAndGet(), "no error");
172         assertEquals(1, count.get());
173         assertEquals(0, appender.getExtracted().size());
174
175         // with an exception
176         Runnable runnable = () -> {
177             count.incrementAndGet();
178             throw new IllegalStateException("expected exception");
179         };
180
181         appender.clearExtractions();
182         Util.runFunction(runnable, "error with no args");
183         List<String> output = appender.getExtracted();
184         assertEquals(1, output.size());
185         assertThat(output.get(0)).contains("error with no args");
186
187         appender.clearExtractions();
188         Util.runFunction(runnable, "error {} {} arg(s)", "with", 2);
189         output = appender.getExtracted();
190         assertEquals(1, output.size());
191         assertThat(output.get(0)).contains("error with 2 arg(s)");
192     }
193
194     @Test
195     public void testTranslate() {
196         // Abc => Abc
197         final Abc abc = Abc.builder().intValue(1).strValue("hello").anotherString("another").build();
198         Abc abc2 = Util.translate("abc to abc", abc, Abc.class);
199         assertEquals(abc, abc2);
200
201         // Abc => Similar
202         Similar sim = Util.translate("abc to similar", abc, Similar.class);
203         assertEquals(abc.getIntValue(), sim.getIntValue());
204         assertEquals(abc.getStrValue(), sim.getStrValue());
205
206         // Abc => Map
207         @SuppressWarnings("unchecked")
208         Map<String, Object> map = Util.translate("abc to map", abc, TreeMap.class);
209         assertEquals("{anotherString=another, intValue=1, strValue=hello}", map.toString());
210
211         // Map => Map
212         @SuppressWarnings("unchecked")
213         Map<String, Object> map2 = Util.translate("map to map", map, LinkedHashMap.class);
214         assertEquals(map.toString(), map2.toString());
215
216         // Map => Abc
217         abc2 = Util.translate("map to abc", map, Abc.class);
218         assertEquals(abc, abc2);
219     }
220
221     @Test
222     public void testTranslateToMap() {
223         assertNull(Util.translateToMap("map: null", null));
224
225         // Abc => Map
226         final Abc abc = Abc.builder().intValue(2).strValue("world").anotherString("some").build();
227         Map<String, Object> map = new TreeMap<>(Util.translateToMap("map: abc to map", abc));
228         assertEquals("{anotherString=some, intValue=2, strValue=world}", map.toString());
229
230         // Map => Map
231         Map<String, Object> map2 = Util.translateToMap("map: map to map", map);
232         assertEquals(map.toString(), map2.toString());
233
234         assertThatIllegalArgumentException().isThrownBy(() -> Util.translateToMap("map: string", "some string"))
235                         .withMessageContaining("map: string");
236     }
237
238     @Data
239     @Builder
240     public static class Abc {
241         private int intValue;
242         private String strValue;
243         private String anotherString;
244     }
245
246     // this shares some fields with Abc so the data should transfer
247     @Data
248     @Builder
249     public static class Similar {
250         private int intValue;
251         private String strValue;
252     }
253
254     // throws an exception when getXxx() is used
255     public static class DataWithException {
256         @SuppressWarnings("unused")
257         private int intValue;
258
259         public int getIntValue() {
260             throw new IllegalStateException();
261         }
262     }
263 }