diff options
author | Luke Parker <lparker@amdocs.com> | 2018-05-08 19:32:41 +1000 |
---|---|---|
committer | Luke Parker <lparker@amdocs.com> | 2018-05-08 19:40:52 +1000 |
commit | abbbaf088ace3917f6cd7839279bd07816e94f80 (patch) | |
tree | cd614bd0cbfa6d8f52a6865c026db8c93f4b997e /reference/slf4j-reference/src/test/java/org | |
parent | 7d1d7a47216de107fdc077f22c8087f8d40d4da9 (diff) |
SLF4J adapter (in 'common') + call graph demo
Issue-ID: LOG-115
Change-Id: I0ba28c64b1aaeb571094409704f4f00313afdf36
Signed-off-by: Luke Parker <lparker@amdocs.com>
Diffstat (limited to 'reference/slf4j-reference/src/test/java/org')
14 files changed, 1427 insertions, 0 deletions
diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/CallGraphTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/CallGraphTest.java new file mode 100644 index 0000000..3d123e0 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/CallGraphTest.java @@ -0,0 +1,207 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.nio.file.Files; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.logging.ref.slf4j.analysis.CallGraphAnalyzer; +import org.onap.logging.ref.slf4j.analysis.CallGraphReportWriter; +import org.onap.logging.ref.slf4j.analysis.LogEntry; +import org.onap.logging.ref.slf4j.demo.bean.Request; +import org.onap.logging.ref.slf4j.demo.bean.Response; +import org.onap.logging.ref.slf4j.demo.component.AbstractComponentTest; +import org.onap.logging.ref.slf4j.demo.component.alpha.ComponentAlpha; +import org.slf4j.LoggerFactory; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.Assert; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * Simple verification that we can easily get a call graph out of + * some calls to logging via <tt>ONAPLogAdapter</tt>. + */ +public class CallGraphTest { + + /** Temporary directory into which logfiles are written. */ + private static File sDir; + + @BeforeSuite + public static void setUp() throws Exception { + AbstractComponentTest.setInProcess(); + sDir = Files.createTempDirectory(CallGraphTest.class.getName()).toFile(); + System.getProperties().setProperty("SLF4J_OUTPUT_DIRECTORY", sDir.getAbsolutePath()); + LoggerFactory.getLogger(CallGraphTest.class).info("Starting."); + } + + @AfterSuite + public static void tearDown() throws Exception { + LoggerFactory.getLogger(CallGraphTest.class).info("Ending."); + Thread.sleep(1000L); + if (sDir != null) { + System.err.println("Should be deleting [" + sDir.getAbsolutePath() + "]..."); + } + } + + @Test(enabled = false) + public void testSimple() throws Exception { + + final HttpServletRequest mock = new MockHttpServletRequest(); + final ComponentAlpha a = new ComponentAlpha(); + final Request request = new Request(); + final Response response = a.execute(request, mock); + assertThat(response.getResponses().size(), is(0)); + } + + /** + * A more complex (interesting) example of generating a call graph. + * @throws Exception test failure. + */ + @Test + public void testComplex() throws Exception { + + Assert.assertNotNull(sDir); + + // Fan out some requests between test components. + + final Request a = new Request(); + a.setService("alpha"); + + final Request b = new Request(); + b.setService("beta"); + + final Request ac = new Request(); + ac.setService("gamma"); + + final Request ad = new Request(); + ad.setService("delta"); + + final Request bc1 = new Request(); + bc1.setService("gamma"); + + final Request bc2 = new Request(); + bc2.setService("gamma"); + + a.getRequests().add(b); + a.getRequests().add(ac); + a.getRequests().add(ad); + b.getRequests().add(bc1); + b.getRequests().add(bc2); + + // Deeper. + + final Request xb = new Request(); + xb.setService("beta"); + + final Request xg = new Request(); + xg.setService("gamma"); + + final Request xd = new Request(); + xd.setService("delta"); + + a.getRequests().add(xb); + xb.getRequests().add(xg); + xg.getRequests().add(xd); + + // Execute. + + final HttpServletRequest mock = new MockHttpServletRequest(); + final ComponentAlpha component = new ComponentAlpha(); + final Response response = component.execute(a, mock); + System.err.println(response); + + assertThat(response.getResponses().size(), is(4)); + + Thread.sleep(1000L); + + // Find logfile. + + File log = null; + for (final File candidate : sDir.listFiles()) { + if (candidate.getName().endsWith(".log")) { + log = candidate; + break; + } + } + + Assert.assertNotNull(log); + + System.err.println("READING LOGFILE: " + log.getAbsolutePath()); + + final CallGraphAnalyzer analyzer = new CallGraphAnalyzer(); + try (final BufferedReader reader = new BufferedReader(new FileReader(log))) { + while (true) { + + final String line = reader.readLine(); + if (line == null) { + break; + } + + final LogEntry entry = new LogEntry(line); + analyzer.add(entry); + } + } + + // + // Debug during dev, but annoying the rest of the time. + // + // System.err.println("--------------------------------------------------"); + // for (final LogEntry e : analyzer.getEntries()) { + // System.err.println(e.toShortString()); + // } + // System.err.println("--------------------------------------------------"); + + final CallGraphReportWriter writer = new CallGraphReportWriter(analyzer); + final String shortReport = writer.getShortReport(); + final String longReport = writer.getLongReport(); + + // Dump long report. + + System.out.println("----\nGraph:\n\n" + longReport + "\n----"); + + // Validate short report. + + assertThat("Alpha\n" + + " Beta\n" + + " Gamma\n" + + " Gamma\n" + + " Gamma\n" + + " Delta\n" + + " Beta\n" + + " Gamma\n" + + " Delta\n", + is(shortReport)); + + // Ensure output reaches System.xxx. + + Thread.sleep(1000L); + } +}
\ No newline at end of file diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/CallGraphAnalyzer.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/CallGraphAnalyzer.java new file mode 100644 index 0000000..208b3e1 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/CallGraphAnalyzer.java @@ -0,0 +1,114 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.analysis; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +/** + * Crude analyzer for log messages, to build a simple + * representation of the call graph. + */ +public class CallGraphAnalyzer { + + /** Messages of interest. */ + private List<LogEntry> mEntries = new ArrayList<>(); + + /** + * Capture entry if it's interesting. + * @param entry candidate. + * @return this. + */ + public CallGraphAnalyzer add(final LogEntry entry) { + + if (entry.getLogger().contains("ONAPLogAdapterTest")) { + return this; + } + + if (StringUtils.isNotBlank(entry.getMarkers())) { + this.mEntries.add(entry); + } + + return this; + } + + /** + * Get all captured entries, for diagnostics only. + * @return entries. + */ + public List<LogEntry> getEntries() { + return this.mEntries; + } + + /** + * Find the entry point into the call graph through the various components. + * @return entry point or (failure) null. + */ + public LogEntry findEntryPoint() { + for (final LogEntry e : this.mEntries) { + if (e.getLogger().endsWith("ComponentAlpha")) { + if ("ENTRY".equals(e.getMarkers())) { + if (StringUtils.isBlank(e.getPartnerName())) { + return e; + } + } + } + } + return null; + } + + /** + * Find entries for where a component invokes others. + * @param parent parent ENTRY (not actually the entry where it's doing the invoking). + * @return components invoked by this one. + */ + public List<LogEntry> findInvokes(final LogEntry parent) { + final List<LogEntry> invokes = new ArrayList<>(); + for (final LogEntry e : this.mEntries) { + if (StringUtils.equals(parent.getInvocationID(), e.getInvocationID())) { + final String invokingID = e.getInvokingID(); + if (StringUtils.isNotBlank(invokingID)) { + invokes.add(e); + } + } + } + return invokes; + } + + /** + * Find a specific invocation. + * @param invoke invocation record. + * @return invocation ENTRY, or (failure) null if not found. + */ + public LogEntry findInvocation(final LogEntry invoke) { + for (final LogEntry e : this.mEntries) { + if ("ENTRY".equals(e.getMarkers())) { + if (StringUtils.equals(invoke.getInvokingID(), e.getInvocationID())) { + return e; + } + } + } + return null; + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/CallGraphReportWriter.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/CallGraphReportWriter.java new file mode 100644 index 0000000..ee67b35 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/CallGraphReportWriter.java @@ -0,0 +1,111 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.analysis; + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.testng.Assert; + +/** + * A simple, recursive text-only report writer for the call graph. + */ +public class CallGraphReportWriter { + + /** The analyzer which does the work. */ + final CallGraphAnalyzer mAnalyzer; + + /** Short report, for validation. */ + final StringBuilder mShortReport = new StringBuilder(); + + /** Longer report, for human eyes. */ + final StringBuilder mLongReport = new StringBuilder(); + + /** + * Construct writer. + * @param analyzer initialized analyzer. + */ + public CallGraphReportWriter(final CallGraphAnalyzer analyzer) { + + this.mAnalyzer = analyzer; + + Assert.assertTrue(analyzer.getEntries().size() > 0); + final LogEntry e0 = analyzer.findEntryPoint(); + Assert.assertNotNull(e0); + + this.mLongReport.append(e0.toShortString()).append("\n"); + this.mShortReport.append(StringUtils.substringAfter(e0.getLogger(), ".Component")).append("\n"); + + this.report(e0, 1); + + } + + /** + * Recursively analyze. + * @param invoker entry point. + * @param depth recursive depth, for handbrake. + */ + private void report(final LogEntry invoker, final int depth) { + + if (depth > 100) { + throw new AssertionError("Recursion ad infinitum"); + } + + final List<LogEntry> invokes0 = this.mAnalyzer.findInvokes(invoker); + for (final LogEntry invoke0 : invokes0) { + + final LogEntry invoked0 = this.mAnalyzer.findInvocation(invoke0); + + Assert.assertNotNull(invoked0); + + final String indent = StringUtils.repeat(' ', depth * 4); + this.mLongReport.append(indent).append(invoked0.toShortString()).append('\n'); + this.mShortReport.append(indent).append(StringUtils.substringAfter(invoked0.getLogger(), ".Component")).append('\n'); + + report(invoked0, depth + 1); + } + } + + /** + * Get report. + * @return short report, for validation. + */ + public String getShortReport() { + return this.mShortReport.toString(); + } + + /** + * Get report. + * @return long report, for printing out. + */ + public String getLongReport() { + return this.mLongReport.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return this.getLongReport(); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/LogEntry.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/LogEntry.java new file mode 100644 index 0000000..b9bd48f --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/LogEntry.java @@ -0,0 +1,238 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.analysis; + +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.slf4j.event.Level; + +/** + * Test class for reading a logentry during analysis. + */ +public class LogEntry { + + /** Property. */ + private final Date mTimestamp; + + /** Property. */ + private final String mThread; + + /** Property. */ + private final Level mLevel; + + /** Property. */ + private final String mLogger; + + /** Property. */ + private final String mMessage; + + /** Property. */ + private final String mException; + + /** Property. */ + private final Map<String, String> mMDCs; + + /** Property. */ + private final String mMarkers; + + /** + * Construct from log line. + * @param line to be parsed. + */ + public LogEntry(final String line) { + + final String [] tokens = line.split("\t", -1); + if (tokens.length < 8) { + throw new IllegalArgumentException("Unsupported line (expected 8+ tokens, got " + + tokens.length + "): " + line); + } + + int index = 0; + + this.mTimestamp = DatatypeConverter.parseDateTime(tokens[index++]).getTime(); + this.mThread = tokens[index++]; + this.mLevel = Level.valueOf(tokens[index++].trim()); + this.mLogger = tokens[index++]; + + this.mMDCs = parseMDCs(tokens[index++]); + this.mMessage = tokens[index++]; + this.mException = tokens[index++]; + this.mMarkers = tokens[index++]; + } + + /** + * Parse serialized MDCs. + * @param mdc serialized DMC map. + * @return parsed. + */ + static Map<String, String> parseMDCs(final String mdc) { + + final Map<String, String> mdcs = new HashMap<>(); + for (final String token : mdc.split(",")) { + final String[] mdcTokens = token.split("="); + if (mdcTokens.length == 2) { + mdcs.put(StringUtils.trim(mdcTokens[0]), StringUtils.trim(mdcTokens[1])); + } + } + return Collections.unmodifiableMap(mdcs); + } + + /** + * Getter. + * @return property. + */ + public Date getTimestamp() { + return this.mTimestamp; + } + + /** + * Getter. + * @return property. + */ + public String getThread() { + return this.mThread; + } + + /** + * Getter. + * @return property. + */ + public Level getLevel() { + return this.mLevel; + } + + /** + * Getter. + * @return property. + */ + public String getLogger() { + return this.mLogger; + } + + /** + * Getter. + * @return property. + */ + public String getMessage() { + return this.mMessage; + } + + /** + * Getter. + * @return property. + */ + public String getException() { + return this.mException; + } + + /** + * Getter. + * @return property. + */ + public Map<String, String> getMDCs() { + return this.mMDCs; + } + + /** + * Getter. + * @return property. + */ + public String getMarkers() { + return this.mMarkers; + } + + /** + * Getter. + * @return property. + */ + public String getRequestID() { + return this.getMDCs().get("RequestID"); + } + + /** + * Getter. + * @return property. + */ + public String getInvocationID() { + return this.getMDCs().get("InvocationID"); + } + + /** + * Getter. + * @return property. + */ + public String getPartnerName() { + return this.getMDCs().get("PartnerName"); + } + + /** + * Getter. + * @return property. + */ + public String getInvokingID() { + if (StringUtils.defaultString(this.getMarkers()).startsWith("INVOKE")) { + return this.getMessage(); + } + return null; + } + + /** + * Getter. + * @return property. + */ + public String toShortString() { + final StringBuilder buf = new StringBuilder(); + buf.append("LogEntry(markers=").append(StringUtils.defaultString(this.getMarkers())); + buf.append(", logger=").append(this.getLogger().substring(1 + this.getLogger().lastIndexOf("."))); + if (StringUtils.isNotBlank(this.getRequestID())) { + buf.append(", requestID=[...]").append(StringUtils.right(this.getRequestID(), 8)); + } + if (StringUtils.isNotBlank(this.getInvocationID())) { + buf.append(", invocationID=[...]").append(StringUtils.right(this.getInvocationID(), 8)); + } + if (StringUtils.isNotBlank(this.getInvokingID())) { + buf.append(", invokingID=[...]").append(StringUtils.right(this.getInvokingID(), 8)); + } + + final Calendar c = Calendar.getInstance(); + c.setTime(this.getTimestamp()); + + buf.append(", timestamp=").append(DatatypeConverter.printDateTime(c)); + return buf.append(")").toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/LogEntryTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/LogEntryTest.java new file mode 100644 index 0000000..63ead27 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/analysis/LogEntryTest.java @@ -0,0 +1,71 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.analysis; + +import java.util.Map; + +import org.slf4j.event.Level; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNull.notNullValue; + +public class LogEntryTest { + + @Test + public void testLogEntry() { + + final String eg = "2018-05-07T16:45:53.056Z\tpool-1-thread-1\tINFO" + + "\torg.onap.logging.ref.slf4j.component.gamma.ComponentGamma\tInstanceUUID=fa8dd337-6991-4535-a069-ca552466d972," + + " RequestID=46161759-1b92-40a4-a408-800e0d62dd9e, ServiceName=service.alpha, EntryTimestamp=2018-05-08T02:45:53.056," + + " InvocationID=aac8fec9-498c-42a2-936b-38f5c0f5ca82, PartnerName=service.beta, ClientIPAddress=127.0.0.1," + + " ServerFQDN=localhost\t\t\tENTRY\t\n"; + + final LogEntry parsed = new LogEntry(eg); + assertThat(parsed.getTimestamp(), notNullValue()); + assertThat(parsed.getThread(), is("pool-1-thread-1")); + assertThat(parsed.getLevel(), is(Level.INFO)); + assertThat(parsed.getLogger(), is("org.onap.logging.ref.slf4j.component.gamma.ComponentGamma")); + assertThat(parsed.getMDCs().get("ServiceName"), is("service.alpha")); + assertThat(parsed.getMDCs().get("PartnerName"), is("service.beta")); + assertThat(parsed.getMessage(), is("")); + assertThat(parsed.getMarkers(), is("ENTRY")); + assertThat(parsed.getException(), is("")); + + } + + @Test + public void testParseMDCsEmpty() { + final Map<String, String> map = LogEntry.parseMDCs(""); + assertThat(map.size(), is(0)); + } + + @Test + public void testParseMDCs() { + final Map<String, String> map = LogEntry.parseMDCs("A=B, C=D , D = F "); + assertThat(map.get("A"), is("B")); + assertThat(map.get("C"), is("D")); + assertThat(map.get("D"), is("F")); + assertThat(map.size(), is(3)); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/common/ONAPLogAdapterTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/common/ONAPLogAdapterTest.java new file mode 100644 index 0000000..60ee60f --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/common/ONAPLogAdapterTest.java @@ -0,0 +1,266 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.common; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.event.Level; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; + +/** + * Tests for {@link ONAPLogAdapter}. + */ +public class ONAPLogAdapterTest { + + /** + * Ensure that MDCs are cleared after each testcase. + */ + @AfterMethod + public void resetMDCs() { + MDC.clear(); + } + + /** + * Test nullcheck. + */ + @Test + public void testCheckNotNull() { + + ONAPLogAdapter.checkNotNull(""); + + try { + ONAPLogAdapter.checkNotNull(null); + Assert.fail("Should throw NullPointerException"); + } + catch (final NullPointerException e) { + + } + } + + /** + * Test defaulting of nulls. + */ + @Test + public void testDefaultToEmpty() { + assertThat(ONAPLogAdapter.defaultToEmpty("123"), is("123")); + assertThat(ONAPLogAdapter.defaultToEmpty(Integer.valueOf(1984)), is("1984")); + assertThat(ONAPLogAdapter.defaultToEmpty(null), is("")); + } + + /** + * Test defaulting of nulls. + */ + @Test + public void testDefaultToUUID() { + assertThat(ONAPLogAdapter.defaultToUUID("123"), is("123")); + UUID.fromString(ONAPLogAdapter.defaultToUUID(null)); + } + + /** + * Test ENTERING. + */ + @Test + public void testEntering() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + http.setRequestURI("uri123"); + http.setServerName("local123"); + http.setRemoteAddr("remote123"); + http.addHeader("X-ONAP-RequestID", "request123"); + http.addHeader("X-ONAP-InvocationID", "invocation123"); + http.addHeader("X-ONAP-PartnerName", "partner123"); + + try { + adapter.getServiceDescriptor().setServiceName("uri123"); + adapter.entering(http); + final Map<String, String> mdcs = MDC.getCopyOfContextMap(); + assertThat(mdcs.get("RequestID"), is("request123")); + assertThat(mdcs.get("InvocationID"), is("invocation123")); + assertThat(mdcs.get("PartnerName"), is("partner123")); + assertThat(mdcs.get("ServiceName"), is("uri123")); + assertThat(mdcs.get("ServerFQDN"), is("local123")); + assertThat(mdcs.get("ClientIPAddress"), is("remote123")); + } + finally { + MDC.clear(); + } + } + + /** + * Test EXITING. + */ + @Test + public void testExiting() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + try { + MDC.put("somekey", "somevalue"); + assertThat(MDC.get("somekey"), is("somevalue")); + adapter.exiting(); + assertThat(MDC.get("somekey"), nullValue()); + } + finally { + MDC.clear(); + } + } + + /** + * Test INVOKE. + */ + @Test + public void testInvokeSyncAsyncNull() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final UUID syncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(syncUUID, notNullValue()); + + final UUID asyncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(asyncUUID, notNullValue()); + + final UUID agnosticUUID = adapter.invoke((ONAPLogConstants.InvocationMode)null); + assertThat(agnosticUUID, notNullValue()); + + } + + /** + * Test INVOKE, with RequestAdapter. + */ + @Test + public void testInvokeWithAdapter() throws Exception { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final Map<String, String> headers = new HashMap<>(); + final ONAPLogAdapter.RequestBuilder builder = new ONAPLogAdapter.RequestBuilder<ONAPLogAdapter.RequestBuilder>() { + @Override + public ONAPLogAdapter.RequestBuilder setHeader(final String name, final String value) { + headers.put(name, value); + return this; + } + }; + + try { + final UUID uuid = adapter.invoke(builder, ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(uuid, notNullValue()); + assertThat(headers.get(ONAPLogConstants.Headers.INVOCATION_ID), is(uuid.toString())); + assertThat(headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME), is(true)); + assertThat(headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID), is(true)); + } + finally { + MDC.clear(); + } + } + + /** + * Exercise the contract, for a caller that's happy to have their + * service name automatically derived. (This validates nothing + * and achieves nothing; it's just to provide an example of minimal usage). + */ + @Test + public void testContract() { + + // Note no wrapper around HttpServletRequest, which will work for + // most invocations (since they come via HTTP), but otherwise + // can implement your own RequestAdapter. + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + + // Immediately log ENTERING marker, with global MDCs. + + adapter.entering(http); + try { + + // Generate (and log) an invocationID, then use it to + // invoke another component. + + final RESTClient client = new RESTClient(); // implements ONAPLogAdapter.RequestBuilder<RESTClient>. + adapter.invoke(client, ONAPLogConstants.InvocationMode.SYNCHRONOUS); + final RESTRequest request = null; // TODO: build real request. + final RESTResponse response = client.execute(request); // TODO: handle real response. + + // Set response details prior to #exiting. + // (Obviously there'd be errorhandling, etc. IRL). + + adapter.getResponseDescriptor() + .setResponseCode((String)null) + .setResponseSeverity(Level.INFO) + .setResponseStatus(ONAPLogConstants.ResponseStatus.COMPLETED); + } + finally { + + // Return, logging EXIT marker, with response MDCs. + + adapter.exiting(); + } + } + + /** + * Dummy class, for example code. + */ + static class RESTClient implements ONAPLogAdapter.RequestBuilder<RESTClient> { + + @Override + public RESTClient setHeader(final String name, final String value) { + return null; + } + + RESTResponse execute(RESTRequest request) { + return null; + } + } + + /** + * Dummy class, for example code. + */ + static class RESTRequest { + + } + + /** + * Dummy class, for example code. + */ + static class RESTResponse { + + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/common/ONAPLogConstantsTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/common/ONAPLogConstantsTest.java new file mode 100644 index 0000000..aa0f7ae --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/common/ONAPLogConstantsTest.java @@ -0,0 +1,86 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.common; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; + +/** + * Tests for {@link ONAPLogConstants}. + */ +public class ONAPLogConstantsTest { + + @Test + public void testConstructor() throws Exception { + try { + ONAPLogConstants.class.getDeclaredConstructors()[0].newInstance(); + Assert.fail("Should fail for hidden constructor."); + } + catch (final IllegalAccessException e) { + + } + } + + @Test + public void testConstructorUnsupported() throws Exception { + try { + Constructor<?> c = ONAPLogConstants.class.getDeclaredConstructors()[0]; + c.setAccessible(true); + c.newInstance(); + Assert.fail("Should fail for hidden constructor."); + } + catch (final InvocationTargetException e) { + assertThat(e.getCause(), instanceOf(UnsupportedOperationException.class)); + } + } + + @Test + public void testHeaders() { + assertThat(ONAPLogConstants.Headers.REQUEST_ID.toString(), is("X-ONAP-RequestID")); + assertThat(ONAPLogConstants.Headers.INVOCATION_ID.toString(), is("X-ONAP-InvocationID")); + assertThat(ONAPLogConstants.Headers.PARTNER_NAME.toString(), is("X-ONAP-PartnerName")); + } + + @Test + public void testMarkers() { + assertThat(ONAPLogConstants.Markers.ENTRY.toString(), is("ENTRY")); + assertThat(ONAPLogConstants.Markers.EXIT.toString(), is("EXIT")); + assertThat(ONAPLogConstants.Markers.INVOKE.toString(), is("INVOKE")); + assertThat(ONAPLogConstants.Markers.INVOKE_ASYNCHRONOUS.toString(), is("INVOKE [ ASYNCHRONOUS ]")); + assertThat(ONAPLogConstants.Markers.INVOKE_SYNCHRONOUS.toString(), is("INVOKE [ SYNCHRONOUS ]")); + } + + @Test + public void testInvocationMode() { + assertThat(ONAPLogConstants.InvocationMode.SYNCHRONOUS.getMarker(), + is(ONAPLogConstants.Markers.INVOKE_SYNCHRONOUS)); + assertThat(ONAPLogConstants.InvocationMode.ASYNCHRONOUS.getMarker(), + is(ONAPLogConstants.Markers.INVOKE_ASYNCHRONOUS)); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/bean/RequestTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/bean/RequestTest.java new file mode 100644 index 0000000..6c622a7 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/bean/RequestTest.java @@ -0,0 +1,64 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.demo.bean; + +import org.json.JSONObject; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class RequestTest { + + @Test + public void testRoundtrip() { + + final Request in = new Request(); + in.setCode("code0"); + in.setService("service0"); + in.setSeverity("severity0"); + + final Request childA = new Request(); + childA.setCode("codeA"); + childA.setService("serviceA"); + childA.setSeverity("severityA"); + + final Request childB = new Request(); + childB.setCode("codeB"); + childB.setService("serviceB"); + childB.setSeverity("severityB"); + + in.getRequests().add(childA); + in.getRequests().add(childB); + + System.out.println(in.toString()); + System.out.println(new JSONObject(in.toString()).toString()); + + final Request out = Request.fromJSON(new JSONObject(in.toString())); + assertThat(out.getCode(), is(in.getCode())); + assertThat(out.getService(), is(in.getService())); + assertThat(out.getSeverity(), is(in.getSeverity())); + assertThat(out.getRequests().size(), is(2)); + assertThat(out.getRequests().get(0).getCode(), is("codeA")); + assertThat(out.getRequests().get(1).getCode(), is("codeB")); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/bean/ResponseTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/bean/ResponseTest.java new file mode 100644 index 0000000..63cc68e --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/bean/ResponseTest.java @@ -0,0 +1,61 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.demo.bean; + +import org.json.JSONObject; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class ResponseTest { + + @Test + public void testRoundtrip() { + + final Response in = new Response(); + in.setCode("code0"); + in.setSeverity("severity0"); + + final Response childA = new Response(); + childA.setCode("codeA"); + childA.setSeverity("severityA"); + + final Response childB = new Response(); + childB.setCode("codeB"); + childB.setSeverity("severityB"); + + in.getResponses().add(childA); + in.getResponses().add(childB); + + System.out.println(in.toString()); + System.out.println(new JSONObject(in.toString()).toString()); + + final Response out = Response.fromJSON(new JSONObject(in.toString())); + assertThat(out.getCode(), is(in.getCode())); + assertThat(out.getSeverity(), is(in.getSeverity())); + assertThat(out.getResponses().size(), is(2)); + assertThat(out.getResponses().get(0).getCode(), is("codeA")); + assertThat(out.getResponses().get(1).getCode(), is("codeB")); + + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/AbstractComponentTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/AbstractComponentTest.java new file mode 100644 index 0000000..5275853 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/AbstractComponentTest.java @@ -0,0 +1,29 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.demo.component; + +public class AbstractComponentTest { + + public static void setInProcess() { + AbstractComponent.setInProcess(); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/alpha/ComponentAlphaTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/alpha/ComponentAlphaTest.java new file mode 100644 index 0000000..50cd80a --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/alpha/ComponentAlphaTest.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.demo.component.alpha; + +import java.util.UUID; + +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * Tests for {@link ComponentAlpha}. + */ +public class ComponentAlphaTest { + + @Test + public void testGetId() { + assertThat(new ComponentAlpha().getId(), is("alpha")); + } + + @Test + public void testGetInstanceUUID() { + UUID.fromString(new ComponentAlpha().getInstanceUUID()); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/beta/ComponentBetaTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/beta/ComponentBetaTest.java new file mode 100644 index 0000000..20f4d72 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/beta/ComponentBetaTest.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.demo.component.beta; + +import java.util.UUID; + +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * Tests for {@link ComponentBeta}. + */ +public class ComponentBetaTest { + + @Test + public void testGetId() { + assertThat(new ComponentBeta().getId(), is("beta")); + } + + @Test + public void testGetInstanceUUID() { + UUID.fromString(new ComponentBeta().getInstanceUUID()); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/delta/ComponentDeltaTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/delta/ComponentDeltaTest.java new file mode 100644 index 0000000..53829a8 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/delta/ComponentDeltaTest.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.demo.component.delta; + +import java.util.UUID; + +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * Tests for {@link ComponentDelta}. + */ +public class ComponentDeltaTest { + + @Test + public void testGetId() { + assertThat(new ComponentDelta().getId(), is("delta")); + } + + @Test + public void testGetInstanceUUID() { + UUID.fromString(new ComponentDelta().getInstanceUUID()); + } +} diff --git a/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/gamma/ComponentGammaTest.java b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/gamma/ComponentGammaTest.java new file mode 100644 index 0000000..24222a6 --- /dev/null +++ b/reference/slf4j-reference/src/test/java/org/onap/logging/ref/slf4j/demo/component/gamma/ComponentGammaTest.java @@ -0,0 +1,45 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j.demo.component.gamma; + +import java.util.UUID; + +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +/** + * Tests for {@link ComponentGamma}. + */ +public class ComponentGammaTest { + + @Test + public void testGetId() { + assertThat(new ComponentGamma().getId(), is("gamma")); + } + + @Test + public void testGetInstanceUUID() { + UUID.fromString(new ComponentGamma().getInstanceUUID()); + } +} |