You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by ma...@apache.org on 2020/08/23 00:16:04 UTC
[logging-log4j2] 03/03: [LOG4J2-2653] Migrate part of log4j-core to
JUnit 5
This is an automated email from the ASF dual-hosted git repository.
mattsicker pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git
commit 00598f2f4265f1c8c9bb540e42bff67f9c42f35c
Author: Matt Sicker <bo...@gmail.com>
AuthorDate: Sat Aug 22 19:15:37 2020 -0500
[LOG4J2-2653] Migrate part of log4j-core to JUnit 5
Signed-off-by: Matt Sicker <bo...@gmail.com>
---
log4j-core/pom.xml | 4 +
.../log4j/core/AppenderRefLevelJsonTest.java | 42 +++----
.../logging/log4j/core/AppenderRefLevelTest.java | 49 ++++-----
.../logging/log4j/core/BasicLoggingTest.java | 7 +-
.../logging/log4j/core/CollectionLoggingTest.java | 42 +++----
.../log4j/core/CustomLevelsOverrideTest.java | 35 +++---
.../logging/log4j/core/CustomLevelsTest.java | 34 +++---
.../log4j/core/CustomLevelsWithFiltersTest.java | 31 ++----
.../apache/logging/log4j/core/DeadlockTest.java | 20 ++--
.../log4j/core/EventParameterMemoryLeakTest.java | 17 +--
.../logging/log4j/core/ExtendedLevelTest.java | 43 +++-----
.../log4j/core/GcFreeAsynchronousLoggingTest.java | 8 +-
.../logging/log4j/core/GcFreeLoggingTestUtil.java | 18 +--
.../log4j/core/GcFreeMixedSyncAyncLoggingTest.java | 5 +-
.../log4j/core/GcFreeSynchronousLoggingTest.java | 5 +-
.../apache/logging/log4j/core/HostNameTest.java | 43 +++-----
.../apache/logging/log4j/core/LateConfigTest.java | 32 +++---
.../org/apache/logging/log4j/core/LevelTest.java | 60 +++++-----
.../apache/logging/log4j/core/Log4j1222Test.java | 4 +-
.../logging/log4j/core/LogEventFactoryTest.java | 37 +++----
.../apache/logging/log4j/core/LogEventTest.java | 24 ++--
.../apache/logging/log4j/core/LoggerDateTest.java | 26 ++---
.../org/apache/logging/log4j/core/LoggerTest.java | 121 ++++++++++-----------
.../logging/log4j/core/LoggerUpdateTest.java | 54 ++++-----
.../org/apache/logging/log4j/core/LoggingTest.java | 69 ------------
.../org/apache/logging/log4j/core/LookupTest.java | 31 ++----
.../logging/log4j/core/PatternSelectorTest.java | 56 ++++------
.../log4j/core/PropertiesFileConfigTest.java | 38 +++----
...ReusableParameterizedMessageMemoryLeakTest.java | 7 +-
.../logging/log4j/core/ShutdownDisabledTest.java | 22 +---
.../core/ShutdownTimeoutConfigurationTest.java | 20 +---
.../logging/log4j/core/StrictXmlConfigTest.java | 56 ++++------
.../logging/log4j/core/TimestampMessageTest.java | 35 +++---
.../org/apache/logging/log4j/core/XmlEvents.java | 20 ++--
.../appender/rolling/action/DeleteActionTest.java | 2 +-
.../selector/ClassLoaderContextSelectorTest.java | 8 +-
.../logging/log4j/core/time/ClockFactoryTest.java | 12 +-
.../log4j/core/time/MutableInstantTest.java | 85 +++++++--------
.../log4j/core/time/SystemNanoClockTest.java | 6 +-
.../core/time/internal/DummyNanoClockTest.java | 5 +-
.../log4j/core/time/internal/SystemClockTest.java | 9 +-
.../log4j/core/tools/GenerateCustomLoggerTest.java | 81 +++++++-------
.../core/tools/GenerateExtendedLoggerTest.java | 80 +++++++-------
.../log4j/core/util/ContextDataProviderTest.java | 25 ++---
.../log4j/core/util/CronExpressionTest.java | 30 ++---
.../logging/log4j/core/util/CyclicBufferTest.java | 22 ++--
.../logging/log4j/core/util/FileUtilsTest.java | 18 ++-
.../apache/logging/log4j/core/util/InitTest.java | 12 +-
.../logging/log4j/core/util/IntegersTest.java | 4 +-
.../logging/log4j/core/util/JsonUtilsTest.java | 4 +-
.../apache/logging/log4j/core/util/LoaderTest.java | 13 ++-
.../logging/log4j/core/util/NetUtilsTest.java | 29 +++--
.../logging/log4j/core/util/ProcessIdUtilTest.java | 9 +-
.../core/util/ShutdownCallbackRegistryTest.java | 29 +++--
.../logging/log4j/core/util/ThrowablesTest.java | 30 ++---
.../apache/logging/log4j/core/util/UuidTest.java | 20 ++--
.../logging/log4j/core/util/WatchHttpTest.java | 2 +-
.../logging/log4j/core/util/WatchManagerTest.java | 28 ++---
.../logging/log4j/junit/AppenderResolver.java | 54 +++++++++
.../logging/log4j/junit/ConfigurationResolver.java | 39 +++++++
.../logging/log4j/junit/LoggerContextResolver.java | 106 ++++++++++++++++++
.../logging/log4j/junit/LoggerContextSource.java | 56 ++++++++++
.../{core/DeadlockTest.java => junit/Named.java} | 31 +++---
.../MutableLogEventWithReusableParamMsgTest.java | 2 +-
.../template/JsonTemplateLayoutGcFreeTest.java | 3 +
65 files changed, 1000 insertions(+), 969 deletions(-)
diff --git a/log4j-core/pom.xml b/log4j-core/pom.xml
index 2a850c4..ac4ea4e 100644
--- a/log4j-core/pom.xml
+++ b/log4j-core/pom.xml
@@ -175,6 +175,10 @@
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-migrationsupport</artifactId>
+ </dependency>
+ <dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<scope>test</scope>
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java
index fb28cf0..f09a3a2 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java
@@ -18,39 +18,33 @@ package org.apache.logging.log4j.core;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
-import org.apache.logging.log4j.categories.Configurations;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.*;
-/**
- *
- */
-@Category(Configurations.Json.class)
+@Tag("json")
+@LoggerContextSource("log4j-reference-level.json")
public class AppenderRefLevelJsonTest {
- private static final String CONFIG = "log4j-reference-level.json";
- private ListAppender app1;
- private ListAppender app2;
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final ListAppender app1;
+ private final ListAppender app2;
- org.apache.logging.log4j.Logger logger1 = context.getLogger("org.apache.logging.log4j.test1");
- org.apache.logging.log4j.Logger logger2 = context.getLogger("org.apache.logging.log4j.test2");
- org.apache.logging.log4j.Logger logger3 = context.getLogger("org.apache.logging.log4j.test3");
+ org.apache.logging.log4j.Logger logger1;
+ org.apache.logging.log4j.Logger logger2;
+ org.apache.logging.log4j.Logger logger3;
Marker testMarker = MarkerManager.getMarker("TEST");
- @Before
- public void before() {
- app1 = context.getListAppender("LIST1").clear();
- app2 = context.getListAppender("LIST2").clear();
+ public AppenderRefLevelJsonTest(final LoggerContext context, @Named("LIST1") final ListAppender first, @Named("LIST2") final ListAppender second) {
+ logger1 = context.getLogger("org.apache.logging.log4j.test1");
+ logger2 = context.getLogger("org.apache.logging.log4j.test2");
+ logger3 = context.getLogger("org.apache.logging.log4j.test3");
+ app1 = first.clear();
+ app2 = second.clear();
}
@Test
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java
index 861ed87..dbe5658 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java
@@ -20,37 +20,32 @@ import java.util.List;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@LoggerContextSource("log4j-reference-level.xml")
public class AppenderRefLevelTest {
- private static final String CONFIG = "log4j-reference-level.xml";
- private ListAppender app1;
- private ListAppender app2;
+ private final ListAppender app1;
+ private final ListAppender app2;
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ public AppenderRefLevelTest(final LoggerContext context, @Named("LIST1") final ListAppender first, @Named("LIST2") final ListAppender second) {
+ logger1 = context.getLogger("org.apache.logging.log4j.test1");
+ logger2 = context.getLogger("org.apache.logging.log4j.test2");
+ logger3 = context.getLogger("org.apache.logging.log4j.test3");
+ app1 = first.clear();
+ app2 = second.clear();
+ }
- org.apache.logging.log4j.Logger logger1 = context.getLogger("org.apache.logging.log4j.test1");
- org.apache.logging.log4j.Logger logger2 = context.getLogger("org.apache.logging.log4j.test2");
- org.apache.logging.log4j.Logger logger3 = context.getLogger("org.apache.logging.log4j.test3");
+ org.apache.logging.log4j.Logger logger1;
+ org.apache.logging.log4j.Logger logger2;
+ org.apache.logging.log4j.Logger logger3;
Marker testMarker = MarkerManager.getMarker("TEST");
- @Before
- public void before() {
- app1 = context.getListAppender("LIST1").clear();
- app2 = context.getListAppender("LIST2").clear();
- }
-
@Test
public void logger1() {
logger1.traceEntry();
@@ -60,9 +55,9 @@ public class AppenderRefLevelTest {
logger1.warn("warn Message");
logger1.traceExit();
List<LogEvent> events = app1.getEvents();
- assertEquals("Incorrect number of events. Expected 6, actual " + events.size(), 6, events.size());
+ assertEquals(6, events.size(), "Incorrect number of events. Expected 6, actual " + events.size());
events = app2.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
}
@Test
@@ -74,9 +69,9 @@ public class AppenderRefLevelTest {
logger2.warn("warn Message");
logger2.traceExit();
List<LogEvent> events = app1.getEvents();
- assertEquals("Incorrect number of events. Expected 2, actual " + events.size(), events.size(), 2);
+ assertEquals(events.size(), 2, "Incorrect number of events. Expected 2, actual " + events.size());
events = app2.getEvents();
- assertEquals("Incorrect number of events. Expected 4, actual " + events.size(), events.size(), 4);
+ assertEquals(events.size(), 4, "Incorrect number of events. Expected 4, actual " + events.size());
}
@Test
@@ -88,7 +83,7 @@ public class AppenderRefLevelTest {
logger3.warn("warn Message");
logger3.traceExit();
final List<LogEvent> events = app1.getEvents();
- assertEquals("Incorrect number of events. Expected 4, actual " + events.size(), 4, events.size());
+ assertEquals(4, events.size(), "Incorrect number of events. Expected 4, actual " + events.size());
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java
index b25844f..568cf06 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java
@@ -18,11 +18,10 @@ package org.apache.logging.log4j.core;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-import org.junit.Test;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
-/**
- *
- */
+@Tag("smoke")
public class BasicLoggingTest {
@Test
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java
index b293ad9..791a370 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java
@@ -16,40 +16,32 @@
*/
package org.apache.logging.log4j.core;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.message.StringMapMessage;
+import org.apache.logging.log4j.test.appender.ListAppender;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.apache.logging.log4j.message.StringMapMessage;
-import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * TODO: Work in progress.
- */
-@Ignore
+@LoggerContextSource("log4j-collectionLogging.xml")
+@Disabled("Work in progress")
public class CollectionLoggingTest {
- private static final String CONFIG = "log4j-collectionLogging.xml";
- private ListAppender app;
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final ListAppender app;
- @Before
- public void before() {
- app = context.getListAppender("List").clear();
+ public CollectionLoggingTest(@Named("List") final ListAppender app) {
+ this.app = app.clear();
}
@Test
- public void testSystemProperties() {
+ public void testSystemProperties(final LoggerContext context) {
final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
logger.error(System.getProperties());
// logger.error(new MapMessage(System.getProperties()));
@@ -57,7 +49,7 @@ public class CollectionLoggingTest {
}
@Test
- public void testSimpleMap() {
+ public void testSimpleMap(final LoggerContext context) {
final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
logger.error(System.getProperties());
final Map<String, String> map = new HashMap<>();
@@ -69,14 +61,14 @@ public class CollectionLoggingTest {
}
@Test
- public void testNetworkInterfaces() throws SocketException {
+ public void testNetworkInterfaces(final LoggerContext context) throws SocketException {
final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
logger.error(NetworkInterface.getNetworkInterfaces());
// TODO: some assertions
}
@Test
- public void testAvailableCharsets() throws SocketException {
+ public void testAvailableCharsets(final LoggerContext context) {
final Logger logger = context.getLogger(CollectionLoggingTest.class.getName());
logger.error(Charset.availableCharsets());
// TODO: some assertions
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java
index 2fed8af..50c63ed 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java
@@ -16,37 +16,31 @@
*/
package org.apache.logging.log4j.core;
+import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.*;
import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+@LoggerContextSource("log4j-customLevels.xml")
public class CustomLevelsOverrideTest {
- private static final String CONFIG = "log4j-customLevels.xml";
+ private final ListAppender listAppender;
+ private final Level warnLevel;
+ private final Level infoLevel;
+ private final Level debugLevel;
+ private final Logger logger;
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
- private ListAppender listAppender;
- private Level warnLevel;
- private Level infoLevel;
- private Level debugLevel;
-
- @Before
- public void before() {
+ public CustomLevelsOverrideTest(final LoggerContext context, @Named("List1") final ListAppender appender) {
warnLevel = Level.getLevel("WARN");
infoLevel = Level.getLevel("INFO");
debugLevel = Level.getLevel("DEBUG");
- listAppender = context.getListAppender("List1").clear();
+ listAppender = appender.clear();
+ logger = context.getLogger(getClass().getName());
}
@Test
@@ -75,7 +69,6 @@ public class CustomLevelsOverrideTest {
@Test
public void testLog() {
- final Logger logger = context.getLogger();
assertThat(listAppender.getEvents(), hasSize(0));
logger.debug("Hello, {}", "World");
assertThat(listAppender.getEvents(), hasSize(1));
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java
index 826b397..98978aa 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java
@@ -16,36 +16,31 @@
*/
package org.apache.logging.log4j.core;
+import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.*;
import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+@LoggerContextSource("log4j-customLevels.xml")
public class CustomLevelsTest {
- private static final String CONFIG = "log4j-customLevels.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
- private ListAppender listAppender;
- private Level diagLevel;
- private Level noticeLevel;
- private Level verboseLevel;
+ private final ListAppender listAppender;
+ private final Level diagLevel;
+ private final Level noticeLevel;
+ private final Level verboseLevel;
+ private final Logger logger;
- @Before
- public void before() {
+ public CustomLevelsTest(final LoggerContext context, @Named("List1") final ListAppender appender) {
diagLevel = Level.getLevel("DIAG");
noticeLevel = Level.getLevel("NOTICE");
verboseLevel = Level.getLevel("VERBOSE");
- listAppender = context.getListAppender("List1").clear();
+ listAppender = appender.clear();
+ logger = context.getLogger(getClass().getName());
}
@Test
@@ -64,7 +59,6 @@ public class CustomLevelsTest {
@Test
public void testLog() {
- final Logger logger = context.getLogger();
assertThat(listAppender.getEvents(), hasSize(0));
logger.debug("Hello, {}", "World");
assertThat(listAppender.getEvents(), hasSize(1));
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java
index 1808492..20b350d 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java
@@ -16,44 +16,33 @@
*/
package org.apache.logging.log4j.core;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.filter.CompositeFilter;
import org.apache.logging.log4j.core.filter.ThresholdFilter;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
-
-/**
- *
- */
-public class CustomLevelsWithFiltersTest {
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
- private static final String CONFIG = "log4j-customLevelsWithFilters.xml";
+import static org.junit.jupiter.api.Assertions.*;
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+@LoggerContextSource("log4j-customLevelsWithFilters.xml")
+public class CustomLevelsWithFiltersTest {
private Level infom1Level;
private Level infop1Level;
- @Before
+ @BeforeEach
public void before() {
infom1Level = Level.getLevel("INFOM1");
infop1Level = Level.getLevel("INFOP1");
}
@Test
- public void testConfiguration() {
- final Configuration configuration = context.getConfiguration();
+ public void testConfiguration(final Configuration configuration, @Named("info") final FileAppender appender) {
assertNotNull(configuration);
- final FileAppender appender = configuration.getAppender("info");
assertNotNull(appender);
final CompositeFilter compFilter = (CompositeFilter) appender.getFilter();
assertNotNull(compFilter);
@@ -67,7 +56,7 @@ public class CustomLevelsWithFiltersTest {
break;
}
}
- Assert.assertTrue("Level not found: " + infom1Level, foundLevel);
+ assertTrue(foundLevel, "Level not found: " + infom1Level);
}
@Test
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java
index c3cc5b4..0f08f3e 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java
@@ -16,22 +16,16 @@
*/
package org.apache.logging.log4j.core;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
-/**
- *
- */
+@LoggerContextSource("log4j-deadlock.xml")
+@Tag("concurrency")
public class DeadlockTest {
- private static final String CONFIG = "log4j-deadlock.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
@Test
- public void deadlockOnReconfigure() {
- context.getLoggerContext().reconfigure();
+ public void deadlockOnReconfigure(final LoggerContext context) {
+ context.reconfigure();
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/EventParameterMemoryLeakTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/EventParameterMemoryLeakTest.java
index 9996f8b..20e7972 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/EventParameterMemoryLeakTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/EventParameterMemoryLeakTest.java
@@ -19,8 +19,9 @@ package org.apache.logging.log4j.core;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.File;
@@ -30,12 +31,12 @@ import java.util.concurrent.TimeUnit;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
+@Tag("functional")
public class EventParameterMemoryLeakTest {
- @BeforeClass
+ @BeforeAll
public static void beforeClass() {
System.setProperty("log4j2.enable.threadlocals", "true");
System.setProperty("log4j2.enable.direct.encoders", "true");
@@ -47,7 +48,7 @@ public class EventParameterMemoryLeakTest {
@SuppressWarnings("UnusedAssignment") // parameter set to null to allow garbage collection
public void testParametersAreNotLeaked() throws Exception {
final File file = new File("target", "EventParameterMemoryLeakTest.log");
- assertTrue("Deleted old file before test", !file.exists() || file.delete());
+ assertTrue(!file.exists() || file.delete(), "Deleted old file before test");
final Logger log = LogManager.getLogger("com.foo.Bar");
CountDownLatch latch = new CountDownLatch(1);
@@ -70,11 +71,11 @@ public class EventParameterMemoryLeakTest {
assertThat(line2, containsString("paramValue"));
assertThat(line3, containsString("paramValue"));
assertThat(line4, containsString("paramValue"));
- assertNull("Expected only three lines", line5);
+ assertNull(line5, "Expected only three lines");
GarbageCollectionHelper gcHelper = new GarbageCollectionHelper();
gcHelper.run();
try {
- assertTrue("Parameter should have been garbage collected", latch.await(30, TimeUnit.SECONDS));
+ assertTrue(latch.await(30, TimeUnit.SECONDS), "Parameter should have been garbage collected");
} finally {
gcHelper.close();
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java
index 8126197..d9ceb4f 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java
@@ -16,54 +16,47 @@
*/
package org.apache.logging.log4j.core;
-import java.util.List;
-
import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.ExtendedLevels;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@LoggerContextSource("log4j-customLevel.xml")
public class ExtendedLevelTest {
- private static final String CONFIG = "log4j-customLevel.xml";
- private ListAppender list1;
- private ListAppender list2;
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final ListAppender list1;
+ private final ListAppender list2;
- @Before
- public void before() {
- list1 = context.getListAppender("List1").clear();
- list2 = context.getListAppender("List2").clear();
+ public ExtendedLevelTest(@Named("List1") final ListAppender list1, @Named("List2") final ListAppender list2) {
+ this.list1 = list1.clear();
+ this.list2 = list2.clear();
}
@Test
- public void testLevelLogging() {
+ public void testLevelLogging(final LoggerContext context) {
org.apache.logging.log4j.Logger logger = context.getLogger("org.apache.logging.log4j.test1");
logger.log(ExtendedLevels.DETAIL, "Detail message");
logger.log(Level.DEBUG, "Debug message");
List<LogEvent> events = list1.getEvents();
- assertNotNull("No events", events);
+ assertNotNull(events, "No events");
assertThat(events, hasSize(1));
LogEvent event = events.get(0);
- assertEquals("Expected level DETAIL, got" + event.getLevel(), "DETAIL", event.getLevel().name());
+ assertEquals("DETAIL", event.getLevel().name(), "Expected level DETAIL, got" + event.getLevel());
logger = context.getLogger("org.apache.logging.log4j.test2");
logger.log(ExtendedLevels.NOTE, "Note message");
logger.log(Level.INFO, "Info message");
events = list2.getEvents();
- assertNotNull("No events", events);
+ assertNotNull(events, "No events");
assertThat(events, hasSize(1));
event = events.get(0);
- assertEquals("Expected level NOTE, got" + event.getLevel(), "NOTE", event.getLevel().name());
+ assertEquals("NOTE", event.getLevel().name(), "Expected level NOTE, got" + event.getLevel());
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java
index 9fb661f..286a113 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java
@@ -16,17 +16,17 @@
*/
package org.apache.logging.log4j.core;
-import org.apache.logging.log4j.categories.AsyncLoggers;
import org.apache.logging.log4j.core.async.AsyncLoggerContextSelector;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
/**
* Verifies steady state logging is GC-free.
*
* @see <a href="https://github.com/google/allocation-instrumenter">https://github.com/google/allocation-instrumenter</a>
*/
-@Category(AsyncLoggers.class)
+@Tag("allocation")
+@Tag("functional")
public class GcFreeAsynchronousLoggingTest {
@Test
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeLoggingTestUtil.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeLoggingTestUtil.java
index 938234f..103233f 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeLoggingTestUtil.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeLoggingTestUtil.java
@@ -33,8 +33,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Utility methods for the GC-free logging tests.
@@ -49,9 +49,9 @@ public enum GcFreeLoggingTestUtil {;
System.setProperty("log4j2.is.webapp", "false");
System.setProperty("log4j.configurationFile", configurationFile);
- assertTrue("Constants.ENABLE_THREADLOCALS", Constants.ENABLE_THREADLOCALS);
- assertTrue("Constants.ENABLE_DIRECT_ENCODERS", Constants.ENABLE_DIRECT_ENCODERS);
- assertFalse("Constants.IS_WEB_APP", Constants.IS_WEB_APP);
+ assertTrue(Constants.ENABLE_THREADLOCALS, "Constants.ENABLE_THREADLOCALS");
+ assertTrue(Constants.ENABLE_DIRECT_ENCODERS, "Constants.ENABLE_DIRECT_ENCODERS");
+ assertFalse(Constants.IS_WEB_APP, "Constants.IS_WEB_APP");
final MyCharSeq myCharSeq = new MyCharSeq();
final Marker testGrandParent = MarkerManager.getMarker("testGrandParent");
@@ -163,15 +163,15 @@ public enum GcFreeLoggingTestUtil {;
"key2=value2, prop1=value1, prop2=value2} " +
"This message is logged to the console"));
assertTrue(
- "pattern mismatch at line 1: " + line,
- line.matches(firstLinePattern));
+ line.matches(firstLinePattern),
+ "pattern mismatch at line 1: " + line);
}
// Check the rest of the lines.
else {
assertFalse(
- "(allocated|array) pattern matches at line " + lineNumber + ": " + line,
- line.contains("allocated") || line.contains("array"));
+ line.contains("allocated") || line.contains("array"),
+ "(allocated|array) pattern matches at line " + lineNumber + ": " + line);
}
});
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAyncLoggingTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAyncLoggingTest.java
index 93ddc2c..ed844d0 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAyncLoggingTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAyncLoggingTest.java
@@ -16,13 +16,16 @@
*/
package org.apache.logging.log4j.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
/**
* Verifies steady state mixed synchronous and asynchronous logging is GC-free.
*
* @see <a href="https://github.com/google/allocation-instrumenter">https://github.com/google/allocation-instrumenter</a>
*/
+@Tag("allocation")
+@Tag("functional")
public class GcFreeMixedSyncAyncLoggingTest {
@Test
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java
index 8ab6e8b..99648de 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java
@@ -16,13 +16,16 @@
*/
package org.apache.logging.log4j.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
/**
* Verifies steady state synchronous logging is GC-free.
*
* @see <a href="https://github.com/google/allocation-instrumenter">https://github.com/google/allocation-instrumenter</a>
*/
+@Tag("allocation")
+@Tag("functional")
public class GcFreeSynchronousLoggingTest {
@Test
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/HostNameTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/HostNameTest.java
index 9d036ad..86b5e07 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/HostNameTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/HostNameTest.java
@@ -20,53 +20,46 @@ import java.util.List;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.util.NetUtils;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.apache.logging.log4j.util.Strings;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@LoggerContextSource("log4j-test2.xml")
public class HostNameTest {
- private static final String CONFIG = "log4j-test2.xml";
- private ListAppender host;
- private RollingFileAppender hostFile;
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final ListAppender host;
+ private final RollingFileAppender hostFile;
- @Before
- public void before() {
- host = context.getListAppender("HostTest").clear();
- hostFile = context.getRequiredAppender("HostFile", RollingFileAppender.class);
+ public HostNameTest(@Named("HostTest") final ListAppender list, @Named("HostFile") final RollingFileAppender rolling) {
+ host = list.clear();
+ hostFile = rolling;
}
@Test
- public void testHostname() {
+ public void testHostname(final LoggerContext context) {
final org.apache.logging.log4j.Logger testLogger = context.getLogger("org.apache.logging.log4j.hosttest");
testLogger.debug("Hello, {}", "World");
final List<String> msgs = host.getMessages();
assertThat(msgs, hasSize(1));
String expected = NetUtils.getLocalHostname() + Strings.LINE_SEPARATOR;
assertThat(msgs.get(0), endsWith(expected));
- assertNotNull("No Host FileAppender file name", hostFile.getFileName());
+ assertNotNull(hostFile.getFileName(), "No Host FileAppender file name");
expected = "target/" + NetUtils.getLocalHostname() + ".log";
String name = hostFile.getFileName();
- assertEquals("Incorrect HostFile FileAppender file name - expected " + expected + " actual - " + name, name,
- expected);
+ assertEquals(name,
+ expected, "Incorrect HostFile FileAppender file name - expected " + expected + " actual - " + name);
name = hostFile.getFilePattern();
- assertNotNull("No file pattern", name);
+ assertNotNull(name, "No file pattern");
expected = "target/" + NetUtils.getLocalHostname() + "-%d{MM-dd-yyyy}-%i.log";
- assertEquals("Incorrect HostFile FileAppender file pattern - expected " + expected + " actual - " + name, name,
- expected);
+ assertEquals(name,
+ expected, "Incorrect HostFile FileAppender file pattern - expected " + expected + " actual - " + name);
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java
index 03d1575..c3a7087 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java
@@ -16,9 +16,6 @@
*/
package org.apache.logging.log4j.core;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
import java.io.File;
import org.apache.logging.log4j.core.config.Configuration;
@@ -26,24 +23,25 @@ import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.apache.logging.log4j.core.config.xml.XmlConfiguration;
import org.apache.logging.log4j.status.StatusLogger;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
-/**
- *
- */
+import static org.junit.jupiter.api.Assertions.*;
+
+@Tag("functional")
public class LateConfigTest {
private static final String CONFIG = "target/test-classes/log4j-test1.xml";
private static LoggerContext context;
- @BeforeClass
+ @BeforeAll
public static void setupClass() {
context = LoggerContext.getContext(false);
}
- @AfterClass
+ @AfterAll
public static void tearDownClass() {
Configurator.shutdown(context);
StatusLogger.getLogger().reset();
@@ -52,17 +50,17 @@ public class LateConfigTest {
@Test
public void testReconfiguration() throws Exception {
final Configuration cfg = context.getConfiguration();
- assertNotNull("No configuration", cfg);
- assertTrue("Not set to default configuration", cfg instanceof DefaultConfiguration);
+ assertNotNull(cfg, "No configuration");
+ assertTrue(cfg instanceof DefaultConfiguration, "Not set to default configuration");
final File file = new File(CONFIG);
final LoggerContext loggerContext = LoggerContext.getContext(null, false, file.toURI());
- assertNotNull("No Logger Context", loggerContext);
+ assertNotNull(loggerContext, "No Logger Context");
final Configuration newConfig = loggerContext.getConfiguration();
- assertTrue("Configuration not reset", cfg != newConfig);
- assertTrue("Reconfiguration failed", newConfig instanceof XmlConfiguration);
+ assertNotSame(cfg, newConfig, "Configuration not reset");
+ assertTrue(newConfig instanceof XmlConfiguration, "Reconfiguration failed");
context = LoggerContext.getContext(false);
final Configuration sameConfig = context.getConfiguration();
- assertTrue("Configuration should not have been reset", newConfig == sameConfig);
+ assertSame(newConfig, sameConfig, "Configuration should not have been reset");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LevelTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LevelTest.java
index a21c90c..393751b 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LevelTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LevelTest.java
@@ -22,43 +22,39 @@ import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.ObjectMessage;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@LoggerContextSource("log4j-Level.xml")
public class LevelTest {
- private static final String CONFIG = "log4j-Level.xml";
- private ListAppender listAll;
- private ListAppender listTrace;
- private ListAppender listDebug;
- private ListAppender listInfo;
- private ListAppender listWarn;
- private ListAppender listError;
- private ListAppender listFatal;
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final ListAppender listAll;
+ private final ListAppender listTrace;
+ private final ListAppender listDebug;
+ private final ListAppender listInfo;
+ private final ListAppender listWarn;
+ private final ListAppender listError;
+ private final ListAppender listFatal;
- @Before
- public void before() {
- listAll = context.getListAppender("ListAll").clear();
- listTrace = context.getListAppender("ListTrace").clear();
- listDebug = context.getListAppender("ListDebug").clear();
- listInfo = context.getListAppender("ListInfo").clear();
- listWarn = context.getListAppender("ListWarn").clear();
- listError = context.getListAppender("ListError").clear();
- listFatal = context.getListAppender("ListFatal").clear();
+ public LevelTest(@Named("ListAll") final ListAppender listAll, @Named("ListTrace") final ListAppender listTrace,
+ @Named("ListDebug") final ListAppender listDebug, @Named("ListInfo") final ListAppender listInfo,
+ @Named("ListWarn") final ListAppender listWarn, @Named("ListError") final ListAppender listError,
+ @Named("ListFatal") final ListAppender listFatal) {
+ this.listAll = listAll.clear();
+ this.listTrace = listTrace.clear();
+ this.listDebug = listDebug.clear();
+ this.listInfo = listInfo.clear();
+ this.listWarn = listWarn.clear();
+ this.listError = listError.clear();
+ this.listFatal = listFatal.clear();
}
// Helper class
@@ -77,7 +73,7 @@ public class LevelTest {
}
@Test
- public void testLevelLogging() {
+ public void testLevelLogging(final LoggerContext context) {
final Marker marker = MarkerManager.getMarker("marker");
final Message msg = new ObjectMessage("msg");
final Throwable t = new Throwable("test");
@@ -119,12 +115,12 @@ public class LevelTest {
for (final Expected expected : expectedResults) {
final String description = expected.description;
final List<LogEvent> events = expected.appender.getEvents();
- assertNotNull(description + ": No events", events);
+ assertNotNull(events, description + ": No events");
assertThat(events, hasSize(expected.expectedEventCount));
final LogEvent event = events.get(0);
assertEquals(
- description + ": Expected level " + expected.expectedInitialEventLevel + ", got" + event.getLevel(),
- event.getLevel().name(), expected.expectedInitialEventLevel);
+ event.getLevel().name(), expected.expectedInitialEventLevel,
+ description + ": Expected level " + expected.expectedInitialEventLevel + ", got" + event.getLevel());
}
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java
index 1e3f5d5..073dfaa 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java
@@ -19,13 +19,15 @@ package org.apache.logging.log4j.core;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.TestLogger;
-import org.junit.Test;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertTrue;
/**
* Tests logging during shutdown.
*/
+@Tag("functional")
public class Log4j1222Test
{
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventFactoryTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventFactoryTest.java
index d2e971c..bdd2c13 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventFactoryTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventFactoryTest.java
@@ -38,8 +38,6 @@ import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.RuleChain;
-import org.junit.rules.TestRule;
-import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
@@ -54,28 +52,23 @@ public class LogEventFactoryTest {
// this would look so cool using lambdas
@ClassRule
- public static RuleChain chain = RuleChain.outerRule(new TestRule() {
+ public static RuleChain chain = RuleChain.outerRule((base, description) -> new Statement() {
@Override
- public Statement apply(final Statement base, final Description description) {
- return new Statement() {
- @Override
- public void evaluate() throws Throwable {
- System.setProperty(Constants.LOG4J_LOG_EVENT_FACTORY, TestLogEventFactory.class.getName());
- resetLogEventFactory(new TestLogEventFactory());
- try {
- base.evaluate();
- } finally {
- System.clearProperty(Constants.LOG4J_LOG_EVENT_FACTORY);
- resetLogEventFactory(new DefaultLogEventFactory());
- }
- }
+ public void evaluate() throws Throwable {
+ System.setProperty(Constants.LOG4J_LOG_EVENT_FACTORY, TestLogEventFactory.class.getName());
+ resetLogEventFactory(new TestLogEventFactory());
+ try {
+ base.evaluate();
+ } finally {
+ System.clearProperty(Constants.LOG4J_LOG_EVENT_FACTORY);
+ resetLogEventFactory(new DefaultLogEventFactory());
+ }
+ }
- private void resetLogEventFactory(final LogEventFactory logEventFactory) throws IllegalAccessException {
- final Field field = FieldUtils.getField(LoggerConfig.class, "LOG_EVENT_FACTORY", true);
- FieldUtils.removeFinalModifier(field, true);
- FieldUtils.writeStaticField(field, logEventFactory, false);
- }
- };
+ private void resetLogEventFactory(final LogEventFactory logEventFactory) throws IllegalAccessException {
+ final Field field = FieldUtils.getField(LoggerConfig.class, "LOG_EVENT_FACTORY", true);
+ FieldUtils.removeFinalModifier(field, true);
+ FieldUtils.writeStaticField(field, logEventFactory, false);
}
}).around(context);
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventTest.java
index bd5ae3e..a707b37 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LogEventTest.java
@@ -28,10 +28,10 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.util.FilteredObjectInputStream;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
*
@@ -98,9 +98,9 @@ public class LogEventTest {
final ObjectInputStream ois = new FilteredObjectInputStream(bais);
final LogEvent actual = (LogEvent) ois.readObject();
- assertNotEquals("Different event: nanoTime", copy, actual);
- assertNotEquals("Different nanoTime", copy.getNanoTime(), actual.getNanoTime());
- assertEquals("deserialized nanoTime is zero", 0, actual.getNanoTime());
+ assertNotEquals(copy, actual, "Different event: nanoTime");
+ assertNotEquals(copy.getNanoTime(), actual.getNanoTime(), "Different nanoTime");
+ assertEquals(0, actual.getNanoTime(), "deserialized nanoTime is zero");
}
@Test
@@ -125,11 +125,11 @@ public class LogEventTest {
final ObjectInputStream ois = new FilteredObjectInputStream(bais);
final LogEvent actual = (LogEvent) ois.readObject();
- assertEquals("both zero nanoTime", event2, actual);
+ assertEquals(event2, actual, "both zero nanoTime");
}
@Test
- @Ignore
+ @Disabled
public void testEquals() {
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName()) //
@@ -149,15 +149,15 @@ public class LogEventTest {
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world!")) //
.build();
- assertNotEquals("Events should not be equal", event1, event2);
- assertEquals("Events should be equal", event2, event3);
+ assertNotEquals(event1, event2, "Events should not be equal");
+ assertEquals(event2, event3, "Events should be equal");
}
@Test
public void testLocation() {
final StackTraceElement ste = TESTER.getEventSource(this.getClass().getName());
- assertNotNull("No StackTraceElement", ste);
- assertEquals("Incorrect event", this.getClass().getName(), ste.getClassName());
+ assertNotNull(ste, "No StackTraceElement");
+ assertEquals(this.getClass().getName(), ste.getClassName(), "Incorrect event");
}
private static class TestClass {
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java
index a6a5ca2..f8bfde9 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java
@@ -19,33 +19,25 @@ package org.apache.logging.log4j.core;
import java.util.Calendar;
import org.apache.logging.log4j.core.appender.FileAppender;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@LoggerContextSource("log4j-date.xml")
public class LoggerDateTest {
- private static final String CONFIG = "log4j-date.xml";
- private FileAppender fileApp;
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final FileAppender fileApp;
- @Before
- public void before() {
- fileApp = context.getRequiredAppender("File", FileAppender.class);
+ public LoggerDateTest(@Named("File") final FileAppender fileApp) {
+ this.fileApp = fileApp;
}
@Test
public void testFileName() {
final String name = fileApp.getFileName();
final int year = Calendar.getInstance().get(Calendar.YEAR);
- assertTrue("Date was not substituted: " + name, name.contains(Integer.toString(year)));
+ assertTrue(name.contains(Integer.toString(year)), "Date was not substituted: " + name);
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerTest.java
index e385277..92e8579 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerTest.java
@@ -16,14 +16,6 @@
*/
package org.apache.logging.log4j.core;
-import java.io.File;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Marker;
@@ -32,7 +24,8 @@ import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.LoggerConfig;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.apache.logging.log4j.junit.Named;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.message.ParameterizedMessageFactory;
@@ -41,47 +34,45 @@ import org.apache.logging.log4j.message.StringFormatterMessageFactory;
import org.apache.logging.log4j.message.StructuredDataMessage;
import org.apache.logging.log4j.spi.AbstractLogger;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
+import org.hamcrest.MatcherAssert;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+
+import java.io.File;
+import java.lang.reflect.Method;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.startsWith;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.*;
+@LoggerContextSource(value = LoggerTest.CONFIG, reconfigure = true)
public class LoggerTest {
- private static final String CONFIG = "log4j-test2.xml";
-
- @Rule
- public final TestName testName = new TestName();
- private ListAppender app;
- private ListAppender host;
- private ListAppender noThrown;
-
- @Rule
- public LoggerContextRule context = new LoggerContextRule(CONFIG);
-
- private void assertEventCount(final List<LogEvent> events, final int expected) {
- assertEquals("Incorrect number of events.", expected, events.size());
- }
+ static final String CONFIG = "log4j-test2.xml";
+ org.apache.logging.log4j.Logger logger;
+ org.apache.logging.log4j.Logger loggerChild;
+ org.apache.logging.log4j.Logger loggerGrandchild;
+ private final ListAppender app;
+ private final ListAppender host;
+ private final ListAppender noThrown;
- @Before
- public void before() {
+ public LoggerTest(final LoggerContext context, @Named("List") final ListAppender app, @Named("HostTest") final ListAppender host, @Named("NoThrowable") final ListAppender noThrown) {
logger = context.getLogger("LoggerTest");
loggerChild = context.getLogger("LoggerTest.child");
loggerGrandchild = context.getLogger("LoggerTest.child.grand");
- //
- app = context.getListAppender("List").clear();
- host = context.getListAppender("HostTest").clear();
- noThrown = context.getListAppender("NoThrowable").clear();
+ this.app = app.clear();
+ this.host = host.clear();
+ this.noThrown = noThrown.clear();
}
- org.apache.logging.log4j.Logger logger;
- org.apache.logging.log4j.Logger loggerChild;
- org.apache.logging.log4j.Logger loggerGrandchild;
+ private void assertEventCount(final List<LogEvent> events, final int expected) {
+ assertEquals(expected, events.size(), "Incorrect number of events.");
+ }
@Test
public void builder() {
@@ -91,10 +82,12 @@ public class LoggerTest {
logger.atWarn().withThrowable(new Throwable("This is a test")).log((Message) new SimpleMessage("Log4j rocks!"));
final List<LogEvent> events = app.getEvents();
assertEventCount(events, 3);
- assertEquals("Incorrect location", "org.apache.logging.log4j.core.LoggerTest.builder(LoggerTest.java:88)", events.get(0).getSource().toString());
- assertEquals("Incorrect Level", Level.DEBUG, events.get(0).getLevel());
- assertThat("Incorrect message", events.get(1).getMessage().getFormattedMessage(), equalTo("Hello John"));
- assertNotNull("Missing Throwable", events.get(2).getThrown());
+ assertEquals(
+ "org.apache.logging.log4j.core.LoggerTest.builder(LoggerTest.java:79)", events.get(0).getSource().toString(),
+ "Incorrect location");
+ assertEquals(Level.DEBUG, events.get(0).getLevel(), "Incorrect Level");
+ MatcherAssert.assertThat("Incorrect message", events.get(1).getMessage().getFormattedMessage(), equalTo("Hello John"));
+ assertNotNull(events.get(2).getThrown(), "Missing Throwable");
}
@Test
@@ -189,7 +182,7 @@ public class LoggerTest {
}
@Test
- public void debugChangeLevelsChildLoggers() {
+ public void debugChangeLevelsChildLoggers(final LoggerContext context) {
final org.apache.logging.log4j.Logger loggerChild = context.getLogger(logger.getName() + ".child");
// Use logger AND loggerChild
logger.debug("Debug message 1");
@@ -259,8 +252,8 @@ public class LoggerTest {
}
@Test
- public void getLogger_String_MessageFactoryMismatch() {
- final Logger testLogger = testMessageFactoryMismatch(testName.getMethodName(),
+ public void getLogger_String_MessageFactoryMismatch(final TestInfo testInfo) {
+ final Logger testLogger = testMessageFactoryMismatch(testInfo.getTestMethod().map(Method::getName).orElseThrow(AssertionError::new),
StringFormatterMessageFactory.INSTANCE, ParameterizedMessageFactory.INSTANCE);
testLogger.debug("%,d", Integer.MAX_VALUE);
final List<LogEvent> events = app.getEvents();
@@ -269,8 +262,8 @@ public class LoggerTest {
}
@Test
- public void getLogger_String_MessageFactoryMismatchNull() {
- final Logger testLogger = testMessageFactoryMismatch(testName.getMethodName(), StringFormatterMessageFactory.INSTANCE, null);
+ public void getLogger_String_MessageFactoryMismatchNull(final TestInfo testInfo) {
+ final Logger testLogger = testMessageFactoryMismatch(testInfo.getTestMethod().map(Method::getName).orElseThrow(AssertionError::new), StringFormatterMessageFactory.INSTANCE, null);
testLogger.debug("%,d", Integer.MAX_VALUE);
final List<LogEvent> events = app.getEvents();
assertEventCount(events, 1);
@@ -313,24 +306,24 @@ public class LoggerTest {
}
@Test
- public void testImpliedThrowable() {
+ public void testImpliedThrowable(final LoggerContext context) {
final org.apache.logging.log4j.Logger testLogger = context.getLogger("org.apache.logging.log4j.hosttest");
testLogger.debug("This is a test", new Throwable("Testing"));
final List<String> msgs = host.getMessages();
- assertEquals("Incorrect number of messages. Expected 1, actual " + msgs.size(), 1, msgs.size());
+ assertEquals(1, msgs.size(), "Incorrect number of messages. Expected 1, actual " + msgs.size());
final String expected = "java.lang.Throwable: Testing";
- assertTrue("Incorrect message data", msgs.get(0).contains(expected));
+ assertTrue(msgs.get(0).contains(expected), "Incorrect message data");
}
@Test
- public void testSuppressedThrowable() {
+ public void testSuppressedThrowable(final LoggerContext context) {
final org.apache.logging.log4j.Logger testLogger = context.getLogger("org.apache.logging.log4j.nothrown");
testLogger.debug("This is a test", new Throwable("Testing"));
final List<String> msgs = noThrown.getMessages();
- assertEquals("Incorrect number of messages. Expected 1, actual " + msgs.size(), 1, msgs.size());
+ assertEquals(1, msgs.size(), "Incorrect number of messages. Expected 1, actual " + msgs.size());
final String suppressed = "java.lang.Throwable: Testing";
- assertTrue("Incorrect message data", !msgs.get(0).contains(suppressed));
+ assertFalse(msgs.get(0).contains(suppressed), "Incorrect message data");
}
@@ -360,13 +353,13 @@ public class LoggerTest {
}
@Test
- public void testReconfiguration() throws Exception {
+ public void testReconfiguration(final LoggerContext context) throws Exception {
final Configuration oldConfig = context.getConfiguration();
final int MONITOR_INTERVAL_SECONDS = 5;
final File file = new File("target/test-classes/" + CONFIG);
final long orig = file.lastModified();
final long newTime = orig + 10000;
- assertTrue("setLastModified should have succeeded.", file.setLastModified(newTime));
+ assertTrue(file.setLastModified(newTime), "setLastModified should have succeeded.");
TimeUnit.SECONDS.sleep(MONITOR_INTERVAL_SECONDS + 1);
for (int i = 0; i < 17; ++i) {
logger.debug("Reconfigure");
@@ -379,12 +372,12 @@ public class LoggerTest {
Thread.sleep(50);
}
final Configuration newConfig = context.getConfiguration();
- assertNotNull("No configuration", newConfig);
- assertNotSame("Reconfiguration failed", newConfig, oldConfig);
+ assertNotNull(newConfig, "No configuration");
+ assertNotSame(newConfig, oldConfig, "Reconfiguration failed");
}
@Test
- public void testAdditivity() throws Exception {
+ public void testAdditivity(final LoggerContext context) throws Exception {
final Logger localLogger = context.getLogger("org.apache.test");
localLogger.error("Test parent additivity");
final List<LogEvent> events = app.getEvents();
@@ -392,25 +385,25 @@ public class LoggerTest {
}
@Test
- public void testLevelInheritence() throws Exception {
+ public void testLevelInheritance(final LoggerContext context) throws Exception {
final Configuration config = context.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig("org.apache.logging.log4j.core.LoggerTest");
assertNotNull(loggerConfig);
assertEquals(loggerConfig.getName(), "org.apache.logging.log4j.core.LoggerTest");
assertEquals(loggerConfig.getLevel(), Level.DEBUG);
final Logger localLogger = context.getLogger("org.apache.logging.log4j.core.LoggerTest");
- assertTrue("Incorrect level - expected DEBUG, actual " + localLogger.getLevel(), localLogger.getLevel() == Level.DEBUG);
+ assertSame(localLogger.getLevel(), Level.DEBUG, "Incorrect level - expected DEBUG, actual " + localLogger.getLevel());
}
@Test
public void paramWithExceptionTest() throws Exception {
logger.error("Throwing with parameters {}", "TestParam", new NullPointerException("Test Exception"));
final List<LogEvent> events = app.getEvents();
- assertNotNull("Log event list not returned", events);
- assertEquals("Incorrect number of log events", 1, events.size());
+ assertNotNull(events, "Log event list not returned");
+ assertEquals(1, events.size(), "Incorrect number of log events");
final LogEvent event = events.get(0);
final Throwable thrown = event.getThrown();
- assertNotNull("No throwable present in log event", thrown);
+ assertNotNull(thrown, "No throwable present in log event");
final Message msg = event.getMessage();
assertEquals("Throwing with parameters {}", msg.getFormat());
assertEquals("Throwing with parameters TestParam", msg.getFormattedMessage());
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java
index 572e392..854fbef 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java
@@ -16,43 +16,35 @@
*/
package org.apache.logging.log4j.core;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.util.List;
-
-import org.apache.logging.log4j.*;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import java.util.List;
-/**
- *
- */
-public class LoggerUpdateTest {
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
- private static final String CONFIG = "log4j-test2.xml";
- private ListAppender app;
+@LoggerContextSource("log4j-test2.xml")
+public class LoggerUpdateTest {
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final ListAppender app;
- @Before
- public void before() {
- app = context.getListAppender("List").clear();
+ public LoggerUpdateTest(@Named("List") final ListAppender app) {
+ this.app = app.clear();
}
@Test
- public void resetLevel() {
+ public void resetLevel(final LoggerContext context) {
final org.apache.logging.log4j.Logger logger = context.getLogger("com.apache.test");
logger.traceEntry();
List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
app.clear();
final LoggerContext ctx = LoggerContext.getContext(false);
final Configuration config = ctx.getConfiguration();
@@ -64,20 +56,16 @@ public class LoggerUpdateTest {
ctx.updateLoggers(); // This causes all Loggers to refetch information from their LoggerConfig.
logger.traceEntry();
events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 0, actual " + events.size(), 0, events.size());
+ assertEquals(0, events.size(), "Incorrect number of events. Expected 0, actual " + events.size());
}
@Test
- public void testUpdateLoggersPropertyListeners() throws Exception {
- final LoggerContext ctx = context.getLoggerContext();
- ctx.addPropertyChangeListener(new PropertyChangeListener() {
- @Override
- public void propertyChange(final PropertyChangeEvent evt) {
- assertEquals(LoggerContext.PROPERTY_CONFIG, evt.getPropertyName());
- assertSame(ctx, evt.getSource());
- }
+ public void testUpdateLoggersPropertyListeners(final LoggerContext context) throws Exception {
+ context.addPropertyChangeListener(evt -> {
+ assertEquals(LoggerContext.PROPERTY_CONFIG, evt.getPropertyName());
+ assertSame(context, evt.getSource());
});
- ctx.updateLoggers();
+ context.updateLoggers();
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggingTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggingTest.java
deleted file mode 100644
index 1365a08..0000000
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LoggingTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You 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.
- */
-package org.apache.logging.log4j.core;
-
-import java.util.List;
-
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.apache.logging.log4j.test.appender.ListAppender;
-import org.apache.logging.log4j.util.Timer;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-
-import static org.junit.Assert.assertEquals;
-
-
-public class LoggingTest {
-
- private static final String CONFIG = "log4j-list.xml";
-
- @Rule
- public final TestName testName = new TestName();
- private ListAppender list;
-
-
- @Rule
- public LoggerContextRule context = new LoggerContextRule(CONFIG);
-
- private void assertEventCount(final List<LogEvent> events, final int expected) {
- assertEquals("Incorrect number of events.", expected, events.size());
- }
-
- @Before
- public void before() {
- logger = context.getLogger("LoggerTest");
- }
-
- org.apache.logging.log4j.Logger logger;
-
- @Test
- public void logTime() {
- Timer timer = new Timer("initial");
- timer.start();
- logger.info("This is a test");
- System.out.println(timer.stop());
- timer = new Timer("more", 100);
-/* timer.start();
- for (int i=0; i < 100; ++i) {
- logger.info("This is another test");
- }
- System.out.println(timer.stop());*/
- }
-}
-
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/LookupTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/LookupTest.java
index 42c7f3c..0bab663 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/LookupTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/LookupTest.java
@@ -18,30 +18,23 @@ package org.apache.logging.log4j.core;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.layout.PatternLayout;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@LoggerContextSource("log4j-lookup.xml")
public class LookupTest {
- private static final String CONFIG = "log4j-lookup.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
@Test
- public void testHostname() {
- final ConsoleAppender app = context.getRequiredAppender("console", ConsoleAppender.class);
- final Layout<?> layout = app.getLayout();
- assertNotNull("No Layout", layout);
- assertTrue("Layout is not a PatternLayout", layout instanceof PatternLayout);
+ public void testHostname(@Named final ConsoleAppender console) {
+ final Layout<?> layout = console.getLayout();
+ assertNotNull(layout, "No Layout");
+ assertTrue(layout instanceof PatternLayout, "Layout is not a PatternLayout");
final String pattern = ((PatternLayout) layout).getConversionPattern();
- assertNotNull("No conversion pattern", pattern);
- assertTrue("No filters", pattern.contains("org.junit,org.apache.maven,org.eclipse,sun.reflect,java.lang.reflect"));
+ assertNotNull(pattern, "No conversion pattern");
+ assertTrue(pattern.contains("org.junit,org.apache.maven,org.eclipse,sun.reflect,java.lang.reflect"),
+ "No filters");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java
index c1df3f8..7fb6cae 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java
@@ -19,59 +19,50 @@ package org.apache.logging.log4j.core;
import java.util.List;
import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.apache.logging.log4j.util.Strings;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-/**
- *
- */
-public class PatternSelectorTest {
+import static org.junit.jupiter.api.Assertions.*;
-
- private static final String CONFIG = "log4j-patternSelector.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+@LoggerContextSource("log4j-patternSelector.xml")
+public class PatternSelectorTest {
@Test
- public void testMarkerPatternSelector() throws Exception {
+ public void testMarkerPatternSelector(@Named("List") final ListAppender app) {
final org.apache.logging.log4j.Logger logger = LogManager.getLogger("TestMarkerPatternSelector");
logger.traceEntry();
logger.info("Hello World");
logger.traceExit();
- final ListAppender app = (ListAppender) context.getRequiredAppender("List");
- assertNotNull("No ListAppender", app);
final List<String> messages = app.getMessages();
- assertNotNull("No Messages", messages);
- assertTrue("Incorrect number of messages. Expected 3, Actual " + messages.size() + ": " + messages, messages.size() == 3);
+ assertNotNull(messages, "No Messages");
+ assertEquals(3, messages.size(),
+ "Incorrect number of messages. Expected 3, Actual " + messages.size() + ": " + messages);
final String expect = String.format("[TRACE] TestMarkerPatternSelector ====== "
- + "o.a.l.l.c.PatternSelectorTest.testMarkerPatternSelector:43 Enter ======%n");
+ + "o.a.l.l.c.PatternSelectorTest.testMarkerPatternSelector:36 Enter ======%n");
assertEquals(expect, messages.get(0));
assertEquals("[INFO ] TestMarkerPatternSelector Hello World" + Strings.LINE_SEPARATOR, messages.get(1));
app.clear();
}
@Test
- public void testScriptPatternSelector() throws Exception {
+ public void testScriptPatternSelector(@Named("List2") final ListAppender app) {
final org.apache.logging.log4j.Logger logger = LogManager.getLogger("TestScriptPatternSelector");
final org.apache.logging.log4j.Logger logger2 = LogManager.getLogger("NoLocation");
logger.traceEntry();
logger.info("Hello World");
logger2.info("No location information");
logger.traceExit();
- final ListAppender app = (ListAppender) context.getRequiredAppender("List2");
- assertNotNull("No ListAppender", app);
final List<String> messages = app.getMessages();
- assertNotNull("No Messages", messages);
- assertTrue("Incorrect number of messages. Expected 4, Actual " + messages.size() + ": " + messages, messages.size() == 4);
+ assertNotNull(messages, "No Messages");
+ assertEquals(4, messages.size(),
+ "Incorrect number of messages. Expected 4, Actual " + messages.size() + ": " + messages);
String expect = "[TRACE] TestScriptPatternSelector ====== " +
- "o.a.l.l.c.PatternSelectorTest.testScriptPatternSelector:62 Enter ======" + Strings.LINE_SEPARATOR;
+ "o.a.l.l.c.PatternSelectorTest.testScriptPatternSelector:54 Enter ======" + Strings.LINE_SEPARATOR;
assertEquals(expect, messages.get(0));
- expect = "[INFO ] TestScriptPatternSelector o.a.l.l.c.PatternSelectorTest.testScriptPatternSelector.63 " +
+ expect = "[INFO ] TestScriptPatternSelector o.a.l.l.c.PatternSelectorTest.testScriptPatternSelector.55 " +
"Hello World" + Strings.LINE_SEPARATOR;
assertEquals(expect, messages.get(1));
assertEquals("[INFO ] NoLocation No location information" + Strings.LINE_SEPARATOR, messages.get(2));
@@ -79,23 +70,22 @@ public class PatternSelectorTest {
}
@Test
- public void testJavaScriptPatternSelector() throws Exception {
+ public void testJavaScriptPatternSelector(@Named("List3") final ListAppender app) {
final org.apache.logging.log4j.Logger logger = LogManager.getLogger("TestJavaScriptPatternSelector");
final org.apache.logging.log4j.Logger logger2 = LogManager.getLogger("JavascriptNoLocation");
logger.traceEntry();
logger.info("Hello World");
logger2.info("No location information");
logger.traceExit();
- final ListAppender app = (ListAppender) context.getRequiredAppender("List3");
- assertNotNull("No ListAppender", app);
final List<String> messages = app.getMessages();
- assertNotNull("No Messages", messages);
- assertTrue("Incorrect number of messages. Expected 4, Actual " + messages.size() + ": " + messages, messages.size() == 4);
+ assertNotNull(messages, "No Messages");
+ assertEquals(4, messages.size(),
+ "Incorrect number of messages. Expected 4, Actual " + messages.size() + ": " + messages);
String expect = "[TRACE] TestJavaScriptPatternSelector ====== " +
- "o.a.l.l.c.PatternSelectorTest.testJavaScriptPatternSelector:85 Enter ======" + Strings.LINE_SEPARATOR;
+ "o.a.l.l.c.PatternSelectorTest.testJavaScriptPatternSelector:76 Enter ======" + Strings.LINE_SEPARATOR;
assertEquals(expect, messages.get(0));
expect = "[INFO ] TestJavaScriptPatternSelector " +
- "o.a.l.l.c.PatternSelectorTest.testJavaScriptPatternSelector.86 Hello World" + Strings.LINE_SEPARATOR;
+ "o.a.l.l.c.PatternSelectorTest.testJavaScriptPatternSelector.77 Hello World" + Strings.LINE_SEPARATOR;
assertEquals(expect, messages.get(1));
assertEquals("[INFO ] JavascriptNoLocation No location information" + Strings.LINE_SEPARATOR, messages.get(2));
app.clear();
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java
index 4893c68..9d12ce3 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java
@@ -16,43 +16,43 @@
*/
package org.apache.logging.log4j.core;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.apache.logging.log4j.test.appender.ListAppender;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.concurrent.TimeUnit;
-import org.apache.logging.log4j.core.config.Configuration;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-/**
- *
- */
+@LoggerContextSource("log4j-test2.properties")
public class PropertiesFileConfigTest {
private static final String CONFIG = "target/test-classes/log4j-test2.properties";
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+ private final org.apache.logging.log4j.Logger logger;
- private final org.apache.logging.log4j.Logger logger = context.getLogger("LoggerTest");
+ public PropertiesFileConfigTest(final LoggerContext context) {
+ logger = context.getLogger("LoggerTest");
+ }
- @Before
- public void before() {
- context.getListAppender("List").clear();
+ @BeforeEach
+ void clear(@Named("List") final ListAppender appender) {
+ appender.clear();
}
@Test
- public void testReconfiguration() throws Exception {
+ public void testReconfiguration(final LoggerContext context) throws Exception {
final Configuration oldConfig = context.getConfiguration();
final int MONITOR_INTERVAL_SECONDS = 5;
final File file = new File(CONFIG);
final long orig = file.lastModified();
final long newTime = orig + 10000;
- assertTrue("setLastModified should have succeeded.", file.setLastModified(newTime));
+ assertTrue(file.setLastModified(newTime), "setLastModified should have succeeded.");
TimeUnit.SECONDS.sleep(MONITOR_INTERVAL_SECONDS + 1);
for (int i = 0; i < 17; ++i) {
logger.info("Reconfigure");
@@ -63,7 +63,7 @@ public class PropertiesFileConfigTest {
Thread.sleep(100);
newConfig = context.getConfiguration();
} while (newConfig == oldConfig && loopCount++ < 5);
- assertNotSame("Reconfiguration failed", newConfig, oldConfig);
+ assertNotSame(newConfig, oldConfig, "Reconfiguration failed");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java
index c08f705..b162d27 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java
@@ -18,17 +18,16 @@ package org.apache.logging.log4j.core;
import org.apache.logging.log4j.message.ReusableMessage;
import org.apache.logging.log4j.message.ReusableMessageFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ReusableParameterizedMessageMemoryLeakTest {
@Test
- @SuppressWarnings("UnusedAssignment") // parameter set to null to allow garbage collection
public void testParametersAreNotLeaked() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
ReusableMessage message = (ReusableMessage) ReusableMessageFactory.INSTANCE.newMessage(
@@ -38,7 +37,7 @@ public class ReusableParameterizedMessageMemoryLeakTest {
GarbageCollectionHelper gcHelper = new GarbageCollectionHelper();
gcHelper.run();
try {
- assertTrue("Parameter should have been garbage collected", latch.await(30, TimeUnit.SECONDS));
+ assertTrue(latch.await(30, TimeUnit.SECONDS), "Parameter should have been garbage collected");
} finally {
gcHelper.close();
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java
index 5fcecd4..ef53e89 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java
@@ -17,27 +17,17 @@
package org.apache.logging.log4j.core;
import org.apache.logging.log4j.core.config.Configuration;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
-/**
- *
- */
+@LoggerContextSource("log4j-test3.xml")
public class ShutdownDisabledTest {
- private static final String CONFIG = "log4j-test3.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
@Test
- public void testShutdownFlag() {
- final Configuration config = context.getConfiguration();
- assertNotNull("No configuration", config);
- assertFalse("Shutdown hook is enabled", config.isShutdownHookEnabled());
+ public void testShutdownFlag(final Configuration config) {
+ assertFalse(config.isShutdownHookEnabled(), "Shutdown hook is enabled");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java
index 5e0734c..dc34879 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java
@@ -17,26 +17,16 @@
package org.apache.logging.log4j.core;
import org.apache.logging.log4j.core.config.Configuration;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.apache.logging.log4j.junit.LoggerContextSource;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@LoggerContextSource("log4j-test-shutdownTimeout.xml")
public class ShutdownTimeoutConfigurationTest {
- private static final String CONFIG = "log4j-test-shutdownTimeout.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
@Test
- public void testShutdownFlag() {
- final Configuration config = context.getConfiguration();
- assertNotNull("No configuration", config);
+ public void testShutdownFlag(final Configuration config) {
assertEquals(5000, config.getShutdownTimeoutMillis());
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java
index 0b6af49..4bf661f 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java
@@ -16,46 +16,38 @@
*/
package org.apache.logging.log4j.core;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.ThreadContext;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.message.EntryMessage;
import org.apache.logging.log4j.message.StructuredDataMessage;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
-/**
- *
- */
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+@LoggerContextSource("log4j-strict1.xml")
public class StrictXmlConfigTest {
- private static final String CONFIG = "log4j-strict1.xml";
+ org.apache.logging.log4j.Logger logger;
private ListAppender app;
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
-
- @Before
- public void setUp() throws Exception {
- app = context.getListAppender("List").clear();
+ public StrictXmlConfigTest(final LoggerContext context, @Named("List") final ListAppender app) {
+ logger = context.getLogger("LoggerTest");
+ this.app = app.clear();
}
- org.apache.logging.log4j.Logger logger = context.getLogger("LoggerTest");
-
@Test
public void basicFlow() {
final EntryMessage entry = logger.traceEntry();
logger.traceExit(entry);
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 2, actual " + events.size(), 2, events.size());
+ assertEquals(2, events.size(), "Incorrect number of events. Expected 2, actual " + events.size());
}
@Test
@@ -63,22 +55,22 @@ public class StrictXmlConfigTest {
logger.traceEntry();
logger.traceExit();
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 2, actual " + events.size(), 2, events.size());
+ assertEquals(2, events.size(), "Incorrect number of events. Expected 2, actual " + events.size());
}
@Test
public void simpleFlow() {
- logger.traceEntry(CONFIG);
+ logger.traceEntry();
logger.traceExit(0);
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 2, actual " + events.size(), 2, events.size());
+ assertEquals(2, events.size(), "Incorrect number of events. Expected 2, actual " + events.size());
}
@Test
public void throwing() {
logger.throwing(new IllegalArgumentException("Test Exception"));
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
}
@Test
@@ -89,28 +81,28 @@ public class StrictXmlConfigTest {
logger.catching(e);
}
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
}
@Test
public void debug() {
logger.debug("Debug message");
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
}
@Test
public void debugObject() {
logger.debug(new Date());
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
}
@Test
public void debugWithParms() {
logger.debug("Hello, {}", "World");
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
}
@Test
@@ -120,7 +112,7 @@ public class StrictXmlConfigTest {
ThreadContext.clearMap();
logger.debug("Debug message");
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 2, actual " + events.size(), 2, events.size());
+ assertEquals(2, events.size(), "Incorrect number of events. Expected 2, actual " + events.size());
}
@Test
@@ -135,7 +127,7 @@ public class StrictXmlConfigTest {
logger.info(MarkerManager.getMarker("EVENT"), msg);
ThreadContext.clearMap();
final List<LogEvent> events = app.getEvents();
- assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
+ assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size());
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java
index 728c038..d22f4e6 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java
@@ -16,26 +16,26 @@
*/
package org.apache.logging.log4j.core;
-import java.util.List;
-
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.time.Clock;
import org.apache.logging.log4j.core.time.ClockFactory;
import org.apache.logging.log4j.core.time.ClockFactoryTest;
import org.apache.logging.log4j.core.util.Constants;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.Named;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.message.TimestampMessage;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.apache.logging.log4j.util.Strings;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Confirms that if you log a {@link TimestampMessage} then there are no unnecessary calls to {@link Clock}.
@@ -43,30 +43,27 @@ import static org.junit.Assert.*;
* See LOG4J2-744.
* </p>
*/
+@LoggerContextSource("log4j2-744.xml")
public class TimestampMessageTest {
private ListAppender app;
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule("log4j2-744.xml");
+ public TimestampMessageTest(@Named("List") final ListAppender app) {
+ this.app = app.clear();
+ }
- @BeforeClass
+ @BeforeAll
public static void beforeClass() {
System.setProperty(ClockFactory.PROPERTY_NAME, PoisonClock.class.getName());
}
- @Before
- public void setUp() throws Exception {
- this.app = context.getListAppender("List").clear();
- }
-
- @AfterClass
+ @AfterAll
public static void afterClass() throws IllegalAccessException {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY);
ClockFactoryTest.resetClocks();
}
@Test
- public void testTimestampMessage() {
+ public void testTimestampMessage(final LoggerContext context) {
final Logger log = context.getLogger("TimestampMessageTest");
log.info((Message) new TimeMsg("Message with embedded timestamp", 123456789000L));
final List<String> msgs = app.getMessages();
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/XmlEvents.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/XmlEvents.java
index c9b6539..cf56051 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/XmlEvents.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/XmlEvents.java
@@ -16,25 +16,19 @@
*/
package org.apache.logging.log4j.core;
-import java.util.Locale;
-
import org.apache.logging.log4j.EventLogger;
import org.apache.logging.log4j.ThreadContext;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.message.AsynchronouslyFormattable;
import org.apache.logging.log4j.message.StructuredDataMessage;
-import org.junit.ClassRule;
-import org.junit.Test;
-
-/**
- *
- */
-public class XmlEvents {
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
- private static final String CONFIG = "xml-events.xml";
+import java.util.Locale;
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+@LoggerContextSource("xml-events.xml")
+@Disabled("TODO")
+public class XmlEvents {
@Test
public void testEvents() {
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java
index 8f13ae2..dbd6c68 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java
@@ -46,7 +46,7 @@ public class DeleteActionTest {
private static DeleteAction create(final String path, final boolean followLinks, final int maxDepth, final boolean testMode,
final PathCondition[] conditions) {
- final Configuration config = new BasicConfigurationFactory().new BasicConfiguration();
+ final Configuration config = new BasicConfigurationFactory.BasicConfiguration();
final DeleteAction delete = DeleteAction.createDeleteAction(path, followLinks, maxDepth, testMode, null, conditions,
null, config);
return delete;
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java
index 0e1460f..6cf7e5c 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java
@@ -20,10 +20,10 @@ import java.lang.reflect.Field;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.util.ReflectionUtil;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class ClassLoaderContextSelectorTest {
@@ -31,7 +31,7 @@ public class ClassLoaderContextSelectorTest {
private ClassLoader loader1, loader2, loader3;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
loader1 = new TestClassLoader();
loader2 = new TestClassLoader();
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/ClockFactoryTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/ClockFactoryTest.java
index 17e184d..dbf7880 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/ClockFactoryTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/ClockFactoryTest.java
@@ -22,13 +22,17 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.core.time.internal.CachedClock;
import org.apache.logging.log4j.core.time.internal.CoarseCachedClock;
import org.apache.logging.log4j.core.time.internal.SystemClock;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledOnJre;
+import org.junit.jupiter.api.condition.JRE;
import java.lang.reflect.Field;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
+// as of Java 12, final fields can no longer be overwritten via reflection
+@EnabledOnJre({ JRE.JAVA_8, JRE.JAVA_9, JRE.JAVA_10, JRE.JAVA_11 })
public class ClockFactoryTest {
public static void resetClocks() throws IllegalAccessException {
@@ -43,7 +47,7 @@ public class ClockFactoryTest {
FieldUtils.writeStaticField(field, ClockFactory.getClock(), false);
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
resetClocks();
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/MutableInstantTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/MutableInstantTest.java
index cf5d563..4a6e9c4 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/MutableInstantTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/MutableInstantTest.java
@@ -17,160 +17,159 @@
package org.apache.logging.log4j.core.time;
import org.apache.logging.log4j.core.time.internal.FixedPreciseClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.*;
public class MutableInstantTest {
@Test
public void testGetEpochSecond() {
MutableInstant instant = new MutableInstant();
- assertEquals("initial", 0, instant.getEpochSecond());
+ assertEquals(0, instant.getEpochSecond(), "initial");
instant.initFromEpochSecond(123, 456);
- assertEquals("returns directly set value", 123, instant.getEpochSecond());
+ assertEquals(123, instant.getEpochSecond(), "returns directly set value");
instant.initFromEpochMilli(123456, 789012);
- assertEquals("returns converted value when initialized from milllis", 123, instant.getEpochSecond());
+ assertEquals(123, instant.getEpochSecond(), "returns converted value when initialized from milllis");
MutableInstant other = new MutableInstant();
other.initFromEpochSecond(788, 456);
instant.initFrom(other);
- assertEquals("returns ref value when initialized from instant", 788, instant.getEpochSecond());
+ assertEquals(788, instant.getEpochSecond(), "returns ref value when initialized from instant");
}
@Test
public void testGetNanoOfSecond() {
MutableInstant instant = new MutableInstant();
- assertEquals("initial", 0, instant.getNanoOfSecond());
+ assertEquals(0, instant.getNanoOfSecond(), "initial");
instant.initFromEpochSecond(123, 456);
- assertEquals("returns directly set value", 456, instant.getNanoOfSecond());
+ assertEquals(456, instant.getNanoOfSecond(), "returns directly set value");
instant.initFromEpochMilli(123456, 789012);
- assertEquals("returns converted value when initialized from milllis", 456789012, instant.getNanoOfSecond());
+ assertEquals(456789012, instant.getNanoOfSecond(), "returns converted value when initialized from milllis");
MutableInstant other = new MutableInstant();
other.initFromEpochSecond(788, 456);
instant.initFrom(other);
- assertEquals("returns ref value when initialized from instant", 456, instant.getNanoOfSecond());
+ assertEquals(456, instant.getNanoOfSecond(), "returns ref value when initialized from instant");
}
@Test
public void testGetEpochMillisecond() {
MutableInstant instant = new MutableInstant();
- assertEquals("initial", 0, instant.getEpochMillisecond());
+ assertEquals(0, instant.getEpochMillisecond(), "initial");
instant.initFromEpochMilli(123, 456);
- assertEquals("returns directly set value", 123, instant.getEpochMillisecond());
+ assertEquals(123, instant.getEpochMillisecond(), "returns directly set value");
instant.initFromEpochSecond(123, 456789012);
- assertEquals("returns converted value when initialized from seconds", 123456, instant.getEpochMillisecond());
+ assertEquals(123456, instant.getEpochMillisecond(), "returns converted value when initialized from seconds");
MutableInstant other = new MutableInstant();
other.initFromEpochMilli(788, 456);
instant.initFrom(other);
- assertEquals("returns ref value when initialized from instant", 788, instant.getEpochMillisecond());
+ assertEquals(788, instant.getEpochMillisecond(), "returns ref value when initialized from instant");
}
@Test
public void getGetNanoOfMillisecond() {
MutableInstant instant = new MutableInstant();
- assertEquals("initial", 0, instant.getNanoOfMillisecond());
+ assertEquals(0, instant.getNanoOfMillisecond(), "initial");
instant.initFromEpochMilli(123, 456);
- assertEquals("returns directly set value", 456, instant.getNanoOfMillisecond());
+ assertEquals(456, instant.getNanoOfMillisecond(), "returns directly set value");
instant.initFromEpochSecond(123, 456789012);
- assertEquals("returns converted value when initialized from milllis", 789012, instant.getNanoOfMillisecond());
+ assertEquals(789012, instant.getNanoOfMillisecond(), "returns converted value when initialized from milllis");
MutableInstant other = new MutableInstant();
other.initFromEpochMilli(788, 456);
instant.initFrom(other);
- assertEquals("returns ref value when initialized from instant", 456, instant.getNanoOfMillisecond());
+ assertEquals(456, instant.getNanoOfMillisecond(), "returns ref value when initialized from instant");
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testInitFromInstantRejectsNull() {
- new MutableInstant().initFrom((Instant) null);
+ assertThrows(NullPointerException.class, () -> new MutableInstant().initFrom((Instant) null));
}
@Test
public void testInitFromInstantCopiesValues() {
MutableInstant other = new MutableInstant();
other.initFromEpochSecond(788, 456);
- assertEquals("epochSec", 788, other.getEpochSecond());
- assertEquals("NanosOfSec", 456, other.getNanoOfSecond());
+ assertEquals(788, other.getEpochSecond(), "epochSec");
+ assertEquals(456, other.getNanoOfSecond(), "NanosOfSec");
MutableInstant instant = new MutableInstant();
instant.initFrom(other);
- assertEquals("epochSec", 788, instant.getEpochSecond());
- assertEquals("NanoOfSec", 456, instant.getNanoOfSecond());
+ assertEquals(788, instant.getEpochSecond(), "epochSec");
+ assertEquals(456, instant.getNanoOfSecond(), "NanoOfSec");
}
@Test
public void testInitFromEpochMillis() {
MutableInstant instant = new MutableInstant();
instant.initFromEpochMilli(123456, 789012);
- assertEquals("epochSec", 123, instant.getEpochSecond());
- assertEquals("NanoOfSec", 456789012, instant.getNanoOfSecond());
- assertEquals("epochMilli", 123456, instant.getEpochMillisecond());
- assertEquals("NanoOfMilli", 789012, instant.getNanoOfMillisecond());
+ assertEquals(123, instant.getEpochSecond(), "epochSec");
+ assertEquals(456789012, instant.getNanoOfSecond(), "NanoOfSec");
+ assertEquals(123456, instant.getEpochMillisecond(), "epochMilli");
+ assertEquals(789012, instant.getNanoOfMillisecond(), "NanoOfMilli");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testInitFromEpochMillisRejectsNegativeNanoOfMilli() {
MutableInstant instant = new MutableInstant();
- instant.initFromEpochMilli(123456, -1);
+ assertThrows(IllegalArgumentException.class, () -> instant.initFromEpochMilli(123456, -1));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testInitFromEpochMillisRejectsTooLargeNanoOfMilli() {
MutableInstant instant = new MutableInstant();
- instant.initFromEpochMilli(123456, 1000_000);
+ assertThrows(IllegalArgumentException.class, () -> instant.initFromEpochMilli(123456, 1000_000));
}
@Test
public void testInitFromEpochMillisAcceptsTooMaxNanoOfMilli() {
MutableInstant instant = new MutableInstant();
instant.initFromEpochMilli(123456, 999_999);
- assertEquals("NanoOfMilli", 999_999, instant.getNanoOfMillisecond());
+ assertEquals(999_999, instant.getNanoOfMillisecond(), "NanoOfMilli");
}
@Test
public void testInitFromEpochSecond() {
MutableInstant instant = new MutableInstant();
instant.initFromEpochSecond(123, 456789012);
- assertEquals("epochSec", 123, instant.getEpochSecond());
- assertEquals("NanoOfSec", 456789012, instant.getNanoOfSecond());
- assertEquals("epochMilli", 123456, instant.getEpochMillisecond());
- assertEquals("NanoOfMilli", 789012, instant.getNanoOfMillisecond());
+ assertEquals(123, instant.getEpochSecond(), "epochSec");
+ assertEquals(456789012, instant.getNanoOfSecond(), "NanoOfSec");
+ assertEquals(123456, instant.getEpochMillisecond(), "epochMilli");
+ assertEquals(789012, instant.getNanoOfMillisecond(), "NanoOfMilli");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testInitFromEpochSecondRejectsNegativeNanoOfMilli() {
MutableInstant instant = new MutableInstant();
- instant.initFromEpochSecond(123456, -1);
+ assertThrows(IllegalArgumentException.class, () -> instant.initFromEpochSecond(123456, -1));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testInitFromEpochSecondRejectsTooLargeNanoOfMilli() {
MutableInstant instant = new MutableInstant();
- instant.initFromEpochSecond(123456, 1000_000_000);
+ assertThrows(IllegalArgumentException.class, () -> instant.initFromEpochSecond(123456, 1000_000_000));
}
@Test
public void testInitFromEpochSecondAcceptsTooMaxNanoOfMilli() {
MutableInstant instant = new MutableInstant();
instant.initFromEpochSecond(123456, 999_999_999);
- assertEquals("NanoOfSec", 999_999_999, instant.getNanoOfSecond());
+ assertEquals(999_999_999, instant.getNanoOfSecond(), "NanoOfSec");
}
@Test
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/SystemNanoClockTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/SystemNanoClockTest.java
index 5ab9404..1676b97 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/SystemNanoClockTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/SystemNanoClockTest.java
@@ -17,11 +17,11 @@
package org.apache.logging.log4j.core.time;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the SystemNanoClock.
@@ -33,7 +33,7 @@ public class SystemNanoClockTest {
final NanoClock clock = new SystemNanoClock();
final long expected = System.nanoTime();
final long actual = clock.nanoTime();
- assertTrue("smal difference", actual - expected < TimeUnit.SECONDS.toNanos(1));
+ assertTrue(actual - expected < TimeUnit.SECONDS.toNanos(1), "smal difference");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/DummyNanoClockTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/DummyNanoClockTest.java
index 04f8956..e45a0e4 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/DummyNanoClockTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/DummyNanoClockTest.java
@@ -17,10 +17,9 @@
package org.apache.logging.log4j.core.time.internal;
-import org.apache.logging.log4j.core.time.internal.DummyNanoClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the DummyNanoClock.
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/SystemClockTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/SystemClockTest.java
index dd4b5c1..b018b19 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/SystemClockTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/time/internal/SystemClockTest.java
@@ -16,10 +16,9 @@
*/
package org.apache.logging.log4j.core.time.internal;
-import org.apache.logging.log4j.core.time.internal.SystemClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class SystemClockTest {
@@ -30,7 +29,7 @@ public class SystemClockTest {
final long diff = sysMillis - millis1;
- assertTrue("diff too large: " + diff, diff <= 1);
+ assertTrue(diff <= 1, "diff too large: " + diff);
}
@Test
@@ -41,7 +40,7 @@ public class SystemClockTest {
final long diff = sysMillis - millis1;
- assertTrue("diff too large: " + diff, diff <= 1);
+ assertTrue(diff <= 1, "diff too large: " + diff);
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java
index 0642253..1707bbd 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java
@@ -24,6 +24,7 @@ import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Locale;
@@ -41,14 +42,16 @@ import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.util.MessageSupplier;
import org.apache.logging.log4j.util.Supplier;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
+@Tag("functional")
public class GenerateCustomLoggerTest {
- @BeforeClass
+ @BeforeAll
public static void beforeClass() {
System.setProperty("log4j2.loggerContextFactory", "org.apache.logging.log4j.TestLoggerContextFactory");
}
@@ -72,8 +75,8 @@ public class GenerateCustomLoggerTest {
final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
final List<String> errors = new ArrayList<>();
try (final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
- final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays
- .asList(f));
+ final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(
+ Collections.singletonList(f));
// compile generated source
compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
@@ -85,16 +88,16 @@ public class GenerateCustomLoggerTest {
}
}
}
- assertTrue(errors.toString(), errors.isEmpty());
+ assertTrue(errors.isEmpty(), errors.toString());
// load the compiled class
final Class<?> cls = Class.forName(CLASSNAME);
// check that all factory methods exist and are static
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[0]).getModifiers()));
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Class.class }).getModifiers()));
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Object.class }).getModifiers()));
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { String.class }).getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create").getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class).getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class).getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", String.class).getModifiers()));
assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class, MessageFactory.class).getModifiers()));
assertTrue(Modifier
.isStatic(cls.getDeclaredMethod("create", Object.class, MessageFactory.class).getModifiers()));
@@ -104,36 +107,38 @@ public class GenerateCustomLoggerTest {
// check that all log methods exist
final String[] logMethods = { "defcon1", "defcon2", "defcon3" };
for (final String name : logMethods) {
- cls.getDeclaredMethod(name, Marker.class, Message.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, Object.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, String.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, Message.class);
- cls.getDeclaredMethod(name, Marker.class, Object.class);
- cls.getDeclaredMethod(name, Marker.class, String.class);
- cls.getDeclaredMethod(name, Message.class);
- cls.getDeclaredMethod(name, Object.class);
- cls.getDeclaredMethod(name, String.class);
- cls.getDeclaredMethod(name, Message.class, Throwable.class);
- cls.getDeclaredMethod(name, Object.class, Throwable.class);
- cls.getDeclaredMethod(name, String.class, Throwable.class);
- cls.getDeclaredMethod(name, String.class, Object[].class);
- cls.getDeclaredMethod(name, Marker.class, String.class, Object[].class);
-
- // 2.4 lambda support
- cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class);
- cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, String.class, Supplier[].class);
- cls.getDeclaredMethod(name, Marker.class, Supplier.class);
- cls.getDeclaredMethod(name, Marker.class, Supplier.class, Throwable.class);
- cls.getDeclaredMethod(name, MessageSupplier.class);
- cls.getDeclaredMethod(name, MessageSupplier.class, Throwable.class);
- cls.getDeclaredMethod(name, String.class, Supplier[].class);
- cls.getDeclaredMethod(name, Supplier.class);
- cls.getDeclaredMethod(name, Supplier.class, Throwable.class);
+ assertDoesNotThrow(() -> {
+ cls.getDeclaredMethod(name, Marker.class, Message.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, Object.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, String.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, Message.class);
+ cls.getDeclaredMethod(name, Marker.class, Object.class);
+ cls.getDeclaredMethod(name, Marker.class, String.class);
+ cls.getDeclaredMethod(name, Message.class);
+ cls.getDeclaredMethod(name, Object.class);
+ cls.getDeclaredMethod(name, String.class);
+ cls.getDeclaredMethod(name, Message.class, Throwable.class);
+ cls.getDeclaredMethod(name, Object.class, Throwable.class);
+ cls.getDeclaredMethod(name, String.class, Throwable.class);
+ cls.getDeclaredMethod(name, String.class, Object[].class);
+ cls.getDeclaredMethod(name, Marker.class, String.class, Object[].class);
+
+ // 2.4 lambda support
+ cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class);
+ cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, String.class, Supplier[].class);
+ cls.getDeclaredMethod(name, Marker.class, Supplier.class);
+ cls.getDeclaredMethod(name, Marker.class, Supplier.class, Throwable.class);
+ cls.getDeclaredMethod(name, MessageSupplier.class);
+ cls.getDeclaredMethod(name, MessageSupplier.class, Throwable.class);
+ cls.getDeclaredMethod(name, String.class, Supplier[].class);
+ cls.getDeclaredMethod(name, Supplier.class);
+ cls.getDeclaredMethod(name, Supplier.class, Throwable.class);
+ });
}
// now see if it actually works...
- final Method create = cls.getDeclaredMethod("create", new Class[] { String.class });
+ final Method create = cls.getDeclaredMethod("create", String.class);
final Object customLogger = create.invoke(null, "X.Y.Z");
int n = 0;
for (final String name : logMethods) {
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java
index 914ada8..127b889 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java
@@ -24,6 +24,7 @@ import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Locale;
@@ -37,20 +38,21 @@ import javax.tools.ToolProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.TestLogger;
-import org.apache.logging.log4j.core.tools.Generate;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.spi.ExtendedLogger;
import org.apache.logging.log4j.util.MessageSupplier;
import org.apache.logging.log4j.util.Supplier;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
+@Tag("functional")
public class GenerateExtendedLoggerTest {
- @BeforeClass
+ @BeforeAll
public static void beforeClass() {
System.setProperty("log4j2.loggerContextFactory", "org.apache.logging.log4j.TestLoggerContextFactory");
}
@@ -75,7 +77,7 @@ public class GenerateExtendedLoggerTest {
final List<String> errors = new ArrayList<>();
try (final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
final Iterable<? extends JavaFileObject> compilationUnits = fileManager
- .getJavaFileObjectsFromFiles(Arrays.asList(f));
+ .getJavaFileObjectsFromFiles(Collections.singletonList(f));
// compile generated source
compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();
@@ -87,16 +89,16 @@ public class GenerateExtendedLoggerTest {
}
}
}
- assertTrue(errors.toString(), errors.isEmpty());
+ assertTrue(errors.isEmpty(), errors.toString());
// load the compiled class
final Class<?> cls = Class.forName(CLASSNAME);
// check that all factory methods exist and are static
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[0]).getModifiers()));
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Class.class }).getModifiers()));
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Object.class }).getModifiers()));
- assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { String.class }).getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create").getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class).getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class).getModifiers()));
+ assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", String.class).getModifiers()));
assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class, MessageFactory.class).getModifiers()));
assertTrue(Modifier
.isStatic(cls.getDeclaredMethod("create", Object.class, MessageFactory.class).getModifiers()));
@@ -106,36 +108,38 @@ public class GenerateExtendedLoggerTest {
// check that the extended log methods exist
final String[] extendedMethods = { "diag", "notice", "verbose" };
for (final String name : extendedMethods) {
- cls.getDeclaredMethod(name, Marker.class, Message.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, Object.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, String.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, Message.class);
- cls.getDeclaredMethod(name, Marker.class, Object.class);
- cls.getDeclaredMethod(name, Marker.class, String.class);
- cls.getDeclaredMethod(name, Message.class);
- cls.getDeclaredMethod(name, Object.class);
- cls.getDeclaredMethod(name, String.class);
- cls.getDeclaredMethod(name, Message.class, Throwable.class);
- cls.getDeclaredMethod(name, Object.class, Throwable.class);
- cls.getDeclaredMethod(name, String.class, Throwable.class);
- cls.getDeclaredMethod(name, String.class, Object[].class);
- cls.getDeclaredMethod(name, Marker.class, String.class, Object[].class);
-
- // 2.4 lambda support
- cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class);
- cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class, Throwable.class);
- cls.getDeclaredMethod(name, Marker.class, String.class, Supplier[].class);
- cls.getDeclaredMethod(name, Marker.class, Supplier.class);
- cls.getDeclaredMethod(name, Marker.class, Supplier.class, Throwable.class);
- cls.getDeclaredMethod(name, MessageSupplier.class);
- cls.getDeclaredMethod(name, MessageSupplier.class, Throwable.class);
- cls.getDeclaredMethod(name, String.class, Supplier[].class);
- cls.getDeclaredMethod(name, Supplier.class);
- cls.getDeclaredMethod(name, Supplier.class, Throwable.class);
+ assertDoesNotThrow(() -> {
+ cls.getDeclaredMethod(name, Marker.class, Message.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, Object.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, String.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, Message.class);
+ cls.getDeclaredMethod(name, Marker.class, Object.class);
+ cls.getDeclaredMethod(name, Marker.class, String.class);
+ cls.getDeclaredMethod(name, Message.class);
+ cls.getDeclaredMethod(name, Object.class);
+ cls.getDeclaredMethod(name, String.class);
+ cls.getDeclaredMethod(name, Message.class, Throwable.class);
+ cls.getDeclaredMethod(name, Object.class, Throwable.class);
+ cls.getDeclaredMethod(name, String.class, Throwable.class);
+ cls.getDeclaredMethod(name, String.class, Object[].class);
+ cls.getDeclaredMethod(name, Marker.class, String.class, Object[].class);
+
+ // 2.4 lambda support
+ cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class);
+ cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class, Throwable.class);
+ cls.getDeclaredMethod(name, Marker.class, String.class, Supplier[].class);
+ cls.getDeclaredMethod(name, Marker.class, Supplier.class);
+ cls.getDeclaredMethod(name, Marker.class, Supplier.class, Throwable.class);
+ cls.getDeclaredMethod(name, MessageSupplier.class);
+ cls.getDeclaredMethod(name, MessageSupplier.class, Throwable.class);
+ cls.getDeclaredMethod(name, String.class, Supplier[].class);
+ cls.getDeclaredMethod(name, Supplier.class);
+ cls.getDeclaredMethod(name, Supplier.class, Throwable.class);
+ });
}
// now see if it actually works...
- final Method create = cls.getDeclaredMethod("create", new Class[] { String.class });
+ final Method create = cls.getDeclaredMethod("create", String.class);
final Object extendedLogger = create.invoke(null, "X.Y.Z");
int n = 0;
for (final String name : extendedMethods) {
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java
index f52c87d..ac01cde 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java
@@ -23,42 +23,39 @@ import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.impl.ThreadContextDataInjector;
import org.apache.logging.log4j.test.appender.ListAppender;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
-/**
- *
- */
+@Tag("functional")
public class ContextDataProviderTest {
private static Logger logger;
private static ListAppender appender;
- @BeforeClass
+ @BeforeAll
public static void beforeClass() {
ThreadContextDataInjector.contextDataProviders.add(new TestContextDataProvider());
- System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j-contextData.xml");
+ System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j-contextData.xml");
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
logger = loggerContext.getLogger(ContextDataProviderTest.class.getName());
appender = loggerContext.getConfiguration().getAppender("List");
- assertNotNull("No List appender", appender);
+ assertNotNull(appender, "No List appender");
}
@Test
- public void testContextProvider() throws Exception {
+ public void testContextProvider() {
ThreadContext.put("loginId", "jdoe");
logger.debug("This is a test");
List<String> messages = appender.getMessages();
- assertEquals("Incorrect number of messages", 1, messages.size());
- assertTrue("Context data missing", messages.get(0).contains("testKey=testValue"));
+ assertEquals(1, messages.size(), "Incorrect number of messages");
+ assertTrue(messages.get(0).contains("testKey=testValue"), "Context data missing");
}
private static class TestContextDataProvider implements ContextDataProvider {
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java
index c00d2f0..007a40e 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java
@@ -16,14 +16,14 @@
*/
package org.apache.logging.log4j.core.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Class Description goes here.
@@ -37,7 +37,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 11, 2).getTime();
final Date fireDate = parser.getNextValidTimeAfter(date);
final Date expected = new GregorianCalendar(2015, 11, 2, 7, 0, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
@Test
@@ -46,7 +46,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 11, 2).getTime();
final Date fireDate = parser.getNextValidTimeAfter(date);
final Date expected = new GregorianCalendar(2015, 11, 4, 7, 0, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
@Test
@@ -55,7 +55,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 11, 2).getTime();
final Date fireDate = parser.getNextValidTimeAfter(date);
final Date expected = new GregorianCalendar(2016, 0, 1, 7, 0, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
@Test
@@ -64,7 +64,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getNextValidTimeAfter(date);
final Date expected = new GregorianCalendar(2015, 10, 30, 7, 0, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
@Test
@@ -73,7 +73,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getNextValidTimeAfter(date);
final Date expected = new GregorianCalendar(2015, 10, 3, 0, 0, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
@Test
@@ -82,7 +82,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getPrevFireTime(date);
final Date expected = new GregorianCalendar(2015, 9, 31, 17, 45, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
@Test
@@ -91,7 +91,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getPrevFireTime(date);
final Date expected = new GregorianCalendar(2015, 10, 1, 18, 55, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
/**
@@ -103,7 +103,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getPrevFireTime(date);
final Date expected = new GregorianCalendar(2015, 10, 1, 23, 55, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
/**
@@ -116,7 +116,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getPrevFireTime(date);
final Date expected = new GregorianCalendar(2015, 10, 1, 10, 15, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
/**
@@ -128,7 +128,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getPrevFireTime(date);
final Date expected = new GregorianCalendar(2015, 10, 1, 14, 59, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
/**
@@ -140,7 +140,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getPrevFireTime(date);
final Date expected = new GregorianCalendar(2015, 2, 25, 14, 44, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
/**
@@ -152,7 +152,7 @@ public class CronExpressionTest {
final Date date = new GregorianCalendar(2015, 10, 2).getTime();
final Date fireDate = parser.getPrevFireTime(date);
final Date expected = new GregorianCalendar(2015, 9, 16, 10, 15, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
/*
@@ -170,7 +170,7 @@ public class CronExpressionTest {
final Date fireDate = parser.getTimeBefore(date);
System.err.println(sdf.format(fireDate));
final Date expected = new GregorianCalendar(2015, 10, 1, 0, 0, 0).getTime();
- assertEquals("Dates not equal.", expected, fireDate);
+ assertEquals(expected, fireDate, "Dates not equal.");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java
index 91f183a..2c48cb9 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java
@@ -16,11 +16,9 @@
*/
package org.apache.logging.log4j.core.util;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.Test;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
public class CyclicBufferTest {
@@ -32,7 +30,7 @@ public class CyclicBufferTest {
buffer.add(1);
assertTrue(buffer.isEmpty());
Integer[] items = buffer.removeAll();
- assertTrue("Incorrect number of items", items.length == 0);
+ assertEquals(0, items.length, "Incorrect number of items");
assertTrue(buffer.isEmpty());
buffer.add(1);
@@ -40,7 +38,7 @@ public class CyclicBufferTest {
buffer.add(3);
buffer.add(4);
items = buffer.removeAll();
- assertTrue("Incorrect number of items", items.length == 0);
+ assertEquals(0, items.length, "Incorrect number of items");
assertTrue(buffer.isEmpty());
}
@@ -52,7 +50,7 @@ public class CyclicBufferTest {
buffer.add(1);
assertFalse(buffer.isEmpty());
Integer[] items = buffer.removeAll();
- assertTrue("Incorrect number of items", items.length == 1);
+ assertEquals(1, items.length, "Incorrect number of items");
assertTrue(buffer.isEmpty());
buffer.add(1);
@@ -60,7 +58,7 @@ public class CyclicBufferTest {
buffer.add(3);
buffer.add(4);
items = buffer.removeAll();
- assertTrue("Incorrect number of items", items.length == 1);
+ assertEquals(1, items.length, "Incorrect number of items");
assertArrayEquals(new Integer[] { 4 }, items);
assertTrue(buffer.isEmpty());
}
@@ -73,7 +71,7 @@ public class CyclicBufferTest {
buffer.add(1);
assertFalse(buffer.isEmpty());
Integer[] items = buffer.removeAll();
- assertTrue("Incorrect number of items", items.length == 1);
+ assertEquals(1, items.length, "Incorrect number of items");
assertTrue(buffer.isEmpty());
buffer.add(1);
@@ -81,14 +79,14 @@ public class CyclicBufferTest {
buffer.add(3);
buffer.add(4);
items = buffer.removeAll();
- assertTrue("Incorrect number of items", items.length == 3);
+ assertEquals(3, items.length, "Incorrect number of items");
assertArrayEquals(new Integer[] { 2, 3, 4 }, items);
assertTrue(buffer.isEmpty());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testSizeNegative() {
- final CyclicBuffer<Integer> buffer = new CyclicBuffer<>(Integer.class, -1);
+ assertThrows(IllegalArgumentException.class, () -> new CyclicBuffer<>(Integer.class, -1));
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java
index 17568dc..fd1539c 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java
@@ -17,16 +17,12 @@
package org.apache.logging.log4j.core.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.net.URI;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the FileUtils class.
@@ -41,7 +37,7 @@ public class FileUtilsTest {
final URI uri = new URI(config);
final File file = FileUtils.fileFromUri(uri);
assertEquals(LOG4J_CONFIG_WITH_PLUS, file.getName());
- assertTrue("file exists", file.exists());
+ assertTrue(file.exists(), "file exists");
}
@Test
@@ -50,7 +46,7 @@ public class FileUtilsTest {
final URI uri = new File(config).toURI();
final File file = FileUtils.fileFromUri(uri);
assertEquals(LOG4J_CONFIG_WITH_PLUS, file.getName());
- assertTrue("file exists", file.exists());
+ assertTrue(file.exists(), "file exists");
}
@Test
@@ -59,7 +55,7 @@ public class FileUtilsTest {
final URI uri = new File(config).toURI();
final File file = FileUtils.fileFromUri(uri);
assertEquals(LOG4J_CONFIG_WITH_PLUS, file.getName());
- assertTrue("file exists", file.exists());
+ assertTrue(file.exists(), "file exists");
}
@Test
@@ -70,7 +66,7 @@ public class FileUtilsTest {
final URI uri = URI.create(uriStr);
final File file = FileUtils.fileFromUri(uri);
assertEquals(LOG4J_CONFIG_WITH_PLUS, file.getName());
- assertTrue("file exists", file.exists());
+ assertTrue(file.exists(), "file exists");
}
@Test
@@ -79,7 +75,7 @@ public class FileUtilsTest {
final URI uri = new URI(config);
final File file = FileUtils.fileFromUri(uri);
assertEquals(LOG4J_CONFIG_WITH_PLUS, file.getName());
- assertTrue("file exists", file.exists());
+ assertTrue(file.exists(), "file exists");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/InitTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/InitTest.java
index 5744886..9da7cd9 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/InitTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/InitTest.java
@@ -16,18 +16,18 @@
*/
package org.apache.logging.log4j.core.util;
-import static org.junit.Assert.assertTrue;
-
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.util.Timer;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test initialization.
*/
-@Ignore
+@Disabled
public class InitTest {
@Test
@@ -38,6 +38,6 @@ public class InitTest {
timer.stop();
long elapsed = timer.getElapsedNanoTime();
System.out.println(timer.toString());
- assertTrue("Initialization time exceeded threshold; elapsed " + elapsed, elapsed < 1000000000);
+ assertTrue(elapsed < 1000000000, "Initialization time exceeded threshold; elapsed " + elapsed);
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java
index 66d5002..63756df 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java
@@ -17,9 +17,9 @@
package org.apache.logging.log4j.core.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the Integers class.
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java
index 76e0f5a..a473028 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java
@@ -17,9 +17,9 @@
package org.apache.logging.log4j.core.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* This class is borrowed from <a href="https://github.com/FasterXML/jackson-core">Jackson</a>.
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java
index f2918b6..caab068 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java
@@ -17,9 +17,9 @@
package org.apache.logging.log4j.core.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests the Loader class.
@@ -28,13 +28,14 @@ public class LoaderTest {
@Test
public void testLoadClassWithNullClassloaderReturnNull() throws Exception {
- assertNull("Expect null return value for null ClassLoader.",
- Loader.loadClass(Loader.class.getCanonicalName(), null));
+ assertNull(
+ Loader.loadClass(Loader.class.getCanonicalName(), null), "Expect null return value for null ClassLoader.");
}
@Test
public void testLoadClassReturnClassForExistingClass() throws Exception {
- assertEquals("Expect Class return value for null ClassLoader.", Loader.class,
- Loader.loadClass(Loader.class.getCanonicalName(), Loader.getClassLoader()));
+ assertEquals(Loader.class,
+ Loader.loadClass(Loader.class.getCanonicalName(), Loader.getClassLoader()),
+ "Expect Class return value for null ClassLoader.");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java
index fc40037..a1cf6ab 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java
@@ -17,47 +17,44 @@
package org.apache.logging.log4j.core.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledOnOs;
+import org.junit.jupiter.api.condition.OS;
import java.net.URI;
-import java.net.URISyntaxException;
-import org.apache.logging.log4j.util.PropertiesUtil;
-import org.junit.Assume;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
public class NetUtilsTest {
- private static final boolean IS_WINDOWS = PropertiesUtil.getProperties().isOsWindows();
-
@Test
public void testToUriWithoutBackslashes() {
final String config = "file:///path/to/something/on/unix";
final URI uri = NetUtils.toURI(config);
- assertNotNull("The URI should not be null.", uri);
- assertEquals("The URI is not correct.", "file:///path/to/something/on/unix", uri.toString());
+ assertNotNull(uri, "The URI should not be null.");
+ assertEquals("file:///path/to/something/on/unix", uri.toString(), "The URI is not correct.");
}
@Test
+ @EnabledOnOs(OS.WINDOWS)
public void testToUriWindowsWithBackslashes() {
- Assume.assumeTrue(IS_WINDOWS);
final String config = "file:///D:\\path\\to\\something/on/windows";
final URI uri = NetUtils.toURI(config);
- assertNotNull("The URI should not be null.", uri);
- assertEquals("The URI is not correct.", "file:///D:/path/to/something/on/windows", uri.toString());
+ assertNotNull(uri, "The URI should not be null.");
+ assertEquals("file:///D:/path/to/something/on/windows", uri.toString(), "The URI is not correct.");
}
@Test
+ @EnabledOnOs(OS.WINDOWS)
public void testToUriWindowsAbsolutePath() {
- Assume.assumeTrue(IS_WINDOWS);
final String config = "D:\\path\\to\\something\\on\\windows";
final URI uri = NetUtils.toURI(config);
- assertNotNull("The URI should not be null.", uri);
- assertEquals("The URI is not correct.", "file:/D:/path/to/something/on/windows", uri.toString());
+ assertNotNull(uri, "The URI should not be null.");
+ assertEquals("file:/D:/path/to/something/on/windows", uri.toString(), "The URI is not correct.");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ProcessIdUtilTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ProcessIdUtilTest.java
index 44cee0a..661f8c8 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ProcessIdUtilTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ProcessIdUtilTest.java
@@ -16,16 +16,15 @@
*/
package org.apache.logging.log4j.core.util;
-import org.apache.logging.log4j.core.util.ProcessIdUtil;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class ProcessIdUtilTest {
@Test
- public void processIdTest() throws Exception {
+ public void processIdTest() {
String processId = ProcessIdUtil.getProcessId();
- assertFalse("ProcessId is default", processId.equals(ProcessIdUtil.DEFAULT_PROCESSID));
+ assertNotEquals(processId, ProcessIdUtil.DEFAULT_PROCESSID, "ProcessId is default");
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java
index 4a86d12..48e4a9e 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java
@@ -24,42 +24,39 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.impl.Log4jContextFactory;
import org.apache.logging.log4j.core.selector.ContextSelector;
-import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.junit.LoggerContextSource;
import org.apache.logging.log4j.status.StatusLogger;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class ShutdownCallbackRegistryTest {
- @Rule
- public final LoggerContextRule ctx = new LoggerContextRule("ShutdownCallbackRegistryTest.xml");
-
- @BeforeClass
- public static void setUpClass() throws Exception {
+ @BeforeAll
+ public static void setUpClass() {
System.setProperty("log4j2.is.webapp", "false");
System.setProperty(ShutdownCallbackRegistry.SHUTDOWN_CALLBACK_REGISTRY, Registry.class.getName());
}
- @AfterClass
+ @AfterAll
public static void afterClass() {
System.clearProperty(ShutdownCallbackRegistry.SHUTDOWN_CALLBACK_REGISTRY);
System.clearProperty("log4j2.is.webapp");
}
@Test
- public void testShutdownCallbackRegistry() throws Exception {
- final LoggerContext context = ctx.getLoggerContext();
- assertTrue("LoggerContext should be started", context.isStarted());
+ @LoggerContextSource("ShutdownCallbackRegistryTest.xml")
+ public void testShutdownCallbackRegistry(final LoggerContext context) {
+ assertTrue(context.isStarted(), "LoggerContext should be started");
assertThat(Registry.CALLBACKS, hasSize(1));
Registry.shutdown();
- assertTrue("LoggerContext should be stopped", context.isStopped());
+ assertTrue(context.isStopped(), "LoggerContext should be stopped");
assertThat(Registry.CALLBACKS, hasSize(0));
final ContextSelector selector = ((Log4jContextFactory) LogManager.getFactory()).getSelector();
assertThat(selector.getLoggerContexts(), not(hasItem(context)));
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ThrowablesTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ThrowablesTest.java
index 7e354bc..098d9ef 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ThrowablesTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/ThrowablesTest.java
@@ -16,22 +16,24 @@
*/
package org.apache.logging.log4j.core.util;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
public class ThrowablesTest {
@Test
public void testGetRootCauseNone() {
final NullPointerException throwable = new NullPointerException();
- Assert.assertEquals(throwable, Throwables.getRootCause(throwable));
+ assertEquals(throwable, Throwables.getRootCause(throwable));
}
@Test
public void testGetRootCauseDepth1() {
final Throwable cause = new NullPointerException();
final Throwable error = new UnsupportedOperationException(cause);
- Assert.assertEquals(cause, Throwables.getRootCause(error));
+ assertEquals(cause, Throwables.getRootCause(error));
}
@Test
@@ -39,31 +41,31 @@ public class ThrowablesTest {
final Throwable rootCause = new NullPointerException();
final Throwable cause = new UnsupportedOperationException(rootCause);
final Throwable error = new IllegalArgumentException(cause);
- Assert.assertEquals(rootCause, Throwables.getRootCause(error));
+ assertEquals(rootCause, Throwables.getRootCause(error));
}
- @Test(expected = IllegalArgumentException.class)
+ @SuppressWarnings("ThrowableNotThrown")
+ @Test
public void testGetRootCauseLoop() {
final Throwable cause1 = new RuntimeException();
final Throwable cause2 = new RuntimeException(cause1);
final Throwable cause3 = new RuntimeException(cause2);
cause1.initCause(cause3);
- // noinspection ThrowableNotThrown
- Throwables.getRootCause(cause3);
+ assertThrows(IllegalArgumentException.class, () -> Throwables.getRootCause(cause3));
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testRethrowRuntimeException() {
- Throwables.rethrow(new NullPointerException());
+ assertThrows(NullPointerException.class, () -> Throwables.rethrow(new NullPointerException()));
}
- @Test(expected = UnknownError.class)
+ @Test
public void testRethrowError() {
- Throwables.rethrow(new UnknownError());
+ assertThrows(UnknownError.class, () -> Throwables.rethrow(new UnknownError()));
}
- @Test(expected = NoSuchMethodException.class)
+ @Test
public void testRethrowCheckedException() {
- Throwables.rethrow(new NoSuchMethodException());
+ assertThrows(NoSuchMethodException.class, () -> Throwables.rethrow(new NoSuchMethodException()));
}
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java
index dbb4517..84bd5cc 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java
@@ -16,14 +16,12 @@
*/
package org.apache.logging.log4j.core.util;
+import org.junit.jupiter.api.Test;
+
import java.util.UUID;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
-import static org.junit.Assert.*;
-/**
- *
- */
public class UuidTest {
private static final int COUNT = 200;
@@ -37,7 +35,7 @@ public class UuidTest {
//final UUID uuid2 = UuidUtil.getTimeBasedUUID(); // unused
final long current = (System.currentTimeMillis() * 10000) + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH;
final long time = uuid.timestamp();
- assertTrue("Incorrect time", current + 10000 - time > 0);
+ assertTrue(current + 10000 - time > 0, "Incorrect time");
final UUID[] uuids = new UUID[COUNT];
final long start = System.nanoTime();
for (int i=0; i < COUNT; ++i) {
@@ -54,13 +52,13 @@ public class UuidTest {
}
}
}
- assertEquals(errors + " duplicate UUIDS", 0, errors);
+ assertEquals(0, errors, errors + " duplicate UUIDS");
final int variant = uuid.variant();
- assertEquals("Incorrect variant. Expected 2 got " + variant, 2, variant);
+ assertEquals(2, variant, "Incorrect variant. Expected 2 got " + variant);
final int version = uuid.version();
- assertEquals("Incorrect version. Expected 1 got " + version, 1, version);
+ assertEquals(1, version, "Incorrect version. Expected 1 got " + version);
final long node = uuid.node();
- assertTrue("Invalid node", node != 0);
+ assertTrue(node != 0, "Invalid node");
}
@Test
@@ -106,7 +104,7 @@ public class UuidTest {
}
}
}
- assertEquals(errors + " duplicate UUIDS", 0, errors);
+ assertEquals(0, errors, errors + " duplicate UUIDS");
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchHttpTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchHttpTest.java
index 8ae5970..87b1aac 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchHttpTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchHttpTest.java
@@ -155,7 +155,7 @@ public class WatchHttpTest {
}
}
- private class TestConfigurationListener implements ConfigurationListener {
+ private static class TestConfigurationListener implements ConfigurationListener {
private final Queue<String> queue;
private final String name;
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchManagerTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchManagerTest.java
index d70ce69..fecb2e7 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchManagerTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/util/WatchManagerTest.java
@@ -16,9 +16,6 @@
*/
package org.apache.logging.log4j.core.util;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
@@ -31,25 +28,26 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.core.config.ConfigurationScheduler;
-import org.apache.logging.log4j.util.PropertiesUtil;
-import org.junit.Assume;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledOnOs;
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
+import org.junit.jupiter.api.condition.OS;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test the WatchManager
*/
+@DisabledOnOs(OS.WINDOWS)
+@EnabledIfSystemProperty(named = "WatchManagerTest.forceRun", matches = "true")
public class WatchManagerTest {
- private static final String FORCE_RUN_KEY = WatchManagerTest.class.getSimpleName() + ".forceRun";
private final String testFile = "target/testWatchFile";
private final String originalFile = "target/test-classes/log4j-test1.xml";
private final String newFile = "target/test-classes/log4j-test1.yaml";
- private static final boolean IS_WINDOWS = PropertiesUtil.getProperties().isOsWindows();
-
@Test
public void testWatchManager() throws Exception {
- Assume.assumeTrue(!IS_WINDOWS || Boolean.getBoolean(FORCE_RUN_KEY));
final ConfigurationScheduler scheduler = new ConfigurationScheduler();
scheduler.incrementScheduledItems();
final WatchManager watchManager = new WatchManager(scheduler);
@@ -71,7 +69,7 @@ public class WatchManagerTest {
Files.copy(source, Paths.get(targetFile.toURI()), StandardCopyOption.REPLACE_EXISTING);
Thread.sleep(1000);
final File f = queue.poll(1, TimeUnit.SECONDS);
- assertNotNull("File change not detected", f);
+ assertNotNull(f, "File change not detected");
} finally {
watchManager.stop();
scheduler.stop();
@@ -80,7 +78,6 @@ public class WatchManagerTest {
@Test
public void testWatchManagerReset() throws Exception {
- Assume.assumeTrue(!IS_WINDOWS || Boolean.getBoolean(FORCE_RUN_KEY));
final ConfigurationScheduler scheduler = new ConfigurationScheduler();
scheduler.incrementScheduledItems();
final WatchManager watchManager = new WatchManager(scheduler);
@@ -105,7 +102,7 @@ public class WatchManagerTest {
watchManager.start();
Thread.sleep(1000);
final File f = queue.poll(1, TimeUnit.SECONDS);
- assertNull("File change detected", f);
+ assertNull(f, "File change detected");
} finally {
watchManager.stop();
scheduler.stop();
@@ -114,7 +111,6 @@ public class WatchManagerTest {
@Test
public void testWatchManagerResetFile() throws Exception {
- Assume.assumeTrue(!IS_WINDOWS || Boolean.getBoolean(FORCE_RUN_KEY));
final ConfigurationScheduler scheduler = new ConfigurationScheduler();
scheduler.incrementScheduledItems();
final WatchManager watchManager = new WatchManager(scheduler);
@@ -139,14 +135,14 @@ public class WatchManagerTest {
watchManager.start();
Thread.sleep(1000);
final File f = queue.poll(1, TimeUnit.SECONDS);
- assertNull("File change detected", f);
+ assertNull(f, "File change detected");
} finally {
watchManager.stop();
scheduler.stop();
}
}
- private class TestWatcher implements FileWatcher {
+ private static class TestWatcher implements FileWatcher {
private final Queue<File> queue;
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/junit/AppenderResolver.java b/log4j-core/src/test/java/org/apache/logging/log4j/junit/AppenderResolver.java
new file mode 100644
index 0000000..cc2f2d4
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/junit/AppenderResolver.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.logging.log4j.junit;
+
+import org.apache.logging.log4j.core.Appender;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.ParameterContext;
+import org.junit.jupiter.api.extension.ParameterResolutionException;
+import org.junit.jupiter.api.extension.ParameterResolver;
+
+import static org.apache.logging.log4j.junit.LoggerContextResolver.getParameterLoggerContext;
+
+class AppenderResolver implements ParameterResolver {
+ @Override
+ public boolean supportsParameter(
+ ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ return Appender.class.isAssignableFrom(parameterContext.getParameter().getType()) && parameterContext
+ .isAnnotated(Named.class);
+ }
+
+ @Override
+ public Object resolveParameter(
+ ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ final LoggerContext loggerContext = getParameterLoggerContext(parameterContext, extensionContext);
+ if (loggerContext == null) {
+ throw new ParameterResolutionException("No LoggerContext defined");
+ }
+ final String name = parameterContext.findAnnotation(Named.class)
+ .map(Named::value)
+ .map(s -> s.isEmpty() ? parameterContext.getParameter().getName() : s)
+ .orElseThrow(() -> new ParameterResolutionException("No @Named present after checking earlier"));
+ final Appender appender = loggerContext.getConfiguration().getAppender(name);
+ if (appender == null) {
+ throw new ParameterResolutionException("No appender named " + name);
+ }
+ return appender;
+ }
+}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/junit/ConfigurationResolver.java b/log4j-core/src/test/java/org/apache/logging/log4j/junit/ConfigurationResolver.java
new file mode 100644
index 0000000..e48b565
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/junit/ConfigurationResolver.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.logging.log4j.junit;
+
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.ParameterContext;
+import org.junit.jupiter.api.extension.ParameterResolutionException;
+import org.junit.jupiter.api.extension.support.TypeBasedParameterResolver;
+
+import static org.apache.logging.log4j.junit.LoggerContextResolver.getParameterLoggerContext;
+
+class ConfigurationResolver extends TypeBasedParameterResolver<Configuration> {
+ @Override
+ public Configuration resolveParameter(
+ ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ final LoggerContext loggerContext = getParameterLoggerContext(parameterContext, extensionContext);
+ if (loggerContext == null) {
+ throw new ParameterResolutionException("No LoggerContext defined");
+ }
+ return loggerContext.getConfiguration();
+ }
+}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/junit/LoggerContextResolver.java b/log4j-core/src/test/java/org/apache/logging/log4j/junit/LoggerContextResolver.java
new file mode 100644
index 0000000..0859bbd
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/junit/LoggerContextResolver.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.logging.log4j.junit;
+
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.config.Configurator;
+import org.junit.jupiter.api.extension.AfterAllCallback;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeAllCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.ParameterContext;
+import org.junit.jupiter.api.extension.ParameterResolutionException;
+import org.junit.jupiter.api.extension.support.TypeBasedParameterResolver;
+
+import java.lang.reflect.Method;
+
+class LoggerContextResolver extends TypeBasedParameterResolver<LoggerContext> implements BeforeAllCallback,
+ AfterAllCallback, BeforeEachCallback, AfterEachCallback {
+ @Override
+ public void beforeAll(ExtensionContext context) throws Exception {
+ final Class<?> testClass = context.getRequiredTestClass();
+ final LoggerContextSource source = testClass.getAnnotation(LoggerContextSource.class);
+ if (source != null) {
+ final LoggerContext loggerContext =
+ Configurator.initialize(context.getDisplayName(), testClass.getClassLoader(), source.value());
+ getTestClassStore(context).put(LoggerContext.class, loggerContext);
+ }
+ }
+
+ @Override
+ public void afterAll(ExtensionContext context) throws Exception {
+ final LoggerContext loggerContext = getTestClassStore(context).get(LoggerContext.class, LoggerContext.class);
+ if (loggerContext != null) {
+ loggerContext.close();
+ }
+ }
+
+ @Override
+ public void beforeEach(ExtensionContext context) throws Exception {
+ final LoggerContextSource source = context.getRequiredTestMethod().getAnnotation(LoggerContextSource.class);
+ if (source != null) {
+ final LoggerContext loggerContext = Configurator
+ .initialize(context.getDisplayName(), context.getRequiredTestClass().getClassLoader(), source.value());
+ getTestInstanceStore(context).put(LoggerContext.class, loggerContext);
+ }
+ }
+
+ @Override
+ public void afterEach(ExtensionContext context) throws Exception {
+ // method-annotated variant
+ final LoggerContext testInstanceContext = getTestInstanceStore(context).get(LoggerContext.class, LoggerContext.class);
+ if (testInstanceContext != null) {
+ testInstanceContext.close();
+ }
+ // reloadable variant
+ final Class<?> testClass = context.getRequiredTestClass();
+ final LoggerContextSource source = testClass.getAnnotation(LoggerContextSource.class);
+ if (source != null && source.reconfigure()) {
+ final LoggerContext loggerContext = getTestClassStore(context).get(LoggerContext.class, LoggerContext.class);
+ if (loggerContext != null) {
+ loggerContext.reconfigure();
+ }
+ }
+ }
+
+ @Override
+ public LoggerContext resolveParameter(
+ ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ return getParameterLoggerContext(parameterContext, extensionContext);
+ }
+
+ private static ExtensionContext.Store getTestClassStore(final ExtensionContext context) {
+ return context.getStore(ExtensionContext.Namespace.create(LoggerContext.class, context.getRequiredTestClass()));
+ }
+
+ private static ExtensionContext.Store getTestInstanceStore(final ExtensionContext context) {
+ return context.getStore(ExtensionContext.Namespace.create(LoggerContext.class, context.getRequiredTestInstance()));
+ }
+
+ static LoggerContext getParameterLoggerContext(ParameterContext parameterContext, ExtensionContext extensionContext) {
+ if (parameterContext.getDeclaringExecutable() instanceof Method) {
+ final LoggerContext loggerContext =
+ getTestInstanceStore(extensionContext).get(LoggerContext.class, LoggerContext.class);
+ return loggerContext != null ? loggerContext :
+ getTestClassStore(extensionContext).get(LoggerContext.class, LoggerContext.class);
+ }
+ return getTestClassStore(extensionContext).get(LoggerContext.class, LoggerContext.class);
+ }
+
+}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/junit/LoggerContextSource.java b/log4j-core/src/test/java/org/apache/logging/log4j/junit/LoggerContextSource.java
new file mode 100644
index 0000000..baf9eb8
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/junit/LoggerContextSource.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+package org.apache.logging.log4j.junit;
+
+import org.apache.logging.log4j.core.LoggerContext;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Specifies a configuration file to use for unit tests. This configuration file will be loaded once and used for all tests
+ * executed in the annotated test class unless otherwise specified by {@link #reconfigure()}. When annotated on a test method, this
+ * will override the class-level configuration if provided for that method.
+ *
+ * @since 3.0.0
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE, ElementType.METHOD})
+@Documented
+@Inherited
+@Tag("functional")
+@ExtendWith(LoggerContextResolver.class)
+@ExtendWith(ConfigurationResolver.class)
+@ExtendWith(AppenderResolver.class)
+public @interface LoggerContextSource {
+ /**
+ * Specifies the name of the configuration file to use for the annotated test.
+ */
+ String value();
+
+ /**
+ * Specifies whether or not to {@linkplain LoggerContext#reconfigure() reconfigure} after each test.
+ */
+ boolean reconfigure() default false;
+}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/junit/Named.java
similarity index 61%
copy from log4j-core/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java
copy to log4j-core/src/test/java/org/apache/logging/log4j/junit/Named.java
index c3cc5b4..fd3e4f4 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/junit/Named.java
@@ -14,24 +14,21 @@
* See the license for the specific language governing permissions and
* limitations under the license.
*/
-package org.apache.logging.log4j.core;
-import org.apache.logging.log4j.junit.LoggerContextRule;
-import org.junit.ClassRule;
-import org.junit.Test;
+package org.apache.logging.log4j.junit;
-/**
- *
- */
-public class DeadlockTest {
-
- private static final String CONFIG = "log4j-deadlock.xml";
-
- @ClassRule
- public static LoggerContextRule context = new LoggerContextRule(CONFIG);
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
- @Test
- public void deadlockOnReconfigure() {
- context.getLoggerContext().reconfigure();
- }
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.PARAMETER)
+@Documented
+public @interface Named {
+ /**
+ * Specifies the name of the configuration item to inject. If blank, uses the name of the annotated parameter.
+ */
+ String value() default "";
}
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java
index 1371ed2..e5f5973 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java
@@ -17,7 +17,7 @@
package org.apache.logging.log4j.message;
import org.apache.logging.log4j.core.impl.MutableLogEvent;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsSame.sameInstance;
diff --git a/log4j-layout-json-template/src/test/java/org/apache/logging/log4j/layout/json/template/JsonTemplateLayoutGcFreeTest.java b/log4j-layout-json-template/src/test/java/org/apache/logging/log4j/layout/json/template/JsonTemplateLayoutGcFreeTest.java
index dfe097a..76b203e 100644
--- a/log4j-layout-json-template/src/test/java/org/apache/logging/log4j/layout/json/template/JsonTemplateLayoutGcFreeTest.java
+++ b/log4j-layout-json-template/src/test/java/org/apache/logging/log4j/layout/json/template/JsonTemplateLayoutGcFreeTest.java
@@ -18,7 +18,10 @@ package org.apache.logging.log4j.layout.json.template;
import org.apache.logging.log4j.core.GcFreeLoggingTestUtil;
import org.junit.Test;
+import org.junit.jupiter.api.Tag;
+@Tag("allocation")
+@Tag("functional")
public class JsonTemplateLayoutGcFreeTest {
@Test