Update MSO change-management URL
[vid.git] / vid-automation / src / test / java / org / onap / vid / more / LoggerFormatTest.java
1 package org.onap.vid.more;
2
3 import static java.util.Collections.reverse;
4 import static java.util.stream.Collectors.toList;
5 import static org.hamcrest.CoreMatchers.containsString;
6 import static org.hamcrest.CoreMatchers.is;
7 import static org.hamcrest.MatcherAssert.assertThat;
8 import static org.hamcrest.Matchers.allOf;
9 import static org.hamcrest.Matchers.contains;
10 import static org.hamcrest.Matchers.containsInAnyOrder;
11 import static org.hamcrest.Matchers.containsInRelativeOrder;
12 import static org.hamcrest.Matchers.greaterThan;
13 import static org.hamcrest.Matchers.greaterThanOrEqualTo;
14 import static org.hamcrest.Matchers.hasSize;
15 import static vid.automation.test.services.SimulatorApi.retrieveRecordedRequests;
16
17 import com.fasterxml.jackson.databind.JsonNode;
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Map;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.logging.log4j.LogManager;
28 import org.apache.logging.log4j.Logger;
29 import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubscribersGet;
30 import org.onap.vid.api.BaseApiTest;
31 import org.springframework.web.client.RestTemplate;
32 import org.testng.annotations.BeforeClass;
33 import org.testng.annotations.Test;
34 import vid.automation.test.services.SimulatorApi;
35 import vid.automation.test.services.SimulatorApi.RecordedRequests;
36
37 public class LoggerFormatTest extends BaseApiTest {
38
39     private final static String logChecker = System.getProperty("EELF_LOG_CHECKER", "http://my-logchecker:8888/validate");
40     private final Logger logger = LogManager.getLogger(LoggerFormatTest.class);
41
42     public enum LogName {
43         audit, error, audit2019, metrics2019, metrics
44     }
45
46     @BeforeClass
47     public void login() {
48         super.login();
49     }
50
51     @BeforeClass
52     public void setAaiSubscribers() {
53         SimulatorApi.registerExpectationFromPreset(new PresetAAIGetSubscribersGet(), SimulatorApi.RegistrationStrategy.CLEAR_THEN_SET);
54     }
55
56     @Test
57     public void validateAuditLogsFormat() {
58         validateLogsFormat(LogName.audit);
59     }
60
61     @Test
62     public void validateAudit2019LogsFormat() {
63         validateLogsFormat(LogName.audit2019, "audit-ELS-2019.11", 0);
64     }
65
66     @Test(enabled = false) // no total-score is returned for error-log
67     public void validateErrorLogsFormat() {
68         validateLogsFormat(LogName.error);
69     }
70
71     @Test
72     public void validateMetricsLogsFormat() {
73         validateLogsFormat(LogName.metrics, "metric");
74     }
75
76     @Test
77     public void validateMetrics2019LogsFormat() {
78         validateLogsFormat(LogName.metrics2019, "metric-ELS-2019.11");
79     }
80
81     private void validateLogsFormat(LogName logName) {
82         validateLogsFormat(logName, logName.name());
83     }
84
85     private void validateLogsFormat(LogName logName, String logType) {
86         validateLogsFormat(logName, logType, 0.95);
87     }
88
89     private void validateLogsFormat(LogName logName, String logType, double score) {
90
91         String logLines = getLogLines(logName);
92         logger.info("logLines are: "+logLines);
93         JsonNode response = getCheckerResults(logType, logLines);
94         logger.info("Response is:" + response.toString());
95
96         int total_records = response.path("summary").path("total_records").asInt();
97         int valid_records = response.path("summary").path("valid_records").asInt();
98
99         assertThat(total_records, greaterThan(30)); //make sure we have at least 30 total records
100         assertThat((double)valid_records/total_records, is(greaterThanOrEqualTo(score)));
101     }
102
103     private String getLogLines(LogName logname) {
104         return getLogLines(logname, 5000, 30, restTemplate, uri);
105     }
106
107     public static String getLogLines(LogName logname, int maxRows, int minRows, RestTemplate restTemplate, URI uri) {
108         String logLines = restTemplate.getForObject(uri + "/logger/" + logname.name() + "?limit={maxRows}", String.class, maxRows);
109         assertThat("expecting at least " + minRows + " rows in " + logname.name(),
110                 StringUtils.countMatches(logLines, '\n') + 1,
111                 is(greaterThanOrEqualTo(minRows)));
112         return logLines;
113     }
114
115     /**
116      * @return Chronological-ordered list of recent log-lines of a given requestId
117      */
118     public static List<String> getRequestLogLines(String requestId, LogName logname, RestTemplate restTemplate, URI uri) {
119         String logLines = LoggerFormatTest.getLogLines(logname, 30, 1, restTemplate, uri);
120
121         // Split
122         List<String> lines = new ArrayList<>(Arrays.asList(logLines.split("(\\r?\\n)")));
123
124         // Filter
125         lines.removeIf(line -> !StringUtils.containsIgnoreCase(line, requestId));
126
127         // Reverse
128         reverse(lines);
129
130         return lines;
131     }
132
133     public static void assertHeadersAndMetricLogs(RestTemplate restTemplate, URI uri, String requestId, String path, int requestsSize) {
134         List<String> logLines =
135             getRequestLogLines(requestId, LogName.metrics2019, restTemplate, uri);
136
137         List<RecordedRequests> requests = retrieveRecordedRequests();
138         List<RecordedRequests> underTestRequests =
139             requests.stream().filter(x->x.path.contains(path)).collect(toList());
140
141         assertThat(underTestRequests, hasSize(requestsSize));
142
143         underTestRequests.forEach(request-> {
144             assertThat("X-ONAP-RequestID", request.headers.get("X-ONAP-RequestID"), contains(requestId));
145             assertThat("X-ECOMP-RequestID", request.headers.get("X-ECOMP-RequestID"), contains(requestId));
146             assertThat("X-ONAP-PartnerName", request.headers.get("X-ONAP-PartnerName"), contains("VID.VID"));
147         });
148
149         List<String> allInvocationIds = new LinkedList<>();
150
151         underTestRequests.forEach(request->{
152
153             List<String> invocationIds = request.headers.get("X-InvocationID");
154             assertThat(invocationIds, hasSize(1));
155
156             String invocationId = invocationIds.get(0);
157             allInvocationIds.add(invocationId);
158
159             assertThat("request id  and invocation id must be found in exactly two rows",
160                 logLines,
161                 containsInRelativeOrder(
162                     allOf(
163                         containsString("RequestID="+requestId),
164                         containsString("InvocationID="+ invocationId),
165                         containsString("Invoke")),
166                     allOf(
167                         containsString("RequestID="+requestId),
168                         containsString("InvocationID="+ invocationId),
169                         containsString("InvokeReturn"))
170                 ));
171         });
172         //make sure no InvocationId is repeated twice
173         assertThat("expect all InvocationIds to be unique",
174             allInvocationIds, containsInAnyOrder(new HashSet<>(allInvocationIds).toArray()));
175     }
176
177     private JsonNode getCheckerResults(String logtype, String logLines) {
178         Map<String, String> params = new HashMap<>();
179         params.put("format", "raw");
180         params.put("type", logtype);
181         params.put("component", "vid");
182         params.put("data", logLines);
183
184         return restTemplate.postForObject(logChecker, params, JsonNode.class);
185     }
186 }