Skip to content

Commit

Permalink
chore: add unit test for LoggingHandler (#813)
Browse files Browse the repository at this point in the history
rename unit tests to reflect the right configuration name being tested.
test log enhancers when redirecting to stdout.
  • Loading branch information
minherz committed Jan 5, 2022
1 parent 735275f commit 9e575b4
Showing 1 changed file with 31 additions and 2 deletions.
Expand Up @@ -21,6 +21,7 @@
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.google.api.client.util.Strings;
Expand Down Expand Up @@ -356,6 +357,34 @@ public void enhanceLogEntry(Builder builder) {
handler.publish(newLogRecord(Level.FINEST, MESSAGE));
}

@Test
public void testEnhancedLogEntryPrintToStdout() {
final String ExpectedOutput =
"{\"severity\":\"INFO\",\"timestamp\":\"1970-01-02T10:17:36.789Z\",\"logging.googleapis.com/labels\":{\"enhanced\":\"true\"},\"logging.googleapis.com/trace_sampled\":false,\"message\":\"message\"}";
replay(options, logging);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bout);
System.setOut(out);

LoggingEnhancer enhancer =
new LoggingEnhancer() {
@Override
public void enhanceLogEntry(Builder builder) {
builder.addLabel("enhanced", "true");
}
};
LoggingHandler handler =
new LoggingHandler(
LOG_NAME, options, DEFAULT_RESOURCE, Collections.singletonList(enhancer));
handler.setLevel(Level.ALL);
handler.setFormatter(new TestFormatter());
handler.setRedirectToStdout(true);
handler.publish(newLogRecord(Level.INFO, MESSAGE));

assertEquals(ExpectedOutput, bout.toString().trim()); // ignore trailing newline!
System.setOut(null);
}

@Test
public void testTraceEnhancedLogEntry() {
logging.write(ImmutableList.of(TRACE_ENTRY), DEFAULT_OPTIONS);
Expand Down Expand Up @@ -545,7 +574,7 @@ public void testAutoPopulationEnabled() {
}

@Test
public void testStructuredLoggingEnabled() {
public void testRedirectToStdoutEnabled() {
setupOptionsToEnableAutoPopulation();
expect(
logging.populateMetadata(
Expand All @@ -572,7 +601,7 @@ public void testStructuredLoggingEnabled() {

@Test
/** Validate that nothing is printed to STDOUT */
public void testStructuredLoggingDisabled() {
public void testRedirectToStdoutDisabled() {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bout);
System.setOut(out);
Expand Down

0 comments on commit 9e575b4

Please sign in to comment.