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