Skip to content

Commit

Permalink
Added tests and replaced IllegalArgumentException with LogCaptorExcep…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
Hakky54 committed Jun 17, 2024
1 parent d62adb7 commit ae16910
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,7 @@ public LogCaptorException(Throwable cause) {
super(cause);
}

public LogCaptorException(String message) {
super(message);
}
}
7 changes: 5 additions & 2 deletions src/main/java/nl/altindag/log/util/LogbackUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,19 @@
*/
public final class LogbackUtils {

private static final int DEFAULT_POLL_COUNTER_LIMIT = 20;
private static final int DEFAULT_POLL_DELAY_MILLISECONDS = 100;

private static final int POLL_COUNTER_LIMIT = Optional.ofNullable(System.getProperty("logcaptor.poll-counter-limit"))
.filter(value -> !value.isEmpty())
.map(String::trim)
.map(Integer::parseInt)
.orElse(20);
.orElse(DEFAULT_POLL_COUNTER_LIMIT);
private static final int POLL_DELAY_MILLISECONDS = Optional.ofNullable(System.getProperty("logcaptor.poll-delay-milliseconds"))
.filter(value -> !value.isEmpty())
.map(String::trim)
.map(Integer::parseInt)
.orElse(100);
.orElse(DEFAULT_POLL_DELAY_MILLISECONDS);

private LogbackUtils() {}

Expand Down
5 changes: 3 additions & 2 deletions src/main/java/nl/altindag/log/util/ValidationUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package nl.altindag.log.util;

import nl.altindag.log.exception.LogCaptorException;
import org.slf4j.Logger;

/**
Expand All @@ -31,11 +32,11 @@ public static <T extends Logger, U extends Logger> void requireLoggerOfType(T ac
if (actualLogger == null || !requiredLogger.getCanonicalName().equals(actualLogger.getClass().getCanonicalName())) {
String actualLoggerType = actualLogger != null ? actualLogger.getClass().getName() : "nothing";

throw new IllegalArgumentException(
throw new LogCaptorException(
String.format("SLF4J Logger implementation should be of the type [%s] but found [%s].", requiredLogger.getName(), actualLoggerType)
);
} else if (!(requiredLogger.isInstance(actualLogger))) {
throw new IllegalArgumentException(
throw new LogCaptorException(
String.format(
"Multiple classloaders are being used. The Logging API is created by the following classloader: [%s], " +
"while it should have been created by the following classloader: [%s].",
Expand Down
7 changes: 4 additions & 3 deletions src/test/java/nl/altindag/log/LogCaptorShould.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import ch.qos.logback.core.spi.FilterReply;
import nl.altindag.console.ConsoleCaptor;
import nl.altindag.log.appender.InMemoryAppender;
import nl.altindag.log.exception.LogCaptorException;
import nl.altindag.log.model.LogEvent;
import nl.altindag.log.service.LogMessage;
import nl.altindag.log.service.Service;
Expand Down Expand Up @@ -437,7 +438,7 @@ void throwExceptionWhenLoggerImplementationIsNull() {
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(null);

assertThatThrownBy(LogCaptor::forRoot)
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(LogCaptorException.class)
.hasMessage("SLF4J Logger implementation should be of the type [ch.qos.logback.classic.Logger] but found [nothing].");
}
}
Expand All @@ -450,7 +451,7 @@ void throwExceptionWhenLoggerImplementationIsNotLogback() {
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);

assertThatThrownBy(LogCaptor::forRoot)
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(LogCaptorException.class)
.hasMessage("SLF4J Logger implementation should be of the type [ch.qos.logback.classic.Logger] but found [org.slf4j.simple.SimpleLogger].");
}
}
Expand All @@ -469,7 +470,7 @@ void throwExceptionWhenLoggerImplementationIsFromAnotherClassloader() throws Inv
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);

assertThatThrownBy(LogCaptor::forRoot)
.isInstanceOf(IllegalArgumentException.class)
.isInstanceOf(LogCaptorException.class)
.hasMessage(String.format("Multiple classloaders are being used. The Logging API is created by the following classloader: [nl.altindag.log.LogCaptorShould$CustomClassLoader], " +
"while it should have been created by the following classloader: [%s].", this.getClass().getClassLoader().getClass().getName()
));
Expand Down
64 changes: 64 additions & 0 deletions src/test/java/nl/altindag/log/util/LogbackUtilsShould.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2019 Thunderberry.
*
* 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
*
* https://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.
*/
package nl.altindag.log.util;

import ch.qos.logback.classic.Logger;
import nl.altindag.log.exception.LogCaptorException;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.SubstituteLogger;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;

class LogbackUtilsShould {

@Test
void getLoggerEvenWhenItHasInitiallyLogger() {
SubstituteLogger substituteLogger = mock(SubstituteLogger.class);
Logger logbackLogger = mock(Logger.class);

try (MockedStatic<LoggerFactory> mockedStatic = mockStatic(LoggerFactory.class)) {
mockedStatic.when(() -> LoggerFactory.getLogger("magic-logger"))
.thenReturn(substituteLogger)
.thenReturn(logbackLogger);

Logger logger = LogbackUtils.getLogger("magic-logger");
assertThat(logger).isEqualTo(logbackLogger);
}
}

@Test
void failToGetLoggerWhenTheUnderlyingLoggerIsNotInitializedYet() {
SubstituteLogger substituteLogger = mock(SubstituteLogger.class);
System.setProperty("logcaptor.poll-counter-limit", "1");

try (MockedStatic<LoggerFactory> mockedStatic = mockStatic(LoggerFactory.class)) {
mockedStatic.when(() -> LoggerFactory.getLogger("magic-logger"))
.thenReturn(substituteLogger);

assertThatThrownBy(() -> LogbackUtils.getLogger("magic-logger"))
.isInstanceOf(LogCaptorException.class)
.hasMessage("SLF4J Logger implementation should be of the type [ch.qos.logback.classic.Logger] but found [org.slf4j.helpers.SubstituteLogger].");
} finally {
System.clearProperty("logcaptor.poll-counter-limit");
}
}

}

0 comments on commit ae16910

Please sign in to comment.