From 414419f6e5d21661a18877b433e1935235fa0e79 Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Tue, 19 Nov 2024 21:23:26 +0100 Subject: [PATCH] Migrate tests to JUnit5 --- .../apache/log4j/BasicConfiguratorTest.java | 12 +- .../apache/log4j/CallerInformationTest.java | 6 +- .../java/org/apache/log4j/CategoryTest.java | 75 ++++---- .../org/apache/log4j/ConsoleAppenderTest.java | 10 +- .../java/org/apache/log4j/LayoutTest.java | 3 +- .../test/java/org/apache/log4j/LevelTest.java | 73 ++++---- .../java/org/apache/log4j/ListAppender.java | 3 +- .../java/org/apache/log4j/LogManagerTest.java | 4 +- .../java/org/apache/log4j/LogWithMDCTest.java | 6 +- .../org/apache/log4j/LogWithRouteTest.java | 6 +- .../org/apache/log4j/LoggerJira3410Test.java | 4 +- .../java/org/apache/log4j/LoggerTest.java | 77 ++++---- .../java/org/apache/log4j/LoggingTest.java | 4 +- .../java/org/apache/log4j/MDCTestCase.java | 10 +- .../test/java/org/apache/log4j/NDCTest.java | 8 +- .../java/org/apache/log4j/PriorityTest.java | 60 +++---- .../log4j/PropertyConfiguratorTest.java | 7 +- .../log4j/bridge/LogEventWrapperTest.java | 6 +- .../log4j/builders/BuilderManagerTest.java | 4 +- .../filter/LevelRangeFilterBuilderTest.java | 16 +- .../layout/PatternLayoutBuilderTest.java | 10 +- ...tractLog4j1ConfigurationConverterTest.java | 2 +- .../AbstractLog4j1ConfigurationTest.java | 106 +++++------ .../log4j/config/AsyncAppenderTest.java | 4 +- .../apache/log4j/config/AutoConfigTest.java | 10 +- .../Log4j1ConfigurationFactoryTest.java | 43 ++--- .../log4j/config/MapRewriteAppenderTest.java | 10 +- .../PropertiesConfigurationFactoryTest.java | 6 +- .../config/PropertiesConfigurationTest.java | 42 ++--- .../config/PropertiesReconfigurationTest.java | 10 +- .../PropertiesRollingWithPropertiesTest.java | 6 +- .../log4j/config/RewriteAppenderTest.java | 10 +- .../SocketAppenderConfigurationTest.java | 11 +- .../SyslogAppenderConfigurationTest.java | 14 +- .../log4j/config/SyslogAppenderTest.java | 10 +- .../config/XmlConfigurationFactoryTest.java | 6 +- .../log4j/config/XmlConfigurationTest.java | 24 +-- .../log4j/config/XmlReconfigurationTest.java | 4 +- .../config/XmlRollingWithPropertiesTest.java | 6 +- .../log4j/helpers/BoundedFIFOTestCase.java | 20 +-- .../log4j/helpers/CyclicBufferTestCase.java | 20 +-- .../helpers/OptionConverterLevelTest.java | 13 +- .../log4j/helpers/UtilLoggingLevelTest.java | 4 +- .../log4j/layout/Log4j1SyslogLayoutTest.java | 4 +- .../log4j/layout/Log4j1XmlLayoutTest.java | 6 +- .../log4j/pattern/FormattingInfoTest.java | 4 +- .../Log4j1LevelPatternConverterTest.java | 4 +- .../Log4j1MdcPatternConverterTest.java | 10 +- .../Log4j1NdcPatternConverterTest.java | 10 +- .../log4j/pattern/NameAbbreviatorTest.java | 2 +- .../log4j/spi/ThrowableInformationTest.java | 10 +- .../org/apache/log4j/xml/DOMTestCase.java | 8 +- .../log4j/util/java9/ProcessIdUtilTest.java | 4 +- .../log4j/util/java9/StackLocatorTest.java | 20 +-- .../log4j/test/AbstractSerializationTest.java | 2 +- .../log4j/test/ThreadContextUtilityClass.java | 4 +- .../logging/log4j/AbstractLoggerTest.java | 42 ++--- .../log4j/CloseableThreadContextTest.java | 30 ++-- .../apache/logging/log4j/EventLoggerTest.java | 6 +- .../logging/log4j/LambdaLoggerTest.java | 146 +++++++-------- .../org/apache/logging/log4j/LevelTest.java | 22 +-- .../apache/logging/log4j/LogManagerTest.java | 22 +-- .../logging/log4j/LoggerSupplierTest.java | 30 ++-- .../org/apache/logging/log4j/LoggerTest.java | 114 ++++++------ .../org/apache/logging/log4j/MarkerTest.java | 20 +-- .../logging/log4j/NoopThreadContextTest.java | 4 +- .../log4j/ThreadContextInheritanceTest.java | 32 ++-- .../logging/log4j/ThreadContextTest.java | 36 ++-- .../logging/log4j/TraceLoggingTest.java | 6 +- .../log4j/internal/DefaultLogBuilderTest.java | 4 +- .../map/UnmodifiableArrayBackedMapTest.java | 75 ++++---- .../log4j/message/FormattedMessageTest.java | 26 +-- .../message/LocalizedMessageFactoryTest.java | 14 +- .../log4j/message/LocalizedMessageTest.java | 14 +- .../logging/log4j/message/MapMessageTest.java | 54 +++--- .../message/MessageFormatMessageTest.java | 16 +- .../log4j/message/MessageFormatsPerfTest.java | 20 +-- .../log4j/message/ObjectArrayMessageTest.java | 6 +- .../log4j/message/ObjectMessageTest.java | 12 +- .../log4j/message/ParameterFormatterTest.java | 6 +- .../message/ReusableMessageFactoryTest.java | 13 +- .../message/ReusableObjectMessageTest.java | 24 +-- .../ReusableParameterizedMessageTest.java | 24 +-- .../message/ReusableSimpleMessageTest.java | 24 +-- .../log4j/message/SimpleMessageTest.java | 4 +- .../message/StringFormattedMessageTest.java | 20 +-- .../message/StructuredDataMessageTest.java | 16 +- .../log4j/message/ThreadDumpMessageTest.java | 12 +- .../log4j/simple/SimpleLoggerTest.java | 12 +- .../spi/DefaultThreadContextStackTest.java | 52 +++--- .../logging/log4j/spi/LoggerAdapterTest.java | 6 +- .../spi/MutableThreadContextStackTest.java | 66 +++---- .../test/junit/TempLoggingDirectoryTest.java | 2 +- .../test/junit/TestPropertySourceTest.java | 8 +- .../apache/logging/log4j/util/CharsTest.java | 6 +- .../logging/log4j/util/ConstantsTest.java | 4 +- .../util/EnvironmentPropertySourceTest.java | 4 +- .../logging/log4j/util/LambdaUtilTest.java | 24 +-- .../LegacyPropertiesCompatibilityTest.java | 4 +- .../util/Log4jCharsetsPropertiesTest.java | 4 +- .../logging/log4j/util/ProcessIdUtilTest.java | 6 +- .../util/PropertiesPropertySourceTest.java | 6 +- .../log4j/util/PropertiesUtilOrderTest.java | 6 +- .../util/PropertySourceCamelCaseTest.java | 4 +- .../util/PropertySourceTokenizerTest.java | 4 +- .../log4j/util/ServiceLoaderUtilTest.java | 8 +- .../log4j/util/SortedArrayStringMapTest.java | 118 ++++++------ .../log4j/util/StackLocatorTestIT.java | 5 +- .../log4j/util/StackLocatorUtilTest.java | 20 +-- .../log4j/util/StringBuildersTest.java | 12 +- .../logging/log4j/util/StringsTest.java | 18 +- .../SystemPropertiesPropertySourceTest.java | 4 +- .../apache/logging/log4j/util/Unbox1Test.java | 26 +-- .../log4j/util/Unbox2ConfigurableTest.java | 10 +- .../log4j/cassandra/CassandraRule.java | 4 +- .../log4j/FilterPerformanceComparison.java | 41 +++-- .../logging/log4j/PerformanceComparison.java | 23 ++- .../apache/logging/log4j/PerformanceRun.java | 2 +- .../logging/log4j/core/SimplePerfTest.java | 37 ++-- .../logging/log4j/core/ThreadedPerfTest.java | 17 +- .../logging/log4j/core/ThreadedTest.java | 9 +- .../core/async/perftest/PerfTestDriver.java | 9 +- .../log4j/FormatterLoggerManualExample.java | 2 +- .../logging/log4j/MarkerMixInJsonTest.java | 7 +- .../apache/logging/log4j/MarkerMixInTest.java | 35 ++-- .../logging/log4j/MarkerMixInXmlTest.java | 7 +- .../logging/log4j/MarkerMixInYamlTest.java | 7 +- .../log4j/core/AppenderRefLevelJsonTest.java | 8 +- .../log4j/core/AppenderRefLevelTest.java | 12 +- .../logging/log4j/core/BasicLoggingTest.java | 4 +- .../log4j/core/CollectionLoggingTest.java | 8 +- .../log4j/core/CustomLevelsOverrideTest.java | 10 +- .../logging/log4j/core/CustomLevelsTest.java | 8 +- .../core/CustomLevelsWithFiltersTest.java | 10 +- .../logging/log4j/core/DeadlockTest.java | 4 +- .../logging/log4j/core/ExtendedLevelTest.java | 4 +- .../core/GcFreeAsynchronousLoggingTest.java | 4 +- .../core/GcFreeMixedSyncAsyncLoggingTest.java | 4 +- .../core/GcFreeSynchronousLoggingTest.java | 4 +- .../logging/log4j/core/HostNameTest.java | 4 +- .../logging/log4j/core/LateConfigTest.java | 14 +- .../apache/logging/log4j/core/LevelTest.java | 4 +- .../logging/log4j/core/Log4j1222Test.java | 11 +- .../logging/log4j/core/LogEventTest.java | 12 +- .../logging/log4j/core/LoggerDateTest.java | 2 +- .../apache/logging/log4j/core/LoggerTest.java | 74 ++++---- .../logging/log4j/core/LoggerUpdateTest.java | 6 +- .../apache/logging/log4j/core/LookupTest.java | 7 +- ...olverDoesNotEvaluateThreadContextTest.java | 10 +- .../log4j/core/PatternSelectorTest.java | 8 +- .../core/PatternVariableResolverTest.java | 2 +- .../log4j/core/PropertiesFileConfigTest.java | 2 +- ...bleParameterizedMessageMemoryLeakTest.java | 4 +- .../log4j/core/ShutdownDisabledTest.java | 4 +- .../ShutdownTimeoutConfigurationTest.java | 4 +- .../log4j/core/StrictXmlConfigTest.java | 22 +-- .../log4j/core/TimestampMessageTest.java | 8 +- .../apache/logging/log4j/core/XmlEvents.java | 4 +- .../appender/AbstractAppenderBuilderTest.java | 4 +- .../AsyncAppenderQueueFullPolicyTest.java | 6 +- .../core/appender/AsyncAppenderTest.java | 25 +-- .../ConsoleAppenderAnsiStyleLayoutMain.java | 6 +- .../ConsoleAppenderAnsiXExceptionMain.java | 6 +- .../appender/ConsoleAppenderBuilderTest.java | 8 +- .../core/appender/ConsoleAppenderTest.java | 16 +- .../core/appender/FailoverAppenderTest.java | 16 +- .../FailoverFailedPrimaryAppenderTest.java | 16 +- .../appender/FileAppenderBuilderTest.java | 12 +- .../appender/FileAppenderPermissionsTest.java | 14 +- .../log4j/core/appender/FileAppenderTest.java | 21 ++- .../log4j/core/appender/HttpAppenderTest.java | 2 +- .../core/appender/InMemoryAppenderTest.java | 8 +- .../JsonCompleteFileAppenderTest.java | 7 +- .../MemoryMappedFileAppenderTest.java | 6 +- .../appender/MemoryMappedFileManagerTest.java | 6 +- .../appender/OutputStreamAppenderTest.java | 42 +++-- .../appender/OutputStreamManagerTest.java | 4 +- .../RandomAccessFileAppenderTest.java | 2 +- .../appender/RandomAccessFileManagerTest.java | 12 +- .../appender/ReconfigureAppenderTest.java | 4 +- .../appender/ScriptAppenderSelectorTest.java | 2 +- .../log4j/core/appender/SmtpAppenderTest.java | 36 ++-- .../appender/SocketAppenderBuilderTest.java | 4 +- .../appender/SocketAppenderReconnectTest.java | 2 +- .../SocketAppenderSocketOptionsTest.java | 8 +- .../SocketAppenderSslSocketOptionsTest.java | 2 +- .../core/appender/SocketAppenderTest.java | 86 ++++----- .../core/appender/SyslogAppenderTestBase.java | 32 ++-- .../core/appender/TlsSyslogAppenderTest.java | 10 +- .../core/appender/TlsSyslogFrameTest.java | 8 +- .../core/appender/WriterAppenderTest.java | 12 +- .../appender/XmlCompactFileAppenderTest.java | 39 ++-- .../appender/XmlCompleteFileAppenderTest.java | 11 +- .../core/appender/XmlFileAppenderTest.java | 30 ++-- .../db/AbstractDatabaseAppenderTest.java | 5 +- .../db/AbstractDatabaseManagerTest.java | 82 ++++----- .../db/jdbc/AbstractJdbcDataSourceTest.java | 4 +- .../appender/db/jdbc/ColumnConfigTest.java | 170 +++++++++--------- .../JdbcAppenderStringSubstitutionTest.java | 2 +- .../core/appender/mom/JmsAppenderTest.java | 4 +- .../mom/jeromq/JeroMqAppenderTest.java | 10 +- .../appender/mom/jeromq/JeroMqTestClient.java | 2 +- .../kafka/KafkaAppenderCloseTimeoutTest.java | 6 +- .../appender/mom/kafka/KafkaAppenderTest.java | 17 +- .../KafkaManagerProducerThreadLeakTest.java | 7 +- .../appender/nosql/NoSqlAppenderTest.java | 36 ++-- .../LoggerNameLevelRewritePolicyTest.java | 4 +- .../rewrite/MapRewritePolicyTest.java | 10 +- .../appender/rewrite/RewriteAppenderTest.java | 10 +- .../rolling/CronTriggeringPolicyTest.java | 16 +- .../appender/rolling/EligibleFilesTest.java | 12 +- .../core/appender/rolling/FileSizeTest.java | 2 +- .../OnStartupTriggeringPolicyTest.java | 8 +- .../rolling/PatternProcessorTest.java | 52 +++--- .../RandomRollingAppenderOnStartupTest.java | 11 +- .../rolling/RollingAppenderCountTest.java | 2 +- .../RollingAppenderCronAndSizeLookupTest.java | 6 +- .../RollingAppenderCronAndSizeTest.java | 4 +- .../RollingAppenderCronOnStartupTest.java | 28 +-- .../RollingAppenderCronOnceADayTest.java | 9 +- .../rolling/RollingAppenderCronTest.java | 5 +- .../RollingAppenderDeleteScriptTest.java | 3 +- .../RollingAppenderDirectWrite1906Test.java | 9 +- ...ingAppenderDirectWriteStartupSizeTest.java | 2 +- ...ectWriteTempCompressedFilePatternTest.java | 4 +- .../RollingAppenderDirectWriteTest.java | 4 +- ...ngAppenderDirectWriteWithFilenameTest.java | 4 +- ...AppenderDirectWriteWithHtmlLayoutTest.java | 2 +- ...ppenderDirectWriteWithReconfigureTest.java | 4 +- ...lingAppenderNoUnconditionalDeleteTest.java | 2 +- .../RollingAppenderOnStartup2Test.java | 29 +-- .../RollingAppenderOnStartupDirectTest.java | 32 ++-- .../rolling/RollingAppenderOnStartupTest.java | 18 +- .../RollingAppenderReconfigureTest.java | 4 +- ...ngAppenderSizeCompressPermissionsTest.java | 2 +- .../RollingAppenderSizeMaxWidthTest.java | 4 +- .../RollingAppenderSizeNoCompressTest.java | 4 +- .../rolling/RollingAppenderSizeTest.java | 6 +- .../RollingAppenderSizeWithTimeTest.java | 2 +- ...AppenderTempCompressedFilePatternTest.java | 4 +- .../RollingAppenderTimeAndSizeDirectTest.java | 4 +- .../RollingAppenderTimeAndSizeTest.java | 4 +- .../RollingAppenderUncompressedTest.java | 2 +- .../rolling/RollingDirectSize3490Test.java | 6 +- .../RollingFileAppenderAccessTest.java | 19 +- .../RollingFileAppenderBuilderTest.java | 11 +- ...lingFileAppenderInterruptedThreadTest.java | 9 +- .../RollingFileAppenderLayoutTest.java | 11 +- .../RollingFileAppenderUpdateDataTest.java | 29 +-- .../rolling/RollingFileManagerTest.java | 22 +-- .../rolling/RollingNewDirectoryTest.java | 2 +- .../RollingRandomAccessFileManagerTest.java | 28 +-- ...enderDirectWriteAndSwitchDirectorTest.java | 4 +- .../RollingRandomAppenderDirectWriteTest.java | 4 +- ...omAppenderDirectWriteWithFilenameTest.java | 4 +- .../rolling/RolloverFilePatternTest.java | 20 +-- .../rolling/RolloverWithPaddingTest.java | 6 +- .../action/Bzip2CompressActionTest.java | 10 +- .../rolling/action/DeleteActionTest.java | 18 +- .../rolling/action/DeletingVisitorTest.java | 20 +-- .../appender/rolling/action/DurationTest.java | 28 +-- .../rolling/action/FileRenameActionTest.java | 12 +- .../appender/rolling/action/FileSizeTest.java | 6 +- .../action/IfAccumulatedFileCountTest.java | 10 +- .../action/IfAccumulatedFileSizeTest.java | 16 +- .../appender/rolling/action/IfAnyTest.java | 10 +- .../rolling/action/IfFileNameTest.java | 20 +-- .../rolling/action/IfLastModifiedTest.java | 14 +- .../appender/rolling/action/IfNotTest.java | 10 +- .../rolling/action/PathConditionTest.java | 10 +- .../PathSortByModificationTimeTest.java | 8 +- .../rolling/action/ScriptConditionTest.java | 16 +- .../rolling/action/SortingVisitorTest.java | 12 +- .../routing/JsonRoutingAppender2Test.java | 3 +- .../routing/JsonRoutingAppenderTest.java | 3 +- .../PropertiesRoutingAppenderTest.java | 7 +- .../routing/RoutingAppender2767Test.java | 4 +- .../routing/RoutingAppender3350Test.java | 2 +- ...outingAppenderKeyLookupEvaluationTest.java | 4 +- .../appender/routing/RoutingAppenderTest.java | 7 +- .../routing/RoutingAppenderWithJndiTest.java | 28 +-- .../RoutingAppenderWithPurgingTest.java | 6 +- .../routing/RoutingDefaultAppenderTest.java | 3 +- .../AsyncAppenderExceptionHandlingTest.java | 13 +- .../AsyncLoggerArgumentFreedOnErrorTest.java | 6 +- .../AsyncLoggerClassLoadDeadlockTest.java | 25 +-- .../async/AsyncLoggerConfigAutoFlushTest.java | 28 +-- .../async/AsyncLoggerConfigErrorOnFormat.java | 34 ++-- .../core/async/AsyncLoggerConfigTest.java | 8 +- .../core/async/AsyncLoggerConfigTest2.java | 26 +-- ...AsyncLoggerConfigUseAfterShutdownTest.java | 18 +- ...AsyncLoggerConfigWithAsyncEnabledTest.java | 30 ++-- ...LoggerContextSelectorInitialStateTest.java | 14 +- .../async/AsyncLoggerContextSelectorTest.java | 31 ++-- .../core/async/AsyncLoggerContextTest.java | 6 +- ...AsyncLoggerCustomSelectorLocationTest.java | 24 +-- .../async/AsyncLoggerDefaultLocationTest.java | 36 ++-- ...ncLoggerEventTranslationExceptionTest.java | 10 +- .../core/async/AsyncLoggerLocationTest.java | 34 ++-- .../core/async/AsyncLoggerNanoTimeTest.java | 41 ++--- .../log4j/core/async/AsyncLoggerTest.java | 38 ++-- .../AsyncLoggerTestCachedThreadName.java | 36 ++-- .../AsyncLoggerTestUncachedThreadName.java | 36 ++-- .../async/AsyncLoggerThreadContextTest.java | 6 +- .../AsyncLoggerThreadNameStrategyTest.java | 38 ++-- .../AsyncLoggerTimestampMessageTest.java | 32 ++-- .../AsyncLoggerUseAfterShutdownTest.java | 24 +-- .../AsyncLoggersWithAsyncAppenderTest.java | 4 +- ...AsyncLoggersWithAsyncLoggerConfigTest.java | 8 +- .../AsyncQueueFullPolicyFactoryTest.java | 36 ++-- .../AsyncRootLoggerDefaultLocationTest.java | 36 ++-- ...trategyFactoryConfigGlobalLoggersTest.java | 28 +-- .../AsyncWaitStrategyFactoryConfigTest.java | 20 +-- ...ctoryIncorrectConfigGlobalLoggersTest.java | 26 +-- .../BasicAsyncLoggerContextSelectorTest.java | 50 +++--- .../DefaultAsyncQueueFullPolicyTest.java | 16 +- .../DiscardingAsyncQueueFullPolicyTest.java | 70 ++++---- .../core/async/Log4j2Jira1688AsyncTest.java | 2 +- .../log4j/core/async/Log4j2Jira1688Test.java | 2 +- .../core/async/QueueFullAsyncLogger3Test.java | 4 +- .../core/async/RingBufferLogEventTest.java | 3 +- .../log4j/core/config/AdvertiserTest.java | 12 +- .../config/AppenderControlArraySetTest.java | 26 +-- .../CompositeConfigurationMissingTest.java | 6 +- .../config/CompositeConfigurationTest.java | 16 +- .../core/config/ConfigurationFactoryTest.java | 5 +- .../config/ConfigurationPropertyTest.java | 6 +- .../core/config/ConfigurationSourceTest.java | 2 +- .../log4j/core/config/Configurator1Test.java | 48 ++--- .../log4j/core/config/Configurator2Test.java | 12 +- .../core/config/ConfiguratorErrorTest.java | 6 +- .../core/config/ConfiguratorSetLevelTest.java | 4 +- .../core/config/CustomConfigurationTest.java | 7 +- .../log4j/core/config/FileOutputTest.java | 5 +- .../core/config/JiraLog4j2_2134Test.java | 12 +- .../log4j/core/config/LoggerConfigTest.java | 16 +- .../log4j/core/config/LoggersPluginTest.java | 4 +- .../core/config/MissingLanguageTest.java | 6 +- .../core/config/MissingRootLoggerTest.java | 4 +- .../core/config/NestedLoggerConfigTest.java | 29 ++- .../log4j/core/config/NoLanguagesTest.java | 6 +- .../core/config/PropertiesPluginTest.java | 6 +- .../log4j/core/config/PropertyTest.java | 12 +- .../config/ReconfigurationDeadlockTest.java | 18 +- .../config/ReconfigurationFailureTest.java | 15 +- .../config/arbiters/BasicArbiterTest.java | 16 +- .../arbiters/EnvironmentArbiterTest.java | 12 +- .../config/arbiters/ScriptArbiterTest.java | 16 +- .../config/arbiters/SelectArbiterTest.java | 14 +- .../arbiters/SystemPropertyArbiterTest.java | 16 +- .../builder/ConfigurationAssemblerTest.java | 12 +- .../builder/ConfigurationBuilderTest.java | 4 +- .../convert/DateTypeConverterTest.java | 26 +-- .../convert/TypeConverterRegistryTest.java | 30 ++-- .../plugins/convert/TypeConvertersTest.java | 29 +-- .../plugins/processor/PluginCacheTest.java | 25 ++- .../processor/PluginProcessorTest.java | 37 ++-- .../util/ResolverUtilCustomProtocolTest.java | 28 ++- .../config/plugins/util/ResolverUtilTest.java | 18 +- .../validators/RequiredValidatorTest.java | 8 +- .../validators/ValidHostValidatorTest.java | 10 +- .../validators/ValidPortValidatorTest.java | 10 +- .../ValidatingPluginWithFailoverTest.java | 6 +- ...alidatingPluginWithGenericBuilderTest.java | 8 +- ...ginWithGenericSubclassFoo1BuilderTest.java | 8 +- .../ValidatingPluginWithTypedBuilderTest.java | 8 +- .../PropertiesConfigurationTest.java | 24 +-- .../config/xml/XmlConfigurationSecurity.java | 5 +- .../core/config/xml/XmlLoggerPropsTest.java | 4 +- ...geFreeSortedArrayThreadContextMapTest.java | 2 +- .../log4j/core/filter/AbstractFilterTest.java | 4 +- .../core/filter/AbstractFilterableTest.java | 54 +++--- .../core/filter/AbstractScriptFilterTest.java | 9 +- .../core/filter/BurstFilterLogDelayTest.java | 4 +- .../log4j/core/filter/BurstFilterTest.java | 4 +- .../core/filter/CompositeFilterTest.java | 4 +- .../filter/DynamicThresholdFilterTest.java | 15 +- .../log4j/core/filter/MapFilterTest.java | 9 +- .../log4j/core/filter/MarkerFilterTest.java | 10 +- .../log4j/core/filter/NoMarkerFilterTest.java | 8 +- .../log4j/core/filter/RegexFilterTest.java | 26 ++- .../core/filter/StringMatchFilterTest.java | 12 +- .../core/filter/StructuredDataFilterTest.java | 9 +- .../filter/ThreadContextMapFilterTest.java | 20 +-- .../core/filter/ThresholdFilterTest.java | 8 +- .../log4j/core/filter/TimeFilterTest.java | 113 ++++-------- ...toryPropertySetMissingConstructorTest.java | 8 +- .../ContextDataFactoryPropertySetTest.java | 14 +- .../core/impl/ContextDataFactoryTest.java | 14 +- .../core/impl/JdkMapAdapterStringMapTest.java | 92 +++++----- .../core/impl/Log4jLogEventNanoTimeTest.java | 13 +- .../log4j/core/impl/Log4jLogEventTest.java | 35 ++-- .../log4j/core/impl/MutableLogEventTest.java | 18 +- .../impl/ReusableLogEventFactoryTest.java | 12 +- .../impl/ThreadContextDataInjectorTest.java | 2 +- .../jackson/JacksonIssue429MyNamesTest.java | 28 +-- .../core/jackson/JacksonIssue429Test.java | 28 +-- .../log4j/core/jackson/LevelMixInXmlTest.java | 2 +- .../jackson/StackTraceElementMixInTest.java | 28 +-- .../logging/log4j/core/jmx/ServerTest.java | 22 +-- .../core/layout/AbstractStringLayoutTest.java | 6 +- .../ConcurrentLoggingWithGelfLayoutTest.java | 4 +- .../ConcurrentLoggingWithJsonLayoutTest.java | 2 +- .../core/layout/CsvLogEventLayoutTest.java | 10 +- .../CsvParameterLayoutAllAsyncTest.java | 27 ++- .../core/layout/CsvParameterLayoutTest.java | 4 +- .../log4j/core/layout/GelfLayout2Test.java | 4 +- .../log4j/core/layout/GelfLayout3Test.java | 6 +- .../layout/GelfLayoutPatternSelectorTest.java | 4 +- .../log4j/core/layout/GelfLayoutTest.java | 30 ++-- .../log4j/core/layout/HtmlLayoutTest.java | 32 ++-- .../core/layout/JsonLayoutMillisTest.java | 2 +- .../log4j/core/layout/JsonLayoutTest.java | 124 +++++++------ .../log4j/core/layout/Log4j2_2195_Test.java | 4 +- .../log4j/core/layout/LogEventFixtures.java | 12 +- .../layout/PatternLayoutLookupDateTest.java | 4 +- .../PatternLayoutMainMapLookupTest.java | 6 +- .../layout/PatternLayoutNoLookupDateTest.java | 9 +- .../log4j/core/layout/PatternLayoutTest.java | 55 +++--- .../core/layout/PatternSelectorTest.java | 6 +- .../log4j/core/layout/Rfc5424LayoutTest.java | 40 ++--- .../core/layout/SerializedLayoutTest.java | 2 +- .../core/layout/StringBuilderEncoderTest.java | 37 ++-- .../log4j/core/layout/SyslogLayoutTest.java | 8 +- .../log4j/core/layout/XmlLayoutTest.java | 16 +- .../log4j/core/layout/YamlLayoutTest.java | 84 +++++---- .../log4j/core/lookup/CaseLookupTest.java | 4 +- .../core/lookup/ContextMapLookupTest.java | 2 +- .../log4j/core/lookup/DateLookupTest.java | 8 +- .../core/lookup/EnvironmentLookupTest.java | 4 +- .../log4j/core/lookup/EventLookupTest.java | 14 +- .../log4j/core/lookup/InterpolatorTest.java | 2 +- .../core/lookup/JndiDisabledLookupTest.java | 6 +- .../log4j/core/lookup/JndiExploit.java | 3 +- .../log4j/core/lookup/JndiLookupTest.java | 2 +- .../core/lookup/JndiRestrictedLookupTest.java | 5 +- .../log4j/core/lookup/Log4jLookupTest.java | 10 +- .../lookup/Log4jLookupWithSpacesTest.java | 10 +- .../log4j/core/lookup/MainLookupTest.java | 4 +- .../log4j/core/lookup/MapLookupTest.java | 18 +- .../core/lookup/MarkerLookupConfigTest.java | 4 +- .../log4j/core/lookup/MarkerLookupTest.java | 14 +- .../core/lookup/PropertiesLookupTest.java | 16 +- .../core/lookup/ResourceBundleLookupTest.java | 11 +- .../log4j/core/lookup/StrSubstitutorTest.java | 56 +++--- .../core/lookup/StructuredDataLookupTest.java | 8 +- .../lookup/SystemPropertiesLookupTest.java | 8 +- .../ExtendedThreadInformationTest.java | 4 +- .../log4j/core/net/JndiManagerTest.java | 14 +- .../logging/log4j/core/net/PriorityTest.java | 4 +- .../log4j/core/net/SmtpManagerTest.java | 10 +- .../core/net/UrlConnectionFactoryTest.java | 2 +- .../ssl/EnvironmentPasswordProviderTest.java | 6 +- .../net/ssl/FilePasswordProviderTest.java | 8 +- .../net/ssl/KeyStoreConfigurationTest.java | 18 +- .../net/ssl/MemoryPasswordProviderTest.java | 8 +- .../net/ssl/SslConfigurationFactoryTest.java | 9 +- .../core/net/ssl/StoreConfigurationTest.java | 8 +- .../net/ssl/TrustStoreConfigurationTest.java | 21 +-- .../core/parser/JsonLogEventParserTest.java | 46 ++--- .../log4j/core/parser/LogEventParserTest.java | 6 +- .../core/parser/XmlLogEventParserTest.java | 44 ++--- .../core/parser/YamlLogEventParserTest.java | 42 ++--- .../core/pattern/CallerInformationTest.java | 6 +- .../pattern/DatePatternConverterTestBase.java | 56 +++--- .../log4j/core/pattern/DisableAnsiTest.java | 6 +- .../pattern/DynamicWordAbbreviatorTest.java | 7 +- .../pattern/EncodingPatternConverterTest.java | 12 +- .../EndOfBatchPatternConverterTest.java | 6 +- ...alsIgnoreCaseReplacementConverterTest.java | 8 +- .../EqualsReplacementConverterTest.java | 18 +- .../core/pattern/FormattingInfoTest.java | 8 +- .../core/pattern/HighlightConverterTest.java | 22 +-- .../pattern/LevelPatternConverterTest.java | 18 +- .../pattern/LiteralPatternConverterTest.java | 6 +- ...nPatternConvertersRequireLocationTest.java | 3 +- .../LoggerFqcnPatternConverterTest.java | 4 +- .../core/pattern/MapPatternConverterTest.java | 8 +- .../pattern/MarkerPatternConverterTest.java | 4 +- .../MarkerSimpleNamePatternConverterTest.java | 4 +- .../core/pattern/MaxLengthConverterTest.java | 8 +- .../core/pattern/MdcPatternConverterTest.java | 22 +-- .../pattern/MessageAnsiConverterTest.java | 6 +- .../pattern/MessagePatternConverterTest.java | 22 +-- .../pattern/MessageStyledConverterTest.java | 6 +- .../core/pattern/NameAbbreviatorTest.java | 40 ++--- .../pattern/NanoTimePatternConverterTest.java | 4 +- .../core/pattern/NdcPatternConverterTest.java | 10 +- .../core/pattern/NoConsoleNoAnsiTest.java | 6 +- .../log4j/core/pattern/PatternParserTest.java | 81 ++++----- .../ProcessIdPatternConverterTest.java | 4 +- .../RegexReplacementConverterTest.java | 4 +- .../core/pattern/RegexReplacementTest.java | 8 +- .../pattern/RepeatPatternConverterTest.java | 4 +- .../SequenceNumberPatternConverterTest.java | 4 +- ...eNumberPatternConverterZeroPaddedTest.java | 4 +- .../SimpleLiteralPatternConverterTest.java | 6 +- .../core/pattern/StyleConverterTest.java | 14 +- .../pattern/ThreadIdPatternConverterTest.java | 4 +- .../ThreadNamePatternConverterTest.java | 4 +- .../ThreadPriorityPatternConverterTest.java | 4 +- ...ablesNotEmptyReplacementConverterTest.java | 14 +- .../selector/BasicContextSelectorTest.java | 24 +-- .../ClassLoaderContextSelectorTest.java | 6 +- .../log4j/core/test/LogBuilderTest.java | 4 +- .../core/tools/GenerateCustomLoggerTest.java | 6 +- .../tools/GenerateExtendedLoggerTest.java | 6 +- .../log4j/core/util/ClockFactoryTest.java | 18 +- .../core/util/ContextDataProviderTest.java | 6 +- .../log4j/core/util/CronExpressionTest.java | 28 +-- .../log4j/core/util/CyclicBufferTest.java | 10 +- .../log4j/core/util/DummyNanoClockTest.java | 6 +- .../log4j/core/util/FileUtilsTest.java | 20 +-- .../logging/log4j/core/util/InitTest.java | 6 +- .../logging/log4j/core/util/IntegersTest.java | 6 +- .../log4j/core/util/JsonUtilsTest.java | 8 +- .../logging/log4j/core/util/LoaderTest.java | 6 +- .../logging/log4j/core/util/NetUtilsTest.java | 12 +- .../log4j/core/util/OptionConverterTest.java | 10 +- .../util/ShutdownCallbackRegistryTest.java | 8 +- .../logging/log4j/core/util/SourceTest.java | 46 +++-- .../log4j/core/util/SystemClockTest.java | 6 +- .../log4j/core/util/SystemNanoClockTest.java | 4 +- .../logging/log4j/core/util/UuidTest.java | 8 +- .../util/datetime/FixedDateFormatTest.java | 54 +++--- .../InstantPatternDynamicFormatterTest.java | 2 +- ...tableLogEventWithReusableParamMsgTest.java | 4 +- .../logging/log4j/io/AbstractStreamTest.java | 2 +- .../logging/log4j/io/IoBuilderTest.java | 4 +- .../io/LoggerPrintStreamCallerInfoTest.java | 28 +-- .../log4j/io/LoggerPrintStreamTest.java | 18 +- .../io/LoggerPrintWriterCallerInfoTest.java | 30 ++-- .../log4j/io/LoggerPrintWriterJdbcH2Test.java | 6 +- .../log4j/io/LoggerPrintWriterTest.java | 18 +- .../log4j/smtp/SmtpAppenderAsyncTest.java | 14 +- .../logging/log4j/smtp/SmtpAppenderTest.java | 17 +- .../logging/log4j/smtp/SmtpManagerTest.java | 8 +- .../Log4jServletContainerInitializerTest.java | 22 +-- .../web/Log4jServletContextListenerTest.java | 12 +- .../log4j/web/Log4jServletFilterTest.java | 12 +- ...hutdownOnContextDestroyedListenerTest.java | 10 +- .../web/Log4jWebInitializerImplTest.java | 40 ++--- .../logging/log4j/web/PropertyTest.java | 6 +- .../logging/log4j/web/TestAsyncServlet.java | 8 +- .../log4j/jcl/CallerInformationTest.java | 6 +- .../jdbc/PoolableConnectionFactoryTest.java | 4 +- .../PoolingDriverConnectionSourceTest.java | 12 +- .../db/jpa/AbstractJpaAppenderTest.java | 5 +- .../appender/db/jpa/JpaH2AppenderTest.java | 7 +- .../db/jpa/JpaHsqldbAppenderTest.java | 14 +- .../appender/db/jpa/LogEventEntityTest.java | 6 +- .../ContextDataAttributeConverterTest.java | 12 +- ...ContextDataJsonAttributeConverterTest.java | 12 +- .../ContextMapAttributeConverterTest.java | 12 +- .../ContextMapJsonAttributeConverterTest.java | 12 +- .../ContextStackAttributeConverterTest.java | 12 +- ...ontextStackJsonAttributeConverterTest.java | 12 +- .../InstantAttributeConverterTest.java | 10 +- .../MarkerAttributeConverterTest.java | 12 +- .../MessageAttributeConverterTest.java | 10 +- ...ackTraceElementAttributeConverterTest.java | 20 +-- .../ThrowableAttributeConverterTest.java | 12 +- .../log4j/jpl/Log4jSystemLoggerTest.java | 24 +-- .../log4j/jul/test/AbstractLoggerTest.java | 50 +++--- .../logging/log4j/jul/test/ApiLoggerTest.java | 50 +++--- .../jul/test/AsyncLoggerThreadsTest.java | 28 +-- .../BracketInNotInterpolatedMessageTest.java | 22 +-- .../log4j/jul/test/CallerInformationTest.java | 4 +- .../log4j/jul/test/CoreLoggerTest.java | 34 ++-- ...aultLevelConverterCustomJulLevelsTest.java | 75 ++++---- .../jul/test/DefaultLevelConverterTest.java | 11 +- .../jul/test/JavaLevelTranslatorTest.java | 29 ++- .../jul/test/Log4jBridgeHandlerTest.java | 60 +++---- .../jul/test/Log4jLevelTranslatorTest.java | 24 +-- ...nTemplateLayoutNullEventDelimiterTest.java | 4 +- .../layout/template/json/LogstashIT.java | 6 +- .../ThreadLocalRecyclerNestedLoggingTest.java | 4 +- .../ReadOnlyStringMapResolverTest.java | 6 +- .../template/json/util/JsonReaderTest.java | 2 +- .../mongodb/AbstractMongoDbCappedIT.java | 12 +- .../log4j/mongodb/MongoDbAuthFailureIT.java | 1 - .../log4j/mongodb/MongoDbMapMessageIT.java | 14 +- .../log4j/mongodb/MongoDbResolver.java | 4 +- .../mongodb4/AbstractMongoDb4CappedIT.java | 12 +- .../log4j/mongodb4/MongoDb4AuthFailureIT.java | 1 - .../log4j/mongodb4/MongoDb4MapMessageIT.java | 14 +- .../log4j/mongodb4/MongoDb4Resolver.java | 4 +- .../other/pkg/LoggerContextAnchorTest.java | 8 +- .../logging/slf4j/CallerInformationTest.java | 6 +- .../apache/logging/slf4j/Log4j1222Test.java | 4 +- .../apache/logging/slf4j/Log4jMarkerTest.java | 8 +- .../logging/slf4j/LoggerContextTest.java | 4 +- .../org/apache/logging/slf4j/LoggerTest.java | 21 ++- .../org/apache/logging/slf4j/MarkerTest.java | 20 +-- .../apache/logging/slf4j/OptionalTest.java | 9 +- .../apache/logging/slf4j/OverflowTest.java | 4 +- .../apache/logging/slf4j/SerializeTest.java | 4 +- .../ThrowableConsumingMessageFactoryTest.java | 2 +- .../other/pkg/LoggerContextAnchorTest.java | 8 +- .../logging/slf4j/CallerInformationTest.java | 8 +- .../apache/logging/slf4j/Log4j1222Test.java | 4 +- .../logging/slf4j/Log4jEventBuilderTest.java | 8 +- .../logging/slf4j/Log4jMDCAdapterTest.java | 4 +- .../apache/logging/slf4j/Log4jMarkerTest.java | 8 +- .../logging/slf4j/LoggerContextTest.java | 4 +- .../org/apache/logging/slf4j/LoggerTest.java | 25 ++- .../org/apache/logging/slf4j/MarkerTest.java | 20 +-- .../apache/logging/slf4j/OverflowTest.java | 4 +- .../apache/logging/slf4j/SerializeTest.java | 4 +- .../ThrowableConsumingMessageFactoryTest.java | 2 +- .../spring/boot/Log4j2SpringBootInitTest.java | 6 +- .../Log4j2SpringBootLoggingSystemTest.java | 13 +- .../log4j/spring/boot/SpringLookupTest.java | 6 +- .../log4j/spring/boot/SpringProfileTest.java | 2 +- .../client/Log4j2EventListenerTest.java | 2 +- .../logging/log4j/taglib/DumpTagTest.java | 40 ++--- .../taglib/ExceptionAwareTagSupportTest.java | 24 +-- .../logging/log4j/taglib/LogTagTest.java | 24 +-- .../taglib/LoggerAwareTagSupportTest.java | 84 ++++----- .../log4j/taglib/SetLoggerTagTest.java | 138 +++++++------- .../logging/log4j/taglib/TagLevelTest.java | 22 +-- .../log4j/taglib/TagUtilsLevelTest.java | 27 +-- .../log4j/taglib/TagUtilsScopeTest.java | 24 +-- .../logging/log4j/tojul/JULLoggerTest.java | 4 +- .../logging/log4j/tojul/LoggerTest.java | 42 ++--- .../logging/slf4j/CallerInformationTest.java | 6 +- .../logging/slf4j/Log4j2Jira1688Test.java | 4 +- .../apache/logging/slf4j/LogBuilderTest.java | 4 +- .../logging/slf4j/LoggerContextResolver.java | 4 +- .../apache/logging/slf4j/LoggerResolver.java | 4 +- .../org/apache/logging/slf4j/LoggerTest.java | 44 ++--- .../Log4jServletContainerInitializerTest.java | 20 +-- .../web/Log4jServletContextListenerTest.java | 12 +- .../log4j/web/Log4jServletFilterTest.java | 12 +- ...hutdownOnContextDestroyedListenerTest.java | 8 +- .../web/Log4jWebInitializerImplTest.java | 40 ++--- .../logging/log4j/web/PropertyTest.java | 6 +- .../log4j/web/ServletAppenderTest.java | 4 +- .../logging/log4j/web/TestAsyncServlet.java | 8 +- .../logging/log4j/web/WebLookupTest.java | 6 +- 640 files changed, 4998 insertions(+), 5088 deletions(-) diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/BasicConfiguratorTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/BasicConfiguratorTest.java index 0d2d8f49003..ab632507dc0 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/BasicConfiguratorTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/BasicConfiguratorTest.java @@ -22,34 +22,34 @@ /** * Test {@link BasicConfigurator}. */ -public class BasicConfiguratorTest { +class BasicConfiguratorTest { @Test - public void testConfigure() { + void testConfigure() { // TODO More... BasicConfigurator.configure(); } @Test - public void testResetConfiguration() { + void testResetConfiguration() { // TODO More... BasicConfigurator.resetConfiguration(); } @Test - public void testConfigureAppender() { + void testConfigureAppender() { BasicConfigurator.configure(null); // TODO More... } @Test - public void testConfigureConsoleAppender() { + void testConfigureConsoleAppender() { // TODO What to do? Map to Log4j 2 Appender deeper in the code? BasicConfigurator.configure(new ConsoleAppender()); } @Test - public void testConfigureNullAppender() { + void testConfigureNullAppender() { // The NullAppender name is null and we do not want an NPE when the name is used as a key in a // ConcurrentHashMap. BasicConfigurator.configure(NullAppender.getNullAppender()); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/CallerInformationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/CallerInformationTest.java index 3c5cb502870..1212fc97c0c 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/CallerInformationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/CallerInformationTest.java @@ -26,10 +26,10 @@ // config from log4j-core test-jar @LoggerContextSource(value = "log4j2-calling-class.xml") -public class CallerInformationTest { +class CallerInformationTest { @Test - public void testClassLogger(@Named("Class") final ListAppender app) { + void testClassLogger(@Named("Class") final ListAppender app) { app.clear(); final Logger logger = Logger.getLogger("ClassLogger"); logger.info("Ignored message contents."); @@ -44,7 +44,7 @@ public void testClassLogger(@Named("Class") final ListAppender app) { } @Test - public void testMethodLogger(@Named("Method") final ListAppender app) { + void testMethodLogger(@Named("Method") final ListAppender app) { app.clear(); final Logger logger = Logger.getLogger("MethodLogger"); logger.info("More messages."); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/CategoryTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/CategoryTest.java index 073fc7f45a5..1604f82c2af 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/CategoryTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/CategoryTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -51,7 +52,7 @@ /** * Tests of Category. */ -public class CategoryTest { +class CategoryTest { static ConfigurationFactory cf = new BasicConfigurationFactory(); @@ -61,7 +62,7 @@ public class CategoryTest { private static final org.apache.log4j.ListAppender version1Appender = new org.apache.log4j.ListAppender(); @BeforeAll - public static void setupAll() { + static void setupAll() { appender.start(); version1Appender.setName(VERSION1_APPENDER_NAME); ConfigurationFactory.setConfigurationFactory(cf); @@ -69,18 +70,18 @@ public static void setupAll() { } @AfterAll - public static void cleanupAll() { + static void cleanupAll() { ConfigurationFactory.removeConfigurationFactory(cf); appender.stop(); } @BeforeEach - public void before() { + void before() { appender.clear(); } @Test - public void testExist() { + void testExist() { assertNull(Category.exists("Does not exist for sure")); } @@ -89,7 +90,7 @@ public void testExist() { */ @Test @SuppressWarnings("deprecation") - public void testForcedLog() { + void testForcedLog() { final MockCategory category = new MockCategory("org.example.foo"); category.setAdditivity(false); category.setHierarchy(LogManager.getHierarchy()); @@ -98,23 +99,23 @@ public void testForcedLog() { category.info("Hello, World"); List list = appender.getEvents(); int events = list.size(); - assertEquals(events, 1, "Number of events"); + assertEquals(1, events, "Number of events"); LogEvent event = list.get(0); Message msg = event.getMessage(); assertNotNull(msg, "No message"); // LOG4J2-3080: use message type consistently - assertTrue(msg instanceof SimpleMessage, "Incorrect Message type"); + assertInstanceOf(SimpleMessage.class, msg, "Incorrect Message type"); assertEquals("Hello, World", msg.getFormat()); appender.clear(); // Logging a String map category.info(Collections.singletonMap("hello", "world")); list = appender.getEvents(); events = list.size(); - assertEquals(events, 1, "Number of events"); + assertEquals(1, events, "Number of events"); event = list.get(0); msg = event.getMessage(); assertNotNull(msg, "No message"); - assertTrue(msg instanceof MapMessage, "Incorrect Message type"); + assertInstanceOf(MapMessage.class, msg, "Incorrect Message type"); Object[] objects = msg.getParameters(); assertEquals("world", objects[0]); appender.clear(); @@ -122,11 +123,11 @@ public void testForcedLog() { category.info(Collections.singletonMap(1234L, "world")); list = appender.getEvents(); events = list.size(); - assertEquals(events, 1, "Number of events"); + assertEquals(1, events, "Number of events"); event = list.get(0); msg = event.getMessage(); assertNotNull(msg, "No message"); - assertTrue(msg instanceof MapMessage, "Incorrect Message type"); + assertInstanceOf(MapMessage.class, msg, "Incorrect Message type"); objects = msg.getParameters(); assertEquals("world", objects[0]); appender.clear(); @@ -135,11 +136,11 @@ public void testForcedLog() { category.info(obj); list = appender.getEvents(); events = list.size(); - assertEquals(events, 1, "Number of events"); + assertEquals(1, events, "Number of events"); event = list.get(0); msg = event.getMessage(); assertNotNull(msg, "No message"); - assertTrue(msg instanceof ObjectMessage, "Incorrect Message type"); + assertInstanceOf(ObjectMessage.class, msg, "Incorrect Message type"); objects = msg.getParameters(); assertEquals(obj, objects[0]); appender.clear(); @@ -147,11 +148,11 @@ public void testForcedLog() { category.log(Priority.INFO, "Hello, World"); list = appender.getEvents(); events = list.size(); - assertEquals(events, 1, "Number of events"); + assertEquals(1, events, "Number of events"); event = list.get(0); msg = event.getMessage(); assertNotNull(msg, "No message"); - assertTrue(msg instanceof SimpleMessage, "Incorrect Message type"); + assertInstanceOf(SimpleMessage.class, msg, "Incorrect Message type"); assertEquals("Hello, World", msg.getFormat()); appender.clear(); } @@ -162,16 +163,16 @@ public void testForcedLog() { * @throws Exception thrown if Category.getChainedPriority can not be found. */ @Test - public void testGetChainedPriorityReturnType() throws Exception { + void testGetChainedPriorityReturnType() throws Exception { final Method method = Category.class.getMethod("getChainedPriority", (Class[]) null); - assertEquals(method.getReturnType(), Priority.class); + assertEquals(Priority.class, method.getReturnType()); } /** * Tests l7dlog(Priority, String, Throwable). */ @Test - public void testL7dlog() { + void testL7dlog() { final Logger logger = Logger.getLogger("org.example.foo"); logger.setLevel(Level.ERROR); final Priority debug = Level.DEBUG; @@ -183,7 +184,7 @@ public void testL7dlog() { * Tests l7dlog(Priority, String, Object[], Throwable). */ @Test - public void testL7dlog4Param() { + void testL7dlog4Param() { final Logger logger = Logger.getLogger("org.example.foo"); logger.setLevel(Level.ERROR); final Priority debug = Level.DEBUG; @@ -195,7 +196,7 @@ public void testL7dlog4Param() { * Test using a pre-existing Log4j 2 logger */ @Test - public void testExistingLog4j2Logger() { + void testExistingLog4j2Logger() { // create the logger using LogManager org.apache.logging.log4j.LogManager.getLogger("existingLogger"); // Logger will be the one created above @@ -217,7 +218,7 @@ public void testExistingLog4j2Logger() { */ @Deprecated @Test - public void testSetPriority() { + void testSetPriority() { final Logger logger = Logger.getLogger("org.example.foo"); final Priority debug = Level.DEBUG; logger.setPriority(debug); @@ -230,12 +231,12 @@ public void testSetPriority() { */ @Deprecated @Test - public void testSetPriorityNull() { + void testSetPriorityNull() { Logger.getLogger("org.example.foo").setPriority(null); } @Test - public void testClassName() { + void testClassName() { final Category category = Category.getInstance("TestCategory"); final Layout layout = PatternLayout.newBuilder().withPattern("%d %p %C{1.} [%t] %m%n").build(); @@ -245,7 +246,7 @@ public void testClassName() { ((org.apache.logging.log4j.core.Logger) category.getLogger()).addAppender(appender); category.error("Test Message"); final List msgs = appender.getMessages(); - assertEquals(msgs.size(), 1, "Incorrect number of messages. Expected 1 got " + msgs.size()); + assertEquals(1, msgs.size(), "Incorrect number of messages. Expected 1 got " + msgs.size()); final String msg = msgs.get(0); appender.clear(); final String threadName = Thread.currentThread().getName(); @@ -256,14 +257,14 @@ public void testClassName() { } @Test - public void testStringLog() { + void testStringLog() { final String payload = "payload"; testMessageImplementation( - payload, SimpleMessage.class, message -> assertEquals(message.getFormattedMessage(), payload)); + payload, SimpleMessage.class, message -> assertEquals(payload, message.getFormattedMessage())); } @Test - public void testCharSequenceLog() { + void testCharSequenceLog() { final CharSequence payload = new CharSequence() { @Override @@ -293,7 +294,7 @@ public String toString() { } @Test - public void testMapLog() { + void testMapLog() { final String key = "key"; final Object value = 0xDEADBEEF; final Map payload = Collections.singletonMap(key, value); @@ -301,7 +302,7 @@ public void testMapLog() { } @Test - public void testObjectLog() { + void testObjectLog() { final Object payload = new Object(); testMessageImplementation( payload, ObjectMessage.class, message -> assertEquals(message.getParameter(), payload)); @@ -335,7 +336,7 @@ private void testMessageImplementation( } @Test - public void testAddAppender() { + void testAddAppender() { try { final Logger rootLogger = LogManager.getRootLogger(); int count = version1Appender.getEvents().size(); @@ -363,7 +364,7 @@ public void testAddAppender() { } @Test - public void testGetAppender() { + void testGetAppender() { try { final Logger rootLogger = LogManager.getRootLogger(); final org.apache.logging.log4j.core.Logger v2RootLogger = @@ -372,15 +373,17 @@ public void testGetAppender() { v2RootLogger.addAppender(appender); final List rootAppenders = Collections.list(rootLogger.getAllAppenders()); assertEquals(1, rootAppenders.size(), "only v1 appenders"); - assertTrue(rootAppenders.get(0) instanceof org.apache.log4j.ListAppender, "appender is a v1 ListAppender"); + assertInstanceOf( + org.apache.log4j.ListAppender.class, rootAppenders.get(0), "appender is a v1 ListAppender"); assertEquals( VERSION1_APPENDER_NAME, rootLogger.getAppender(VERSION1_APPENDER_NAME).getName(), "explicitly named appender"); final Appender v2ListAppender = rootLogger.getAppender(VERSION2_APPENDER_NAME); - assertTrue(v2ListAppender instanceof AppenderWrapper, "explicitly named appender"); - assertTrue( - ((AppenderWrapper) v2ListAppender).getAppender() instanceof ListAppender, + assertInstanceOf(AppenderWrapper.class, v2ListAppender, "explicitly named appender"); + assertInstanceOf( + ListAppender.class, + ((AppenderWrapper) v2ListAppender).getAppender(), "appender is a v2 ListAppender"); final Logger logger = LogManager.getLogger(CategoryTest.class); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/ConsoleAppenderTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/ConsoleAppenderTest.java index 9b55dd31f84..7fe9a08e29f 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/ConsoleAppenderTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/ConsoleAppenderTest.java @@ -16,8 +16,8 @@ */ package org.apache.log4j; -import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -25,24 +25,24 @@ /** * Used to test Log4j 1 support. */ -public class ConsoleAppenderTest { +class ConsoleAppenderTest { private ConsoleAppender consoleAppender; @BeforeEach - public void beforeEach() { + void beforeEach() { consoleAppender = new ConsoleAppender(); } @Test - public void testFollow() { + void testFollow() { // Only really care that it compiles, behavior is secondary at this level. consoleAppender.setFollow(true); assertTrue(consoleAppender.getFollow()); } @Test - public void testTarget() { + void testTarget() { // Only really care that it compiles, behavior is secondary at this level. consoleAppender.setTarget(ConsoleAppender.SYSTEM_OUT); assertEquals(ConsoleAppender.SYSTEM_OUT, consoleAppender.getTarget()); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LayoutTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LayoutTest.java index c85b7fe68a1..35c1b2cf1b3 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LayoutTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LayoutTest.java @@ -116,9 +116,8 @@ protected Layout createLayout() { /** * Tests format. * - * @throws Exception derived tests, particular XMLLayoutTest, may throw exceptions. */ - public void testFormat() throws Exception { + public void testFormat() { final Logger logger = Logger.getLogger("org.apache.log4j.LayoutTest"); final LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LevelTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LevelTest.java index b8d0ed92e66..32b574b8de3 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LevelTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LevelTest.java @@ -17,6 +17,7 @@ package org.apache.log4j; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Locale; @@ -31,7 +32,7 @@ * * @since 1.2.12 */ -public class LevelTest { +class LevelTest { /** * Serialize Level.INFO and check against witness. @@ -39,7 +40,7 @@ public class LevelTest { * @throws Exception if exception during test. */ @Test - public void testSerializeINFO() throws Exception { + void testSerializeINFO() throws Exception { final int[] skip = new int[] {}; SerializationTestHelper.assertSerializationEquals( "target/test-classes/witness/serialization/info.bin", Level.INFO, skip, Integer.MAX_VALUE); @@ -51,16 +52,16 @@ public void testSerializeINFO() throws Exception { * @throws Exception if exception during test. */ @Test - public void testDeserializeINFO() throws Exception { + void testDeserializeINFO() throws Exception { final Object obj = SerializationTestHelper.deserializeStream("target/test-classes/witness/serialization/info.bin"); - assertTrue(obj instanceof Level); + assertInstanceOf(Level.class, obj); final Level info = (Level) obj; assertEquals("INFO", info.toString()); // // JDK 1.1 doesn't support readResolve necessary for the assertion if (!System.getProperty("java.version").startsWith("1.1.")) { - assertEquals(obj, Level.INFO); + assertEquals(Level.INFO, obj); } } @@ -71,10 +72,10 @@ public void testDeserializeINFO() throws Exception { * @throws Exception if exception during test. */ @Test - public void testCustomLevelSerialization() throws Exception { + void testCustomLevelSerialization() throws Exception { final CustomLevel custom = new CustomLevel(); final Object obj = SerializationTestHelper.serializeClone(custom); - assertTrue(obj instanceof CustomLevel); + assertInstanceOf(CustomLevel.class, obj); final CustomLevel clone = (CustomLevel) obj; assertEquals(Level.INFO.level, clone.level); @@ -105,7 +106,7 @@ public CustomLevel() { * Tests Level.TRACE_INT. */ @Test - public void testTraceInt() { + void testTraceInt() { assertEquals(5000, Level.TRACE_INT); } @@ -113,7 +114,7 @@ public void testTraceInt() { * Tests Level.TRACE. */ @Test - public void testTrace() { + void testTrace() { assertEquals("TRACE", Level.TRACE.toString()); assertEquals(5000, Level.TRACE.toInt()); assertEquals(7, Level.TRACE.getSyslogEquivalent()); @@ -123,7 +124,7 @@ public void testTrace() { * Tests Level.toLevel(Level.TRACE_INT). */ @Test - public void testIntToTrace() { + void testIntToTrace() { final Level trace = Level.toLevel(5000); assertEquals("TRACE", trace.toString()); } @@ -132,7 +133,7 @@ public void testIntToTrace() { * Tests Level.toLevel("TRACE"); */ @Test - public void testStringToTrace() { + void testStringToTrace() { final Level trace = Level.toLevel("TRACE"); assertEquals("TRACE", trace.toString()); } @@ -141,7 +142,7 @@ public void testStringToTrace() { * Tests that Level extends Priority. */ @Test - public void testLevelExtendsPriority() { + void testLevelExtendsPriority() { assertTrue(Priority.class.isAssignableFrom(Level.class)); } @@ -149,64 +150,64 @@ public void testLevelExtendsPriority() { * Tests Level.OFF. */ @Test - public void testOFF() { - assertTrue(Level.OFF instanceof Level); + void testOFF() { + assertInstanceOf(Level.class, Level.OFF); } /** * Tests Level.FATAL. */ @Test - public void testFATAL() { - assertTrue(Level.FATAL instanceof Level); + void testFATAL() { + assertInstanceOf(Level.class, Level.FATAL); } /** * Tests Level.ERROR. */ @Test - public void testERROR() { - assertTrue(Level.ERROR instanceof Level); + void testERROR() { + assertInstanceOf(Level.class, Level.ERROR); } /** * Tests Level.WARN. */ @Test - public void testWARN() { - assertTrue(Level.WARN instanceof Level); + void testWARN() { + assertInstanceOf(Level.class, Level.WARN); } /** * Tests Level.INFO. */ @Test - public void testINFO() { - assertTrue(Level.INFO instanceof Level); + void testINFO() { + assertInstanceOf(Level.class, Level.INFO); } /** * Tests Level.DEBUG. */ @Test - public void testDEBUG() { - assertTrue(Level.DEBUG instanceof Level); + void testDEBUG() { + assertInstanceOf(Level.class, Level.DEBUG); } /** * Tests Level.TRACE. */ @Test - public void testTRACE() { - assertTrue(Level.TRACE instanceof Level); + void testTRACE() { + assertInstanceOf(Level.class, Level.TRACE); } /** * Tests Level.ALL. */ @Test - public void testALL() { - assertTrue(Level.ALL instanceof Level); + void testALL() { + assertInstanceOf(Level.class, Level.ALL); } /** @@ -214,7 +215,7 @@ public void testALL() { */ @ParameterizedTest @MethodSource("org.apache.log4j.helpers.OptionConverterLevelTest#standardLevels") - public void testVersion2Level(final Level log4j1Level, final org.apache.logging.log4j.Level log4j2Level) { + void testVersion2Level(final Level log4j1Level, final org.apache.logging.log4j.Level log4j2Level) { assertEquals(log4j2Level, log4j1Level.getVersion2Level()); } @@ -222,7 +223,7 @@ public void testVersion2Level(final Level log4j1Level, final org.apache.logging. * Tests Level.toLevel(Level.All_INT). */ @Test - public void testIntToAll() { + void testIntToAll() { final Level level = Level.toLevel(Priority.ALL_INT); assertEquals("ALL", level.toString()); } @@ -231,7 +232,7 @@ public void testIntToAll() { * Tests Level.toLevel(Level.FATAL_INT). */ @Test - public void testIntToFatal() { + void testIntToFatal() { final Level level = Level.toLevel(Priority.FATAL_INT); assertEquals("FATAL", level.toString()); } @@ -240,7 +241,7 @@ public void testIntToFatal() { * Tests Level.toLevel(Level.OFF_INT). */ @Test - public void testIntToOff() { + void testIntToOff() { final Level level = Level.toLevel(Priority.OFF_INT); assertEquals("OFF", level.toString()); } @@ -249,7 +250,7 @@ public void testIntToOff() { * Tests Level.toLevel(17, Level.FATAL). */ @Test - public void testToLevelUnrecognizedInt() { + void testToLevelUnrecognizedInt() { final Level level = Level.toLevel(17, Level.FATAL); assertEquals("FATAL", level.toString()); } @@ -258,7 +259,7 @@ public void testToLevelUnrecognizedInt() { * Tests Level.toLevel(null, Level.FATAL). */ @Test - public void testToLevelNull() { + void testToLevelNull() { final Level level = Level.toLevel(null, Level.FATAL); assertEquals("FATAL", level.toString()); } @@ -267,7 +268,7 @@ public void testToLevelNull() { * Test that dotless lower I + "nfo" is recognized as INFO. */ @Test - public void testDotlessLowerI() { + void testDotlessLowerI() { final Level level = Level.toLevel("\u0131nfo"); assertEquals("INFO", level.toString()); } @@ -277,7 +278,7 @@ public void testDotlessLowerI() { * even in Turkish locale. */ @Test - public void testDottedLowerI() { + void testDottedLowerI() { final Locale defaultLocale = Locale.getDefault(); final Locale turkey = new Locale("tr", "TR"); Locale.setDefault(turkey); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/ListAppender.java b/log4j-1.2-api/src/test/java/org/apache/log4j/ListAppender.java index cfc9fe49bcc..34bce86bd63 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/ListAppender.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/ListAppender.java @@ -71,8 +71,7 @@ public List getMessages() { * Polls the messages list for it to grow to a given minimum size at most timeout timeUnits and return a copy of * what we have so far. */ - public List getMessages(final int minSize, final long timeout, final TimeUnit timeUnit) - throws InterruptedException { + public List getMessages(final int minSize, final long timeout, final TimeUnit timeUnit) { waitAtMost(timeout, timeUnit).until(() -> messages.size() >= minSize); return getMessages(); } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LogManagerTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LogManagerTest.java index 23f4d0f6f30..501d2c36709 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LogManagerTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LogManagerTest.java @@ -27,7 +27,7 @@ /** * Tests {@link LogManager}. */ -public class LogManagerTest { +class LogManagerTest { private static final String SIMPLE_NAME = LogManagerTest.class.getSimpleName(); @@ -38,7 +38,7 @@ List getCurrentLoggerNames() { } @Test - public void testGetCurrentLoggers() { + void testGetCurrentLoggers() { Logger.getLogger(SIMPLE_NAME); Logger.getLogger(SIMPLE_NAME + ".foo"); Logger.getLogger(SIMPLE_NAME + ".foo.bar"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithMDCTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithMDCTest.java index c908f56f926..0e5165d4796 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithMDCTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithMDCTest.java @@ -30,10 +30,10 @@ * Test logging with MDC values. */ @LoggerContextSource("logWithMDC.xml") -public class LogWithMDCTest { +class LogWithMDCTest { @Test - public void testMDC(@Named("List") final ListAppender listApp) { + void testMDC(@Named("List") final ListAppender listApp) { MDC.put("Key1", "John"); MDC.put("Key2", "Smith"); try { @@ -42,7 +42,7 @@ public void testMDC(@Named("List") final ListAppender listApp) { assertNotNull(listApp); final List msgs = listApp.getMessages(); assertNotNull(msgs, "No messages received"); - assertEquals(msgs.size(), 1); + assertEquals(1, msgs.size()); assertTrue(msgs.get(0).contains("Key1=John"), "Key1 is missing"); assertTrue(msgs.get(0).contains("Key2=Smith"), "Key2 is missing"); } finally { diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithRouteTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithRouteTest.java index ffd09175f58..18ad15293c8 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithRouteTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LogWithRouteTest.java @@ -30,10 +30,10 @@ * Test passing MDC values to the Routing appender. */ @LoggerContextSource("log-RouteWithMDC.xml") -public class LogWithRouteTest { +class LogWithRouteTest { @Test - public void testMDC(@Named("List") final ListAppender listApp) { + void testMDC(@Named("List") final ListAppender listApp) { MDC.put("Type", "Service"); MDC.put("Name", "John Smith"); try { @@ -42,7 +42,7 @@ public void testMDC(@Named("List") final ListAppender listApp) { assertNotNull(listApp); final List msgs = listApp.getMessages(); assertNotNull(msgs, "No messages received"); - assertEquals(msgs.size(), 1); + assertEquals(1, msgs.size()); assertTrue(msgs.get(0).contains("Type=Service"), "Type is missing"); assertTrue(msgs.get(0).contains("Name=John Smith"), "Name is missing"); } finally { diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerJira3410Test.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerJira3410Test.java index e7502f7d40c..be16d3d0953 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerJira3410Test.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerJira3410Test.java @@ -33,10 +33,10 @@ /** * Tests Jira3410. */ -public class LoggerJira3410Test { +class LoggerJira3410Test { @Test - public void test() throws Exception { + void test() throws Exception { try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/log4j1-list.properties")) { final Logger logger = LogManager.getLogger("test"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerTest.java index a2fef9d77b4..da857121038 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LoggerTest.java @@ -46,7 +46,7 @@ /** * Used for internal unit testing the Logger class. */ -public class LoggerTest { +class LoggerTest { Appender a1; Appender a2; @@ -61,7 +61,7 @@ public class LoggerTest { static ConfigurationFactory configurationFactory = new BasicConfigurationFactory(); @BeforeAll - public static void setUpAll() { + static void setUpAll() { rbUS = ResourceBundle.getBundle("L7D", new Locale("en", "US")); assertNotNull(rbUS); @@ -75,12 +75,12 @@ public static void setUpAll() { } @AfterAll - public static void tearDownAll() { + static void tearDownAll() { ConfigurationFactory.removeConfigurationFactory(configurationFactory); } @BeforeEach - public void resetTest() { + void resetTest() { Objects.requireNonNull(LogManager.getHierarchy()).resetConfiguration(); a1 = null; a2 = null; @@ -123,7 +123,7 @@ public void resetTest() { * Test if logger a.b inherits its appender from a. */ @Test - public void testAdditivity1() { + void testAdditivity1() { final Logger loggerA = Logger.getLogger("a"); final Logger loggerAB = Logger.getLogger("a.b"); final CountingAppender coutingAppender = new CountingAppender(); @@ -150,7 +150,7 @@ public void testAdditivity1() { * Test multiple additivity. */ @Test - public void testAdditivity2() { + void testAdditivity2() { final Logger a = Logger.getLogger("a"); final Logger ab = Logger.getLogger("a.b"); final Logger abc = Logger.getLogger("a.b.c"); @@ -165,20 +165,20 @@ public void testAdditivity2() { ((org.apache.logging.log4j.core.Logger) a.getLogger()).addAppender(ca1); ((org.apache.logging.log4j.core.Logger) abc.getLogger()).addAppender(ca2); - assertEquals(ca1.counter, 0); - assertEquals(ca2.counter, 0); + assertEquals(0, ca1.counter); + assertEquals(0, ca2.counter); ab.debug(MSG); - assertEquals(ca1.counter, 1); - assertEquals(ca2.counter, 0); + assertEquals(1, ca1.counter); + assertEquals(0, ca2.counter); abc.debug(MSG); - assertEquals(ca1.counter, 2); - assertEquals(ca2.counter, 1); + assertEquals(2, ca1.counter); + assertEquals(1, ca2.counter); x.debug(MSG); - assertEquals(ca1.counter, 2); - assertEquals(ca2.counter, 1); + assertEquals(2, ca1.counter); + assertEquals(1, ca2.counter); ca1.stop(); ca2.stop(); } finally { @@ -191,7 +191,7 @@ public void testAdditivity2() { * Test additivity flag. */ @Test - public void testAdditivity3() { + void testAdditivity3() { final Logger root = Logger.getRootLogger(); final Logger a = Logger.getLogger("a"); final Logger ab = Logger.getLogger("a.b"); @@ -209,26 +209,26 @@ public void testAdditivity3() { ((org.apache.logging.log4j.core.Logger) a.getLogger()).addAppender(caA); ((org.apache.logging.log4j.core.Logger) abc.getLogger()).addAppender(caABC); - assertEquals(caRoot.counter, 0); - assertEquals(caA.counter, 0); - assertEquals(caABC.counter, 0); + assertEquals(0, caRoot.counter); + assertEquals(0, caA.counter); + assertEquals(0, caABC.counter); ab.setAdditivity(false); a.debug(MSG); - assertEquals(caRoot.counter, 1); - assertEquals(caA.counter, 1); - assertEquals(caABC.counter, 0); + assertEquals(1, caRoot.counter); + assertEquals(1, caA.counter); + assertEquals(0, caABC.counter); ab.debug(MSG); - assertEquals(caRoot.counter, 1); - assertEquals(caA.counter, 1); - assertEquals(caABC.counter, 0); + assertEquals(1, caRoot.counter); + assertEquals(1, caA.counter); + assertEquals(0, caABC.counter); abc.debug(MSG); - assertEquals(caRoot.counter, 1); - assertEquals(caA.counter, 1); - assertEquals(caABC.counter, 1); + assertEquals(1, caRoot.counter); + assertEquals(1, caA.counter); + assertEquals(1, caABC.counter); caRoot.stop(); caA.stop(); caABC.stop(); @@ -304,7 +304,7 @@ public void testDisable1() { } */ @Test - public void testRB1() { + void testRB1() { final Logger root = Logger.getRootLogger(); root.setResourceBundle(rbUS); ResourceBundle t = root.getResourceBundle(); @@ -323,7 +323,7 @@ public void testRB1() { } @Test - public void testRB2() { + void testRB2() { final Logger root = Logger.getRootLogger(); root.setResourceBundle(rbUS); ResourceBundle t = root.getResourceBundle(); @@ -343,7 +343,7 @@ public void testRB2() { } @Test - public void testRB3() { + void testRB3() { final Logger root = Logger.getRootLogger(); root.setResourceBundle(rbUS); ResourceBundle t = root.getResourceBundle(); @@ -364,7 +364,7 @@ public void testRB3() { } @Test - public void testExists() { + void testExists() { final Logger a = Logger.getLogger("a"); final Logger a_b = Logger.getLogger("a.b"); final Logger a_b_c = Logger.getLogger("a.b.c"); @@ -379,6 +379,7 @@ public void testExists() { t = LogManager.exists("a.b.c"); assertSame(a_b_c, t); } + /* Don't support hierarchy public void testHierarchy1() { Hierarchy h = new Hierarchy(new RootLogger((Level) Level.ERROR)); @@ -395,7 +396,7 @@ public void testHierarchy1() { * Tests logger.trace(Object). */ @Test - public void testTrace() { + void testTrace() { final ListAppender appender = new ListAppender("List"); appender.start(); final Logger root = Logger.getRootLogger(); @@ -422,7 +423,7 @@ public void testTrace() { * Tests logger.trace(Object, Exception). */ @Test - public void testTraceWithException() { + void testTraceWithException() { final ListAppender appender = new ListAppender("List"); appender.start(); final Logger root = Logger.getRootLogger(); @@ -453,7 +454,7 @@ public void testTraceWithException() { * Tests isTraceEnabled. */ @Test - public void testIsTraceEnabled() { + void testIsTraceEnabled() { final ListAppender appender = new ListAppender("List"); appender.start(); final Logger root = Logger.getRootLogger(); @@ -474,7 +475,7 @@ public void testIsTraceEnabled() { @Test @SuppressWarnings("deprecation") - public void testLog() { + void testLog() { final PatternLayout layout = PatternLayout.newBuilder().withPattern("%d %C %L %m").build(); final ListAppender appender = new ListAppender("List", null, layout, false, false); @@ -488,7 +489,7 @@ public void testLog() { root.log(Priority.INFO, "Test msg2", null); root.log(Priority.INFO, "Test msg3"); final List msgs = appender.getMessages(); - assertEquals(msgs.size(), 3, "Incorrect number of messages"); + assertEquals(3, msgs.size(), "Incorrect number of messages"); final String msg = msgs.get(0); assertTrue(msg.contains(LoggerTest.class.getName()), "Message contains incorrect class name: " + msg); appender.stop(); @@ -498,7 +499,7 @@ public void testLog() { } @Test - public void testSetLevel() { + void testSetLevel() { final Logger a = Logger.getLogger("a"); final Logger a_b = Logger.getLogger("a.b"); final Logger a_b_c = Logger.getLogger("a.b.c"); @@ -523,7 +524,7 @@ public void testSetLevel() { } @Test - public void testSetPriority() { + void testSetPriority() { final Logger a = Logger.getLogger("a"); final Logger a_b = Logger.getLogger("a.b"); final Logger a_b_c = Logger.getLogger("a.b.c"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/LoggingTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/LoggingTest.java index 017dde05fa6..0e77fd8962e 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/LoggingTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/LoggingTest.java @@ -26,10 +26,10 @@ * */ @LoggerContextSource("log4j2-config.xml") -public class LoggingTest { +class LoggingTest { @Test - public void testParent() { + void testParent() { final Logger logger = Logger.getLogger("org.apache.test.logging.Test"); final Category parent = logger.getParent(); assertNotNull(parent, "No parent Logger"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/MDCTestCase.java b/log4j-1.2-api/src/test/java/org/apache/log4j/MDCTestCase.java index 75353d7dba3..b90b59ae671 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/MDCTestCase.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/MDCTestCase.java @@ -22,27 +22,27 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class MDCTestCase { +class MDCTestCase { @BeforeEach - public void setUp() { + void setUp() { MDC.clear(); } @AfterEach - public void tearDown() { + void tearDown() { MDC.clear(); } @Test - public void testPut() { + void testPut() { MDC.put("key", "some value"); assertEquals("some value", MDC.get("key")); assertEquals(1, MDC.getContext().size()); } @Test - public void testRemoveLastKey() { + void testRemoveLastKey() { MDC.put("key", "some value"); MDC.remove("key"); } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/NDCTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/NDCTest.java index a45d0702b5d..30173b5e2ee 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/NDCTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/NDCTest.java @@ -22,23 +22,23 @@ import org.apache.logging.log4j.util.Strings; import org.junit.jupiter.api.Test; -public class NDCTest { +class NDCTest { @Test - public void testPopEmpty() { + void testPopEmpty() { NDC.clear(); assertEquals(Strings.EMPTY, NDC.pop()); } @Test - public void testPeekEmpty() { + void testPeekEmpty() { NDC.clear(); assertEquals(Strings.EMPTY, NDC.peek()); } @SuppressWarnings({"rawtypes"}) @Test - public void testCompileCloneToInherit() { + void testCompileCloneToInherit() { NDC.inherit(NDC.cloneStack()); final Stack stackRaw = NDC.cloneStack(); NDC.inherit(stackRaw); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/PriorityTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/PriorityTest.java index 5fb356d61b5..7d649fdc9b5 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/PriorityTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/PriorityTest.java @@ -18,7 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.Locale; import java.util.stream.Stream; @@ -31,13 +31,13 @@ * Tests of Priority. * */ -public class PriorityTest { +class PriorityTest { /** * Tests Priority.OFF_INT. */ @Test - public void testOffInt() { + void testOffInt() { assertEquals(Integer.MAX_VALUE, Priority.OFF_INT); } @@ -45,7 +45,7 @@ public void testOffInt() { * Tests Priority.FATAL_INT. */ @Test - public void testFatalInt() { + void testFatalInt() { assertEquals(50000, Priority.FATAL_INT); } @@ -53,7 +53,7 @@ public void testFatalInt() { * Tests Priority.ERROR_INT. */ @Test - public void testErrorInt() { + void testErrorInt() { assertEquals(40000, Priority.ERROR_INT); } @@ -61,7 +61,7 @@ public void testErrorInt() { * Tests Priority.WARN_INT. */ @Test - public void testWarnInt() { + void testWarnInt() { assertEquals(30000, Priority.WARN_INT); } @@ -69,7 +69,7 @@ public void testWarnInt() { * Tests Priority.INFO_INT. */ @Test - public void testInfoInt() { + void testInfoInt() { assertEquals(20000, Priority.INFO_INT); } @@ -77,7 +77,7 @@ public void testInfoInt() { * Tests Priority.DEBUG_INT. */ @Test - public void testDebugInt() { + void testDebugInt() { assertEquals(10000, Priority.DEBUG_INT); } @@ -85,7 +85,7 @@ public void testDebugInt() { * Tests Priority.ALL_INT. */ @Test - public void testAllInt() { + void testAllInt() { assertEquals(Integer.MIN_VALUE, Priority.ALL_INT); } @@ -104,7 +104,7 @@ static Stream testVersion2Level() { */ @ParameterizedTest @MethodSource() - public void testVersion2Level(final Priority log4j1Priority, final org.apache.logging.log4j.Level log4j2Level) { + void testVersion2Level(final Priority log4j1Priority, final org.apache.logging.log4j.Level log4j2Level) { assertEquals(log4j2Level, log4j1Priority.getVersion2Level()); } @@ -113,7 +113,7 @@ public void testVersion2Level(final Priority log4j1Priority, final org.apache.lo */ @Test @SuppressWarnings("deprecation") - public void testFATAL() { + void testFATAL() { assertFalse(Priority.FATAL instanceof Level); } @@ -122,7 +122,7 @@ public void testFATAL() { */ @Test @SuppressWarnings("deprecation") - public void testERROR() { + void testERROR() { assertFalse(Priority.ERROR instanceof Level); } @@ -131,7 +131,7 @@ public void testERROR() { */ @Test @SuppressWarnings("deprecation") - public void testWARN() { + void testWARN() { assertFalse(Priority.WARN instanceof Level); } @@ -140,7 +140,7 @@ public void testWARN() { */ @Test @SuppressWarnings("deprecation") - public void testINFO() { + void testINFO() { assertFalse(Priority.INFO instanceof Level); } @@ -149,7 +149,7 @@ public void testINFO() { */ @Test @SuppressWarnings("deprecation") - public void testDEBUG() { + void testDEBUG() { assertFalse(Priority.DEBUG instanceof Level); } @@ -158,8 +158,8 @@ public void testDEBUG() { */ @Test @SuppressWarnings("deprecation") - public void testEqualsNull() { - assertFalse(Priority.DEBUG.equals(null)); + void testEqualsNull() { + assertNotEquals(null, Priority.DEBUG); } /** @@ -167,11 +167,11 @@ public void testEqualsNull() { */ @Test @SuppressWarnings("deprecation") - public void testEqualsLevel() { + void testEqualsLevel() { // // this behavior violates the equals contract. // - assertTrue(Priority.DEBUG.equals(Level.DEBUG)); + assertEquals(Priority.DEBUG, Level.DEBUG); } /** @@ -179,7 +179,7 @@ public void testEqualsLevel() { */ @Test @SuppressWarnings("deprecation") - public void testGetAllPossiblePriorities() { + void testGetAllPossiblePriorities() { final Priority[] priorities = Priority.getAllPossiblePriorities(); assertEquals(5, priorities.length); } @@ -189,8 +189,8 @@ public void testGetAllPossiblePriorities() { */ @Test @SuppressWarnings("deprecation") - public void testToPriorityString() { - assertEquals(Priority.toPriority("DEBUG"), Level.DEBUG); + void testToPriorityString() { + assertEquals(Level.DEBUG, Priority.toPriority("DEBUG")); } /** @@ -198,8 +198,8 @@ public void testToPriorityString() { */ @Test @SuppressWarnings("deprecation") - public void testToPriorityInt() { - assertEquals(Priority.toPriority(Priority.DEBUG_INT), Level.DEBUG); + void testToPriorityInt() { + assertEquals(Level.DEBUG, Priority.toPriority(Priority.DEBUG_INT)); } /** @@ -207,8 +207,8 @@ public void testToPriorityInt() { */ @Test @SuppressWarnings("deprecation") - public void testToPriorityStringPriority() { - assertEquals(Priority.toPriority("foo", Priority.DEBUG), Priority.DEBUG); + void testToPriorityStringPriority() { + assertEquals(Priority.DEBUG, Priority.toPriority("foo", Priority.DEBUG)); } /** @@ -216,8 +216,8 @@ public void testToPriorityStringPriority() { */ @Test @SuppressWarnings("deprecation") - public void testToPriorityIntPriority() { - assertEquals(Priority.toPriority(17, Priority.DEBUG), Priority.DEBUG); + void testToPriorityIntPriority() { + assertEquals(Priority.DEBUG, Priority.toPriority(17, Priority.DEBUG)); } /** @@ -225,7 +225,7 @@ public void testToPriorityIntPriority() { */ @Test @SuppressWarnings("deprecation") - public void testDotlessLowerI() { + void testDotlessLowerI() { final Priority level = Priority.toPriority("\u0131nfo"); assertEquals("INFO", level.toString()); } @@ -236,7 +236,7 @@ public void testDotlessLowerI() { */ @Test @SuppressWarnings("deprecation") - public void testDottedLowerI() { + void testDottedLowerI() { final Locale defaultLocale = Locale.getDefault(); final Locale turkey = new Locale("tr", "TR"); Locale.setDefault(turkey); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/PropertyConfiguratorTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/PropertyConfiguratorTest.java index f5190e83468..b80296f898f 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/PropertyConfiguratorTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/PropertyConfiguratorTest.java @@ -271,7 +271,7 @@ void testInputStream() throws IOException { * @throws IOException if IOException creating properties jar. */ @Test - public void testJarURL() throws IOException { + void testJarURL() throws IOException { final File dir = new File("output"); dir.mkdirs(); final File file = new File("output/properties.jar"); @@ -287,7 +287,7 @@ public void testJarURL() throws IOException { } @Test - public void testLocalVsGlobal() { + void testLocalVsGlobal() { LoggerRepository repos1, repos2; final Logger catA = Logger.getLogger(CAT_A_NAME); final Logger catB = Logger.getLogger(CAT_B_NAME); @@ -360,10 +360,9 @@ void testURL() throws IOException { /** * Test for bug 40944. configure(URL) did not catch IllegalArgumentException and did not close stream. * - * @throws IOException if IOException creating properties file. */ @Test - void testURLBadEscape() throws IOException { + void testURLBadEscape() { final URL configURL = PropertyConfiguratorTest.class.getResource(BAD_ESCAPE_PROPERTIES); PropertyConfigurator.configure(configURL); } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/bridge/LogEventWrapperTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/bridge/LogEventWrapperTest.java index 8a3e9dd2cfa..ff5faff5f1d 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/bridge/LogEventWrapperTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/bridge/LogEventWrapperTest.java @@ -23,10 +23,10 @@ import org.apache.logging.log4j.core.LogEvent; import org.junit.jupiter.api.Test; -public class LogEventWrapperTest { +class LogEventWrapperTest { @Test - public void testThread() { + void testThread() { final Thread currentThread = Thread.currentThread(); final String threadName = currentThread.getName(); final LoggingEvent log4j1Event = new LoggingEvent() { @@ -42,7 +42,7 @@ public String getThreadName() { } @Test - public void testToImmutable() { + void testToImmutable() { final LogEventWrapper wrapper = new LogEventWrapper(new LoggingEvent()); assertSame(wrapper, wrapper.toImmutable()); } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/builders/BuilderManagerTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/builders/BuilderManagerTest.java index 9b29ba0dd61..8d6b5a23f9d 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/builders/BuilderManagerTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/builders/BuilderManagerTest.java @@ -26,7 +26,7 @@ import org.apache.log4j.varia.StringMatchFilter; import org.junit.jupiter.api.Test; -public class BuilderManagerTest { +class BuilderManagerTest { /** * This test ensures that instantiation failures due to missing parameters @@ -34,7 +34,7 @@ public class BuilderManagerTest { * "instantiate by classname" fallback mechanism for supported components. */ @Test - public void testReturnInvalidValueOnError() { + void testReturnInvalidValueOnError() { final PropertiesConfiguration config = new PropertiesConfiguration(null, null); final BuilderManager manager = new BuilderManager(); final Properties props = new Properties(); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/builders/filter/LevelRangeFilterBuilderTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/builders/filter/LevelRangeFilterBuilderTest.java index 854c945f311..4a6290da846 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/builders/filter/LevelRangeFilterBuilderTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/builders/filter/LevelRangeFilterBuilderTest.java @@ -35,11 +35,11 @@ import org.w3c.dom.Element; import org.xml.sax.InputSource; -public class LevelRangeFilterBuilderTest { +class LevelRangeFilterBuilderTest { @ParameterizedTest @ArgumentsSource(TestLevelRangeFilterBuilderProvider.class) - public void testAcceptOnMatchTrue(final TestLevelRangeFilterBuilder builder) throws Exception { + void testAcceptOnMatchTrue(final TestLevelRangeFilterBuilder builder) throws Exception { final LevelRangeFilter levelRangeFilter = builder.build(Level.INFO, Level.ERROR, true); assertResult(Result.DENY, levelRangeFilter, Level.ALL); @@ -53,7 +53,7 @@ public void testAcceptOnMatchTrue(final TestLevelRangeFilterBuilder builder) thr @ParameterizedTest @ArgumentsSource(TestLevelRangeFilterBuilderProvider.class) - public void testAcceptOnMatchFalse(final TestLevelRangeFilterBuilder builder) throws Exception { + void testAcceptOnMatchFalse(final TestLevelRangeFilterBuilder builder) throws Exception { final LevelRangeFilter levelRangeFilter = builder.build(Level.INFO, Level.ERROR, false); assertResult(Result.DENY, levelRangeFilter, Level.ALL); @@ -67,7 +67,7 @@ public void testAcceptOnMatchFalse(final TestLevelRangeFilterBuilder builder) th @ParameterizedTest @ArgumentsSource(TestLevelRangeFilterBuilderProvider.class) - public void testAcceptOnMatchNull(final TestLevelRangeFilterBuilder builder) throws Exception { + void testAcceptOnMatchNull(final TestLevelRangeFilterBuilder builder) throws Exception { final LevelRangeFilter levelRangeFilter = builder.build(Level.INFO, Level.ERROR, null); assertResult(Result.DENY, levelRangeFilter, Level.ALL); @@ -81,7 +81,7 @@ public void testAcceptOnMatchNull(final TestLevelRangeFilterBuilder builder) thr @ParameterizedTest @ArgumentsSource(TestLevelRangeFilterBuilderProvider.class) - public void testMinLevelNull(final TestLevelRangeFilterBuilder builder) throws Exception { + void testMinLevelNull(final TestLevelRangeFilterBuilder builder) throws Exception { final LevelRangeFilter levelRangeFilter = builder.build(null, Level.ERROR, true); assertResult(Result.ACCEPT, levelRangeFilter, Level.ALL); @@ -95,7 +95,7 @@ public void testMinLevelNull(final TestLevelRangeFilterBuilder builder) throws E @ParameterizedTest @ArgumentsSource(TestLevelRangeFilterBuilderProvider.class) - public void testMaxLevelNull(final TestLevelRangeFilterBuilder builder) throws Exception { + void testMaxLevelNull(final TestLevelRangeFilterBuilder builder) throws Exception { final LevelRangeFilter levelRangeFilter = builder.build(Level.INFO, null, true); assertResult(Result.DENY, levelRangeFilter, Level.ALL); @@ -109,7 +109,7 @@ public void testMaxLevelNull(final TestLevelRangeFilterBuilder builder) throws E @ParameterizedTest @ArgumentsSource(TestLevelRangeFilterBuilderProvider.class) - public void testMinMaxLevelSame(final TestLevelRangeFilterBuilder builder) throws Exception { + void testMinMaxLevelSame(final TestLevelRangeFilterBuilder builder) throws Exception { final LevelRangeFilter levelRangeFilter = builder.build(Level.INFO, Level.INFO, true); assertResult(Result.DENY, levelRangeFilter, Level.ALL); @@ -123,7 +123,7 @@ public void testMinMaxLevelSame(final TestLevelRangeFilterBuilder builder) throw @ParameterizedTest @ArgumentsSource(TestLevelRangeFilterBuilderProvider.class) - public void testMinMaxLevelNull(final TestLevelRangeFilterBuilder builder) throws Exception { + void testMinMaxLevelNull(final TestLevelRangeFilterBuilder builder) throws Exception { final LevelRangeFilter levelRangeFilter = builder.build(null, null, true); assertResult(Result.ACCEPT, levelRangeFilter, Level.ALL); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/builders/layout/PatternLayoutBuilderTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/builders/layout/PatternLayoutBuilderTest.java index 430b02a98cc..c64dfc3df37 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/builders/layout/PatternLayoutBuilderTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/builders/layout/PatternLayoutBuilderTest.java @@ -18,7 +18,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.Arrays; import java.util.stream.Stream; import org.apache.log4j.bridge.LayoutAdapter; import org.apache.logging.log4j.core.layout.PatternLayout; @@ -26,10 +25,10 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -public class PatternLayoutBuilderTest { +class PatternLayoutBuilderTest { static Stream patterns() { - return Arrays.asList( + return Stream.of( Arguments.of("%p", "%v1Level"), Arguments.of("%100p", "%100v1Level"), Arguments.of("%-100p", "%-100v1Level"), @@ -41,13 +40,12 @@ static Stream patterns() { Arguments.of("%XX", "%XX"), Arguments.of("%p id", "%v1Level id"), Arguments.of("%x Ex", "%ndc Ex"), - Arguments.of("%X X", "%properties X")) - .stream(); + Arguments.of("%X X", "%properties X")); } @ParameterizedTest @MethodSource("patterns") - public void testLevelPatternReplacement(final String v1Pattern, final String v2Pattern) { + void testLevelPatternReplacement(final String v1Pattern, final String v2Pattern) { final PatternLayoutBuilder builder = new PatternLayoutBuilder(); final PatternLayout layout = (PatternLayout) LayoutAdapter.adapt(builder.createLayout(v1Pattern, null)); assertEquals(v2Pattern, layout.getConversionPattern()); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationConverterTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationConverterTest.java index 2d242cb838a..f27722278dc 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationConverterTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationConverterTest.java @@ -38,7 +38,7 @@ protected static List getPaths(final String root) throws IOException { final List paths = new ArrayList<>(); Files.walkFileTree(Paths.get(root), new SimpleFileVisitor() { @Override - public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { + public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) { paths.add(file.toAbsolutePath()); return FileVisitResult.CONTINUE; } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationTest.java index 7874ffe2d85..b9967d0de41 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AbstractLog4j1ConfigurationTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -67,7 +68,7 @@ import org.apache.logging.log4j.core.layout.PatternLayout; import org.junit.jupiter.api.io.TempDir; -public abstract class AbstractLog4j1ConfigurationTest { +abstract class AbstractLog4j1ConfigurationTest { @TempDir File tempDir; @@ -85,14 +86,14 @@ protected LoggerContext configure(final String configResourcePrefix) throws URIS return (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false); } - public void testConsoleCapitalization() throws Exception { + void testConsoleCapitalization() throws Exception { final Configuration config = getConfiguration("config-1.2/log4j-capitalization"); final Appender capitalized = config.getAppender("ConsoleCapitalized"); assertNotNull(capitalized); - assertEquals(capitalized.getClass(), ConsoleAppender.class); + assertEquals(ConsoleAppender.class, capitalized.getClass()); final Appender javaStyle = config.getAppender("ConsoleJavaStyle"); assertNotNull(javaStyle); - assertEquals(javaStyle.getClass(), ConsoleAppender.class); + assertEquals(ConsoleAppender.class, javaStyle.getClass()); testConsoleAppender((ConsoleAppender) capitalized, (ConsoleAppender) javaStyle); } @@ -116,7 +117,7 @@ private Layout testConsole(final String configResource) throws Exception { final ConsoleAppender appender = configuration.getAppender(name); assertNotNull( appender, "Missing appender '" + name + "' in configuration " + configResource + " → " + configuration); - assertEquals(true, getFollowProperty(appender), "follow"); + assertTrue(getFollowProperty(appender), "follow"); assertEquals(Target.SYSTEM_ERR, appender.getTarget()); // final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo"); @@ -128,24 +129,24 @@ private Layout testConsole(final String configResource) throws Exception { return appender.getLayout(); } - public void testConsoleTtccLayout() throws Exception { + void testConsoleTtccLayout() throws Exception { final PatternLayout layout = (PatternLayout) testConsole("config-1.2/log4j-console-TTCCLayout"); assertEquals("%d{ISO8601}{CET} %p - %m%n", layout.getConversionPattern()); } - public void testRollingFileAppender() throws Exception { + void testRollingFileAppender() throws Exception { testRollingFileAppender("config-1.2/log4j-RollingFileAppender"); } - public void testDailyRollingFileAppender() throws Exception { + void testDailyRollingFileAppender() throws Exception { testDailyRollingFileAppender("config-1.2/log4j-DailyRollingFileAppender"); } - public void testRollingFileAppenderWithProperties() throws Exception { + void testRollingFileAppenderWithProperties() throws Exception { testRollingFileAppender("config-1.2/log4j-RollingFileAppender-with-props"); } - public void testSystemProperties1() throws Exception { + void testSystemProperties1() throws Exception { final String tempFileName = System.getProperty("java.io.tmpdir") + "/hadoop.log"; final Path tempFilePath = new File(tempFileName).toPath(); Files.deleteIfExists(tempFilePath); @@ -162,7 +163,7 @@ public void testSystemProperties1() throws Exception { final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies(); assertEquals(1, triggeringPolicies.length); final TriggeringPolicy tp = triggeringPolicies[0]; - assertTrue(tp instanceof SizeBasedTriggeringPolicy, tp.getClass().getName()); + assertInstanceOf(SizeBasedTriggeringPolicy.class, tp, tp.getClass().getName()); final SizeBasedTriggeringPolicy sbtp = (SizeBasedTriggeringPolicy) tp; assertEquals(20 * 1024 * 1024, sbtp.getMaxFileSize()); appender.stop(10, TimeUnit.SECONDS); @@ -174,7 +175,7 @@ public void testSystemProperties1() throws Exception { } } - public void testSystemProperties2() throws Exception { + void testSystemProperties2() throws Exception { final Configuration configuration = getConfiguration("config-1.2/log4j-system-properties-2"); final RollingFileAppender appender = configuration.getAppender("RFA"); final String tmpDir = System.getProperty("java.io.tmpdir"); @@ -192,11 +193,12 @@ private void testRollingFileAppender(final String configResource) throws Excepti final Appender appender = configuration.getAppender("RFA"); assertNotNull(appender); assertEquals("RFA", appender.getName()); - assertTrue(appender instanceof RollingFileAppender, appender.getClass().getName()); + assertInstanceOf( + RollingFileAppender.class, appender, appender.getClass().getName()); final RollingFileAppender rfa = (RollingFileAppender) appender; - assertTrue( - rfa.getManager().getRolloverStrategy() instanceof DefaultRolloverStrategy, "defaultRolloverStrategy"); + assertInstanceOf( + DefaultRolloverStrategy.class, rfa.getManager().getRolloverStrategy(), "defaultRolloverStrategy"); assertFalse(((DefaultRolloverStrategy) rfa.getManager().getRolloverStrategy()).isUseMax(), "rolloverStrategy"); assertFalse(getAppendProperty(rfa), "append"); assertEquals(1000, rfa.getManager().getBufferSize(), "bufferSize"); @@ -205,19 +207,21 @@ private void testRollingFileAppender(final String configResource) throws Excepti assertEquals("target/hadoop.log.%i", rfa.getFilePattern()); final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy(); assertNotNull(triggeringPolicy); - assertTrue( - triggeringPolicy instanceof CompositeTriggeringPolicy, + assertInstanceOf( + CompositeTriggeringPolicy.class, + triggeringPolicy, triggeringPolicy.getClass().getName()); final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy; final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies(); assertEquals(1, triggeringPolicies.length); final TriggeringPolicy tp = triggeringPolicies[0]; - assertTrue(tp instanceof SizeBasedTriggeringPolicy, tp.getClass().getName()); + assertInstanceOf(SizeBasedTriggeringPolicy.class, tp, tp.getClass().getName()); final SizeBasedTriggeringPolicy sbtp = (SizeBasedTriggeringPolicy) tp; assertEquals(256 * 1024 * 1024, sbtp.getMaxFileSize()); final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy(); - assertTrue( - rolloverStrategy instanceof DefaultRolloverStrategy, + assertInstanceOf( + DefaultRolloverStrategy.class, + rolloverStrategy, rolloverStrategy.getClass().getName()); final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy; assertEquals(20, drs.getMaxIndex()); @@ -231,8 +235,8 @@ private void testDailyRollingFileAppender(final String configResource) throws Ex final Appender appender = configuration.getAppender("DRFA"); assertNotNull(appender); assertEquals("DRFA", appender.getName()); - assertTrue( - appender instanceof RollingFileAppender, appender.getClass().getName()); + assertInstanceOf( + RollingFileAppender.class, appender, appender.getClass().getName()); final RollingFileAppender rfa = (RollingFileAppender) appender; assertFalse(getAppendProperty(rfa), "append"); assertEquals(1000, rfa.getManager().getBufferSize(), "bufferSize"); @@ -241,19 +245,21 @@ private void testDailyRollingFileAppender(final String configResource) throws Ex assertEquals("target/hadoop.log%d{.dd-MM-yyyy}", rfa.getFilePattern()); final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy(); assertNotNull(triggeringPolicy); - assertTrue( - triggeringPolicy instanceof CompositeTriggeringPolicy, + assertInstanceOf( + CompositeTriggeringPolicy.class, + triggeringPolicy, triggeringPolicy.getClass().getName()); final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy; final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies(); assertEquals(1, triggeringPolicies.length); final TriggeringPolicy tp = triggeringPolicies[0]; - assertTrue(tp instanceof TimeBasedTriggeringPolicy, tp.getClass().getName()); + assertInstanceOf(TimeBasedTriggeringPolicy.class, tp, tp.getClass().getName()); final TimeBasedTriggeringPolicy tbtp = (TimeBasedTriggeringPolicy) tp; assertEquals(1, tbtp.getInterval()); final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy(); - assertTrue( - rolloverStrategy instanceof DefaultRolloverStrategy, + assertInstanceOf( + DefaultRolloverStrategy.class, + rolloverStrategy, rolloverStrategy.getClass().getName()); final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy; assertEquals(Integer.MAX_VALUE, drs.getMaxIndex()); @@ -280,40 +286,40 @@ private Layout testFile() throws Exception { return appender.getLayout(); } - public void testConsoleEnhancedPatternLayout() throws Exception { + void testConsoleEnhancedPatternLayout() throws Exception { final PatternLayout layout = (PatternLayout) testConsole("config-1.2/log4j-console-EnhancedPatternLayout"); // %p, %X and %x converted to their Log4j 1.x bridge equivalent assertEquals("%d{ISO8601} [%t][%c] %-5v1Level %properties %ndc: %m%n", layout.getConversionPattern()); } - public void testConsoleHtmlLayout() throws Exception { + void testConsoleHtmlLayout() throws Exception { final HtmlLayout layout = (HtmlLayout) testConsole("config-1.2/log4j-console-HtmlLayout"); assertEquals("Headline", layout.getTitle()); assertTrue(layout.isLocationInfo()); } - public void testConsolePatternLayout() throws Exception { + void testConsolePatternLayout() throws Exception { final PatternLayout layout = (PatternLayout) testConsole("config-1.2/log4j-console-PatternLayout"); // %p converted to its Log4j 1.x bridge equivalent assertEquals("%d{ISO8601} [%t][%c] %-5v1Level: %m%n", layout.getConversionPattern()); } - public void testConsoleSimpleLayout() throws Exception { + void testConsoleSimpleLayout() throws Exception { final PatternLayout layout = (PatternLayout) testConsole("config-1.2/log4j-console-SimpleLayout"); assertEquals("%v1Level - %m%n", layout.getConversionPattern()); } - public void testFileSimpleLayout() throws Exception { + void testFileSimpleLayout() throws Exception { final PatternLayout layout = (PatternLayout) testFile(); assertEquals("%v1Level - %m%n", layout.getConversionPattern()); } - public void testNullAppender() throws Exception { + void testNullAppender() throws Exception { final Configuration configuration = getConfiguration("config-1.2/log4j-NullAppender"); final Appender appender = configuration.getAppender("NullAppender"); assertNotNull(appender); assertEquals("NullAppender", appender.getName()); - assertTrue(appender instanceof NullAppender, appender.getClass().getName()); + assertInstanceOf(NullAppender.class, appender, appender.getClass().getName()); } private boolean getFollowProperty(final ConsoleAppender consoleAppender) throws Exception { @@ -362,7 +368,7 @@ private Layout testLayout(final Configuration config, final String appenderNa /** * Test if the default values from Log4j 1.x are respected. */ - public void testDefaultValues() throws Exception { + void testDefaultValues() throws Exception { final Configuration config = getConfiguration("config-1.2/log4j-defaultValues"); // HtmlLayout final HtmlLayout htmlLayout = (HtmlLayout) testLayout(config, "HTMLLayout"); @@ -394,7 +400,7 @@ public void testDefaultValues() throws Exception { assertEquals( "target/dailyRollingFileAppender%d{.yyyy-MM-dd}", dailyRollingFileAppender.getFilePattern(), "equivalent file pattern"); - assertEquals(true, getAppendProperty(dailyRollingFileAppender), "append"); + assertTrue(getAppendProperty(dailyRollingFileAppender), "append"); assertEquals(8192, dailyRollingFileAppender.getManager().getBufferSize(), "bufferSize"); assertTrue(dailyRollingFileAppender.getImmediateFlush(), "immediateFlush"); // FileAppender @@ -472,7 +478,7 @@ private int checkFilters(final org.apache.log4j.spi.Filter filter) { return count; } - public void testMultipleFilters() throws Exception { + void testMultipleFilters() throws Exception { System.setProperty("test.tmpDir", tempDir.getCanonicalPath()); try (final LoggerContext loggerContext = configure("log4j-multipleFilters")) { @@ -500,7 +506,7 @@ public void testMultipleFilters() throws Exception { final ListAppender legacyAppender = (ListAppender) ((Adapter) appender).getAppender(); final org.apache.logging.log4j.core.test.appender.ListAppender nativeAppender = configuration.getAppender("LIST2"); - assertEquals(3, checkFilters(((Filterable) nativeAppender).getFilter())); + assertEquals(3, checkFilters(nativeAppender.getFilter())); final Logger logger = LogManager.getLogger(PropertiesConfigurationTest.class); int expected = 0; @@ -531,11 +537,11 @@ public void testMultipleFilters() throws Exception { } } - public void testGlobalThreshold() throws Exception { + void testGlobalThreshold() throws Exception { try (final LoggerContext ctx = configure("config-1.2/log4j-global-threshold")) { final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); - assertTrue(filter instanceof ThresholdFilter); + assertInstanceOf(ThresholdFilter.class, filter); final ThresholdFilter thresholdFilter = (ThresholdFilter) filter; assertEquals(Level.INFO, thresholdFilter.getLevel()); assertEquals(Filter.Result.NEUTRAL, thresholdFilter.getOnMatch()); @@ -565,7 +571,7 @@ protected void testEnhancedRollingFileAppender(final Configuration configuration DefaultRolloverStrategy defaultRolloverStrategy; // Time policy with default attributes appender = configuration.getAppender("DEFAULT_TIME"); - assertTrue(appender instanceof RollingFileAppender, "is RollingFileAppender"); + assertInstanceOf(RollingFileAppender.class, appender, "is RollingFileAppender"); final RollingFileAppender defaultTime = (RollingFileAppender) appender; assertTrue(defaultTime.getManager().isAppend(), "append"); assertEquals(8192, defaultTime.getManager().getBufferSize(), "bufferSize"); @@ -575,10 +581,10 @@ protected void testEnhancedRollingFileAppender(final Configuration configuration "target/EnhancedRollingFileAppender/defaultTime.%d{yyyy-MM-dd}.log", defaultTime.getFilePattern(), "filePattern"); policy = defaultTime.getTriggeringPolicy(); - assertTrue(policy instanceof TimeBasedTriggeringPolicy, "is TimeBasedTriggeringPolicy"); + assertInstanceOf(TimeBasedTriggeringPolicy.class, policy, "is TimeBasedTriggeringPolicy"); // Size policy with default attributes appender = configuration.getAppender("DEFAULT_SIZE"); - assertTrue(appender instanceof RollingFileAppender, "is RollingFileAppender"); + assertInstanceOf(RollingFileAppender.class, appender, "is RollingFileAppender"); final RollingFileAppender defaultSize = (RollingFileAppender) appender; assertTrue(defaultSize.getManager().isAppend(), "append"); assertEquals(8192, defaultSize.getManager().getBufferSize(), "bufferSize"); @@ -587,16 +593,16 @@ protected void testEnhancedRollingFileAppender(final Configuration configuration assertEquals( "target/EnhancedRollingFileAppender/defaultSize.%i.log", defaultSize.getFilePattern(), "filePattern"); policy = defaultSize.getTriggeringPolicy(); - assertTrue(policy instanceof SizeBasedTriggeringPolicy, "is SizeBasedTriggeringPolicy"); + assertInstanceOf(SizeBasedTriggeringPolicy.class, policy, "is SizeBasedTriggeringPolicy"); assertEquals(10 * 1024 * 1024L, ((SizeBasedTriggeringPolicy) policy).getMaxFileSize()); strategy = defaultSize.getManager().getRolloverStrategy(); - assertTrue(strategy instanceof DefaultRolloverStrategy, "is DefaultRolloverStrategy"); + assertInstanceOf(DefaultRolloverStrategy.class, strategy, "is DefaultRolloverStrategy"); defaultRolloverStrategy = (DefaultRolloverStrategy) strategy; assertEquals(1, defaultRolloverStrategy.getMinIndex()); assertEquals(7, defaultRolloverStrategy.getMaxIndex()); // Time policy with custom attributes appender = configuration.getAppender("TIME"); - assertTrue(appender instanceof RollingFileAppender, "is RollingFileAppender"); + assertInstanceOf(RollingFileAppender.class, appender, "is RollingFileAppender"); final RollingFileAppender time = (RollingFileAppender) appender; assertFalse(time.getManager().isAppend(), "append"); assertEquals(1000, time.getManager().getBufferSize(), "bufferSize"); @@ -605,10 +611,10 @@ protected void testEnhancedRollingFileAppender(final Configuration configuration assertEquals( "target/EnhancedRollingFileAppender/time.%d{yyyy-MM-dd}.log", time.getFilePattern(), "filePattern"); policy = time.getTriggeringPolicy(); - assertTrue(policy instanceof TimeBasedTriggeringPolicy, "is TimeBasedTriggeringPolicy"); + assertInstanceOf(TimeBasedTriggeringPolicy.class, policy, "is TimeBasedTriggeringPolicy"); // Size policy with custom attributes appender = configuration.getAppender("SIZE"); - assertTrue(appender instanceof RollingFileAppender, "is RollingFileAppender"); + assertInstanceOf(RollingFileAppender.class, appender, "is RollingFileAppender"); final RollingFileAppender size = (RollingFileAppender) appender; assertFalse(size.getManager().isAppend(), "append"); assertEquals(1000, size.getManager().getBufferSize(), "bufferSize"); @@ -616,10 +622,10 @@ protected void testEnhancedRollingFileAppender(final Configuration configuration assertEquals("target/EnhancedRollingFileAppender/size.log", size.getFileName(), "fileName"); assertEquals("target/EnhancedRollingFileAppender/size.%i.log", size.getFilePattern(), "filePattern"); policy = size.getTriggeringPolicy(); - assertTrue(policy instanceof SizeBasedTriggeringPolicy, "is SizeBasedTriggeringPolicy"); + assertInstanceOf(SizeBasedTriggeringPolicy.class, policy, "is SizeBasedTriggeringPolicy"); assertEquals(10_000_000L, ((SizeBasedTriggeringPolicy) policy).getMaxFileSize()); strategy = size.getManager().getRolloverStrategy(); - assertTrue(strategy instanceof DefaultRolloverStrategy, "is DefaultRolloverStrategy"); + assertInstanceOf(DefaultRolloverStrategy.class, strategy, "is DefaultRolloverStrategy"); defaultRolloverStrategy = (DefaultRolloverStrategy) strategy; assertEquals(11, defaultRolloverStrategy.getMinIndex()); assertEquals(20, defaultRolloverStrategy.getMaxIndex()); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AsyncAppenderTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AsyncAppenderTest.java index 93b9a5d4d4d..b74c3365ae7 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AsyncAppenderTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AsyncAppenderTest.java @@ -37,7 +37,7 @@ * Test configuration from XML. */ @UsingStatusListener -public class AsyncAppenderTest { +class AsyncAppenderTest { private static long DEFAULT_TIMEOUT_MS = 500; @@ -51,7 +51,7 @@ static Stream testAsyncAppender() { @ParameterizedTest @MethodSource - public void testAsyncAppender(final String configLocation) throws Exception { + void testAsyncAppender(final String configLocation) throws Exception { try (final LoggerContext loggerContext = TestConfigurator.configure(configLocation)) { final Logger logger = LogManager.getLogger("test"); logger.debug("This is a test of the root logger"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AutoConfigTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AutoConfigTest.java index 12419de4796..be551f3d8cd 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/AutoConfigTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/AutoConfigTest.java @@ -36,15 +36,15 @@ /** * Test configuration from XML. */ -public class AutoConfigTest { +class AutoConfigTest { @BeforeAll - public static void beforeAll() { + static void beforeAll() { System.setProperty(ConfigurationFactory.LOG4J1_EXPERIMENTAL, "true"); } @Test - public void testListAppender() { + void testListAppender() { final Logger logger = LogManager.getLogger("test"); logger.debug("This is a test of the root logger"); final LoggerContext loggerContext = org.apache.logging.log4j.LogManager.getContext(false); @@ -63,8 +63,8 @@ public void testListAppender() { assertNotNull(eventAppender, "No Event Appender"); assertNotNull(messageAppender, "No Message Appender"); final List events = eventAppender.getEvents(); - assertTrue(events != null && events.size() > 0, "No events"); + assertTrue(events != null && !events.isEmpty(), "No events"); final List messages = messageAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages"); + assertTrue(messages != null && !messages.isEmpty(), "No messages"); } } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/Log4j1ConfigurationFactoryTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/Log4j1ConfigurationFactoryTest.java index 12b9e907209..6636544668f 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/Log4j1ConfigurationFactoryTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/Log4j1ConfigurationFactoryTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -39,7 +40,7 @@ import org.apache.logging.log4j.core.layout.PatternLayout; import org.junit.jupiter.api.Test; -public class Log4j1ConfigurationFactoryTest extends AbstractLog4j1ConfigurationTest { +class Log4j1ConfigurationFactoryTest extends AbstractLog4j1ConfigurationTest { private static final String SUFFIX = ".properties"; @@ -71,35 +72,35 @@ private Layout testConsole(final String configResource) throws Exception { @Override @Test - public void testConsoleEnhancedPatternLayout() throws Exception { + void testConsoleEnhancedPatternLayout() throws Exception { super.testConsoleEnhancedPatternLayout(); } @Override @Test - public void testConsoleHtmlLayout() throws Exception { + void testConsoleHtmlLayout() throws Exception { super.testConsoleHtmlLayout(); } @Test - public void testConsolePatternLayout() throws Exception { + void testConsolePatternLayout() throws Exception { super.testConsolePatternLayout(); } @Override @Test - public void testConsoleSimpleLayout() throws Exception { + void testConsoleSimpleLayout() throws Exception { super.testConsoleSimpleLayout(); } @Override @Test - public void testConsoleTtccLayout() throws Exception { + void testConsoleTtccLayout() throws Exception { super.testConsoleTtccLayout(); } @Test - public void testConsoleXmlLayout() throws Exception { + void testConsoleXmlLayout() throws Exception { final Log4j1XmlLayout layout = (Log4j1XmlLayout) testConsole("config-1.2/log4j-console-XmlLayout"); assertTrue(layout.isLocationInfo()); assertFalse(layout.isProperties()); @@ -107,67 +108,67 @@ public void testConsoleXmlLayout() throws Exception { @Override @Test - public void testFileSimpleLayout() throws Exception { + void testFileSimpleLayout() throws Exception { super.testFileSimpleLayout(); } @Override @Test - public void testNullAppender() throws Exception { + void testNullAppender() throws Exception { super.testNullAppender(); } @Override @Test - public void testRollingFileAppender() throws Exception { + void testRollingFileAppender() throws Exception { super.testRollingFileAppender(); } @Override @Test - public void testDailyRollingFileAppender() throws Exception { + void testDailyRollingFileAppender() throws Exception { super.testDailyRollingFileAppender(); } @Test - public void testRollingFileAppenderWithProperties() throws Exception { + void testRollingFileAppenderWithProperties() throws Exception { super.testRollingFileAppenderWithProperties(); } @Override @Test - public void testSystemProperties1() throws Exception { + void testSystemProperties1() throws Exception { super.testSystemProperties1(); } @Override @Test - public void testSystemProperties2() throws Exception { + void testSystemProperties2() throws Exception { super.testSystemProperties2(); } @Override @Test - public void testConsoleCapitalization() throws Exception { + void testConsoleCapitalization() throws Exception { super.testConsoleCapitalization(); } @Override @Test - public void testDefaultValues() throws Exception { + void testDefaultValues() throws Exception { super.testDefaultValues(); } @Test - public void testUntrimmedValues() throws Exception { + void testUntrimmedValues() throws Exception { try { final Configuration config = getConfiguration("config-1.2/log4j-untrimmed"); final LoggerConfig rootLogger = config.getRootLogger(); assertEquals(Level.DEBUG, rootLogger.getLevel()); final Appender appender = config.getAppender("Console"); - assertTrue(appender instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, appender); final Layout layout = appender.getLayout(); - assertTrue(layout instanceof PatternLayout); + assertInstanceOf(PatternLayout.class, layout); assertEquals("%v1Level - %m%n", ((PatternLayout) layout).getConversionPattern()); // No filter support config.start(); @@ -178,11 +179,11 @@ public void testUntrimmedValues() throws Exception { } @Test - public void testGlobalThreshold() throws Exception { + void testGlobalThreshold() throws Exception { try (final LoggerContext ctx = configure("config-1.2/log4j-global-threshold")) { final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); - assertTrue(filter instanceof ThresholdFilter); + assertInstanceOf(ThresholdFilter.class, filter); final ThresholdFilter thresholdFilter = (ThresholdFilter) filter; assertEquals(Level.INFO, thresholdFilter.getLevel()); assertEquals(Filter.Result.NEUTRAL, thresholdFilter.getOnMatch()); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/MapRewriteAppenderTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/MapRewriteAppenderTest.java index ef95d1633cf..bcae05d6bee 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/MapRewriteAppenderTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/MapRewriteAppenderTest.java @@ -40,21 +40,21 @@ /** * Test RewriteAppender */ -public class MapRewriteAppenderTest { +class MapRewriteAppenderTest { @BeforeAll - public static void beforeAll() { + static void beforeAll() { System.setProperty( ConfigurationFactory.LOG4J1_CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j1-mapRewrite.xml"); } @AfterEach - public void after() { + void after() { ThreadContext.clearMap(); } @Test - public void testRewrite() { + void testRewrite() { final Logger logger = LogManager.getLogger("test"); final Map map = new HashMap<>(); map.put("message", "This is a test"); @@ -71,7 +71,7 @@ public void testRewrite() { } assertNotNull(eventAppender, "No Event Appender"); final List events = eventAppender.getEvents(); - assertTrue(events != null && events.size() > 0, "No events"); + assertTrue(events != null && !events.isEmpty(), "No events"); assertNotNull(events.get(0).getProperties(), "No properties in the event"); assertTrue(events.get(0).getProperties().containsKey("hello"), "Key was not inserted"); assertEquals("world", events.get(0).getProperties().get("hello"), "Key value is incorrect"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationFactoryTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationFactoryTest.java index 0cc7f5ae7e6..7b14885786d 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationFactoryTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationFactoryTest.java @@ -28,17 +28,17 @@ /** * Test configuration from Properties. */ -public class PropertiesConfigurationFactoryTest { +class PropertiesConfigurationFactoryTest { @BeforeAll - public static void beforeAll() { + static void beforeAll() { System.setProperty( ConfigurationFactory.LOG4J1_CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j1-file-1.properties"); } @Test - public void testProperties() { + void testProperties() { final Logger logger = LogManager.getLogger("test"); logger.debug("This is a test of the root logger"); File file = new File("target/temp.A1"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationTest.java index 93ff778154a..fb8ed815671 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesConfigurationTest.java @@ -17,6 +17,7 @@ package org.apache.log4j.config; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -25,7 +26,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.Serializable; -import java.net.URISyntaxException; import java.util.List; import java.util.Map; import org.apache.log4j.ListAppender; @@ -55,13 +55,13 @@ /** * Test configuration from Properties. */ -public class PropertiesConfigurationTest extends AbstractLog4j1ConfigurationTest { +class PropertiesConfigurationTest extends AbstractLog4j1ConfigurationTest { private static final String TEST_KEY = "log4j.test.tmpdir"; private static final String SUFFIX = ".properties"; @Override - Configuration getConfiguration(final String configResourcePrefix) throws URISyntaxException, IOException { + Configuration getConfiguration(final String configResourcePrefix) throws IOException { final String configResource = configResourcePrefix + SUFFIX; final InputStream inputStream = getResourceAsStream(configResource); final ConfigurationSource source = new ConfigurationSource(inputStream); @@ -73,7 +73,7 @@ Configuration getConfiguration(final String configResourcePrefix) throws URISynt } @Test - public void testConfigureNullPointerException() throws Exception { + void testConfigureNullPointerException() throws Exception { try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/LOG4J2-3247.properties")) { // [LOG4J2-3247] configure() should not throw an NPE. @@ -85,7 +85,7 @@ public void testConfigureNullPointerException() throws Exception { } @Test - public void testConsoleAppenderFilter() throws Exception { + void testConsoleAppenderFilter() throws Exception { try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/LOG4J2-3247.properties")) { // LOG4J2-3281 PropertiesConfiguration.buildAppender not adding filters to appender @@ -96,12 +96,12 @@ public void testConsoleAppenderFilter() throws Exception { final Filterable filterable = (Filterable) appender; final FilterAdapter filter = (FilterAdapter) filterable.getFilter(); assertNotNull(filter); - assertTrue(filter.getFilter() instanceof NeutralFilterFixture); + assertInstanceOf(NeutralFilterFixture.class, filter.getFilter()); } } @Test - public void testCustomAppenderFilter() throws Exception { + void testCustomAppenderFilter() throws Exception { try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/LOG4J2-3281.properties")) { // LOG4J2-3281 PropertiesConfiguration.buildAppender not adding filters to appender @@ -112,12 +112,12 @@ public void testCustomAppenderFilter() throws Exception { final Filterable filterable = (Filterable) appender; final FilterAdapter filter = (FilterAdapter) filterable.getFilter(); assertNotNull(filter); - assertTrue(filter.getFilter() instanceof NeutralFilterFixture); + assertInstanceOf(NeutralFilterFixture.class, filter.getFilter()); } } @Test - public void testConsoleAppenderLevelRangeFilter() throws Exception { + void testConsoleAppenderLevelRangeFilter() throws Exception { PluginManager.addPackage("org.apache.log4j.builders.filter"); try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/LOG4J2-3326.properties")) { @@ -164,7 +164,7 @@ public void testConsoleAppenderLevelRangeFilter() throws Exception { } @Test - public void testConfigureAppenderDoesNotExist() throws Exception { + void testConfigureAppenderDoesNotExist() throws Exception { // Verify that we tolerate a logger which specifies an appender that does not exist. try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/LOG4J2-3407.properties")) { @@ -174,7 +174,7 @@ public void testConfigureAppenderDoesNotExist() throws Exception { } @Test - public void testListAppender() throws Exception { + void testListAppender() throws Exception { try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/log4j1-list.properties")) { final Logger logger = LogManager.getLogger("test"); @@ -193,14 +193,14 @@ public void testListAppender() throws Exception { assertNotNull(eventAppender, "No Event Appender"); assertNotNull(messageAppender, "No Message Appender"); final List events = eventAppender.getEvents(); - assertTrue(events != null && events.size() > 0, "No events"); + assertTrue(events != null && !events.isEmpty(), "No events"); final List messages = messageAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages"); + assertTrue(messages != null && !messages.isEmpty(), "No messages"); } } @Test - public void testProperties() throws Exception { + void testProperties() throws Exception { try (final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/log4j1-file-1.properties")) { final Logger logger = LogManager.getLogger("test"); @@ -215,7 +215,7 @@ public void testProperties() throws Exception { } @Test - public void testSystemProperties() throws Exception { + void testSystemProperties() throws Exception { final String testPathLocation = "target"; System.setProperty(TEST_KEY, testPathLocation); try (final LoggerContext loggerContext = @@ -226,7 +226,7 @@ public void testSystemProperties() throws Exception { final String name = "FILE_APPENDER"; final Appender appender = configuration.getAppender(name); assertNotNull(appender, name); - assertTrue(appender instanceof FileAppender, appender.getClass().getName()); + assertInstanceOf(FileAppender.class, appender, appender.getClass().getName()); final FileAppender fileAppender = (FileAppender) appender; // Two slashes because that's how the config file is setup. assertEquals(testPathLocation + "/hadoop.log", fileAppender.getFileName()); @@ -326,18 +326,18 @@ public void testMultipleFilters() throws Exception { } @Test - public void testUntrimmedValues() throws Exception { + void testUntrimmedValues() throws Exception { try { final Configuration config = getConfiguration("config-1.2/log4j-untrimmed"); final LoggerConfig rootLogger = config.getRootLogger(); assertEquals(Level.DEBUG, rootLogger.getLevel()); final Appender appender = config.getAppender("Console"); - assertTrue(appender instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, appender); final Layout layout = appender.getLayout(); - assertTrue(layout instanceof PatternLayout); + assertInstanceOf(PatternLayout.class, layout); assertEquals("%v1Level - %m%n", ((PatternLayout) layout).getConversionPattern()); final Filter filter = ((Filterable) appender).getFilter(); - assertTrue(filter instanceof DenyAllFilter); + assertInstanceOf(DenyAllFilter.class, filter); config.start(); config.stop(); } catch (NoClassDefFoundError e) { @@ -352,7 +352,7 @@ public void testGlobalThreshold() throws Exception { } @Test - public void testEnhancedRollingFileAppender() throws Exception { + void testEnhancedRollingFileAppender() throws Exception { try (final LoggerContext ctx = configure("config-1.2/log4j-EnhancedRollingFileAppender")) { final Configuration configuration = ctx.getConfiguration(); assertNotNull(configuration); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesReconfigurationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesReconfigurationTest.java index 9c5f852be79..dbdca87084c 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesReconfigurationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesReconfigurationTest.java @@ -48,7 +48,7 @@ /** * Test reconfiguring with an XML configuration. */ -public class PropertiesReconfigurationTest { +class PropertiesReconfigurationTest { private class TestListener implements ConfigurationListener { @@ -177,7 +177,7 @@ private T getAppenderFromContext(final Str * Tests that configuring and reconfiguring CUSTOM appenders properly pick up different settings. */ @Test - public void testCustomAppenders_TestConfigurator() throws IOException { + void testCustomAppenders_TestConfigurator() throws IOException { checkConfigureCustomAppenders(CONFIG_CUSTOM_APPENDERS_1, true, 1, "A", TestConfigurator::configure); checkConfigureCustomAppenders(CONFIG_CUSTOM_APPENDERS_2, false, 2, "B", TestConfigurator::configure); checkConfigureCustomAppenders(CONFIG_CUSTOM_APPENDERS_1, true, 1, "A", TestConfigurator::configure); @@ -188,7 +188,7 @@ public void testCustomAppenders_TestConfigurator() throws IOException { * Tests that configuring and reconfiguring CUSTOM appenders properly pick up different settings. */ @Test - public void testCustomAppenders_PropertyConfigurator() throws IOException { + void testCustomAppenders_PropertyConfigurator() throws IOException { checkConfigureCustomAppenders(CONFIG_CUSTOM_APPENDERS_1, true, 1, "A", PropertyConfigurator::configure); checkConfigureCustomAppenders(CONFIG_CUSTOM_APPENDERS_2, false, 2, "B", PropertyConfigurator::configure); checkConfigureCustomAppenders(CONFIG_CUSTOM_APPENDERS_1, true, 1, "A", PropertyConfigurator::configure); @@ -199,7 +199,7 @@ public void testCustomAppenders_PropertyConfigurator() throws IOException { * Tests that configuring and reconfiguring STOCK file appenders properly pick up different settings. */ @Test - public void testFileAppenders() throws Exception { + void testFileAppenders() throws Exception { checkConfigureFileAppender(CONFIG_FILE_APPENDER_1, false); checkConfigureFileAppender(CONFIG_FILE_APPENDER_2, true); checkConfigureFileAppender(CONFIG_FILE_APPENDER_1, false); @@ -207,7 +207,7 @@ public void testFileAppenders() throws Exception { } @Test - public void testTestListener() throws Exception { + void testTestListener() throws Exception { System.setProperty(Log4j1Configuration.MONITOR_INTERVAL, "1"); final File file = new File(CONFIG_FILE_APPENDER_1); assertTrue(file.exists(), "No Config file"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesRollingWithPropertiesTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesRollingWithPropertiesTest.java index c136a6dcc0f..ea740d93d4f 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesRollingWithPropertiesTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/PropertiesRollingWithPropertiesTest.java @@ -29,19 +29,19 @@ /** * Test configuration from Properties. */ -public class PropertiesRollingWithPropertiesTest { +class PropertiesRollingWithPropertiesTest { private static final String TEST_DIR = "target/" + PropertiesRollingWithPropertiesTest.class.getSimpleName(); @BeforeAll - public static void setupSystemProperties() { + static void setupSystemProperties() { // Set system properties as a replacement for SystemPropertyTestRule System.setProperty("test.directory", TEST_DIR); System.setProperty("log4j.configuration", "target/test-classes/log4j1-rolling-properties.properties"); } @Test - public void testProperties() throws Exception { + void testProperties() throws Exception { final Path path = Paths.get(TEST_DIR, "somefile.log"); Files.deleteIfExists(path); final Logger logger = LogManager.getLogger("test"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/RewriteAppenderTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/RewriteAppenderTest.java index ac68e6ce9fc..86af9aea741 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/RewriteAppenderTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/RewriteAppenderTest.java @@ -39,21 +39,21 @@ /** * Test RewriteAppender */ -public class RewriteAppenderTest { +class RewriteAppenderTest { @BeforeAll - public static void beforeAll() { + static void beforeAll() { System.setProperty( ConfigurationFactory.LOG4J1_CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j1-rewrite.xml"); } @AfterEach - public void after() { + void after() { ThreadContext.clearMap(); } @Test - public void testRewrite() { + void testRewrite() { final Logger logger = LogManager.getLogger("test"); ThreadContext.put("key1", "This is a test"); ThreadContext.put("hello", "world"); @@ -70,7 +70,7 @@ public void testRewrite() { } assertNotNull(eventAppender, "No Event Appender"); final List events = eventAppender.getEvents(); - assertTrue(events != null && events.size() > 0, "No events"); + assertTrue(events != null && !events.isEmpty(), "No events"); assertNotNull(events.get(0).getProperties(), "No properties in the event"); assertTrue(events.get(0).getProperties().containsKey("key2"), "Key was not inserted"); assertEquals("Log4j", events.get(0).getProperties().get("key2"), "Key value is incorrect"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/SocketAppenderConfigurationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/SocketAppenderConfigurationTest.java index d58479cd82f..2294c556d18 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/SocketAppenderConfigurationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/SocketAppenderConfigurationTest.java @@ -17,6 +17,7 @@ package org.apache.log4j.config; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -35,7 +36,7 @@ /** * Tests configuring a Syslog appender. */ -public class SocketAppenderConfigurationTest { +class SocketAppenderConfigurationTest { private SocketAppender check(final Protocol expected, final Configuration configuration) { final Map appenders = configuration.getAppenders(); @@ -71,19 +72,19 @@ private SocketAppender checkProtocolXmlConfig(final Protocol expected, final Str } @Test - public void testProperties() throws Exception { + void testProperties() throws Exception { checkProtocolXmlConfig(Protocol.TCP, "target/test-classes/log4j1-socket.properties"); } @Test - public void testPropertiesXmlLayout() throws Exception { + void testPropertiesXmlLayout() throws Exception { final SocketAppender socketAppender = checkProtocolXmlConfig(Protocol.TCP, "target/test-classes/log4j1-socket-xml-layout.properties"); - assertTrue(socketAppender.getLayout() instanceof Log4j1XmlLayout); + assertInstanceOf(Log4j1XmlLayout.class, socketAppender.getLayout()); } @Test - public void testXml() throws Exception { + void testXml() throws Exception { checkProtocolXmlConfig(Protocol.TCP, "target/test-classes/log4j1-socket.xml"); } } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderConfigurationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderConfigurationTest.java index 8d077ae6883..1313cee2c44 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderConfigurationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderConfigurationTest.java @@ -41,7 +41,7 @@ */ @UsingStatusListener @WritesSystemProperty -public class SyslogAppenderConfigurationTest { +class SyslogAppenderConfigurationTest { private static ServerSocket tcpSocket; @@ -89,32 +89,32 @@ private void checkProtocolXmlConfig(final Protocol expected, final String xmlPat } @Test - public void testPropertiesProtocolDefault() throws Exception { + void testPropertiesProtocolDefault() throws Exception { checkProtocolPropertiesConfig(Protocol.TCP, "target/test-classes/log4j1-syslog-protocol-default.properties"); } @Test - public void testPropertiesProtocolTcp() throws Exception { + void testPropertiesProtocolTcp() throws Exception { checkProtocolPropertiesConfig(Protocol.TCP, "target/test-classes/log4j1-syslog-protocol-tcp.properties"); } @Test - public void testPropertiesProtocolUdp() throws Exception { + void testPropertiesProtocolUdp() throws Exception { checkProtocolPropertiesConfig(Protocol.UDP, "target/test-classes/log4j1-syslog-protocol-udp.properties"); } @Test - public void testXmlProtocolDefault() throws Exception { + void testXmlProtocolDefault() throws Exception { checkProtocolXmlConfig(Protocol.TCP, "target/test-classes/log4j1-syslog.xml"); } @Test - public void testXmlProtocolTcp() throws Exception { + void testXmlProtocolTcp() throws Exception { checkProtocolXmlConfig(Protocol.TCP, "target/test-classes/log4j1-syslog-protocol-tcp.xml"); } @Test - public void testXmlProtocolUdp() throws Exception { + void testXmlProtocolUdp() throws Exception { checkProtocolXmlConfig(Protocol.UDP, "target/test-classes/log4j1-syslog-protocol-udp.xml"); } } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderTest.java index 66be7c89ab7..720577bc86e 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderTest.java @@ -30,12 +30,12 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class SyslogAppenderTest { +class SyslogAppenderTest { private static MockSyslogServer syslogServer; @BeforeAll - public static void beforeAll() throws IOException { + static void beforeAll() throws IOException { initTCPTestEnvironment(null); System.setProperty("syslog.port", Integer.toString(syslogServer.getLocalPort())); System.setProperty( @@ -43,20 +43,20 @@ public static void beforeAll() throws IOException { } @AfterAll - public static void afterAll() { + static void afterAll() { System.clearProperty(ConfigurationFactory.LOG4J1_CONFIGURATION_FILE_PROPERTY); syslogServer.shutdown(); } @Test - public void sendMessage() throws Exception { + void sendMessage() throws Exception { final Logger logger = LogManager.getLogger(SyslogAppenderTest.class); logger.info("This is a test"); List messages = null; for (int i = 0; i < 5; ++i) { Thread.sleep(250); messages = syslogServer.getMessageList(); - if (messages != null && messages.size() > 0) { + if (messages != null && !messages.isEmpty()) { break; } } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationFactoryTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationFactoryTest.java index 408d3bb4b32..e28121da899 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationFactoryTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationFactoryTest.java @@ -28,16 +28,16 @@ /** * Test configuration from XML. */ -public class XmlConfigurationFactoryTest { +class XmlConfigurationFactoryTest { @BeforeAll - public static void beforeAll() { + static void beforeAll() { System.setProperty( ConfigurationFactory.LOG4J1_CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j1-file.xml"); } @Test - public void testXML() { + void testXML() { final Logger logger = LogManager.getLogger("test"); logger.debug("This is a test of the root logger"); File file = new File("target/temp.A1"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationTest.java index 5990021923a..95a260ed862 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlConfigurationTest.java @@ -17,13 +17,13 @@ package org.apache.log4j.config; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.net.URISyntaxException; import java.util.List; import java.util.Map; import org.apache.log4j.ListAppender; @@ -46,12 +46,12 @@ /** * Test configuration from XML. */ -public class XmlConfigurationTest extends AbstractLog4j1ConfigurationTest { +class XmlConfigurationTest extends AbstractLog4j1ConfigurationTest { private static final String SUFFIX = ".xml"; @Override - Configuration getConfiguration(final String configResourcePrefix) throws URISyntaxException, IOException { + Configuration getConfiguration(final String configResourcePrefix) throws IOException { final String configResource = configResourcePrefix + SUFFIX; final InputStream inputStream = getResourceAsStream(configResource); final ConfigurationSource source = new ConfigurationSource(inputStream); @@ -63,7 +63,7 @@ Configuration getConfiguration(final String configResourcePrefix) throws URISynt } @Test - public void testListAppender() throws Exception { + void testListAppender() throws Exception { final LoggerContext loggerContext = TestConfigurator.configure("target/test-classes/log4j1-list.xml"); final Logger logger = LogManager.getLogger("test"); logger.debug("This is a test of the root logger"); @@ -81,13 +81,13 @@ public void testListAppender() throws Exception { assertNotNull(eventAppender, "No Event Appender"); assertNotNull(messageAppender, "No Message Appender"); final List events = eventAppender.getEvents(); - assertTrue(events != null && events.size() > 0, "No events"); + assertTrue(events != null && !events.isEmpty(), "No events"); final List messages = messageAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages"); + assertTrue(messages != null && !messages.isEmpty(), "No messages"); } @Test - public void testXML() throws Exception { + void testXML() throws Exception { TestConfigurator.configure("target/test-classes/log4j1-file.xml"); final Logger logger = LogManager.getLogger("test"); logger.debug("This is a test of the root logger"); @@ -184,20 +184,20 @@ public void testGlobalThreshold() throws Exception { } @Test - public void testEnhancedRollingFileAppender() throws Exception { + void testEnhancedRollingFileAppender() throws Exception { try (final LoggerContext ctx = configure("config-1.2/log4j-EnhancedRollingFileAppender")) { final Configuration configuration = ctx.getConfiguration(); assertNotNull(configuration); testEnhancedRollingFileAppender(configuration); // Only supported through XML configuration final Appender appender = configuration.getAppender("MIXED"); - assertTrue(appender instanceof RollingFileAppender, "is RollingFileAppender"); + assertInstanceOf(RollingFileAppender.class, appender, "is RollingFileAppender"); final TriggeringPolicy policy = ((RollingFileAppender) appender).getTriggeringPolicy(); - assertTrue(policy instanceof CompositeTriggeringPolicy, "is CompositeTriggeringPolicy"); + assertInstanceOf(CompositeTriggeringPolicy.class, policy, "is CompositeTriggeringPolicy"); final TriggeringPolicy[] policies = ((CompositeTriggeringPolicy) policy).getTriggeringPolicies(); assertEquals(2, policies.length); - assertTrue(policies[0] instanceof TimeBasedTriggeringPolicy, "is TimeBasedTriggeringPolicy"); - assertTrue(policies[1] instanceof SizeBasedTriggeringPolicy, "is SizeBasedTriggeringPolicy"); + assertInstanceOf(TimeBasedTriggeringPolicy.class, policies[0], "is TimeBasedTriggeringPolicy"); + assertInstanceOf(SizeBasedTriggeringPolicy.class, policies[1], "is SizeBasedTriggeringPolicy"); } } diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlReconfigurationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlReconfigurationTest.java index af91d40ae59..ee9dbfcdb9a 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlReconfigurationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlReconfigurationTest.java @@ -35,7 +35,7 @@ /** * Test reconfiguring with an XML configuration. */ -public class XmlReconfigurationTest { +class XmlReconfigurationTest { private static final String CONFIG = "target/test-classes/log4j1-file.xml"; private static final long FIVE_MINUTES = 5 * 60 * 1000; @@ -43,7 +43,7 @@ public class XmlReconfigurationTest { private final CountDownLatch toggle = new CountDownLatch(1); @Test - public void testReconfiguration() throws Exception { + void testReconfiguration() throws Exception { System.setProperty(Log4j1Configuration.MONITOR_INTERVAL, "1"); final File file = new File(CONFIG); assertNotNull(file, "No Config file"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlRollingWithPropertiesTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlRollingWithPropertiesTest.java index bd2e9a2b2ba..0847a3cc93e 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlRollingWithPropertiesTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/config/XmlRollingWithPropertiesTest.java @@ -29,18 +29,18 @@ /** * Test configuration from Properties. */ -public class XmlRollingWithPropertiesTest { +class XmlRollingWithPropertiesTest { private static final String TEST_DIR = "target/" + XmlRollingWithPropertiesTest.class.getSimpleName(); @BeforeAll - public static void setupSystemProperties() { + static void setupSystemProperties() { System.setProperty("test.directory", TEST_DIR); System.setProperty("log4j.configuration", "target/test-classes/log4j1-rolling-properties.xml"); } @Test - public void testProperties() throws Exception { + void testProperties() throws Exception { // ${test.directory}/logs/etl.log final Path path = Paths.get(TEST_DIR, "logs/etl.log"); Files.deleteIfExists(path); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/BoundedFIFOTestCase.java b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/BoundedFIFOTestCase.java index 38dc4573afc..d45b21448e0 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/BoundedFIFOTestCase.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/BoundedFIFOTestCase.java @@ -56,7 +56,7 @@ public BoundedFIFOTestCase(final String name) { } int min(final int a, final int b) { - return a < b ? a : b; + return Math.min(a, b); } @Override @@ -82,11 +82,11 @@ public void test1() { bf.put(e[j]); assertEquals(bf.length(), j < size ? j + 1 : size); } - final int max = size < j ? size : j; + final int max = Math.min(size, j); j--; for (k = 0; k <= j; k++) { // System.out.println("max="+max+", j="+j+", k="+k); - assertEquals(bf.length(), max - k > 0 ? max - k : 0); + assertEquals(bf.length(), Math.max(max - k, 0)); final Object r = bf.get(); // System.out.println("Got "+r); if (k >= size) { @@ -112,19 +112,19 @@ public void test2() { assertNull(bf.get()); bf.put(e[1]); - assertEquals(bf.length(), 1); + assertEquals(1, bf.length()); bf.put(e[2]); - assertEquals(bf.length(), 2); + assertEquals(2, bf.length()); bf.put(e[3]); - assertEquals(bf.length(), 3); + assertEquals(3, bf.length()); assertEquals(bf.get(), e[1]); - assertEquals(bf.length(), 2); + assertEquals(2, bf.length()); assertEquals(bf.get(), e[2]); - assertEquals(bf.length(), 1); + assertEquals(1, bf.length()); assertEquals(bf.get(), e[3]); - assertEquals(bf.length(), 0); + assertEquals(0, bf.length()); assertNull(bf.get()); - assertEquals(bf.length(), 0); + assertEquals(0, bf.length()); } /** diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/CyclicBufferTestCase.java b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/CyclicBufferTestCase.java index a2f19761b57..864e400e30a 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/CyclicBufferTestCase.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/CyclicBufferTestCase.java @@ -64,7 +64,7 @@ void doTest1(final int size) { for (int i = 0; i < MAX; i++) { cb.add(e[i]); - final int limit = i < size - 1 ? i : size - 1; + final int limit = Math.min(i, size - 1); // System.out.println("\nLimit is " + limit + ", i="+i); @@ -91,8 +91,8 @@ void doTestResize(final int initialSize, final int numberOfAdds, final int newSi offset = 0; } - int len = newSize < numberOfAdds ? newSize : numberOfAdds; - len = len < initialSize ? len : initialSize; + int len = Math.min(newSize, numberOfAdds); + len = Math.min(len, initialSize); // System.out.println("Len = "+len+", offset="+offset); for (int j = 0; j < len; j++) { assertEquals(cb.get(j), e[offset + j]); @@ -109,22 +109,22 @@ public void test0() { assertEquals(size, cb.getMaxSize()); cb.add(e[0]); - assertEquals(cb.length(), 1); + assertEquals(1, cb.length()); assertEquals(cb.get(), e[0]); - assertEquals(cb.length(), 0); + assertEquals(0, cb.length()); assertNull(cb.get()); - assertEquals(cb.length(), 0); + assertEquals(0, cb.length()); cb = new CyclicBuffer(size); cb.add(e[0]); cb.add(e[1]); - assertEquals(cb.length(), 2); + assertEquals(2, cb.length()); assertEquals(cb.get(), e[0]); - assertEquals(cb.length(), 1); + assertEquals(1, cb.length()); assertEquals(cb.get(), e[1]); - assertEquals(cb.length(), 0); + assertEquals(0, cb.length()); assertNull(cb.get()); - assertEquals(cb.length(), 0); + assertEquals(0, cb.length()); } /** diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/OptionConverterLevelTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/OptionConverterLevelTest.java index 65a1cb69c5d..2156540c111 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/OptionConverterLevelTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/OptionConverterLevelTest.java @@ -34,7 +34,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -public class OptionConverterLevelTest { +class OptionConverterLevelTest { static Stream standardLevels() { return Arrays.stream(StandardLevel.values()) @@ -47,7 +47,7 @@ static Stream standardLevels() { */ @ParameterizedTest @MethodSource("standardLevels") - public void testStandardLevelConversion(final Level log4j1Level, final org.apache.logging.log4j.Level log4j2Level) { + void testStandardLevelConversion(final Level log4j1Level, final org.apache.logging.log4j.Level log4j2Level) { assertThat(log4j2Level).isSameAs(OptionConverter.convertLevel(log4j1Level)); assertThat(log4j1Level).isSameAs(OptionConverter.convertLevel(log4j2Level)); assertThat(OptionConverter.toLevel(org.apache.logging.log4j.Level.class.getName(), log4j2Level.name(), null)) @@ -59,14 +59,13 @@ public void testStandardLevelConversion(final Level log4j1Level, final org.apach */ @ParameterizedTest @MethodSource("standardLevels") - public void testStandardIntLevelConversion( - final Level log4j1Level, final org.apache.logging.log4j.Level log4j2Level) { + void testStandardIntLevelConversion(final Level log4j1Level, final org.apache.logging.log4j.Level log4j2Level) { assertEquals(log4j2Level.intLevel(), toLog4j2Level(log4j1Level.toInt())); assertEquals(log4j1Level.toInt(), toLog4j1Level(log4j2Level.intLevel())); } @Test - public void testMaxMinCutoff() { + void testMaxMinCutoff() { // The cutoff values are transformed into ALL and OFF assertEquals(StandardLevel.ALL.intLevel(), toLog4j2Level(OptionConverter.MIN_CUTOFF_LEVEL)); assertEquals(StandardLevel.OFF.intLevel(), toLog4j2Level(OptionConverter.MAX_CUTOFF_LEVEL)); @@ -87,7 +86,7 @@ public void testMaxMinCutoff() { * correctly. */ @Test - public void testUsefulRange() { + void testUsefulRange() { for (int intLevel = StandardLevel.OFF.intLevel(); intLevel <= StandardLevel.TRACE.intLevel(); intLevel++) { assertEquals(intLevel, toLog4j2Level(toLog4j1Level(intLevel))); } @@ -101,7 +100,7 @@ public void testUsefulRange() { * used in {@link LogEventAdapter}. */ @Test - public void testCustomLog4j2Levels() { + void testCustomLog4j2Levels() { final int infoDebug = (StandardLevel.INFO.intLevel() + StandardLevel.DEBUG.intLevel()) / 2; final org.apache.logging.log4j.Level v2Level = org.apache.logging.log4j.Level.forName("INFO_DEBUG", infoDebug); final Level v1Level = diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/UtilLoggingLevelTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/UtilLoggingLevelTest.java index f9ee8c548c3..2e41de6b142 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/UtilLoggingLevelTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/helpers/UtilLoggingLevelTest.java @@ -20,6 +20,7 @@ import java.util.stream.Stream; import org.apache.log4j.Level; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -32,6 +33,7 @@ public class UtilLoggingLevelTest { /** * Test toLevel("fiNeSt"). */ + @Test public void testToLevelFINEST() { assertEquals(UtilLoggingLevel.FINEST, UtilLoggingLevel.toLevel("fiNeSt")); } @@ -43,7 +45,7 @@ static Stream namesAndLevels() { @ParameterizedTest @MethodSource("namesAndLevels") - public void testOptionConverterToLevel(final String name, final UtilLoggingLevel level) { + void testOptionConverterToLevel(final String name, final UtilLoggingLevel level) { assertEquals(level, OptionConverter.toLevel(name, Level.ALL), "get v1 level by name"); // Comparison of Log4j 2.x levels assertEquals(level.getVersion2Level(), org.apache.logging.log4j.Level.getLevel(name), "get v2 level by name"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1SyslogLayoutTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1SyslogLayoutTest.java index bb4f4428df2..b19382edd3a 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1SyslogLayoutTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1SyslogLayoutTest.java @@ -35,7 +35,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -public class Log4j1SyslogLayoutTest { +class Log4j1SyslogLayoutTest { private static final SimpleMessage MESSAGE = new SimpleMessage("Hello world!"); private static final long TIMESTAMP = LocalDateTime.of(2022, 4, 5, 12, 34, 56) @@ -68,7 +68,7 @@ static Stream configurations() { @ParameterizedTest @MethodSource("configurations") - public void testSimpleLayout( + void testSimpleLayout( final String expected, final Facility facility, final boolean header, final boolean facilityPrinting) { final LogEvent logEvent = createLogEvent(); StringLayout appenderLayout = Log4j1SyslogLayout.newBuilder() diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1XmlLayoutTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1XmlLayoutTest.java index 46d6bf4cbc7..1af12167a60 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1XmlLayoutTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/layout/Log4j1XmlLayoutTest.java @@ -27,10 +27,10 @@ import org.junit.jupiter.api.Test; @UsingThreadContextStack -public class Log4j1XmlLayoutTest { +class Log4j1XmlLayoutTest { @Test - public void testWithoutThrown() { + void testWithoutThrown() { final Log4j1XmlLayout layout = Log4j1XmlLayout.createLayout(false, true); final Log4jLogEvent event = Log4jLogEvent.newBuilder() @@ -51,7 +51,7 @@ public void testWithoutThrown() { } @Test - public void testWithPropertiesAndLocationInfo() { + void testWithPropertiesAndLocationInfo() { final Log4j1XmlLayout layout = Log4j1XmlLayout.createLayout(true, true); final StringMap contextMap = ContextDataFactory.createContextData(2); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/FormattingInfoTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/FormattingInfoTest.java index 529220966e3..291224674ea 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/FormattingInfoTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/FormattingInfoTest.java @@ -43,7 +43,7 @@ public void testConstructor() { assertNotNull(field); assertEquals(3, field.getMinLength()); assertEquals(6, field.getMaxLength()); - assertEquals(true, field.isLeftAligned()); + assertTrue(field.isLeftAligned()); } /** @@ -55,7 +55,7 @@ public void testGetDefault() { assertNotNull(field); assertEquals(0, field.getMinLength()); assertEquals(Integer.MAX_VALUE, field.getMaxLength()); - assertEquals(false, field.isLeftAligned()); + assertFalse(field.isLeftAligned()); } /** diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1LevelPatternConverterTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1LevelPatternConverterTest.java index 4170859d7fb..d6bcbb50fe2 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1LevelPatternConverterTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1LevelPatternConverterTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class Log4j1LevelPatternConverterTest { +class Log4j1LevelPatternConverterTest { /** * Tests if the converter returns the Log4j 1.x {@code toString()} value of @@ -35,7 +35,7 @@ public class Log4j1LevelPatternConverterTest { */ @ParameterizedTest @MethodSource("org.apache.log4j.helpers.UtilLoggingLevel#getAllPossibleLevels") - public void testUtilLoggingLevels(final Level level) { + void testUtilLoggingLevels(final Level level) { final Log4j1LevelPatternConverter converter = Log4j1LevelPatternConverter.newInstance(null); final LogEvent logEvent = mock(LogEvent.class); when(logEvent.getLevel()).thenReturn(level.getVersion2Level()); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1MdcPatternConverterTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1MdcPatternConverterTest.java index aa9359a3b75..7b791c1442d 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1MdcPatternConverterTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1MdcPatternConverterTest.java @@ -26,17 +26,17 @@ import org.apache.logging.log4j.util.StringMap; import org.junit.jupiter.api.Test; -public class Log4j1MdcPatternConverterTest { +class Log4j1MdcPatternConverterTest { @Test - public void testConverter0() { + void testConverter0() { final StringMap contextMap = ContextDataFactory.createContextData(0); final String expected = "{}"; test(contextMap, expected, null); } @Test - public void testConverter1() { + void testConverter1() { final StringMap contextMap = ContextDataFactory.createContextData(1); contextMap.putValue("key1", "value1"); final String expected = "{{key1,value1}}"; @@ -44,7 +44,7 @@ public void testConverter1() { } @Test - public void testConverter2() { + void testConverter2() { final StringMap contextMap = ContextDataFactory.createContextData(2); contextMap.putValue("key1", "value1"); contextMap.putValue("key2", "value2"); @@ -53,7 +53,7 @@ public void testConverter2() { } @Test - public void testConverterWithKey() { + void testConverterWithKey() { final StringMap contextMap = ContextDataFactory.createContextData(2); contextMap.putValue("key1", "value1"); contextMap.putValue("key2", "value2"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1NdcPatternConverterTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1NdcPatternConverterTest.java index 146ac902ed2..a0b3da20d40 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1NdcPatternConverterTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/Log4j1NdcPatternConverterTest.java @@ -27,28 +27,28 @@ import org.junit.jupiter.api.Test; @UsingThreadContextStack -public class Log4j1NdcPatternConverterTest { +class Log4j1NdcPatternConverterTest { @Test - public void testEmpty() { + void testEmpty() { testConverter(""); } @Test - public void test1() { + void test1() { ThreadContext.push("foo"); testConverter("foo"); } @Test - public void test2() { + void test2() { ThreadContext.push("foo"); ThreadContext.push("bar"); testConverter("foo bar"); } @Test - public void test3() { + void test3() { ThreadContext.push("foo"); ThreadContext.push("bar"); ThreadContext.push("baz"); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/NameAbbreviatorTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/NameAbbreviatorTest.java index d051581f38c..06f2e9698c2 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/NameAbbreviatorTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/pattern/NameAbbreviatorTest.java @@ -39,7 +39,7 @@ public NameAbbreviatorTest(final String name) { public void testBlank() { final NameAbbreviator abbrev = NameAbbreviator.getAbbreviator(" "); final NameAbbreviator defaultAbbrev = NameAbbreviator.getDefaultAbbreviator(); - assertTrue(abbrev == defaultAbbrev); + assertSame(abbrev, defaultAbbrev); } /** diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/spi/ThrowableInformationTest.java b/log4j-1.2-api/src/test/java/org/apache/log4j/spi/ThrowableInformationTest.java index 36e25538418..bd8549c0a2d 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/spi/ThrowableInformationTest.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/spi/ThrowableInformationTest.java @@ -119,11 +119,11 @@ public void testNotOverriddenBehavior() { assertEquals(7, rep.length); final StringBuffer buf = new StringBuffer(String.valueOf(true)); buf.append('a'); - buf.append(String.valueOf(1)); - buf.append(String.valueOf(2L)); - buf.append(String.valueOf(Float.MAX_VALUE)); - buf.append(String.valueOf(Double.MIN_VALUE)); - buf.append(String.valueOf(true)); + buf.append(1); + buf.append(2L); + buf.append(Float.MAX_VALUE); + buf.append(Double.MIN_VALUE); + buf.append(true); assertEquals(buf.toString(), rep[0]); assertEquals("a", rep[1]); assertEquals(String.valueOf(1), rep[2]); diff --git a/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java b/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java index fb63057df19..695d32179ff 100644 --- a/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java +++ b/log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java @@ -53,13 +53,13 @@ class DOMTestCase { Logger logger; @BeforeEach - public void setUp() { + void setUp() { root = Logger.getRootLogger(); logger = Logger.getLogger(DOMTestCase.class); } @AfterEach - public void tearDown() { + void tearDown() { root.getLoggerRepository().resetConfiguration(); } @@ -110,7 +110,7 @@ void testJarURL() throws Exception { * */ @Test - public void testOverrideSubst() { + void testOverrideSubst() { final DOMConfigurator configurator = new DOMConfigurator(); configurator.doConfigure( DOMTestCase.class.getResource("/DOMTestCase/DOMTestCase1.xml"), LogManager.getLoggerRepository()); @@ -131,7 +131,7 @@ public void testOverrideSubst() { * */ @Test - public void testReset() { + void testReset() { final VectorAppender appender = new VectorAppender(); appender.setName("V1"); Logger.getRootLogger().addAppender(appender); diff --git a/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/ProcessIdUtilTest.java b/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/ProcessIdUtilTest.java index 7b7e86bc3df..1a24860f57d 100644 --- a/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/ProcessIdUtilTest.java +++ b/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/ProcessIdUtilTest.java @@ -21,10 +21,10 @@ import org.apache.logging.log4j.util.ProcessIdUtil; import org.junit.jupiter.api.Test; -public class ProcessIdUtilTest { +class ProcessIdUtilTest { @Test - public void processIdTest() { + void processIdTest() { final String processId = ProcessIdUtil.getProcessId(); assertNotEquals(processId, ProcessIdUtil.DEFAULT_PROCESSID, "ProcessId is default"); } diff --git a/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/StackLocatorTest.java b/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/StackLocatorTest.java index 1e8591c2074..2ccebbde0f3 100644 --- a/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/StackLocatorTest.java +++ b/log4j-api-java9/src/test/java/org/apache/logging/log4j/util/java9/StackLocatorTest.java @@ -26,10 +26,10 @@ import org.apache.logging.log4j.util.StackLocator; import org.junit.jupiter.api.Test; -public class StackLocatorTest { +class StackLocatorTest { @Test - public void testGetCallerClass() { + void testGetCallerClass() { final Class expected = StackLocatorTest.class; final StackLocator stackLocator = StackLocator.getInstance(); final Class actual = stackLocator.getCallerClass(1); @@ -37,14 +37,14 @@ public void testGetCallerClass() { } @Test - public void testGetCallerClassNameViaStackTrace() throws Exception { + void testGetCallerClassNameViaStackTrace() throws Exception { final Class expected = StackLocatorTest.class; final Class actual = Class.forName(new Throwable().getStackTrace()[0].getClassName()); assertSame(expected, actual); } @Test - public void testGetCurrentStackTrace() { + void testGetCurrentStackTrace() { final StackLocator stackLocator = StackLocator.getInstance(); final Deque> classes = stackLocator.getCurrentStackTrace(); final Stack> reversed = new Stack<>(); @@ -60,12 +60,12 @@ public void testGetCurrentStackTrace() { } @Test - public void testGetCallerClassViaName() { + void testGetCallerClassViaName() { Inner.assertCallerClassViaName(); } @Test - public void testGetCallerClassViaAnchorClass() { + void testGetCallerClassViaAnchorClass() { Inner.assertCallerClassViaAnchorClass(); } @@ -86,7 +86,7 @@ private static void assertCallerClassViaAnchorClass() { } @Test - public void testLocateClass() { + void testLocateClass() { final ClassLocator locator = new ClassLocator(); final Class clazz = locator.locateClass(); assertNotNull(clazz, "Could not locate class"); @@ -117,7 +117,7 @@ private StackTraceElement quux() { } @Test - public void testCalcLocation() { + void testCalcLocation() { /* * We are setting up a stack trace that looks like: * - org.apache.logging.log4j.util.test.StackLocatorTest#quux(line:118) @@ -135,14 +135,14 @@ public void testCalcLocation() { } @Test - public void testTopElementInStackTrace() { + void testTopElementInStackTrace() { final StackLocator stackLocator = StackLocator.getInstance(); final Deque> classes = stackLocator.getCurrentStackTrace(); assertSame(StackLocator.class, classes.getFirst()); } @Test - public void testCalcLocationWhenNotInTheStack() { + void testCalcLocationWhenNotInTheStack() { final StackLocator stackLocator = StackLocator.getInstance(); final StackTraceElement stackTraceElement = stackLocator.calcLocation("java.util.Logger"); assertNull(stackTraceElement); diff --git a/log4j-api-test/src/main/java/org/apache/logging/log4j/test/AbstractSerializationTest.java b/log4j-api-test/src/main/java/org/apache/logging/log4j/test/AbstractSerializationTest.java index 900fea6ab54..a2b67b64889 100644 --- a/log4j-api-test/src/main/java/org/apache/logging/log4j/test/AbstractSerializationTest.java +++ b/log4j-api-test/src/main/java/org/apache/logging/log4j/test/AbstractSerializationTest.java @@ -17,7 +17,7 @@ package org.apache.logging.log4j.test; import static org.apache.logging.log4j.test.SerializableMatchers.serializesRoundTrip; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.Serializable; import org.junit.Test; diff --git a/log4j-api-test/src/main/java/org/apache/logging/log4j/test/ThreadContextUtilityClass.java b/log4j-api-test/src/main/java/org/apache/logging/log4j/test/ThreadContextUtilityClass.java index 396039a50b1..eed1952c324 100644 --- a/log4j-api-test/src/main/java/org/apache/logging/log4j/test/ThreadContextUtilityClass.java +++ b/log4j-api-test/src/main/java/org/apache/logging/log4j/test/ThreadContextUtilityClass.java @@ -16,10 +16,10 @@ */ package org.apache.logging.log4j.test; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/AbstractLoggerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/AbstractLoggerTest.java index f83afb25a9c..79a8fd75dd8 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/AbstractLoggerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/AbstractLoggerTest.java @@ -48,7 +48,7 @@ @ResourceLock(value = Log4jStaticResources.MARKER_MANAGER, mode = ResourceAccessMode.READ) @SetSystemProperty(key = "log4j2.status.entries", value = "200") @SetSystemProperty(key = "log4j2.StatusLogger.level", value = "WARN") -public class AbstractLoggerTest { +class AbstractLoggerTest { private static final StringBuilder CHAR_SEQ = new StringBuilder("CharSeq"); @@ -94,7 +94,7 @@ public class AbstractLoggerTest { }; @Test - public void testDebug() { + void testDebug() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.DEBUG); @@ -149,7 +149,7 @@ public void testDebug() { } @Test - public void testError() { + void testError() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.ERROR); @@ -204,7 +204,7 @@ public void testError() { } @Test - public void testFatal() { + void testFatal() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.FATAL); @@ -259,7 +259,7 @@ public void testFatal() { } @Test - public void testInfo() { + void testInfo() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.INFO); @@ -314,7 +314,7 @@ public void testInfo() { } @Test - public void testLogDebug() { + void testLogDebug() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.DEBUG); @@ -369,7 +369,7 @@ public void testLogDebug() { } @Test - public void testLogError() { + void testLogError() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.ERROR); @@ -424,7 +424,7 @@ public void testLogError() { } @Test - public void testLogFatal() { + void testLogFatal() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.FATAL); @@ -479,7 +479,7 @@ public void testLogFatal() { } @Test - public void testLogInfo() { + void testLogInfo() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.INFO); @@ -534,7 +534,7 @@ public void testLogInfo() { } @Test - public void testLogTrace() { + void testLogTrace() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.TRACE); @@ -589,7 +589,7 @@ public void testLogTrace() { } @Test - public void testLogWarn() { + void testLogWarn() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.WARN); @@ -644,7 +644,7 @@ public void testLogWarn() { } @Test - public void testTrace() { + void testTrace() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.TRACE); @@ -699,7 +699,7 @@ public void testTrace() { } @Test - public void testWarn() { + void testWarn() { final CountingLogger logger = new CountingLogger(); logger.setCurrentLevel(Level.WARN); @@ -754,7 +754,7 @@ public void testWarn() { } @Test - public void testMessageWithThrowable() { + void testMessageWithThrowable() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(true); final ThrowableMessage message = new ThrowableMessage(t); @@ -776,7 +776,7 @@ public void testMessageWithThrowable() { } @Test - public void testMessageWithoutThrowable() { + void testMessageWithoutThrowable() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false); final ThrowableMessage message = new ThrowableMessage(null); @@ -798,7 +798,7 @@ public void testMessageWithoutThrowable() { } @Test - public void testMessageSupplierWithThrowable() { + void testMessageSupplierWithThrowable() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(true); final ThrowableMessage message = new ThrowableMessage(t); final MessageSupplier supplier = () -> message; @@ -821,7 +821,7 @@ public void testMessageSupplierWithThrowable() { } @Test - public void testMessageSupplierWithoutThrowable() { + void testMessageSupplierWithoutThrowable() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false); final ThrowableMessage message = new ThrowableMessage(null); final MessageSupplier supplier = () -> message; @@ -844,7 +844,7 @@ public void testMessageSupplierWithoutThrowable() { } @Test - public void testSupplierWithThrowable() { + void testSupplierWithThrowable() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(true); final ThrowableMessage message = new ThrowableMessage(t); final Supplier supplier = () -> message; @@ -867,7 +867,7 @@ public void testSupplierWithThrowable() { } @Test - public void testSupplierWithoutThrowable() { + void testSupplierWithoutThrowable() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false); final ThrowableMessage message = new ThrowableMessage(null); final Supplier supplier = () -> message; @@ -891,7 +891,7 @@ public void testSupplierWithoutThrowable() { @Test @ResourceLock("log4j2.StatusLogger") - public void testMessageThrows() { + void testMessageThrows() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false); logger.error(new TestMessage( () -> { @@ -909,7 +909,7 @@ public void testMessageThrows() { @Test @ResourceLock("log4j2.StatusLogger") - public void testMessageThrowsAndNullFormat() { + void testMessageThrowsAndNullFormat() { final ThrowableExpectingLogger logger = new ThrowableExpectingLogger(false); logger.error(new TestMessage( () -> { diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/CloseableThreadContextTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/CloseableThreadContextTest.java index bc053b080c3..c6bab5da531 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/CloseableThreadContextTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/CloseableThreadContextTest.java @@ -38,7 +38,7 @@ * @since 2.6 */ @ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceAccessMode.READ) -public class CloseableThreadContextTest { +class CloseableThreadContextTest { private final String key = "key"; private final String value = "value"; @@ -50,7 +50,7 @@ void clearThreadContext() { } @Test - public void shouldAddAnEntryToTheMap() { + void shouldAddAnEntryToTheMap() { try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value)) { assertNotNull(ignored); assertEquals(value, ThreadContext.get(key)); @@ -58,7 +58,7 @@ public void shouldAddAnEntryToTheMap() { } @Test - public void shouldAddTwoEntriesToTheMap() { + void shouldAddTwoEntriesToTheMap() { final String key2 = "key2"; final String value2 = "value2"; try (final CloseableThreadContext.Instance ignored = @@ -70,7 +70,7 @@ public void shouldAddTwoEntriesToTheMap() { } @Test - public void shouldNestEntries() { + void shouldNestEntries() { final String oldValue = "oldValue"; final String innerValue = "innerValue"; ThreadContext.put(key, oldValue); @@ -87,7 +87,7 @@ public void shouldNestEntries() { } @Test - public void shouldPreserveOldEntriesFromTheMapWhenAutoClosed() { + void shouldPreserveOldEntriesFromTheMapWhenAutoClosed() { final String oldValue = "oldValue"; ThreadContext.put(key, oldValue); try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value)) { @@ -98,7 +98,7 @@ public void shouldPreserveOldEntriesFromTheMapWhenAutoClosed() { } @Test - public void ifTheSameKeyIsAddedTwiceTheOriginalShouldBeUsed() { + void ifTheSameKeyIsAddedTwiceTheOriginalShouldBeUsed() { final String oldValue = "oldValue"; final String secondValue = "innerValue"; ThreadContext.put(key, oldValue); @@ -111,7 +111,7 @@ public void ifTheSameKeyIsAddedTwiceTheOriginalShouldBeUsed() { } @Test - public void shouldPushAndPopAnEntryToTheStack() { + void shouldPushAndPopAnEntryToTheStack() { final String message = "message"; try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.push(message)) { assertNotNull(ignored); @@ -121,7 +121,7 @@ public void shouldPushAndPopAnEntryToTheStack() { } @Test - public void shouldPushAndPopTwoEntriesToTheStack() { + void shouldPushAndPopTwoEntriesToTheStack() { final String message1 = "message1"; final String message2 = "message2"; try (final CloseableThreadContext.Instance ignored = @@ -133,7 +133,7 @@ public void shouldPushAndPopTwoEntriesToTheStack() { } @Test - public void shouldPushAndPopAParameterizedEntryToTheStack() { + void shouldPushAndPopAParameterizedEntryToTheStack() { final String parameterizedMessage = "message {}"; final String parameterizedMessageParameter = "param"; final String formattedMessage = parameterizedMessage.replace("{}", parameterizedMessageParameter); @@ -146,7 +146,7 @@ public void shouldPushAndPopAParameterizedEntryToTheStack() { } @Test - public void shouldRemoveAnEntryFromTheMapWhenAutoClosed() { + void shouldRemoveAnEntryFromTheMapWhenAutoClosed() { try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value)) { assertNotNull(ignored); assertEquals(value, ThreadContext.get(key)); @@ -155,7 +155,7 @@ public void shouldRemoveAnEntryFromTheMapWhenAutoClosed() { } @Test - public void shouldAddEntriesToBothStackAndMap() { + void shouldAddEntriesToBothStackAndMap() { final String stackValue = "something"; try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value).push(stackValue)) { @@ -168,7 +168,7 @@ public void shouldAddEntriesToBothStackAndMap() { } @Test - public void canReuseCloseableThreadContext() { + void canReuseCloseableThreadContext() { final String stackValue = "something"; // Create a ctc and close it final CloseableThreadContext.Instance ctc = @@ -195,7 +195,7 @@ public void canReuseCloseableThreadContext() { } @Test - public void closeIsIdempotent() { + void closeIsIdempotent() { final String originalMapValue = "map to keep"; final String originalStackValue = "stack to keep"; @@ -218,7 +218,7 @@ public void closeIsIdempotent() { } @Test - public void putAllWillPutAllValues() { + void putAllWillPutAllValues() { final String oldValue = "oldValue"; ThreadContext.put(key, oldValue); @@ -234,7 +234,7 @@ public void putAllWillPutAllValues() { } @Test - public void pushAllWillPushAllValues() { + void pushAllWillPushAllValues() { ThreadContext.push(key); final List messages = ThreadContext.getImmutableStack().asList(); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/EventLoggerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/EventLoggerTest.java index c13829e27bb..a6611bbf27f 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/EventLoggerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/EventLoggerTest.java @@ -27,18 +27,18 @@ import org.junit.jupiter.api.parallel.ResourceLock; @ResourceLock("log4j2.TestLogger") -public class EventLoggerTest { +class EventLoggerTest { TestLogger logger = (TestLogger) LogManager.getLogger("EventLogger"); List results = logger.getEntries(); @BeforeEach - public void setup() { + void setup() { results.clear(); } @Test - public void structuredData() { + void structuredData() { ThreadContext.put("loginId", "JohnDoe"); ThreadContext.put("ipAddress", "192.168.0.120"); ThreadContext.put("locale", Locale.US.getDisplayName(Locale.US)); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/LambdaLoggerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/LambdaLoggerTest.java index b5ce701d154..c84ba45e91b 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/LambdaLoggerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/LambdaLoggerTest.java @@ -34,7 +34,7 @@ /** * Tests the AbstractLogger implementation of the Logger2 interface. */ -public class LambdaLoggerTest { +class LambdaLoggerTest { private static class LogEvent { @SuppressWarnings("unused") @@ -275,14 +275,14 @@ public String get() { final Supplier[] supplierArray2 = new Supplier[] {supplier, supplier2}; @BeforeEach - public void beforeEachTest() { + void beforeEachTest() { logger2.list.clear(); supplier.invoked = false; messageSupplier.invoked = false; } @Test - public void testDebugMarkerMessageSupplier() { + void testDebugMarkerMessageSupplier() { logger2.disable().debug(marker, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -298,7 +298,7 @@ public void testDebugMarkerMessageSupplier() { } @Test - public void testDebugMessageSupplier() { + void testDebugMessageSupplier() { logger2.disable().debug(messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -313,7 +313,7 @@ public void testDebugMessageSupplier() { } @Test - public void testDebugMarkerMessageSupplierThrowable() { + void testDebugMarkerMessageSupplierThrowable() { logger2.disable().debug(marker, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -330,7 +330,7 @@ public void testDebugMarkerMessageSupplierThrowable() { } @Test - public void testDebugMessageSupplierThrowable() { + void testDebugMessageSupplierThrowable() { logger2.disable().debug(messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -346,7 +346,7 @@ public void testDebugMessageSupplierThrowable() { } @Test - public void testDebugMarkerSupplier() { + void testDebugMarkerSupplier() { logger2.disable().debug(marker, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -362,7 +362,7 @@ public void testDebugMarkerSupplier() { } @Test - public void testDebugSupplier() { + void testDebugSupplier() { logger2.disable().debug(supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -377,7 +377,7 @@ public void testDebugSupplier() { } @Test - public void testDebugMarkerSupplierThrowable() { + void testDebugMarkerSupplierThrowable() { logger2.disable().debug(marker, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -394,7 +394,7 @@ public void testDebugMarkerSupplierThrowable() { } @Test - public void testDebugSupplierThrowable() { + void testDebugSupplierThrowable() { logger2.disable().debug(supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -410,7 +410,7 @@ public void testDebugSupplierThrowable() { } @Test - public void testDebugStringParamSupplier() { + void testDebugStringParamSupplier() { logger2.disable().debug("abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -425,7 +425,7 @@ public void testDebugStringParamSupplier() { } @Test - public void testDebugMarkerStringParamSupplier() { + void testDebugMarkerStringParamSupplier() { logger2.disable().debug(marker, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -441,7 +441,7 @@ public void testDebugMarkerStringParamSupplier() { } @Test - public void testErrorMarkerMessageSupplier() { + void testErrorMarkerMessageSupplier() { logger2.disable().error(marker, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -457,7 +457,7 @@ public void testErrorMarkerMessageSupplier() { } @Test - public void testErrorMessageSupplier() { + void testErrorMessageSupplier() { logger2.disable().error(messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -472,7 +472,7 @@ public void testErrorMessageSupplier() { } @Test - public void testErrorMarkerMessageSupplierThrowable() { + void testErrorMarkerMessageSupplierThrowable() { logger2.disable().error(marker, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -489,7 +489,7 @@ public void testErrorMarkerMessageSupplierThrowable() { } @Test - public void testErrorMessageSupplierThrowable() { + void testErrorMessageSupplierThrowable() { logger2.disable().error(messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -505,7 +505,7 @@ public void testErrorMessageSupplierThrowable() { } @Test - public void testErrorMarkerSupplier() { + void testErrorMarkerSupplier() { logger2.disable().error(marker, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -521,7 +521,7 @@ public void testErrorMarkerSupplier() { } @Test - public void testErrorSupplier() { + void testErrorSupplier() { logger2.disable().error(supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -536,7 +536,7 @@ public void testErrorSupplier() { } @Test - public void testErrorMarkerSupplierThrowable() { + void testErrorMarkerSupplierThrowable() { logger2.disable().error(marker, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -553,7 +553,7 @@ public void testErrorMarkerSupplierThrowable() { } @Test - public void testErrorSupplierThrowable() { + void testErrorSupplierThrowable() { logger2.disable().error(supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -569,7 +569,7 @@ public void testErrorSupplierThrowable() { } @Test - public void testErrorStringParamSupplier() { + void testErrorStringParamSupplier() { logger2.disable().error("abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -584,7 +584,7 @@ public void testErrorStringParamSupplier() { } @Test - public void testErrorMarkerStringParamSupplier() { + void testErrorMarkerStringParamSupplier() { logger2.disable().error(marker, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -600,7 +600,7 @@ public void testErrorMarkerStringParamSupplier() { } @Test - public void testFatalMarkerMessageSupplier() { + void testFatalMarkerMessageSupplier() { logger2.disable().fatal(marker, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -616,7 +616,7 @@ public void testFatalMarkerMessageSupplier() { } @Test - public void testFatalMessageSupplier() { + void testFatalMessageSupplier() { logger2.disable().fatal(messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -631,7 +631,7 @@ public void testFatalMessageSupplier() { } @Test - public void testFatalMarkerMessageSupplierThrowable() { + void testFatalMarkerMessageSupplierThrowable() { logger2.disable().fatal(marker, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -648,7 +648,7 @@ public void testFatalMarkerMessageSupplierThrowable() { } @Test - public void testFatalMessageSupplierThrowable() { + void testFatalMessageSupplierThrowable() { logger2.disable().fatal(messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -664,7 +664,7 @@ public void testFatalMessageSupplierThrowable() { } @Test - public void testFatalMarkerSupplier() { + void testFatalMarkerSupplier() { logger2.disable().fatal(marker, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -680,7 +680,7 @@ public void testFatalMarkerSupplier() { } @Test - public void testFatalSupplier() { + void testFatalSupplier() { logger2.disable().fatal(supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -695,7 +695,7 @@ public void testFatalSupplier() { } @Test - public void testFatalMarkerSupplierThrowable() { + void testFatalMarkerSupplierThrowable() { logger2.disable().fatal(marker, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -712,7 +712,7 @@ public void testFatalMarkerSupplierThrowable() { } @Test - public void testFatalSupplierThrowable() { + void testFatalSupplierThrowable() { logger2.disable().fatal(supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -728,7 +728,7 @@ public void testFatalSupplierThrowable() { } @Test - public void testFatalStringParamSupplier() { + void testFatalStringParamSupplier() { logger2.disable().fatal("abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -743,7 +743,7 @@ public void testFatalStringParamSupplier() { } @Test - public void testFatalStringParam2Suppliers() { + void testFatalStringParam2Suppliers() { logger2.disable().fatal("abc {}{}", supplierArray2); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -760,7 +760,7 @@ public void testFatalStringParam2Suppliers() { } @Test - public void testFatalMarkerStringParamSupplier() { + void testFatalMarkerStringParamSupplier() { logger2.disable().fatal(marker, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -776,7 +776,7 @@ public void testFatalMarkerStringParamSupplier() { } @Test - public void testInfoMarkerMessageSupplier() { + void testInfoMarkerMessageSupplier() { logger2.disable().info(marker, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -792,7 +792,7 @@ public void testInfoMarkerMessageSupplier() { } @Test - public void testInfoMessageSupplier() { + void testInfoMessageSupplier() { logger2.disable().info(messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -807,7 +807,7 @@ public void testInfoMessageSupplier() { } @Test - public void testInfoMarkerMessageSupplierThrowable() { + void testInfoMarkerMessageSupplierThrowable() { logger2.disable().info(marker, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -824,7 +824,7 @@ public void testInfoMarkerMessageSupplierThrowable() { } @Test - public void testInfoMessageSupplierThrowable() { + void testInfoMessageSupplierThrowable() { logger2.disable().info(messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -840,7 +840,7 @@ public void testInfoMessageSupplierThrowable() { } @Test - public void testInfoMarkerSupplier() { + void testInfoMarkerSupplier() { logger2.disable().info(marker, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -856,7 +856,7 @@ public void testInfoMarkerSupplier() { } @Test - public void testInfoSupplier() { + void testInfoSupplier() { logger2.disable().info(supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -871,7 +871,7 @@ public void testInfoSupplier() { } @Test - public void testInfoMarkerSupplierThrowable() { + void testInfoMarkerSupplierThrowable() { logger2.disable().info(marker, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -888,7 +888,7 @@ public void testInfoMarkerSupplierThrowable() { } @Test - public void testInfoSupplierThrowable() { + void testInfoSupplierThrowable() { logger2.disable().info(supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -904,7 +904,7 @@ public void testInfoSupplierThrowable() { } @Test - public void testInfoStringParamSupplier() { + void testInfoStringParamSupplier() { logger2.disable().info("abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -919,7 +919,7 @@ public void testInfoStringParamSupplier() { } @Test - public void testInfoMarkerStringParamSupplier() { + void testInfoMarkerStringParamSupplier() { logger2.disable().info(marker, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -935,7 +935,7 @@ public void testInfoMarkerStringParamSupplier() { } @Test - public void testTraceMarkerMessageSupplier() { + void testTraceMarkerMessageSupplier() { logger2.disable().trace(marker, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -951,7 +951,7 @@ public void testTraceMarkerMessageSupplier() { } @Test - public void testTraceMessageSupplier() { + void testTraceMessageSupplier() { logger2.disable().trace(messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -966,7 +966,7 @@ public void testTraceMessageSupplier() { } @Test - public void testTraceMarkerMessageSupplierThrowable() { + void testTraceMarkerMessageSupplierThrowable() { logger2.disable().trace(marker, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -983,7 +983,7 @@ public void testTraceMarkerMessageSupplierThrowable() { } @Test - public void testTraceMessageSupplierThrowable() { + void testTraceMessageSupplierThrowable() { logger2.disable().trace(messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -999,7 +999,7 @@ public void testTraceMessageSupplierThrowable() { } @Test - public void testTraceMarkerSupplier() { + void testTraceMarkerSupplier() { logger2.disable().trace(marker, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1015,7 +1015,7 @@ public void testTraceMarkerSupplier() { } @Test - public void testTraceSupplier() { + void testTraceSupplier() { logger2.disable().trace(supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1030,7 +1030,7 @@ public void testTraceSupplier() { } @Test - public void testTraceMarkerSupplierThrowable() { + void testTraceMarkerSupplierThrowable() { logger2.disable().trace(marker, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1047,7 +1047,7 @@ public void testTraceMarkerSupplierThrowable() { } @Test - public void testTraceSupplierThrowable() { + void testTraceSupplierThrowable() { logger2.disable().trace(supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1063,7 +1063,7 @@ public void testTraceSupplierThrowable() { } @Test - public void testTraceStringParamSupplier() { + void testTraceStringParamSupplier() { logger2.disable().trace("abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1078,7 +1078,7 @@ public void testTraceStringParamSupplier() { } @Test - public void testTraceMarkerStringParamSupplier() { + void testTraceMarkerStringParamSupplier() { logger2.disable().trace(marker, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1094,7 +1094,7 @@ public void testTraceMarkerStringParamSupplier() { } @Test - public void testWarnMarkerMessageSupplier() { + void testWarnMarkerMessageSupplier() { logger2.disable().warn(marker, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1110,7 +1110,7 @@ public void testWarnMarkerMessageSupplier() { } @Test - public void testWarnMessageSupplier() { + void testWarnMessageSupplier() { logger2.disable().warn(messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1125,7 +1125,7 @@ public void testWarnMessageSupplier() { } @Test - public void testWarnMarkerMessageSupplierThrowable() { + void testWarnMarkerMessageSupplierThrowable() { logger2.disable().warn(marker, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1142,7 +1142,7 @@ public void testWarnMarkerMessageSupplierThrowable() { } @Test - public void testWarnMessageSupplierThrowable() { + void testWarnMessageSupplierThrowable() { logger2.disable().warn(messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1158,7 +1158,7 @@ public void testWarnMessageSupplierThrowable() { } @Test - public void testWarnMarkerSupplier() { + void testWarnMarkerSupplier() { logger2.disable().warn(marker, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1174,7 +1174,7 @@ public void testWarnMarkerSupplier() { } @Test - public void testWarnSupplier() { + void testWarnSupplier() { logger2.disable().warn(supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1189,7 +1189,7 @@ public void testWarnSupplier() { } @Test - public void testWarnMarkerSupplierThrowable() { + void testWarnMarkerSupplierThrowable() { logger2.disable().warn(marker, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1206,7 +1206,7 @@ public void testWarnMarkerSupplierThrowable() { } @Test - public void testWarnSupplierThrowable() { + void testWarnSupplierThrowable() { logger2.disable().warn(supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1222,7 +1222,7 @@ public void testWarnSupplierThrowable() { } @Test - public void testWarnStringParamSupplier() { + void testWarnStringParamSupplier() { logger2.disable().warn("abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1237,7 +1237,7 @@ public void testWarnStringParamSupplier() { } @Test - public void testWarnMarkerStringParamSupplier() { + void testWarnMarkerStringParamSupplier() { logger2.disable().warn(marker, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1253,7 +1253,7 @@ public void testWarnMarkerStringParamSupplier() { } @Test - public void testLogMarkerMessageSupplier() { + void testLogMarkerMessageSupplier() { logger2.disable().log(Level.WARN, marker, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1269,7 +1269,7 @@ public void testLogMarkerMessageSupplier() { } @Test - public void testLogMessageSupplier() { + void testLogMessageSupplier() { logger2.disable().log(Level.WARN, messageSupplier); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1284,7 +1284,7 @@ public void testLogMessageSupplier() { } @Test - public void testLogMarkerMessageSupplierThrowable() { + void testLogMarkerMessageSupplierThrowable() { logger2.disable().log(Level.WARN, marker, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1301,7 +1301,7 @@ public void testLogMarkerMessageSupplierThrowable() { } @Test - public void testLogMessageSupplierThrowable() { + void testLogMessageSupplierThrowable() { logger2.disable().log(Level.WARN, messageSupplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(messageSupplier.invoked); @@ -1317,7 +1317,7 @@ public void testLogMessageSupplierThrowable() { } @Test - public void testLogMarkerSupplier() { + void testLogMarkerSupplier() { logger2.disable().log(Level.WARN, marker, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1333,7 +1333,7 @@ public void testLogMarkerSupplier() { } @Test - public void testLogSupplier() { + void testLogSupplier() { logger2.disable().log(Level.WARN, supplier); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1348,7 +1348,7 @@ public void testLogSupplier() { } @Test - public void testLogMarkerSupplierThrowable() { + void testLogMarkerSupplierThrowable() { logger2.disable().log(Level.WARN, marker, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1365,7 +1365,7 @@ public void testLogMarkerSupplierThrowable() { } @Test - public void testLogSupplierThrowable() { + void testLogSupplierThrowable() { logger2.disable().log(Level.WARN, supplier, throwable); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1381,7 +1381,7 @@ public void testLogSupplierThrowable() { } @Test - public void testLogStringParamSupplier() { + void testLogStringParamSupplier() { logger2.disable().log(Level.WARN, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); @@ -1396,7 +1396,7 @@ public void testLogStringParamSupplier() { } @Test - public void testLogMarkerStringParamSupplier() { + void testLogMarkerStringParamSupplier() { logger2.disable().log(Level.WARN, marker, "abc {}", supplierArray1); assertTrue(logger2.list.isEmpty()); assertFalse(supplier.invoked); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/LevelTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/LevelTest.java index 690d7c74371..30f9e4073d5 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/LevelTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/LevelTest.java @@ -25,17 +25,17 @@ import org.junit.jupiter.api.Test; -public class LevelTest { +class LevelTest { @Test - public void testDefault() { + void testDefault() { final Level level = Level.toLevel("Information", Level.ERROR); assertNotNull(level); assertEquals(Level.ERROR, level); } @Test - public void testForNameEquals() { + void testForNameEquals() { final String name = "Foo"; final int intValue = 1; final Level level = Level.forName(name, intValue); @@ -47,7 +47,7 @@ public void testForNameEquals() { } @Test - public void testThrowsOnNull() { + void testThrowsOnNull() { assertThrowsExactly(IllegalArgumentException.class, () -> Level.forName(null, 100)); assertThrowsExactly(IllegalArgumentException.class, () -> Level.getLevel(null)); // the intLevel should be checked only if we create a new level @@ -56,14 +56,14 @@ public void testThrowsOnNull() { } @Test - public void testGoodLevels() { + void testGoodLevels() { final Level level = Level.toLevel("INFO"); assertNotNull(level); assertEquals(Level.INFO, level); } @Test - public void testIsInRangeErrorToDebug() { + void testIsInRangeErrorToDebug() { assertFalse(Level.OFF.isInRange(Level.ERROR, Level.DEBUG)); assertFalse(Level.FATAL.isInRange(Level.ERROR, Level.DEBUG)); assertTrue(Level.ERROR.isInRange(Level.ERROR, Level.DEBUG)); @@ -75,7 +75,7 @@ public void testIsInRangeErrorToDebug() { } @Test - public void testIsInRangeFatalToTrace() { + void testIsInRangeFatalToTrace() { assertFalse(Level.OFF.isInRange(Level.FATAL, Level.TRACE)); assertTrue(Level.FATAL.isInRange(Level.FATAL, Level.TRACE)); assertTrue(Level.ERROR.isInRange(Level.FATAL, Level.TRACE)); @@ -87,7 +87,7 @@ public void testIsInRangeFatalToTrace() { } @Test - public void testIsInRangeOffToAll() { + void testIsInRangeOffToAll() { assertTrue(Level.OFF.isInRange(Level.OFF, Level.ALL)); assertTrue(Level.FATAL.isInRange(Level.OFF, Level.ALL)); assertTrue(Level.ERROR.isInRange(Level.OFF, Level.ALL)); @@ -99,7 +99,7 @@ public void testIsInRangeOffToAll() { } @Test - public void testIsInRangeSameLevels() { + void testIsInRangeSameLevels() { // Level.OFF assertTrue(Level.OFF.isInRange(Level.OFF, Level.OFF)); assertFalse(Level.OFF.isInRange(Level.FATAL, Level.FATAL)); @@ -175,7 +175,7 @@ public void testIsInRangeSameLevels() { } @Test - public void testIsInRangeWarnToInfo() { + void testIsInRangeWarnToInfo() { assertFalse(Level.OFF.isInRange(Level.WARN, Level.INFO)); assertFalse(Level.FATAL.isInRange(Level.WARN, Level.INFO)); assertFalse(Level.ERROR.isInRange(Level.WARN, Level.INFO)); @@ -187,7 +187,7 @@ public void testIsInRangeWarnToInfo() { } @Test - public void testIsLessSpecificThan() { + void testIsLessSpecificThan() { // Level.OFF assertTrue(Level.OFF.isLessSpecificThan(Level.OFF)); assertFalse(Level.OFF.isLessSpecificThan(Level.FATAL)); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/LogManagerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/LogManagerTest.java index 5b3bd70d8b8..6d54a96c52a 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/LogManagerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/LogManagerTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.parallel.ResourceLock; @ResourceLock(value = "log4j2.LoggerContextFactory", mode = ResourceAccessMode.READ) -public class LogManagerTest { +class LogManagerTest { @SuppressWarnings("InnerClassMayBeStatic") class Inner { @@ -49,7 +49,7 @@ static class StaticInnerByClass { } @Test - public void testGetLogger() { + void testGetLogger() { Logger logger = LogManager.getLogger(); assertNotNull(logger, "No Logger returned"); assertEquals(LogManagerTest.class.getName(), logger.getName(), "Incorrect Logger name: " + logger.getName()); @@ -77,13 +77,13 @@ public void testGetLogger() { } @Test - public void testGetLoggerForAnonymousInnerClass1() throws IOException { + void testGetLoggerForAnonymousInnerClass1() throws IOException { final Closeable closeable = new Closeable() { final Logger LOGGER = LogManager.getLogger(); @Override - public void close() throws IOException { + public void close() { assertEquals("org.apache.logging.log4j.LogManagerTest$1", LOGGER.getName()); } }; @@ -91,13 +91,13 @@ public void close() throws IOException { } @Test - public void testGetLoggerForAnonymousInnerClass2() throws IOException { + void testGetLoggerForAnonymousInnerClass2() throws IOException { final Closeable closeable = new Closeable() { final Logger LOGGER = LogManager.getLogger(getClass()); @Override - public void close() throws IOException { + public void close() { assertEquals("org.apache.logging.log4j.LogManagerTest$2", LOGGER.getName()); } }; @@ -105,27 +105,27 @@ public void close() throws IOException { } @Test - public void testGetLoggerForInner() { + void testGetLoggerForInner() { assertEquals("org.apache.logging.log4j.LogManagerTest.Inner", new Inner().LOGGER.getName()); } @Test - public void testGetLoggerForInnerByClass() { + void testGetLoggerForInnerByClass() { assertEquals("org.apache.logging.log4j.LogManagerTest.InnerByClass", new InnerByClass().LOGGER.getName()); } @Test - public void testGetLoggerForStaticInner() { + void testGetLoggerForStaticInner() { assertEquals("org.apache.logging.log4j.LogManagerTest.StaticInner", StaticInner.LOGGER.getName()); } @Test - public void testGetLoggerForStaticInnerByClass() { + void testGetLoggerForStaticInnerByClass() { assertEquals("org.apache.logging.log4j.LogManagerTest.StaticInnerByClass", StaticInnerByClass.LOGGER.getName()); } @Test - public void testShutdown() { + void testShutdown() { final LoggerContext loggerContext = LogManager.getContext(false); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerSupplierTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerSupplierTest.java index d458c27cbee..761425eabb2 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerSupplierTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerSupplierTest.java @@ -44,7 +44,7 @@ */ @ResourceLock(Resources.LOCALE) @ResourceLock("log4j2.TestLogger") -public class LoggerSupplierTest { +class LoggerSupplierTest { private final TestLogger logger = (TestLogger) LogManager.getLogger("LoggerTest"); @@ -53,7 +53,7 @@ public class LoggerSupplierTest { Locale defaultLocale; @Test - public void flowTracing_SupplierOfFormattedMessage() { + void flowTracing_SupplierOfFormattedMessage() { logger.traceEntry(() -> new FormattedMessage("int foo={}", 1234567890)); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -64,7 +64,7 @@ public void flowTracing_SupplierOfFormattedMessage() { } @Test - public void flowTracing_SupplierOfJsonMessage() { + void flowTracing_SupplierOfJsonMessage() { final Properties props = new Properties(); props.setProperty("foo", "bar"); logger.traceEntry(() -> new JsonMessage(props)); @@ -77,7 +77,7 @@ public void flowTracing_SupplierOfJsonMessage() { } @Test - public void flowTracing_SupplierOfLocalizedMessage() { + void flowTracing_SupplierOfLocalizedMessage() { logger.traceEntry(() -> new LocalizedMessage("int foo={}", 1234567890)); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -88,7 +88,7 @@ public void flowTracing_SupplierOfLocalizedMessage() { } @Test - public void flowTracing_SupplierOfLong() { + void flowTracing_SupplierOfLong() { logger.traceEntry(() -> 1234567890L); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -99,7 +99,7 @@ public void flowTracing_SupplierOfLong() { } @Test - public void flowTracing_SupplierOfMessageFormatMessage() { + void flowTracing_SupplierOfMessageFormatMessage() { logger.traceEntry(() -> new MessageFormatMessage("int foo={0}", 1234567890)); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -110,7 +110,7 @@ public void flowTracing_SupplierOfMessageFormatMessage() { } @Test - public void flowTracing_SupplierOfObjectArrayMessage() { + void flowTracing_SupplierOfObjectArrayMessage() { logger.traceEntry(() -> new ObjectArrayMessage(1234567890)); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -121,7 +121,7 @@ public void flowTracing_SupplierOfObjectArrayMessage() { } @Test - public void flowTracing_SupplierOfObjectMessage() { + void flowTracing_SupplierOfObjectMessage() { logger.traceEntry(() -> new ObjectMessage(1234567890)); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -132,7 +132,7 @@ public void flowTracing_SupplierOfObjectMessage() { } @Test - public void flowTracing_SupplierOfParameterizedMessage() { + void flowTracing_SupplierOfParameterizedMessage() { logger.traceEntry(() -> new ParameterizedMessage("int foo={}", 1234567890)); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -143,7 +143,7 @@ public void flowTracing_SupplierOfParameterizedMessage() { } @Test - public void flowTracing_SupplierOfSimpleMessage() { + void flowTracing_SupplierOfSimpleMessage() { logger.traceEntry(() -> new SimpleMessage("1234567890")); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -154,7 +154,7 @@ public void flowTracing_SupplierOfSimpleMessage() { } @Test - public void flowTracing_SupplierOfString() { + void flowTracing_SupplierOfString() { logger.traceEntry(() -> "1234567890"); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -165,7 +165,7 @@ public void flowTracing_SupplierOfString() { } @Test - public void flowTracing_SupplierOfStringFormattedMessage() { + void flowTracing_SupplierOfStringFormattedMessage() { logger.traceEntry(() -> new StringFormattedMessage("int foo=%,d", 1234567890)); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -176,7 +176,7 @@ public void flowTracing_SupplierOfStringFormattedMessage() { } @Test - public void flowTracing_SupplierOfThreadDumpMessage() { + void flowTracing_SupplierOfThreadDumpMessage() { logger.traceEntry(() -> new ThreadDumpMessage("Title of ...")); assertThat(results).hasSize(1); final String entry = results.get(0); @@ -186,14 +186,14 @@ public void flowTracing_SupplierOfThreadDumpMessage() { } @BeforeEach - public void setup() { + void setup() { results.clear(); defaultLocale = Locale.getDefault(Locale.Category.FORMAT); Locale.setDefault(Locale.Category.FORMAT, java.util.Locale.US); } @AfterEach - public void tearDown() { + void tearDown() { Locale.setDefault(Locale.Category.FORMAT, defaultLocale); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerTest.java index 9c276044684..ac00b97be9a 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/LoggerTest.java @@ -53,7 +53,7 @@ @ResourceLock(value = Log4jStaticResources.MARKER_MANAGER, mode = ResourceAccessMode.READ) @ReadsSystemProperty -public class LoggerTest { +class LoggerTest { private static class TestParameterizedMessageFactory { // empty @@ -68,7 +68,7 @@ private static class TestStringFormatterMessageFactory { private final List results = logger.getEntries(); @Test - public void builder() { + void builder() { logger.atDebug().withLocation().log("Hello"); logger.atError().withMarker(marker).log("Hello {}", "John"); logger.atWarn().withThrowable(new Throwable("This is a test")).log((Message) new SimpleMessage("Log4j rocks!")); @@ -89,7 +89,7 @@ public void builder() { } @Test - public void basicFlow() { + void basicFlow() { logger.entry(); logger.exit(); assertEquals(2, results.size()); @@ -98,7 +98,7 @@ public void basicFlow() { } @Test - public void flowTracingMessage() { + void flowTracingMessage() { final Properties props = new Properties(); props.setProperty("foo", "bar"); logger.traceEntry(new JsonMessage(props)); @@ -110,7 +110,7 @@ public void flowTracingMessage() { } @Test - public void flowTracingString_ObjectArray1() { + void flowTracingString_ObjectArray1() { logger.traceEntry("doFoo(a={}, b={})", 1, 2); logger.traceExit("doFoo(a=1, b=2): {}", 3); assertThat(results).hasSize(2); @@ -119,7 +119,7 @@ public void flowTracingString_ObjectArray1() { } @Test - public void flowTracingExitValueOnly() { + void flowTracingExitValueOnly() { logger.traceEntry("doFoo(a={}, b={})", 1, 2); logger.traceExit(3); assertThat(results).hasSize(2); @@ -128,7 +128,7 @@ public void flowTracingExitValueOnly() { } @Test - public void flowTracingString_ObjectArray2() { + void flowTracingString_ObjectArray2() { final EntryMessage msg = logger.traceEntry("doFoo(a={}, b={})", 1, 2); logger.traceExit(msg, 3); assertThat(results).hasSize(2); @@ -137,7 +137,7 @@ public void flowTracingString_ObjectArray2() { } @Test - public void flowTracingVoidReturn() { + void flowTracingVoidReturn() { final EntryMessage msg = logger.traceEntry("doFoo(a={}, b={})", 1, 2); logger.traceExit(msg); assertThat(results).hasSize(2); @@ -146,7 +146,7 @@ public void flowTracingVoidReturn() { } @Test - public void flowTracingNoExitArgs() { + void flowTracingNoExitArgs() { logger.traceEntry(); logger.traceExit(); assertThat(results).hasSize(2); @@ -155,7 +155,7 @@ public void flowTracingNoExitArgs() { } @Test - public void flowTracingNoArgs() { + void flowTracingNoArgs() { final EntryMessage message = logger.traceEntry(); logger.traceExit(message); assertThat(results).hasSize(2); @@ -164,7 +164,7 @@ public void flowTracingNoArgs() { } @Test - public void flowTracingString_SupplierOfObjectMessages() { + void flowTracingString_SupplierOfObjectMessages() { final EntryMessage msg = logger.traceEntry( "doFoo(a={}, b={})", (Supplier) () -> new ObjectMessage(1), (Supplier) () -> new ObjectMessage(2)); @@ -175,7 +175,7 @@ public void flowTracingString_SupplierOfObjectMessages() { } @Test - public void flowTracingString_SupplierOfStrings() { + void flowTracingString_SupplierOfStrings() { final EntryMessage msg = logger.traceEntry("doFoo(a={}, b={})", (Supplier) () -> "1", (Supplier) () -> "2"); logger.traceExit(msg, 3); @@ -185,7 +185,7 @@ public void flowTracingString_SupplierOfStrings() { } @Test - public void flowTracingNoFormat() { + void flowTracingNoFormat() { logger.traceEntry(null, 1, "2", new ObjectMessage(3)); logger.traceExit((String) null, 4); assertThat(results).hasSize(2); @@ -194,7 +194,7 @@ public void flowTracingNoFormat() { } @Test - public void catching() { + void catching() { try { throw new NullPointerException(); } catch (final Exception e) { @@ -208,28 +208,28 @@ public void catching() { } @Test - public void debug() { + void debug() { logger.debug("Debug message"); assertEquals(1, results.size()); assertTrue(results.get(0).startsWith(" DEBUG Debug message"), "Incorrect message"); } @Test - public void debugObject() { + void debugObject() { logger.debug(new Date()); assertEquals(1, results.size()); assertTrue(results.get(0).length() > 7, "Invalid length"); } @Test - public void debugWithParms() { + void debugWithParms() { logger.debug("Hello, {}", "World"); assertEquals(1, results.size()); assertTrue(results.get(0).startsWith(" DEBUG Hello, World"), "Incorrect substitution"); } @Test - public void debugWithParmsAndThrowable() { + void debugWithParmsAndThrowable() { logger.debug("Hello, {}", "World", new RuntimeException("Test Exception")); assertEquals(1, results.size()); assertTrue( @@ -239,7 +239,7 @@ public void debugWithParmsAndThrowable() { @Test @ResourceLock(value = org.junit.jupiter.api.parallel.Resources.LOCALE, mode = ResourceAccessMode.READ) - public void getFormatterLogger() { + void getFormatterLogger() { // The TestLogger logger was already created in an instance variable for this class. // The message factory is only used when the logger is created. final TestLogger testLogger = (TestLogger) LogManager.getFormatterLogger(); @@ -257,7 +257,7 @@ public void getFormatterLogger() { @Test @ResourceLock(value = org.junit.jupiter.api.parallel.Resources.LOCALE, mode = ResourceAccessMode.READ) - public void getFormatterLogger_Class() { + void getFormatterLogger_Class() { // The TestLogger logger was already created in an instance variable for this class. // The message factory is only used when the logger is created. final TestLogger testLogger = @@ -281,7 +281,7 @@ private static void assertMessageFactoryInstanceOf(MessageFactory factory, final @Test @ResourceLock(value = org.junit.jupiter.api.parallel.Resources.LOCALE, mode = ResourceAccessMode.READ) - public void getFormatterLogger_Object() { + void getFormatterLogger_Object() { // The TestLogger logger was already created in an instance variable for this class. // The message factory is only used when the logger is created. final TestLogger testLogger = @@ -298,7 +298,7 @@ public void getFormatterLogger_Object() { @Test @ResourceLock(value = org.junit.jupiter.api.parallel.Resources.LOCALE, mode = ResourceAccessMode.READ) - public void getFormatterLogger_String() { + void getFormatterLogger_String() { final StringFormatterMessageFactory messageFactory = StringFormatterMessageFactory.INSTANCE; final TestLogger testLogger = (TestLogger) LogManager.getFormatterLogger("getLogger_String_StringFormatterMessageFactory"); @@ -313,7 +313,7 @@ public void getFormatterLogger_String() { } @Test - public void getLogger_Class_ParameterizedMessageFactory() { + void getLogger_Class_ParameterizedMessageFactory() { // The TestLogger logger was already created in an instance variable for this class. // The message factory is only used when the logger is created. final ParameterizedMessageFactory messageFactory = ParameterizedMessageFactory.INSTANCE; @@ -327,7 +327,7 @@ public void getLogger_Class_ParameterizedMessageFactory() { } @Test - public void getLogger_Class_StringFormatterMessageFactory() { + void getLogger_Class_StringFormatterMessageFactory() { // The TestLogger logger was already created in an instance variable for this class. // The message factory is only used when the logger is created. final TestLogger testLogger = (TestLogger) @@ -342,7 +342,7 @@ public void getLogger_Class_StringFormatterMessageFactory() { } @Test - public void getLogger_Object_ParameterizedMessageFactory() { + void getLogger_Object_ParameterizedMessageFactory() { // The TestLogger logger was already created in an instance variable for this class. // The message factory is only used when the logger is created. final ParameterizedMessageFactory messageFactory = ParameterizedMessageFactory.INSTANCE; @@ -364,7 +364,7 @@ private void assertEqualMessageFactory(final MessageFactory messageFactory, fina } @Test - public void getLogger_Object_StringFormatterMessageFactory() { + void getLogger_Object_StringFormatterMessageFactory() { // The TestLogger logger was already created in an instance variable for this class. // The message factory is only used when the logger is created. final StringFormatterMessageFactory messageFactory = StringFormatterMessageFactory.INSTANCE; @@ -380,7 +380,7 @@ public void getLogger_Object_StringFormatterMessageFactory() { } @Test - public void getLogger_String_MessageFactoryMismatch() { + void getLogger_String_MessageFactoryMismatch() { final StringFormatterMessageFactory messageFactory = StringFormatterMessageFactory.INSTANCE; final TestLogger testLogger = (TestLogger) LogManager.getLogger("getLogger_String_MessageFactoryMismatch", messageFactory); @@ -400,7 +400,7 @@ public void getLogger_String_MessageFactoryMismatch() { } @Test - public void getLogger_String_ParameterizedMessageFactory() { + void getLogger_String_ParameterizedMessageFactory() { final ParameterizedMessageFactory messageFactory = ParameterizedMessageFactory.INSTANCE; final TestLogger testLogger = (TestLogger) LogManager.getLogger("getLogger_String_ParameterizedMessageFactory", messageFactory); @@ -412,7 +412,7 @@ public void getLogger_String_ParameterizedMessageFactory() { } @Test - public void getLogger_String_SimpleMessageFactory() { + void getLogger_String_SimpleMessageFactory() { final SimpleMessageFactory messageFactory = SimpleMessageFactory.INSTANCE; final TestLogger testLogger = (TestLogger) LogManager.getLogger("getLogger_String_StringFormatterMessageFactory", messageFactory); @@ -424,7 +424,7 @@ public void getLogger_String_SimpleMessageFactory() { } @Test - public void getLogger_String_StringFormatterMessageFactory() { + void getLogger_String_StringFormatterMessageFactory() { final StringFormatterMessageFactory messageFactory = StringFormatterMessageFactory.INSTANCE; final TestLogger testLogger = (TestLogger) LogManager.getLogger("getLogger_String_StringFormatterMessageFactory", messageFactory); @@ -438,38 +438,38 @@ public void getLogger_String_StringFormatterMessageFactory() { } @Test - public void getLoggerByClass() { + void getLoggerByClass() { final Logger classLogger = LogManager.getLogger(LoggerTest.class); assertNotNull(classLogger); } @Test - public void getLoggerByNullClass() { + void getLoggerByNullClass() { // Returns a SimpleLogger assertNotNull(LogManager.getLogger((Class) null)); } @Test - public void getLoggerByNullObject() { + void getLoggerByNullObject() { // Returns a SimpleLogger assertNotNull(LogManager.getLogger((Object) null)); } @Test - public void getLoggerByNullString() { + void getLoggerByNullString() { // Returns a SimpleLogger assertNotNull(LogManager.getLogger((String) null)); } @Test - public void getLoggerByObject() { + void getLoggerByObject() { final Logger classLogger = LogManager.getLogger(this); assertNotNull(classLogger); assertEquals(classLogger, LogManager.getLogger(LoggerTest.class)); } @Test - public void getRootLogger() { + void getRootLogger() { assertNotNull(LogManager.getRootLogger()); assertNotNull(LogManager.getLogger(Strings.EMPTY)); assertNotNull(LogManager.getLogger(LogManager.ROOT_LOGGER_NAME)); @@ -478,100 +478,100 @@ public void getRootLogger() { } @Test - public void isAllEnabled() { + void isAllEnabled() { assertTrue(logger.isEnabled(Level.ALL), "Incorrect level"); } @Test - public void isDebugEnabled() { + void isDebugEnabled() { assertTrue(logger.isDebugEnabled(), "Incorrect level"); assertTrue(logger.isEnabled(Level.DEBUG), "Incorrect level"); } @Test - public void isErrorEnabled() { + void isErrorEnabled() { assertTrue(logger.isErrorEnabled(), "Incorrect level"); assertTrue(logger.isEnabled(Level.ERROR), "Incorrect level"); } @Test - public void isFatalEnabled() { + void isFatalEnabled() { assertTrue(logger.isFatalEnabled(), "Incorrect level"); assertTrue(logger.isEnabled(Level.FATAL), "Incorrect level"); } @Test - public void isInfoEnabled() { + void isInfoEnabled() { assertTrue(logger.isInfoEnabled(), "Incorrect level"); assertTrue(logger.isEnabled(Level.INFO), "Incorrect level"); } @Test - public void isOffEnabled() { + void isOffEnabled() { assertTrue(logger.isEnabled(Level.OFF), "Incorrect level"); } @Test - public void isTraceEnabled() { + void isTraceEnabled() { assertTrue(logger.isTraceEnabled(), "Incorrect level"); assertTrue(logger.isEnabled(Level.TRACE), "Incorrect level"); } @Test - public void isWarnEnabled() { + void isWarnEnabled() { assertTrue(logger.isWarnEnabled(), "Incorrect level"); assertTrue(logger.isEnabled(Level.WARN), "Incorrect level"); } @Test - public void isAllEnabledWithMarker() { + void isAllEnabledWithMarker() { assertTrue(logger.isEnabled(Level.ALL, marker), "Incorrect level"); } @Test - public void isDebugEnabledWithMarker() { + void isDebugEnabledWithMarker() { assertTrue(logger.isDebugEnabled(marker), "Incorrect level"); assertTrue(logger.isEnabled(Level.DEBUG, marker), "Incorrect level"); } @Test - public void isErrorEnabledWithMarker() { + void isErrorEnabledWithMarker() { assertTrue(logger.isErrorEnabled(marker), "Incorrect level"); assertTrue(logger.isEnabled(Level.ERROR, marker), "Incorrect level"); } @Test - public void isFatalEnabledWithMarker() { + void isFatalEnabledWithMarker() { assertTrue(logger.isFatalEnabled(marker), "Incorrect level"); assertTrue(logger.isEnabled(Level.FATAL, marker), "Incorrect level"); } @Test - public void isInfoEnabledWithMarker() { + void isInfoEnabledWithMarker() { assertTrue(logger.isInfoEnabled(marker), "Incorrect level"); assertTrue(logger.isEnabled(Level.INFO, marker), "Incorrect level"); } @Test - public void isOffEnabledWithMarker() { + void isOffEnabledWithMarker() { assertTrue(logger.isEnabled(Level.OFF, marker), "Incorrect level"); } @Test - public void isTraceEnabledWithMarker() { + void isTraceEnabledWithMarker() { assertTrue(logger.isTraceEnabled(marker), "Incorrect level"); assertTrue(logger.isEnabled(Level.TRACE, marker), "Incorrect level"); } @Test - public void isWarnEnabledWithMarker() { + void isWarnEnabledWithMarker() { assertTrue(logger.isWarnEnabled(marker), "Incorrect level"); assertTrue(logger.isEnabled(Level.WARN, marker), "Incorrect level"); } @Test @UsingThreadContextMap - public void mdc() { + void mdc() { ThreadContext.put("TestYear", Integer.toString(2010)); logger.debug("Debug message"); final String testYear = ThreadContext.get("TestYear"); @@ -588,7 +588,7 @@ public void mdc() { } @Test - public void printf() { + void printf() { logger.printf(Level.DEBUG, "Debug message %d", 1); logger.printf(Level.DEBUG, MarkerManager.getMarker("Test"), "Debug message %d", 2); assertEquals(2, results.size()); @@ -597,12 +597,12 @@ public void printf() { } @BeforeEach - public void setup() { + void setup() { results.clear(); } @Test - public void structuredData() { + void structuredData() { ThreadContext.put("loginId", "JohnDoe"); ThreadContext.put("ipAddress", "192.168.0.120"); ThreadContext.put("locale", Locale.US.getDisplayName()); @@ -621,7 +621,7 @@ public void structuredData() { } @Test - public void throwing() { + void throwing() { logger.throwing(new IllegalArgumentException("Test Exception")); assertEquals(1, results.size()); assertThat( diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/MarkerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/MarkerTest.java index 901f55a0136..411dd5766cd 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/MarkerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/MarkerTest.java @@ -28,21 +28,21 @@ import org.junit.jupiter.api.parallel.ResourceLock; @ResourceLock(value = Log4jStaticResources.MARKER_MANAGER, mode = ResourceAccessMode.READ_WRITE) -public class MarkerTest { +class MarkerTest { @BeforeEach - public void setUp() { + void setUp() { MarkerManager.clear(); } @Test - public void testGetMarker() { + void testGetMarker() { final Marker expected = MarkerManager.getMarker("A"); assertNull(expected.getParents()); } @Test - public void testGetMarkerWithParents() { + void testGetMarkerWithParents() { final Marker expected = MarkerManager.getMarker("A"); final Marker p1 = MarkerManager.getMarker("P1"); p1.addParents(MarkerManager.getMarker("PP1")); @@ -53,7 +53,7 @@ public void testGetMarkerWithParents() { } @Test - public void testHasParents() { + void testHasParents() { final Marker parent = MarkerManager.getMarker("PARENT"); final Marker existing = MarkerManager.getMarker("EXISTING"); assertFalse(existing.hasParents()); @@ -62,7 +62,7 @@ public void testHasParents() { } @Test - public void testMarker() { + void testMarker() { // root (level 1) final Marker parent = MarkerManager.getMarker("PARENT"); // level 2 @@ -83,7 +83,7 @@ public void testMarker() { } @Test - public void testMarkerSharedIntermediaryMarker() { + void testMarkerSharedIntermediaryMarker() { final Marker parent1 = MarkerManager.getMarker("PARENT1"); final Marker parent2 = MarkerManager.getMarker("PARENT2"); final Marker test1 = MarkerManager.getMarker("TEST1").setParents(parent1, parent2); @@ -96,7 +96,7 @@ public void testMarkerSharedIntermediaryMarker() { } @Test - public void testMultipleParents() { + void testMultipleParents() { final Marker parent1 = MarkerManager.getMarker("PARENT1"); final Marker parent2 = MarkerManager.getMarker("PARENT2"); final Marker test1 = MarkerManager.getMarker("TEST1").setParents(parent1, parent2); @@ -112,7 +112,7 @@ public void testMultipleParents() { } @Test - public void testAddToExistingParents() { + void testAddToExistingParents() { final Marker parent = MarkerManager.getMarker("PARENT"); final Marker existing = MarkerManager.getMarker("EXISTING"); final Marker test1 = MarkerManager.getMarker("TEST1").setParents(existing); @@ -124,7 +124,7 @@ public void testAddToExistingParents() { } @Test - public void testDuplicateParents() { + void testDuplicateParents() { final Marker parent = MarkerManager.getMarker("PARENT"); final Marker existing = MarkerManager.getMarker("EXISTING"); final Marker test1 = MarkerManager.getMarker("TEST1").setParents(existing); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/NoopThreadContextTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/NoopThreadContextTest.java index d4ce703b56d..c4d9bebd81c 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/NoopThreadContextTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/NoopThreadContextTest.java @@ -28,10 +28,10 @@ @SetTestProperty(key = "log4j2.disableThreadContext", value = "true") @SetTestProperty(key = "log4j2.disableThreadContextMap", value = "true") @UsingThreadContextMap -public class NoopThreadContextTest { +class NoopThreadContextTest { @Test - public void testNoop() { + void testNoop() { ThreadContext.put("Test", "Test"); final String value = ThreadContext.get("Test"); assertNull(value, "value was saved"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextInheritanceTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextInheritanceTest.java index c800b396a61..8e398910d14 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextInheritanceTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextInheritanceTest.java @@ -37,72 +37,72 @@ @SetTestProperty(key = DefaultThreadContextMap.INHERITABLE_MAP, value = "true") @UsingThreadContextMap @UsingThreadContextStack -public class ThreadContextInheritanceTest { +class ThreadContextInheritanceTest { @BeforeAll - public static void setupClass() { + static void setupClass() { System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true"); ThreadContext.init(); } @AfterAll - public static void tearDownClass() { + static void tearDownClass() { System.clearProperty(DefaultThreadContextMap.INHERITABLE_MAP); ThreadContext.init(); } @Test - public void testPush() { + void testPush() { ThreadContext.push("Hello"); ThreadContext.push("{} is {}", ThreadContextInheritanceTest.class.getSimpleName(), "running"); assertEquals( - ThreadContext.pop(), "ThreadContextInheritanceTest is running", "Incorrect parameterized stack value"); - assertEquals(ThreadContext.pop(), "Hello", "Incorrect simple stack value"); + "ThreadContextInheritanceTest is running", ThreadContext.pop(), "Incorrect parameterized stack value"); + assertEquals("Hello", ThreadContext.pop(), "Incorrect simple stack value"); } @Test @Tag("performance") - public void perfTest() { + void perfTest() { ThreadContextUtilityClass.perfTest(); } @Test - public void testGetContextReturnsEmptyMapIfEmpty() { + void testGetContextReturnsEmptyMapIfEmpty() { ThreadContextUtilityClass.testGetContextReturnsEmptyMapIfEmpty(); } @Test - public void testGetContextReturnsMutableCopy() { + void testGetContextReturnsMutableCopy() { ThreadContextUtilityClass.testGetContextReturnsMutableCopy(); } @Test - public void testGetImmutableContextReturnsEmptyMapIfEmpty() { + void testGetImmutableContextReturnsEmptyMapIfEmpty() { ThreadContextUtilityClass.testGetImmutableContextReturnsEmptyMapIfEmpty(); } @Test - public void testGetImmutableContextReturnsImmutableMapIfNonEmpty() { + void testGetImmutableContextReturnsImmutableMapIfNonEmpty() { ThreadContextUtilityClass.testGetImmutableContextReturnsImmutableMapIfNonEmpty(); } @Test - public void testGetImmutableContextReturnsImmutableMapIfEmpty() { + void testGetImmutableContextReturnsImmutableMapIfEmpty() { ThreadContextUtilityClass.testGetImmutableContextReturnsImmutableMapIfEmpty(); } @Test - public void testGetImmutableStackReturnsEmptyStackIfEmpty() { + void testGetImmutableStackReturnsEmptyStackIfEmpty() { ThreadContextUtilityClass.testGetImmutableStackReturnsEmptyStackIfEmpty(); } @Test - public void testPut() { + void testPut() { ThreadContextUtilityClass.testPut(); } @Test - public void testRemove() { + void testRemove() { ThreadContext.clearMap(); assertNull(ThreadContext.get("testKey")); ThreadContext.put("testKey", "testValue"); @@ -114,7 +114,7 @@ public void testRemove() { } @Test - public void testContainsKey() { + void testContainsKey() { ThreadContext.clearMap(); assertFalse(ThreadContext.containsKey("testKey")); ThreadContext.put("testKey", "testValue"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextTest.java index e84958bcf05..a06fd7c2611 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/ThreadContextTest.java @@ -30,18 +30,18 @@ import org.junit.jupiter.api.Test; @UsingAnyThreadContext -public class ThreadContextTest { +class ThreadContextTest { @Test - public void testPush() { + void testPush() { ThreadContext.push("Hello"); ThreadContext.push("{} is {}", ThreadContextTest.class.getSimpleName(), "running"); - assertEquals(ThreadContext.pop(), "ThreadContextTest is running", "Incorrect parameterized stack value"); - assertEquals(ThreadContext.pop(), "Hello", "Incorrect simple stack value"); + assertEquals("ThreadContextTest is running", ThreadContext.pop(), "Incorrect parameterized stack value"); + assertEquals("Hello", ThreadContext.pop(), "Incorrect simple stack value"); } @Test - public void testInheritanceSwitchedOffByDefault() throws Exception { + void testInheritanceSwitchedOffByDefault() throws Exception { ThreadContext.put("Greeting", "Hello"); StringBuilder sb = new StringBuilder(); TestThread thread = new TestThread(sb); @@ -59,47 +59,47 @@ public void testInheritanceSwitchedOffByDefault() throws Exception { @Test @Tag("performance") - public void perfTest() { + void perfTest() { ThreadContextUtilityClass.perfTest(); } @Test - public void testGetContextReturnsEmptyMapIfEmpty() { + void testGetContextReturnsEmptyMapIfEmpty() { ThreadContextUtilityClass.testGetContextReturnsEmptyMapIfEmpty(); } @Test - public void testGetContextReturnsMutableCopy() { + void testGetContextReturnsMutableCopy() { ThreadContextUtilityClass.testGetContextReturnsMutableCopy(); } @Test - public void testGetImmutableContextReturnsEmptyMapIfEmpty() { + void testGetImmutableContextReturnsEmptyMapIfEmpty() { ThreadContextUtilityClass.testGetImmutableContextReturnsEmptyMapIfEmpty(); } @Test - public void testGetImmutableContextReturnsImmutableMapIfNonEmpty() { + void testGetImmutableContextReturnsImmutableMapIfNonEmpty() { ThreadContextUtilityClass.testGetImmutableContextReturnsImmutableMapIfNonEmpty(); } @Test - public void testGetImmutableContextReturnsImmutableMapIfEmpty() { + void testGetImmutableContextReturnsImmutableMapIfEmpty() { ThreadContextUtilityClass.testGetImmutableContextReturnsImmutableMapIfEmpty(); } @Test - public void testGetImmutableStackReturnsEmptyStackIfEmpty() { + void testGetImmutableStackReturnsEmptyStackIfEmpty() { ThreadContextUtilityClass.testGetImmutableStackReturnsEmptyStackIfEmpty(); } @Test - public void testPut() { + void testPut() { ThreadContextUtilityClass.testPut(); } @Test - public void testPutIfNotNull() { + void testPutIfNotNull() { ThreadContext.clearMap(); assertNull(ThreadContext.get("testKey")); ThreadContext.put("testKey", "testValue"); @@ -111,7 +111,7 @@ public void testPutIfNotNull() { } @Test - public void testPutAll() { + void testPutAll() { assertTrue(ThreadContext.isEmpty()); assertFalse(ThreadContext.containsKey("key")); final int mapSize = 10; @@ -128,7 +128,7 @@ public void testPutAll() { } @Test - public void testRemove() { + void testRemove() { assertNull(ThreadContext.get("testKey")); ThreadContext.put("testKey", "testValue"); assertEquals("testValue", ThreadContext.get("testKey")); @@ -139,7 +139,7 @@ public void testRemove() { } @Test - public void testRemoveAll() { + void testRemoveAll() { ThreadContext.put("testKey1", "testValue1"); ThreadContext.put("testKey2", "testValue2"); assertEquals("testValue1", ThreadContext.get("testKey1")); @@ -153,7 +153,7 @@ public void testRemoveAll() { } @Test - public void testContainsKey() { + void testContainsKey() { assertFalse(ThreadContext.containsKey("testKey")); ThreadContext.put("testKey", "testValue"); assertTrue(ThreadContext.containsKey("testKey")); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/TraceLoggingTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/TraceLoggingTest.java index c8227698f33..dcc16803baa 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/TraceLoggingTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/TraceLoggingTest.java @@ -32,7 +32,7 @@ import org.apache.logging.log4j.spi.AbstractLogger; import org.junit.jupiter.api.Test; -public class TraceLoggingTest extends AbstractLogger { +class TraceLoggingTest extends AbstractLogger { static final StringBuilder CHAR_SEQ = new StringBuilder("CharSeq"); private int charSeqCount; private int objectCount; @@ -323,7 +323,7 @@ public void logMessage( } @Test - public void testTraceEntryExit() { + void testTraceEntryExit() { currentLevel = Level.TRACE; final FlowMessageFactory fact = new DefaultFlowMessageFactory(); @@ -348,7 +348,7 @@ public void testTraceEntryExit() { } @Test - public void testTraceEntryMessage() { + void testTraceEntryMessage() { currentLevel = Level.TRACE; final FlowMessageFactory fact = new DefaultFlowMessageFactory(); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/DefaultLogBuilderTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/DefaultLogBuilderTest.java index 3ed88257cb2..4bff93565cd 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/DefaultLogBuilderTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/DefaultLogBuilderTest.java @@ -25,13 +25,13 @@ import org.apache.logging.log4j.test.TestLogger; import org.junit.jupiter.api.Test; -public class DefaultLogBuilderTest { +class DefaultLogBuilderTest { private final TestLogger logger1 = (TestLogger) LogManager.getLogger(DefaultLogBuilderTest.class); private final TestLogger logger2 = (TestLogger) LogManager.getLogger("second.logger"); @Test - public void testConcurrentUsage() { + void testConcurrentUsage() { logger1.getEntries().clear(); logger2.getEntries().clear(); final List logBuilders = diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/map/UnmodifiableArrayBackedMapTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/map/UnmodifiableArrayBackedMapTest.java index 092c082ed4e..612840bbf5e 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/map/UnmodifiableArrayBackedMapTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/internal/map/UnmodifiableArrayBackedMapTest.java @@ -20,6 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -37,7 +38,7 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; -public class UnmodifiableArrayBackedMapTest { +class UnmodifiableArrayBackedMapTest { private static final int TEST_DATA_SIZE = 5; private HashMap getTestParameters() { @@ -54,25 +55,25 @@ private HashMap getTestParameters(int numParams) { } @Test - public void testCopyAndPut() { + void testCopyAndPut() { UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP; testMap = testMap.copyAndPut("6", "value6"); assertTrue(testMap.containsKey("6")); - assertEquals(testMap.get("6"), "value6"); + assertEquals("value6", testMap.get("6")); testMap = testMap.copyAndPut("6", "another value"); assertTrue(testMap.containsKey("6")); - assertEquals(testMap.get("6"), "another value"); + assertEquals("another value", testMap.get("6")); HashMap newValues = getTestParameters(); testMap = testMap.copyAndPutAll(newValues); - assertEquals(testMap.get("1"), "value1"); - assertEquals(testMap.get("4"), "value4"); - assertEquals(testMap.get("6"), "another value"); + assertEquals("value1", testMap.get("1")); + assertEquals("value4", testMap.get("4")); + assertEquals("another value", testMap.get("6")); } @Test - public void testCopyAndRemove() { + void testCopyAndRemove() { // general removing from well-populated set HashMap params = getTestParameters(); UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); @@ -104,7 +105,7 @@ public void testCopyAndRemove() { } @Test - public void testCopyAndRemoveAll() { + void testCopyAndRemoveAll() { HashMap initialMapContents = getTestParameters(15); initialMapContents.put("extra_key", "extra_value"); @@ -138,23 +139,23 @@ public void testCopyAndRemoveAll() { assertEquals(testMapWithSetRemoval, testMapWithArrayListRemoval); testMap = UnmodifiableArrayBackedMap.EMPTY_MAP; - assertEquals(testMap.copyAndRemoveAll(initialMapContents.keySet()).size(), 0); + assertEquals(0, testMap.copyAndRemoveAll(initialMapContents.keySet()).size()); testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPut("test", "test"); - assertEquals(testMap.copyAndRemoveAll(initialMapContents.keySet()).size(), 1); + assertEquals(1, testMap.copyAndRemoveAll(initialMapContents.keySet()).size()); testMap = testMap.copyAndRemoveAll(Collections.singleton("not found")); - assertEquals(testMap.copyAndRemoveAll(testMap.keySet()).size(), 0); + assertEquals(0, testMap.copyAndRemoveAll(testMap.keySet()).size()); testMap = testMap.copyAndRemoveAll(Collections.singleton("test")); - assertEquals(testMap.copyAndRemoveAll(testMap.keySet()).size(), 0); + assertEquals(0, testMap.copyAndRemoveAll(testMap.keySet()).size()); } @Test - public void testEmptyMap() { + void testEmptyMap() { assertNull(UnmodifiableArrayBackedMap.EMPTY_MAP.get("test")); } @Test - public void testEntrySetIteratorAndSize() { + void testEntrySetIteratorAndSize() { UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(getTestParameters()); Set> entrySet = testMap.entrySet(); int numEntriesFound = 0; @@ -167,7 +168,7 @@ public void testEntrySetIteratorAndSize() { } @Test - public void testEntrySetMutatorsBlocked() { + void testEntrySetMutatorsBlocked() { UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(getTestParameters()); Set> entrySet = testMap.entrySet(); for (Map.Entry entry : entrySet) { @@ -199,7 +200,7 @@ public void testEntrySetMutatorsBlocked() { * as well as UnmodifiableArrayBackedMap.equals(HashMap). */ @Test - public void testEqualsHashCodeWithIdenticalContent() { + void testEqualsHashCodeWithIdenticalContent() { HashMap params = getTestParameters(); UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); assertEquals(params, testMap); @@ -208,18 +209,18 @@ public void testEqualsHashCodeWithIdenticalContent() { } @Test - public void testEqualsHashCodeWithOneEmptyMap() { + void testEqualsHashCodeWithOneEmptyMap() { HashMap params = getTestParameters(); UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); // verify empty maps are not equal to non-empty maps - assertNotEquals(params, UnmodifiableArrayBackedMap.EMPTY_MAP); + assertNotEquals(UnmodifiableArrayBackedMap.EMPTY_MAP, params); assertNotEquals(new HashMap<>(), testMap); assertNotEquals(UnmodifiableArrayBackedMap.EMPTY_MAP, params); - assertNotEquals(testMap, new HashMap<>()); + assertNotEquals(new HashMap<>(), testMap); } @Test - public void testEqualsHashCodeWithOneKeyRemoved() { + void testEqualsHashCodeWithOneKeyRemoved() { HashMap params = getTestParameters(); UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); @@ -233,7 +234,7 @@ public void testEqualsHashCodeWithOneKeyRemoved() { } @Test - public void testEqualsWhenOneValueDiffers() { + void testEqualsWhenOneValueDiffers() { HashMap params = getTestParameters(); UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); assertNotEquals(params, testMap.copyAndPut("1", "different value")); @@ -241,7 +242,7 @@ public void testEqualsWhenOneValueDiffers() { } @Test - public void testForEachBiConsumer_JavaUtil() { + void testForEachBiConsumer_JavaUtil() { final Map map = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(getTestParameters()); final Collection keys = new HashSet<>(); map.forEach((key, value) -> keys.add(key)); @@ -249,7 +250,7 @@ public void testForEachBiConsumer_JavaUtil() { } @Test - public void testForEachBiConsumer_Log4jUtil() { + void testForEachBiConsumer_Log4jUtil() { final ReadOnlyStringMap map = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(getTestParameters()); final Collection keys = new HashSet<>(); map.forEach((key, value) -> keys.add(key)); @@ -257,7 +258,7 @@ public void testForEachBiConsumer_Log4jUtil() { } @Test - public void testForEachTriConsumer() { + void testForEachTriConsumer() { UnmodifiableArrayBackedMap map = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(getTestParameters()); HashMap iterationResultMap = new HashMap<>(); TriConsumer> triConsumer = @@ -272,7 +273,7 @@ public void accept(String k, String v, Map s) { } @Test - public void testImmutability() { + void testImmutability() { HashMap params = getTestParameters(); UnmodifiableArrayBackedMap originalMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); UnmodifiableArrayBackedMap modifiedMap = originalMap.copyAndPutAll(getTestParameters()); @@ -285,7 +286,7 @@ public void testImmutability() { } @Test - public void testInstanceCopy() { + void testInstanceCopy() { HashMap params = getTestParameters(); UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); @@ -294,7 +295,7 @@ public void testInstanceCopy() { } @Test - public void testMutatorsBlocked() { + void testMutatorsBlocked() { UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(getTestParameters()); try { testMap.put("a", "a"); @@ -322,18 +323,18 @@ public void testMutatorsBlocked() { } @Test - public void testNullValue() { + void testNullValue() { UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP; testMap = testMap.copyAndPut("key", null); assertTrue(testMap.containsKey("key")); assertTrue(testMap.containsValue(null)); - assertTrue(testMap.size() == 1); - assertEquals(testMap.get("key"), null); + assertEquals(1, testMap.size()); + assertNull(testMap.get("key")); } @Test - public void testReads() { - assertEquals(UnmodifiableArrayBackedMap.EMPTY_MAP.get("test"), null); + void testReads() { + assertNull(UnmodifiableArrayBackedMap.EMPTY_MAP.get("test")); HashMap params = getTestParameters(); UnmodifiableArrayBackedMap testMap = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPutAll(params); for (Map.Entry entry : params.entrySet()) { @@ -345,11 +346,11 @@ public void testReads() { } assertFalse(testMap.containsKey("not_present")); assertFalse(testMap.containsValue("not_present")); - assertEquals(null, testMap.get("not_present")); + assertNull(testMap.get("not_present")); } @Test - public void testState() { + void testState() { UnmodifiableArrayBackedMap originalMap; UnmodifiableArrayBackedMap newMap; @@ -369,10 +370,10 @@ public void testState() { } @Test - public void testToMap() { + void testToMap() { UnmodifiableArrayBackedMap map = UnmodifiableArrayBackedMap.EMPTY_MAP.copyAndPut("test", "test"); // verify same instance, not just equals() - assertTrue(map == map.toMap()); + assertSame(map, map.toMap()); } @Test diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/FormattedMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/FormattedMessageTest.java index 72518c97241..f2a35b2474a 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/FormattedMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/FormattedMessageTest.java @@ -33,7 +33,7 @@ import org.junit.jupiter.api.parallel.Resources; @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) -public class FormattedMessageTest { +class FormattedMessageTest { private static final String SPACE = Constants.JAVA_MAJOR_VERSION < 9 ? " " : "\u00a0"; @@ -41,7 +41,7 @@ public class FormattedMessageTest { String[] array = new String[LOOP_CNT]; @Test - public void testStringNoArgs() { + void testStringNoArgs() { final String testMsg = "Test message %1s"; FormattedMessage msg = new FormattedMessage(testMsg, (Object[]) null); String result = msg.getFormattedMessage(); @@ -54,7 +54,7 @@ public void testStringNoArgs() { } @Test - public void tesStringOneStringArg() { + void tesStringOneStringArg() { final String testMsg = "Test message %1s"; final FormattedMessage msg = new FormattedMessage(testMsg, "Apache"); final String result = msg.getFormattedMessage(); @@ -63,7 +63,7 @@ public void tesStringOneStringArg() { } @Test - public void tesStringOneArgLocaleFrance_StringFormattedMessage() { + void tesStringOneArgLocaleFrance_StringFormattedMessage() { final String testMsg = "Test message e = %+10.4f"; final FormattedMessage msg = new FormattedMessage(Locale.FRANCE, testMsg, Math.E); final String result = msg.getFormattedMessage(); @@ -72,7 +72,7 @@ public void tesStringOneArgLocaleFrance_StringFormattedMessage() { } @Test - public void tesStringOneArgLocaleFrance_MessageFormatMessage() { + void tesStringOneArgLocaleFrance_MessageFormatMessage() { final String testMsg = "Test message {0,number,currency}"; final FormattedMessage msg = new FormattedMessage(Locale.FRANCE, testMsg, 12); final String result = msg.getFormattedMessage(); @@ -81,7 +81,7 @@ public void tesStringOneArgLocaleFrance_MessageFormatMessage() { } @Test - public void tesStringOneArgLocaleUs_MessageFormatMessage() { + void tesStringOneArgLocaleUs_MessageFormatMessage() { final String testMsg = "Test message {0,number,currency}"; final FormattedMessage msg = new FormattedMessage(Locale.US, testMsg, 12); final String result = msg.getFormattedMessage(); @@ -90,7 +90,7 @@ public void tesStringOneArgLocaleUs_MessageFormatMessage() { } @Test - public void tesStringOneArgLocaleUs() { + void tesStringOneArgLocaleUs() { final String testMsg = "Test message e = %+10.4f"; final FormattedMessage msg = new FormattedMessage(Locale.US, testMsg, Math.E); final String result = msg.getFormattedMessage(); @@ -99,7 +99,7 @@ public void tesStringOneArgLocaleUs() { } @Test - public void testNoArgs() { + void testNoArgs() { final String testMsg = "Test message {0}"; FormattedMessage msg = new FormattedMessage(testMsg, (Object[]) null); String result = msg.getFormattedMessage(); @@ -112,7 +112,7 @@ public void testNoArgs() { } @Test - public void testOneArg() { + void testOneArg() { final String testMsg = "Test message {0}"; final FormattedMessage msg = new FormattedMessage(testMsg, "Apache"); final String result = msg.getFormattedMessage(); @@ -121,7 +121,7 @@ public void testOneArg() { } @Test - public void testParamNoArgs() { + void testParamNoArgs() { final String testMsg = "Test message {}"; FormattedMessage msg = new FormattedMessage(testMsg, (Object[]) null); String result = msg.getFormattedMessage(); @@ -133,7 +133,7 @@ public void testParamNoArgs() { } @Test - public void testUnsafeWithMutableParams() { // LOG4J2-763 + void testUnsafeWithMutableParams() { // LOG4J2-763 final String testMsg = "Test message %s"; final Mutable param = new Mutable().set("abc"); final FormattedMessage msg = new FormattedMessage(testMsg, param); @@ -145,7 +145,7 @@ public void testUnsafeWithMutableParams() { // LOG4J2-763 } @Test - public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 + void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 final String testMsg = "Test message %s"; final Mutable param = new Mutable().set("abc"); final FormattedMessage msg = new FormattedMessage(testMsg, param); @@ -158,7 +158,7 @@ public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 } @Test - public void testSerialization() throws IOException, ClassNotFoundException { + void testSerialization() throws IOException, ClassNotFoundException { final FormattedMessage expected = new FormattedMessage("Msg", "a", "b", "c"); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final ObjectOutputStream out = new ObjectOutputStream(baos)) { diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageFactoryTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageFactoryTest.java index 7375e71797e..06d3fb8088e 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageFactoryTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageFactoryTest.java @@ -25,10 +25,10 @@ /** * Tests {@link LocalizedMessageFactory}. */ -public class LocalizedMessageFactoryTest { +class LocalizedMessageFactoryTest { @Test - public void testMessageMarkersDataNo() { + void testMessageMarkersDataNo() { final LocalizedMessageFactory localizedMessageFactory = new LocalizedMessageFactory(ResourceBundle.getBundle("MF", Locale.US)); final Message message = localizedMessageFactory.newMessage("msg1"); @@ -36,7 +36,7 @@ public void testMessageMarkersDataNo() { } @Test - public void testMessageMarkersNoDataYes() { + void testMessageMarkersNoDataYes() { final LocalizedMessageFactory localizedMessageFactory = new LocalizedMessageFactory(ResourceBundle.getBundle("MF", Locale.US)); final Message message = localizedMessageFactory.newMessage("msg1", 1, "two"); @@ -44,7 +44,7 @@ public void testMessageMarkersNoDataYes() { } @Test - public void testNewMessage() { + void testNewMessage() { final LocalizedMessageFactory localizedMessageFactory = new LocalizedMessageFactory(ResourceBundle.getBundle("MF", Locale.US)); final Message message = localizedMessageFactory.newMessage("hello_world"); @@ -52,7 +52,7 @@ public void testNewMessage() { } @Test - public void testNoMatch() { + void testNoMatch() { final LocalizedMessageFactory localizedMessageFactory = new LocalizedMessageFactory(ResourceBundle.getBundle("MF", Locale.US)); final Message message = localizedMessageFactory.newMessage("no match"); @@ -60,7 +60,7 @@ public void testNoMatch() { } @Test - public void testNoMatchPercentInMessageNoArgsNo() { + void testNoMatchPercentInMessageNoArgsNo() { // LOG4J2-3458 LocalizedMessage causes a lot of noise on the console // // ERROR StatusLogger Unable to format msg: C:/Program%20Files/Some%20Company/Some%20Product%20Name/ @@ -87,7 +87,7 @@ public void testNoMatchPercentInMessageNoArgsNo() { } @Test - public void testNoMatchPercentInMessageArgsYes() { + void testNoMatchPercentInMessageArgsYes() { final LocalizedMessageFactory localizedMessageFactory = new LocalizedMessageFactory(ResourceBundle.getBundle("MF", Locale.US)); final Message message = localizedMessageFactory.newMessage( diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageTest.java index e2af8b65fbe..832230d53c8 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/LocalizedMessageTest.java @@ -31,21 +31,21 @@ * Tests LocalizedMessage. */ @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) -public class LocalizedMessageTest { +class LocalizedMessageTest { private T roundtrip(final T msg) { return SerializationUtils.roundtrip(msg); } @Test - public void testMessageFormat() { + void testMessageFormat() { final LocalizedMessage msg = new LocalizedMessage("MF", new Locale("en", "US"), "msg1", new Object[] {"1", "Test"}); assertEquals("This is test number 1 with string argument Test.", msg.getFormattedMessage()); } @Test - public void testSerializationMessageFormat() { + void testSerializationMessageFormat() { final LocalizedMessage msg = new LocalizedMessage("MF", new Locale("en", "US"), "msg1", new Object[] {"1", "Test"}); assertEquals("This is test number 1 with string argument Test.", msg.getFormattedMessage()); @@ -54,7 +54,7 @@ public void testSerializationMessageFormat() { } @Test - public void testSerializationStringFormat() { + void testSerializationStringFormat() { final LocalizedMessage msg = new LocalizedMessage("SF", new Locale("en", "US"), "msg1", new Object[] {"1", "Test"}); assertEquals("This is test number 1 with string argument Test.", msg.getFormattedMessage()); @@ -63,14 +63,14 @@ public void testSerializationStringFormat() { } @Test - public void testStringFormat() { + void testStringFormat() { final LocalizedMessage msg = new LocalizedMessage("SF", new Locale("en", "US"), "msg1", new Object[] {"1", "Test"}); assertEquals("This is test number 1 with string argument Test.", msg.getFormattedMessage()); } @Test - public void testUnsafeWithMutableParams() { // LOG4J2-763 + void testUnsafeWithMutableParams() { // LOG4J2-763 final String testMsg = "Test message %s"; final Mutable param = new Mutable().set("abc"); final LocalizedMessage msg = new LocalizedMessage(testMsg, param); @@ -82,7 +82,7 @@ public void testUnsafeWithMutableParams() { // LOG4J2-763 } @Test - public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 + void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 final String testMsg = "Test message %s"; final Mutable param = new Mutable().set("abc"); final LocalizedMessage msg = new LocalizedMessage(testMsg, param); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MapMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MapMessageTest.java index 048801128d8..a36bb6b4ae9 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MapMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MapMessageTest.java @@ -35,10 +35,10 @@ /** * */ -public class MapMessageTest { +class MapMessageTest { @Test - public void testMap() { + void testMap() { final String testMsg = "Test message {}"; final StringMapMessage msg = new StringMapMessage(); msg.put("message", testMsg); @@ -49,7 +49,7 @@ public void testMap() { } @Test - public void testBuilder() { + void testBuilder() { final String testMsg = "Test message {}"; final StringMapMessage msg = new StringMapMessage().with("message", testMsg).with("project", "Log4j"); @@ -59,7 +59,7 @@ public void testBuilder() { } @Test - public void testXML() { + void testXML() { final String testMsg = "Test message {}"; final StringMapMessage msg = new StringMapMessage(); msg.put("message", testMsg); @@ -71,7 +71,7 @@ public void testXML() { } @Test - public void testXMLEscape() { + void testXMLEscape() { final String testMsg = "Test message "; final StringMapMessage msg = new StringMapMessage(); msg.put("message", testMsg); @@ -81,7 +81,7 @@ public void testXMLEscape() { } @Test - public void testJSON() { + void testJSON() { final String testMsg = "Test message {}"; final StringMapMessage msg = new StringMapMessage(); msg.put("message", testMsg); @@ -92,7 +92,7 @@ public void testJSON() { } @Test - public void testJSONEscape() { + void testJSONEscape() { final String testMsg = "Test message \"Hello, World!\""; final StringMapMessage msg = new StringMapMessage(); msg.put("message", testMsg); @@ -102,7 +102,7 @@ public void testJSONEscape() { } @Test - public void testJSONEscapeNewlineAndOtherControlCharacters() { + void testJSONEscapeNewlineAndOtherControlCharacters() { final String testMsg = "hello\tworld\r\nhh\bere is it\f"; final StringMapMessage msg = new StringMapMessage(); msg.put("one\ntwo", testMsg); @@ -112,7 +112,7 @@ public void testJSONEscapeNewlineAndOtherControlCharacters() { } @Test - public void testJsonFormatterNestedObjectSupport() { + void testJsonFormatterNestedObjectSupport() { final Map map = new LinkedHashMap<>(); map.put("chars", new char[] {'a', 'b', 'c'}); map.put("booleans", new boolean[] {true, false}); @@ -157,7 +157,7 @@ public void testJsonFormatterNestedObjectSupport() { } @Test - public void testJsonFormatterInfiniteRecursionPrevention() { + void testJsonFormatterInfiniteRecursionPrevention() { final List recursiveValue = Arrays.asList(1, null); // noinspection CollectionAddedToSelf recursiveValue.set(1, recursiveValue); @@ -167,13 +167,13 @@ public void testJsonFormatterInfiniteRecursionPrevention() { } @Test - public void testJsonFormatterMaxDepthViolation() { + void testJsonFormatterMaxDepthViolation() { assertThrows( IllegalArgumentException.class, () -> testJsonFormatterMaxDepth(MapMessageJsonFormatter.MAX_DEPTH - 1)); } @Test - public void testJsonFormatterMaxDepthConformance() { + void testJsonFormatterMaxDepthConformance() { final int depth = MapMessageJsonFormatter.MAX_DEPTH - 2; final String expectedJson = String.format( "{'key':%s1%s}", StringUtils.repeat("[", depth), StringUtils.repeat("]", depth)) @@ -193,7 +193,7 @@ public static String testJsonFormatterMaxDepth(final int depth) { } @Test - public void testJava() { + void testJava() { final String testMsg = "Test message {}"; final StringMapMessage msg = new StringMapMessage(); msg.put("message", testMsg); @@ -204,7 +204,7 @@ public void testJava() { } @Test - public void testMutableByDesign() { // LOG4J2-763 + void testMutableByDesign() { // LOG4J2-763 final StringMapMessage msg = new StringMapMessage(); // modify parameter before calling msg.getFormattedMessage @@ -222,21 +222,21 @@ public void testMutableByDesign() { // LOG4J2-763 } @Test - public void testGetNonStringValue() { + void testGetNonStringValue() { final String key = "Key"; final ObjectMapMessage msg = new ObjectMapMessage().with(key, 1L); assertEquals("1", msg.get(key)); } @Test - public void testRemoveNonStringValue() { + void testRemoveNonStringValue() { final String key = "Key"; final ObjectMapMessage msg = new ObjectMapMessage().with(key, 1L); assertEquals("1", msg.remove(key)); } @Test - public void testJSONFormatNonStringValue() { + void testJSONFormatNonStringValue() { final ObjectMapMessage msg = new ObjectMapMessage().with("key", 1L); final String result = msg.getFormattedMessage(new String[] {"JSON"}); final String expected = "{'key':1}".replace('\'', '"'); @@ -244,7 +244,7 @@ public void testJSONFormatNonStringValue() { } @Test - public void testXMLFormatNonStringValue() { + void testXMLFormatNonStringValue() { final ObjectMapMessage msg = new ObjectMapMessage().with("key", 1L); final String result = msg.getFormattedMessage(new String[] {"XML"}); final String expected = "\n 1\n"; @@ -252,7 +252,7 @@ public void testXMLFormatNonStringValue() { } @Test - public void testFormatToUsedInOutputXml() { + void testFormatToUsedInOutputXml() { final ObjectMapMessage msg = new ObjectMapMessage().with("key", new FormattableTestType()); final String result = msg.getFormattedMessage(new String[] {"XML"}); final String expected = "\n formatTo\n"; @@ -260,7 +260,7 @@ public void testFormatToUsedInOutputXml() { } @Test - public void testFormatToUsedInOutputJson() { + void testFormatToUsedInOutputJson() { final ObjectMapMessage msg = new ObjectMapMessage().with("key", new FormattableTestType()); final String result = msg.getFormattedMessage(new String[] {"JSON"}); final String expected = "{\"key\":\"formatTo\"}"; @@ -268,7 +268,7 @@ public void testFormatToUsedInOutputJson() { } @Test - public void testFormatToUsedInOutputJava() { + void testFormatToUsedInOutputJava() { final ObjectMapMessage msg = new ObjectMapMessage().with("key", new FormattableTestType()); final String result = msg.getFormattedMessage(new String[] {"JAVA"}); final String expected = "{key=\"formatTo\"}"; @@ -276,7 +276,7 @@ public void testFormatToUsedInOutputJava() { } @Test - public void testFormatToUsedInOutputDefault() { + void testFormatToUsedInOutputDefault() { final ObjectMapMessage msg = new ObjectMapMessage().with("key", new FormattableTestType()); final String result = msg.getFormattedMessage(null); final String expected = "key=\"formatTo\""; @@ -284,7 +284,7 @@ public void testFormatToUsedInOutputDefault() { } @Test - public void testGetUsesDeepToString() { + void testGetUsesDeepToString() { final String key = "key"; final ObjectMapMessage msg = new ObjectMapMessage().with(key, new FormattableTestType()); final String result = msg.get(key); @@ -293,7 +293,7 @@ public void testGetUsesDeepToString() { } @Test - public void testRemoveUsesDeepToString() { + void testRemoveUsesDeepToString() { final String key = "key"; final ObjectMapMessage msg = new ObjectMapMessage().with(key, new FormattableTestType()); final String result = msg.remove(key); @@ -302,14 +302,14 @@ public void testRemoveUsesDeepToString() { } @Test - public void testTime() throws Exception { + void testTime() { final Time time = new Time(12, 5, 5); final ObjectMapMessage message = new ObjectMapMessage().with("time", time); - assertEquals("time=\"" + time.toString() + "\"", message.getFormattedMessage(), "Incorrect time format"); + assertEquals("time=\"" + time + "\"", message.getFormattedMessage(), "Incorrect time format"); } @Test - public void testDate() { + void testDate() { final Date date = new Date(System.currentTimeMillis()); final ObjectMapMessage message = new ObjectMapMessage().with("date", date); assertEquals("date=\"" + date + "\"", message.getFormattedMessage(), "Incorrect date format"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatMessageTest.java index a2cd664daff..44fc67cc383 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatMessageTest.java @@ -30,7 +30,7 @@ import org.junit.jupiter.api.parallel.Resources; @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) -public class MessageFormatMessageTest { +class MessageFormatMessageTest { private static final char SPACE = ' '; private static final char NB_SPACE = '\u00a0'; @@ -40,7 +40,7 @@ public class MessageFormatMessageTest { String[] array = new String[LOOP_CNT]; @Test - public void testNoArgs() { + void testNoArgs() { final String testMsg = "Test message {0}"; MessageFormatMessage msg = new MessageFormatMessage(testMsg, (Object[]) null); String result = msg.getFormattedMessage(); @@ -54,7 +54,7 @@ public void testNoArgs() { } @Test - public void testOneStringArg() { + void testOneStringArg() { final String testMsg = "Test message {0}"; final MessageFormatMessage msg = new MessageFormatMessage(testMsg, "Apache"); final String result = msg.getFormattedMessage(); @@ -63,7 +63,7 @@ public void testOneStringArg() { } @Test - public void testOneIntArgLocaleUs() { + void testOneIntArgLocaleUs() { final String testMsg = "Test message {0,number,currency}"; final MessageFormatMessage msg = new MessageFormatMessage(Locale.US, testMsg, 1234567890); final String result = msg.getFormattedMessage(); @@ -72,7 +72,7 @@ public void testOneIntArgLocaleUs() { } @Test - public void testOneIntArgLocaleFrance() { + void testOneIntArgLocaleFrance() { final String testMsg = "Test message {0,number,currency}"; final MessageFormatMessage msg = new MessageFormatMessage(Locale.FRANCE, testMsg, 1234567890); final String result = msg.getFormattedMessage(); @@ -84,7 +84,7 @@ public void testOneIntArgLocaleFrance() { } @Test - public void testException() { + void testException() { final String testMsg = "Test message {0}"; final MessageFormatMessage msg = new MessageFormatMessage(testMsg, "Apache", new NullPointerException("Null")); final String result = msg.getFormattedMessage(); @@ -95,7 +95,7 @@ public void testException() { } @Test - public void testUnsafeWithMutableParams() { // LOG4J2-763 + void testUnsafeWithMutableParams() { // LOG4J2-763 final String testMsg = "Test message {0}"; final Mutable param = new Mutable().set("abc"); final MessageFormatMessage msg = new MessageFormatMessage(testMsg, param); @@ -107,7 +107,7 @@ public void testUnsafeWithMutableParams() { // LOG4J2-763 } @Test - public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 + void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 final String testMsg = "Test message {0}"; final Mutable param = new Mutable().set("abc"); final MessageFormatMessage msg = new MessageFormatMessage(testMsg, param); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatsPerfTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatsPerfTest.java index 374c9f15ba2..90fe41b7aed 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatsPerfTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/MessageFormatsPerfTest.java @@ -29,7 +29,7 @@ */ @Tag("performance") @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) -public class MessageFormatsPerfTest { +class MessageFormatsPerfTest { private static final int LOOP_CNT = 500; String[] array = new String[LOOP_CNT]; @@ -39,7 +39,7 @@ public class MessageFormatsPerfTest { private static long formattedTime = 0; @AfterAll - public static void after() { + static void after() { if (stringTime > paramTime) { System.out.println(String.format( "Parameterized is %1$.2f times faster than StringFormat.", ((float) stringTime / paramTime))); @@ -70,7 +70,7 @@ public static void after() { } @Test - public void testStringPerf() { + void testStringPerf() { final String testMsg = "Test message %1s %2s"; final Timer timer = new Timer("StringFormat", LOOP_CNT); timer.start(); @@ -80,11 +80,11 @@ public void testStringPerf() { } timer.stop(); stringTime = timer.getElapsedNanoTime(); - System.out.println(timer.toString()); + System.out.println(timer); } @Test - public void testMessageFormatPerf() { + void testMessageFormatPerf() { final String testMsg = "Test message {0} {1}"; final Timer timer = new Timer("MessageFormat", LOOP_CNT); timer.start(); @@ -94,11 +94,11 @@ public void testMessageFormatPerf() { } timer.stop(); msgFormatTime = timer.getElapsedNanoTime(); - System.out.println(timer.toString()); + System.out.println(timer); } @Test - public void testParameterizedPerf() { + void testParameterizedPerf() { final String testMsg = "Test message {} {}"; final Timer timer = new Timer("Parameterized", LOOP_CNT); timer.start(); @@ -108,11 +108,11 @@ public void testParameterizedPerf() { } timer.stop(); paramTime = timer.getElapsedNanoTime(); - System.out.println(timer.toString()); + System.out.println(timer); } @Test - public void testFormattedParameterizedPerf() { + void testFormattedParameterizedPerf() { final String testMsg = "Test message {} {}"; final Timer timer = new Timer("FormattedParameterized", LOOP_CNT); timer.start(); @@ -122,6 +122,6 @@ public void testFormattedParameterizedPerf() { } timer.stop(); formattedTime = timer.getElapsedNanoTime(); - System.out.println(timer.toString()); + System.out.println(timer); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectArrayMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectArrayMessageTest.java index c0c315aab62..cdfb2c9bd26 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectArrayMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectArrayMessageTest.java @@ -24,18 +24,18 @@ /** * @since 2.4 */ -public class ObjectArrayMessageTest { +class ObjectArrayMessageTest { private static final Object[] ARRAY = {"A", "B", "C"}; private static final ObjectArrayMessage OBJECT_ARRAY_MESSAGE = new ObjectArrayMessage(ARRAY); @Test - public void testGetParameters() { + void testGetParameters() { assertArrayEquals(ARRAY, OBJECT_ARRAY_MESSAGE.getParameters()); } @Test - public void testGetThrowable() { + void testGetThrowable() { assertNull(OBJECT_ARRAY_MESSAGE.getThrowable()); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectMessageTest.java index b2ef7ca9784..2bdc1d7a68a 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ObjectMessageTest.java @@ -30,17 +30,17 @@ /** * Tests {@link ObjectMessage}. */ -public class ObjectMessageTest { +class ObjectMessageTest { @Test - public void testNull() { + void testNull() { final ObjectMessage msg = new ObjectMessage(null); final String result = msg.getFormattedMessage(); assertEquals("null", result); } @Test - public void testNotNull() { + void testNotNull() { final String testMsg = "Test message {}"; final ObjectMessage msg = new ObjectMessage(testMsg); final String result = msg.getFormattedMessage(); @@ -48,7 +48,7 @@ public void testNotNull() { } @Test - public void testUnsafeWithMutableParams() { // LOG4J2-763 + void testUnsafeWithMutableParams() { // LOG4J2-763 final Mutable param = new Mutable().set("abc"); final ObjectMessage msg = new ObjectMessage(param); @@ -59,7 +59,7 @@ public void testUnsafeWithMutableParams() { // LOG4J2-763 } @Test - public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 + void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 final Mutable param = new Mutable().set("abc"); final ObjectMessage msg = new ObjectMessage(param); @@ -71,7 +71,7 @@ public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 } @Test - public void formatTo_usesCachedMessageString() throws Exception { + void formatTo_usesCachedMessageString() { final StringBuilder charSequence = new StringBuilder("initial value"); final ObjectMessage message = new ObjectMessage(charSequence); assertEquals("initial value", message.getFormattedMessage()); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ParameterFormatterTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ParameterFormatterTest.java index 638ab5c0dd2..70194a265b9 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ParameterFormatterTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ParameterFormatterTest.java @@ -147,7 +147,7 @@ static Object[][] messageFormattingTestCases() { } @Test - public void testDeepToString() { + void testDeepToString() { final List list = new ArrayList<>(); list.add(1); // noinspection CollectionAddedToSelf @@ -159,7 +159,7 @@ public void testDeepToString() { } @Test - public void testDeepToStringUsingNonRecursiveButConsequentObjects() { + void testDeepToStringUsingNonRecursiveButConsequentObjects() { final List list = new ArrayList<>(); final Object item = Collections.singletonList(0); list.add(1); @@ -173,7 +173,7 @@ public void testDeepToStringUsingNonRecursiveButConsequentObjects() { } @Test - public void testIdentityToString() { + void testIdentityToString() { final List list = new ArrayList<>(); list.add(1); // noinspection CollectionAddedToSelf diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableMessageFactoryTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableMessageFactoryTest.java index 6eee8f73f79..c79f459a9ac 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableMessageFactoryTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableMessageFactoryTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; @@ -34,10 +35,10 @@ /** * Tests the ReusableMessageFactory class. */ -public class ReusableMessageFactoryTest { +class ReusableMessageFactoryTest { @Test - public void testCreateEventReturnsDifferentInstanceIfNotReleased() throws Exception { + void testCreateEventReturnsDifferentInstanceIfNotReleased() { final ReusableMessageFactory factory = new ReusableMessageFactory(); final Message message1 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 1, 2, 3, 4); final Message message2 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 9, 8, 7, 6); @@ -47,7 +48,7 @@ public void testCreateEventReturnsDifferentInstanceIfNotReleased() throws Except } @Test - public void testCreateEventReturnsSameInstance() throws Exception { + void testCreateEventReturnsSameInstance() { final ReusableMessageFactory factory = new ReusableMessageFactory(); final Message message1 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 1, 2, 3, 4); @@ -62,7 +63,7 @@ public void testCreateEventReturnsSameInstance() throws Exception { } private void assertReusableParameterizeMessage(final Message message, final String txt, final Object[] params) { - assertTrue(message instanceof ReusableParameterizedMessage); + assertInstanceOf(ReusableParameterizedMessage.class, message); final ReusableParameterizedMessage msg = (ReusableParameterizedMessage) message; assertTrue(msg.reserved, "reserved"); @@ -75,7 +76,7 @@ private void assertReusableParameterizeMessage(final Message message, final Stri } @Test - public void testCreateEventOverwritesFields() throws Exception { + void testCreateEventOverwritesFields() { final ReusableMessageFactory factory = new ReusableMessageFactory(); final Message message1 = factory.newMessage("text, p0={} p1={} p2={} p3={}", 1, 2, 3, 4); assertReusableParameterizeMessage(message1, "text, p0={} p1={} p2={} p3={}", new Object[] { @@ -98,7 +99,7 @@ public void testCreateEventOverwritesFields() throws Exception { } @Test - public void testCreateEventReturnsThreadLocalInstance() throws Exception { + void testCreateEventReturnsThreadLocalInstance() throws Exception { final ReusableMessageFactory factory = new ReusableMessageFactory(); final AtomicReference message1 = new AtomicReference<>(); final AtomicReference message2 = new AtomicReference<>(); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableObjectMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableObjectMessageTest.java index 2d1ff583fed..a7d5e8ce1ee 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableObjectMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableObjectMessageTest.java @@ -30,22 +30,22 @@ /** * Tests ReusableObjectMessage. */ -public class ReusableObjectMessageTest { +class ReusableObjectMessageTest { @Test - public void testSet_InitializesFormattedMessage() throws Exception { + void testSet_InitializesFormattedMessage() { final ReusableObjectMessage msg = new ReusableObjectMessage(); msg.set("abc"); assertEquals("abc", msg.getFormattedMessage()); } @Test - public void testGetFormattedMessage_InitiallyNullString() throws Exception { + void testGetFormattedMessage_InitiallyNullString() { assertEquals("null", new ReusableObjectMessage().getFormattedMessage()); } @Test - public void testGetFormattedMessage_ReturnsLatestSetString() throws Exception { + void testGetFormattedMessage_ReturnsLatestSetString() { final ReusableObjectMessage msg = new ReusableObjectMessage(); msg.set("abc"); assertEquals("abc", msg.getFormattedMessage()); @@ -56,12 +56,12 @@ public void testGetFormattedMessage_ReturnsLatestSetString() throws Exception { } @Test - public void testGetFormat_InitiallyNull() throws Exception { + void testGetFormat_InitiallyNull() { assertNull(new ReusableObjectMessage().getFormat()); } @Test - public void testGetFormat_ReturnsLatestSetString() throws Exception { + void testGetFormat_ReturnsLatestSetString() { final ReusableObjectMessage msg = new ReusableObjectMessage(); msg.set("abc"); assertEquals("abc", msg.getFormat()); @@ -72,12 +72,12 @@ public void testGetFormat_ReturnsLatestSetString() throws Exception { } @Test - public void testGetParameters_InitiallyReturnsNullObjectInLength1Array() throws Exception { + void testGetParameters_InitiallyReturnsNullObjectInLength1Array() { assertArrayEquals(new Object[] {null}, new ReusableObjectMessage().getParameters()); } @Test - public void testGetParameters_ReturnsSetObjectInParameterArrayAfterMessageSet() throws Exception { + void testGetParameters_ReturnsSetObjectInParameterArrayAfterMessageSet() { final ReusableObjectMessage msg = new ReusableObjectMessage(); msg.set("abc"); assertArrayEquals(new Object[] {"abc"}, msg.getParameters()); @@ -86,12 +86,12 @@ public void testGetParameters_ReturnsSetObjectInParameterArrayAfterMessageSet() } @Test - public void testGetThrowable_InitiallyReturnsNull() throws Exception { + void testGetThrowable_InitiallyReturnsNull() { assertNull(new ReusableObjectMessage().getThrowable()); } @Test - public void testGetThrowable_ReturnsNullAfterMessageSet() throws Exception { + void testGetThrowable_ReturnsNullAfterMessageSet() { final ReusableObjectMessage msg = new ReusableObjectMessage(); msg.set("abc"); assertNull(msg.getThrowable()); @@ -100,7 +100,7 @@ public void testGetThrowable_ReturnsNullAfterMessageSet() throws Exception { } @Test - public void testFormatTo_InitiallyWritesNull() throws Exception { + void testFormatTo_InitiallyWritesNull() { final ReusableObjectMessage msg = new ReusableObjectMessage(); final StringBuilder sb = new StringBuilder(); msg.formatTo(sb); @@ -108,7 +108,7 @@ public void testFormatTo_InitiallyWritesNull() throws Exception { } @Test - public void testFormatTo_WritesLatestSetString() throws Exception { + void testFormatTo_WritesLatestSetString() { final ReusableObjectMessage msg = new ReusableObjectMessage(); final StringBuilder sb = new StringBuilder(); msg.formatTo(sb); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableParameterizedMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableParameterizedMessageTest.java index aabe4e9d4ae..fc7e30aa607 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableParameterizedMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableParameterizedMessageTest.java @@ -41,7 +41,7 @@ public static ReusableParameterizedMessage set( } @Test - public void testNoArgs() { + void testNoArgs() { final String testMsg = "Test message {}"; final ReusableParameterizedMessage msg = new ReusableParameterizedMessage(); msg.set(testMsg, (Object[]) null); @@ -58,7 +58,7 @@ public void testNoArgs() { } @Test - public void testFormat3StringArgs() { + void testFormat3StringArgs() { final String testMsg = "Test message {}{} {}"; final String[] args = {"a", "b", "c"}; final String result = @@ -67,7 +67,7 @@ public void testFormat3StringArgs() { } @Test - public void testFormatNullArgs() { + void testFormatNullArgs() { final String testMsg = "Test message {} {} {} {} {} {}"; final String[] args = {"a", null, "c", null, null, null}; final String result = @@ -76,7 +76,7 @@ public void testFormatNullArgs() { } @Test - public void testFormatStringArgsIgnoresSuperfluousArgs() { + void testFormatStringArgsIgnoresSuperfluousArgs() { final String testMsg = "Test message {}{} {}"; final String[] args = {"a", "b", "c", "unnecessary", "superfluous"}; final String result = @@ -85,7 +85,7 @@ public void testFormatStringArgsIgnoresSuperfluousArgs() { } @Test - public void testFormatStringArgsWithEscape() { + void testFormatStringArgsWithEscape() { final String testMsg = "Test message \\{}{} {}"; final String[] args = {"a", "b", "c"}; final String result = @@ -94,7 +94,7 @@ public void testFormatStringArgsWithEscape() { } @Test - public void testFormatStringArgsWithTrailingEscape() { + void testFormatStringArgsWithTrailingEscape() { final String testMsg = "Test message {}{} {}\\"; final String[] args = {"a", "b", "c"}; final String result = @@ -103,7 +103,7 @@ public void testFormatStringArgsWithTrailingEscape() { } @Test - public void testFormatStringArgsWithTrailingText() { + void testFormatStringArgsWithTrailingText() { final String testMsg = "Test message {}{} {}Text"; final String[] args = {"a", "b", "c"}; final String result = @@ -112,7 +112,7 @@ public void testFormatStringArgsWithTrailingText() { } @Test - public void testFormatStringArgsWithTrailingEscapedEscape() { + void testFormatStringArgsWithTrailingEscapedEscape() { final String testMsg = "Test message {}{} {}\\\\"; final String[] args = {"a", "b", "c"}; final String result = @@ -121,7 +121,7 @@ public void testFormatStringArgsWithTrailingEscapedEscape() { } @Test - public void testFormatStringArgsWithEscapedEscape() { + void testFormatStringArgsWithEscapedEscape() { final String testMsg = "Test message \\\\{}{} {}"; final Object[] args = {"a", "b", "c"}; final String result = @@ -130,7 +130,7 @@ public void testFormatStringArgsWithEscapedEscape() { } @Test - public void testNotSafeWithMutableParams() { + void testNotSafeWithMutableParams() { final String testMsg = "Test message {}"; final Mutable param = new Mutable().set("abc"); final ReusableParameterizedMessage msg = new ReusableParameterizedMessage(); @@ -148,7 +148,7 @@ public void testNotSafeWithMutableParams() { } @Test - public void testThrowable() { + void testThrowable() { final String testMsg = "Test message {}"; final ReusableParameterizedMessage msg = new ReusableParameterizedMessage(); final Throwable EXCEPTION1 = new IllegalAccessError("#1"); @@ -161,7 +161,7 @@ public void testThrowable() { } @Test - public void testParameterConsumer() { + void testParameterConsumer() { final String testMsg = "Test message {}"; final ReusableParameterizedMessage msg = new ReusableParameterizedMessage(); final Throwable EXCEPTION1 = new IllegalAccessError("#1"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableSimpleMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableSimpleMessageTest.java index ab985dd7eab..637f6d48c32 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableSimpleMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ReusableSimpleMessageTest.java @@ -31,22 +31,22 @@ /** * Tests ReusableSimpleMessage. */ -public class ReusableSimpleMessageTest { +class ReusableSimpleMessageTest { @Test - public void testSet_InitializesFormattedMessage() throws Exception { + void testSet_InitializesFormattedMessage() { final ReusableSimpleMessage msg = new ReusableSimpleMessage(); msg.set("abc"); assertEquals("abc", msg.getFormattedMessage()); } @Test - public void testGetFormattedMessage_InitiallyStringNull() throws Exception { + void testGetFormattedMessage_InitiallyStringNull() { assertEquals("null", new ReusableSimpleMessage().getFormattedMessage()); } @Test - public void testGetFormattedMessage_ReturnsLatestSetString() throws Exception { + void testGetFormattedMessage_ReturnsLatestSetString() { final ReusableSimpleMessage msg = new ReusableSimpleMessage(); msg.set("abc"); assertEquals("abc", msg.getFormattedMessage()); @@ -57,12 +57,12 @@ public void testGetFormattedMessage_ReturnsLatestSetString() throws Exception { } @Test - public void testGetFormat_InitiallyStringNull() throws Exception { + void testGetFormat_InitiallyStringNull() { assertNull(new ReusableSimpleMessage().getFormat()); } @Test - public void testGetFormat_ReturnsLatestSetString() throws Exception { + void testGetFormat_ReturnsLatestSetString() { final ReusableSimpleMessage msg = new ReusableSimpleMessage(); msg.set("abc"); assertEquals("abc", msg.getFormat()); @@ -73,12 +73,12 @@ public void testGetFormat_ReturnsLatestSetString() throws Exception { } @Test - public void testGetParameters_InitiallyReturnsEmptyArray() throws Exception { + void testGetParameters_InitiallyReturnsEmptyArray() { assertArrayEquals(Constants.EMPTY_OBJECT_ARRAY, new ReusableSimpleMessage().getParameters()); } @Test - public void testGetParameters_ReturnsEmptyArrayAfterMessageSet() throws Exception { + void testGetParameters_ReturnsEmptyArrayAfterMessageSet() { final ReusableSimpleMessage msg = new ReusableSimpleMessage(); msg.set("abc"); assertArrayEquals(Constants.EMPTY_OBJECT_ARRAY, msg.getParameters()); @@ -87,12 +87,12 @@ public void testGetParameters_ReturnsEmptyArrayAfterMessageSet() throws Exceptio } @Test - public void testGetThrowable_InitiallyReturnsNull() throws Exception { + void testGetThrowable_InitiallyReturnsNull() { assertNull(new ReusableSimpleMessage().getThrowable()); } @Test - public void testGetThrowable_ReturnsNullAfterMessageSet() throws Exception { + void testGetThrowable_ReturnsNullAfterMessageSet() { final ReusableSimpleMessage msg = new ReusableSimpleMessage(); msg.set("abc"); assertNull(msg.getThrowable()); @@ -101,7 +101,7 @@ public void testGetThrowable_ReturnsNullAfterMessageSet() throws Exception { } @Test - public void testFormatTo_InitiallyWritesNull() throws Exception { + void testFormatTo_InitiallyWritesNull() { final ReusableSimpleMessage msg = new ReusableSimpleMessage(); final StringBuilder sb = new StringBuilder(); msg.formatTo(sb); @@ -109,7 +109,7 @@ public void testFormatTo_InitiallyWritesNull() throws Exception { } @Test - public void testFormatTo_WritesLatestSetString() throws Exception { + void testFormatTo_WritesLatestSetString() { final ReusableSimpleMessage msg = new ReusableSimpleMessage(); final StringBuilder sb = new StringBuilder(); msg.formatTo(sb); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/SimpleMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/SimpleMessageTest.java index 7552531d73c..a97367a6a23 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/SimpleMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/SimpleMessageTest.java @@ -28,9 +28,9 @@ /** * Tests the SimpleMessage class. */ -public class SimpleMessageTest { +class SimpleMessageTest { @Test - public void formatTo_usesCachedMessageString() throws Exception { + void formatTo_usesCachedMessageString() { final StringBuilder charSequence = new StringBuilder("initial value"); final SimpleMessage message = new SimpleMessage(charSequence); assertEquals("initial value", message.getFormattedMessage()); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StringFormattedMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StringFormattedMessageTest.java index 667f4b40e33..29309b36592 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StringFormattedMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StringFormattedMessageTest.java @@ -33,13 +33,13 @@ import org.junit.jupiter.api.parallel.Resources; @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) -public class StringFormattedMessageTest { +class StringFormattedMessageTest { private static final int LOOP_CNT = 500; String[] array = new String[LOOP_CNT]; @Test - public void testNoArgs() { + void testNoArgs() { final String testMsg = "Test message %1s"; StringFormattedMessage msg = new StringFormattedMessage(testMsg, (Object[]) null); String result = msg.getFormattedMessage(); @@ -52,7 +52,7 @@ public void testNoArgs() { } @Test - public void testOneStringArg() { + void testOneStringArg() { final String testMsg = "Test message %1s"; final StringFormattedMessage msg = new StringFormattedMessage(testMsg, "Apache"); final String result = msg.getFormattedMessage(); @@ -61,7 +61,7 @@ public void testOneStringArg() { } @Test - public void testOneIntArgLocaleUs() { + void testOneIntArgLocaleUs() { final String testMsg = "Test e = %+10.4f"; final StringFormattedMessage msg = new StringFormattedMessage(Locale.US, testMsg, Math.E); final String result = msg.getFormattedMessage(); @@ -70,7 +70,7 @@ public void testOneIntArgLocaleUs() { } @Test - public void testOneArgLocaleFrance() { + void testOneArgLocaleFrance() { final String testMsg = "Test e = %+10.4f"; final StringFormattedMessage msg = new StringFormattedMessage(Locale.FRANCE, testMsg, Math.E); final String result = msg.getFormattedMessage(); @@ -79,7 +79,7 @@ public void testOneArgLocaleFrance() { } @Test - public void testException() { + void testException() { final String testMsg = "Test message {0}"; final MessageFormatMessage msg = new MessageFormatMessage(testMsg, "Apache", new NullPointerException("Null")); final String result = msg.getFormattedMessage(); @@ -90,7 +90,7 @@ public void testException() { } @Test - public void testUnsafeWithMutableParams() { // LOG4J2-763 + void testUnsafeWithMutableParams() { // LOG4J2-763 final String testMsg = "Test message %s"; final Mutable param = new Mutable().set("abc"); final StringFormattedMessage msg = new StringFormattedMessage(testMsg, param); @@ -102,7 +102,7 @@ public void testUnsafeWithMutableParams() { // LOG4J2-763 } @Test - public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 + void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 final String testMsg = "Test message %s"; final Mutable param = new Mutable().set("abc"); final StringFormattedMessage msg = new StringFormattedMessage(testMsg, param); @@ -115,7 +115,7 @@ public void testSafeAfterGetFormattedMessageIsCalled() { // LOG4J2-763 } @Test - public void testSerialization() throws IOException, ClassNotFoundException { + void testSerialization() throws IOException, ClassNotFoundException { final StringFormattedMessage expected = new StringFormattedMessage("Msg", "a", "b", "c"); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final ObjectOutputStream out = new ObjectOutputStream(baos)) { @@ -131,7 +131,7 @@ public void testSerialization() throws IOException, ClassNotFoundException { } @Test - public void testPercentInMessageNoArgs() { + void testPercentInMessageNoArgs() { // LOG4J2-3458 LocalizedMessage causes a lot of noise on the console // // ERROR StatusLogger Unable to format msg: C:/Program%20Files/Some%20Company/Some%20Product%20Name/ diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StructuredDataMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StructuredDataMessageTest.java index 7fb9f2c571b..f02d95eefef 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StructuredDataMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/StructuredDataMessageTest.java @@ -25,10 +25,10 @@ /** * */ -public class StructuredDataMessageTest { +class StructuredDataMessageTest { @Test - public void testMsg() { + void testMsg() { final String testMsg = "Test message {}"; final StructuredDataMessage msg = new StructuredDataMessage("MsgId@12345", testMsg, "Alert"); msg.put("message", testMsg); @@ -41,7 +41,7 @@ public void testMsg() { } @Test - public void testMsgNonFull() { + void testMsgNonFull() { final String testMsg = "Test message {}"; final StructuredDataMessage msg = new StructuredDataMessage("MsgId@12345", testMsg, "Alert"); msg.put("message", testMsg); @@ -54,7 +54,7 @@ public void testMsgNonFull() { } @Test - public void testMsgXml() { + void testMsgXml() { final String testMsg = "Test message {}"; final StructuredDataMessage msg = new StructuredDataMessage("MsgId@12345", testMsg, "Alert"); msg.put("message", testMsg); @@ -74,7 +74,7 @@ public void testMsgXml() { } @Test - public void testBuilder() { + void testBuilder() { final String testMsg = "Test message {}"; final StructuredDataMessage msg = new StructuredDataMessage("MsgId@12345", testMsg, "Alert") .with("message", testMsg) @@ -87,7 +87,7 @@ public void testBuilder() { } @Test - public void testMsgWithKeyTooLong() { + void testMsgWithKeyTooLong() { final String testMsg = "Test message {}"; final StructuredDataMessage msg = new StructuredDataMessage("MsgId@12345", testMsg, "Alert"); assertThrows( @@ -96,7 +96,7 @@ public void testMsgWithKeyTooLong() { } @Test - public void testMutableByDesign() { // LOG4J2-763 + void testMutableByDesign() { // LOG4J2-763 final String testMsg = "Test message {}"; final StructuredDataMessage msg = new StructuredDataMessage("MsgId@1", testMsg, "Alert"); @@ -116,7 +116,7 @@ public void testMutableByDesign() { // LOG4J2-763 } @Test - public void testEnterpriseNoAsOidFragment() { + void testEnterpriseNoAsOidFragment() { final String testMsg = "Test message {}"; final StructuredDataMessage structuredDataMessage = new StructuredDataMessage("XX_DATA@1234.55.6.7", testMsg, "Nothing"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ThreadDumpMessageTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ThreadDumpMessageTest.java index 7cd5347292d..6c1e4508dff 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ThreadDumpMessageTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/message/ThreadDumpMessageTest.java @@ -25,10 +25,10 @@ import java.util.concurrent.locks.ReentrantLock; import org.junit.jupiter.api.Test; -public class ThreadDumpMessageTest { +class ThreadDumpMessageTest { @Test - public void testMessage() { + void testMessage() { final ThreadDumpMessage msg = new ThreadDumpMessage("Testing"); final String message = msg.getFormattedMessage(); @@ -39,7 +39,7 @@ public void testMessage() { } @Test - public void testMessageWithLocks() throws Exception { + void testMessageWithLocks() throws Exception { final ReentrantLock lock = new ReentrantLock(); lock.lock(); final Thread thread1 = new Thread1(lock); @@ -66,7 +66,7 @@ public void testMessageWithLocks() throws Exception { } @Test - public void testToString() { + void testToString() { final ThreadDumpMessage msg = new ThreadDumpMessage("Test"); final String actual = msg.toString(); assertTrue(actual.contains("Test")); @@ -75,7 +75,7 @@ public void testToString() { } @Test - public void testUseConstructorThread() throws InterruptedException { // LOG4J2-763 + void testUseConstructorThread() throws InterruptedException { // LOG4J2-763 final ThreadDumpMessage msg = new ThreadDumpMessage("Test"); final AtomicReference actual = new AtomicReference<>(); @@ -92,7 +92,7 @@ public void run() { } @Test - public void formatTo_usesCachedMessageString() throws Exception { + void formatTo_usesCachedMessageString() throws Exception { final ThreadDumpMessage message = new ThreadDumpMessage(""); final String initial = message.getFormattedMessage(); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/simple/SimpleLoggerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/simple/SimpleLoggerTest.java index 1d64ea71d4e..c6ba817dc61 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/simple/SimpleLoggerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/simple/SimpleLoggerTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; @Tag("smoke") -public class SimpleLoggerTest { +class SimpleLoggerTest { @RegisterExtension public static final LoggerContextFactoryExtension EXTENSION = @@ -34,17 +34,17 @@ public class SimpleLoggerTest { private final Logger logger = LogManager.getLogger("TestError"); @Test - public void testString() { + void testString() { logger.error("Logging without args"); } @Test - public void testMissingMessageArg() { + void testMissingMessageArg() { logger.error("Logging without args {}"); } @Test - public void testEmptyObjectArray() { + void testEmptyObjectArray() { logger.error(Constants.EMPTY_OBJECT_ARRAY); } @@ -52,7 +52,7 @@ public void testEmptyObjectArray() { * Tests LOG4J2-811. */ @Test - public void testMessageWithEmptyObjectArray() { + void testMessageWithEmptyObjectArray() { logger.error("Logging with an empty Object[] {} {}", Constants.EMPTY_BYTE_ARRAY); } @@ -60,7 +60,7 @@ public void testMessageWithEmptyObjectArray() { * Tests LOG4J2-811. */ @Test - public void testMessageWithShortArray() { + void testMessageWithShortArray() { logger.error("Logging with a size 1 Object[] {} {}", new Object[] {"only one param"}); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/DefaultThreadContextStackTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/DefaultThreadContextStackTest.java index 4778ec63c1a..08f1755042e 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/DefaultThreadContextStackTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/DefaultThreadContextStackTest.java @@ -33,10 +33,10 @@ import org.junit.jupiter.api.Test; @UsingAnyThreadContext -public class DefaultThreadContextStackTest { +class DefaultThreadContextStackTest { @Test - public void testEqualsVsSameKind() { + void testEqualsVsSameKind() { final DefaultThreadContextStack stack1 = createStack(); final DefaultThreadContextStack stack2 = createStack(); assertEquals(stack1, stack1); @@ -46,7 +46,7 @@ public void testEqualsVsSameKind() { } @Test - public void testEqualsVsMutable() { + void testEqualsVsMutable() { final ThreadContextStack stack1 = createStack(); final ThreadContextStack stack2 = MutableThreadContextStackTest.createStack(); assertEquals(stack1, stack1); @@ -56,21 +56,21 @@ public void testEqualsVsMutable() { } @Test - public void testHashCodeVsSameKind() { + void testHashCodeVsSameKind() { final DefaultThreadContextStack stack1 = createStack(); final DefaultThreadContextStack stack2 = createStack(); assertEquals(stack1.hashCode(), stack2.hashCode()); } @Test - public void testImmutableOrNullReturnsNullIfUseStackIsFalse() { + void testImmutableOrNullReturnsNullIfUseStackIsFalse() { final DefaultThreadContextStack stack = new DefaultThreadContextStack(false); stack.clear(); assertNull(stack.getImmutableStackOrNull()); } @Test - public void testImmutableOrNullReturnsNullIfStackIsEmpty() { + void testImmutableOrNullReturnsNullIfStackIsEmpty() { final DefaultThreadContextStack stack = new DefaultThreadContextStack(true); stack.clear(); assertTrue(stack.isEmpty()); @@ -78,7 +78,7 @@ public void testImmutableOrNullReturnsNullIfStackIsEmpty() { } @Test - public void testImmutableOrNullReturnsCopyOfContents() { + void testImmutableOrNullReturnsCopyOfContents() { final DefaultThreadContextStack stack = createStack(); assertFalse(stack.isEmpty()); final ContextStack actual = stack.getImmutableStackOrNull(); @@ -87,7 +87,7 @@ public void testImmutableOrNullReturnsCopyOfContents() { } @Test - public void testModifyingImmutableOrNullThrowsException() { + void testModifyingImmutableOrNullThrowsException() { final DefaultThreadContextStack stack = createStack(); final int originalSize = stack.size(); assertTrue(originalSize > 0); @@ -98,7 +98,7 @@ public void testModifyingImmutableOrNullThrowsException() { } @Test - public void testDoesNothingIfConstructedWithUseStackIsFalse() { + void testDoesNothingIfConstructedWithUseStackIsFalse() { final DefaultThreadContextStack stack = new DefaultThreadContextStack(false); stack.clear(); assertTrue(stack.isEmpty()); @@ -110,7 +110,7 @@ public void testDoesNothingIfConstructedWithUseStackIsFalse() { } @Test - public void testPushAndAddIncreaseStack() { + void testPushAndAddIncreaseStack() { final DefaultThreadContextStack stack = new DefaultThreadContextStack(true); stack.clear(); assertTrue(stack.isEmpty()); @@ -121,7 +121,7 @@ public void testPushAndAddIncreaseStack() { } @Test - public void testPeekReturnsLastAddedItem() { + void testPeekReturnsLastAddedItem() { final DefaultThreadContextStack stack = new DefaultThreadContextStack(true); stack.clear(); assertTrue(stack.isEmpty()); @@ -136,7 +136,7 @@ public void testPeekReturnsLastAddedItem() { } @Test - public void testPopRemovesLastAddedItem() { + void testPopRemovesLastAddedItem() { final DefaultThreadContextStack stack = createStack(); assertEquals(3, stack.getDepth()); @@ -154,7 +154,7 @@ public void testPopRemovesLastAddedItem() { } @Test - public void testAsList() { + void testAsList() { final DefaultThreadContextStack stack = new DefaultThreadContextStack(true); stack.clear(); assertTrue(stack.isEmpty()); @@ -166,7 +166,7 @@ public void testAsList() { } @Test - public void testTrim() { + void testTrim() { final DefaultThreadContextStack stack = createStack(); stack.trim(1); @@ -175,7 +175,7 @@ public void testTrim() { } @Test - public void testCopy() { + void testCopy() { final DefaultThreadContextStack stack = createStack(); final ThreadContextStack copy = stack.copy(); @@ -205,7 +205,7 @@ public void testCopy() { } @Test - public void testClear() { + void testClear() { final DefaultThreadContextStack stack = createStack(); stack.clear(); @@ -227,7 +227,7 @@ static DefaultThreadContextStack createStack() { } @Test - public void testContains() { + void testContains() { final DefaultThreadContextStack stack = createStack(); assertTrue(stack.contains("msg1")); @@ -236,7 +236,7 @@ public void testContains() { } @Test - public void testIteratorReturnsInListOrderNotStackOrder() { + void testIteratorReturnsInListOrderNotStackOrder() { final DefaultThreadContextStack stack = createStack(); final Iterator iter = stack.iterator(); @@ -250,7 +250,7 @@ public void testIteratorReturnsInListOrderNotStackOrder() { } @Test - public void testToArray() { + void testToArray() { final DefaultThreadContextStack stack = createStack(); final String[] expecteds = {"msg1", "msg2", "msg3"}; @@ -258,7 +258,7 @@ public void testToArray() { } @Test - public void testToArrayTArray() { + void testToArrayTArray() { final DefaultThreadContextStack stack = createStack(); final String[] expecteds = {"msg1", "msg2", "msg3"}; @@ -268,7 +268,7 @@ public void testToArrayTArray() { } @Test - public void testRemove() { + void testRemove() { final DefaultThreadContextStack stack = createStack(); assertTrue(stack.containsAll(Arrays.asList("msg1", "msg2", "msg3"))); @@ -284,14 +284,14 @@ public void testRemove() { } @Test - public void testContainsAll() { + void testContainsAll() { final DefaultThreadContextStack stack = createStack(); assertTrue(stack.containsAll(Arrays.asList("msg1", "msg2", "msg3"))); } @Test - public void testAddAll() { + void testAddAll() { final DefaultThreadContextStack stack = createStack(); stack.addAll(Arrays.asList("msg4", "msg5")); @@ -304,7 +304,7 @@ public void testAddAll() { } @Test - public void testRemoveAll() { + void testRemoveAll() { final DefaultThreadContextStack stack = createStack(); stack.removeAll(Arrays.asList("msg1", "msg3")); @@ -315,7 +315,7 @@ public void testRemoveAll() { } @Test - public void testRetainAll() { + void testRetainAll() { final DefaultThreadContextStack stack = createStack(); stack.retainAll(Arrays.asList("msg1", "msg3")); @@ -326,7 +326,7 @@ public void testRetainAll() { } @Test - public void testToStringShowsListContents() { + void testToStringShowsListContents() { final DefaultThreadContextStack stack = new DefaultThreadContextStack(true); stack.clear(); assertEquals("[]", stack.toString()); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/LoggerAdapterTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/LoggerAdapterTest.java index 0bbe8eaa01a..a8b90c54c57 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/LoggerAdapterTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/LoggerAdapterTest.java @@ -34,7 +34,7 @@ /** * Created by Pavel.Sivolobtchik@uxpsystems.com on 2016-10-19. */ -public class LoggerAdapterTest { +class LoggerAdapterTest { private static class RunnableThreadTest implements Runnable { private final AbstractLoggerAdapter adapter; @@ -132,7 +132,7 @@ public void shutdown() { } @Test - public void testCleanup() throws Exception { + void testCleanup() { final LoggerContextFactory factory = new TestLoggerContextFactory(); final TestLoggerAdapter2 adapter = new TestLoggerAdapter2(); for (int i = 0; i < 5; ++i) { @@ -151,7 +151,7 @@ public void testCleanup() throws Exception { * Testing synchronization in the getLoggersInContext() method */ @Test - public synchronized void testGetLoggersInContextSynch() throws Exception { + synchronized void testGetLoggersInContextSynch() throws Exception { final TestLoggerAdapter adapter = new TestLoggerAdapter(); final int num = 500; diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/MutableThreadContextStackTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/MutableThreadContextStackTest.java index 09a340dc771..2c1fb007dc8 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/MutableThreadContextStackTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/spi/MutableThreadContextStackTest.java @@ -29,16 +29,16 @@ import java.util.List; import org.junit.jupiter.api.Test; -public class MutableThreadContextStackTest { +class MutableThreadContextStackTest { @Test - public void testEmptyIfConstructedWithEmptyList() { + void testEmptyIfConstructedWithEmptyList() { final MutableThreadContextStack stack = new MutableThreadContextStack(new ArrayList<>()); assertTrue(stack.isEmpty()); } @Test - public void testConstructorCopiesListContents() { + void testConstructorCopiesListContents() { final List initial = Arrays.asList("a", "b", "c"); final MutableThreadContextStack stack = new MutableThreadContextStack(initial); assertFalse(stack.isEmpty()); @@ -46,7 +46,7 @@ public void testConstructorCopiesListContents() { } @Test - public void testPushAndAddIncreaseStack() { + void testPushAndAddIncreaseStack() { final MutableThreadContextStack stack = new MutableThreadContextStack(new ArrayList<>()); stack.clear(); assertTrue(stack.isEmpty()); @@ -57,7 +57,7 @@ public void testPushAndAddIncreaseStack() { } @Test - public void testPeekReturnsLastAddedItem() { + void testPeekReturnsLastAddedItem() { final MutableThreadContextStack stack = new MutableThreadContextStack(new ArrayList<>()); stack.clear(); assertTrue(stack.isEmpty()); @@ -72,7 +72,7 @@ public void testPeekReturnsLastAddedItem() { } @Test - public void testPopRemovesLastAddedItem() { + void testPopRemovesLastAddedItem() { final MutableThreadContextStack stack = createStack(); assertEquals(3, stack.getDepth()); @@ -90,7 +90,7 @@ public void testPopRemovesLastAddedItem() { } @Test - public void testAsList() { + void testAsList() { final MutableThreadContextStack stack = new MutableThreadContextStack(new ArrayList<>()); stack.clear(); assertTrue(stack.isEmpty()); @@ -102,7 +102,7 @@ public void testAsList() { } @Test - public void testTrim() { + void testTrim() { final MutableThreadContextStack stack = createStack(); stack.trim(1); @@ -111,7 +111,7 @@ public void testTrim() { } @Test - public void testCopy() { + void testCopy() { final MutableThreadContextStack stack = createStack(); final ThreadContextStack copy = stack.copy(); @@ -141,7 +141,7 @@ public void testCopy() { } @Test - public void testClear() { + void testClear() { final MutableThreadContextStack stack = createStack(); stack.clear(); @@ -149,7 +149,7 @@ public void testClear() { } @Test - public void testEqualsVsSameKind() { + void testEqualsVsSameKind() { final MutableThreadContextStack stack1 = createStack(); final MutableThreadContextStack stack2 = createStack(); assertEquals(stack1, stack1); @@ -159,7 +159,7 @@ public void testEqualsVsSameKind() { } @Test - public void testHashCodeVsSameKind() { + void testHashCodeVsSameKind() { final MutableThreadContextStack stack1 = createStack(); final MutableThreadContextStack stack2 = createStack(); assertEquals(stack1.hashCode(), stack2.hashCode()); @@ -180,7 +180,7 @@ static MutableThreadContextStack createStack() { } @Test - public void testContains() { + void testContains() { final MutableThreadContextStack stack = createStack(); assertTrue(stack.contains("msg1")); @@ -189,7 +189,7 @@ public void testContains() { } @Test - public void testIteratorReturnsInListOrderNotStackOrder() { + void testIteratorReturnsInListOrderNotStackOrder() { final MutableThreadContextStack stack = createStack(); final Iterator iter = stack.iterator(); @@ -203,7 +203,7 @@ public void testIteratorReturnsInListOrderNotStackOrder() { } @Test - public void testToArray() { + void testToArray() { final MutableThreadContextStack stack = createStack(); final String[] expecteds = {"msg1", "msg2", "msg3"}; @@ -211,7 +211,7 @@ public void testToArray() { } @Test - public void testToArrayTArray() { + void testToArrayTArray() { final MutableThreadContextStack stack = createStack(); final String[] expecteds = {"msg1", "msg2", "msg3"}; @@ -221,7 +221,7 @@ public void testToArrayTArray() { } @Test - public void testRemove() { + void testRemove() { final MutableThreadContextStack stack = createStack(); assertTrue(stack.containsAll(Arrays.asList("msg1", "msg2", "msg3"))); @@ -237,14 +237,14 @@ public void testRemove() { } @Test - public void testContainsAll() { + void testContainsAll() { final MutableThreadContextStack stack = createStack(); assertTrue(stack.containsAll(Arrays.asList("msg1", "msg2", "msg3"))); } @Test - public void testAddAll() { + void testAddAll() { final MutableThreadContextStack stack = createStack(); stack.addAll(Arrays.asList("msg4", "msg5")); @@ -257,7 +257,7 @@ public void testAddAll() { } @Test - public void testRemoveAll() { + void testRemoveAll() { final MutableThreadContextStack stack = createStack(); stack.removeAll(Arrays.asList("msg1", "msg3")); @@ -268,7 +268,7 @@ public void testRemoveAll() { } @Test - public void testRetainAll() { + void testRetainAll() { final MutableThreadContextStack stack = createStack(); stack.retainAll(Arrays.asList("msg1", "msg3")); @@ -279,7 +279,7 @@ public void testRetainAll() { } @Test - public void testToStringShowsListContents() { + void testToStringShowsListContents() { final MutableThreadContextStack stack = new MutableThreadContextStack(new ArrayList<>()); assertEquals("[]", stack.toString()); @@ -293,13 +293,13 @@ public void testToStringShowsListContents() { } @Test - public void testIsFrozenIsFalseByDefault() { + void testIsFrozenIsFalseByDefault() { assertFalse(new MutableThreadContextStack().isFrozen()); assertFalse(createStack().isFrozen()); } @Test - public void testIsFrozenIsTrueAfterCallToFreeze() { + void testIsFrozenIsTrueAfterCallToFreeze() { final MutableThreadContextStack stack = new MutableThreadContextStack(); assertFalse(stack.isFrozen()); stack.freeze(); @@ -307,63 +307,63 @@ public void testIsFrozenIsTrueAfterCallToFreeze() { } @Test - public void testAddAllOnFrozenStackThrowsException() { + void testAddAllOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, () -> stack.addAll(Arrays.asList("a", "b", "c"))); } @Test - public void testAddOnFrozenStackThrowsException() { + void testAddOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, () -> stack.add("a")); } @Test - public void testClearOnFrozenStackThrowsException() { + void testClearOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, stack::clear); } @Test - public void testPopOnFrozenStackThrowsException() { + void testPopOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, stack::pop); } @Test - public void testPushOnFrozenStackThrowsException() { + void testPushOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, () -> stack.push("a")); } @Test - public void testRemoveOnFrozenStackThrowsException() { + void testRemoveOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, () -> stack.remove("a")); } @Test - public void testRemoveAllOnFrozenStackThrowsException() { + void testRemoveAllOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, () -> stack.removeAll(Arrays.asList("a", "b"))); } @Test - public void testRetainAllOnFrozenStackThrowsException() { + void testRetainAllOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, () -> stack.retainAll(Arrays.asList("a", "b"))); } @Test - public void testTrimOnFrozenStackThrowsException() { + void testTrimOnFrozenStackThrowsException() { final MutableThreadContextStack stack = new MutableThreadContextStack(); stack.freeze(); assertThrows(UnsupportedOperationException.class, () -> stack.trim(3)); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TempLoggingDirectoryTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TempLoggingDirectoryTest.java index 0a1dd2f15f3..f6cef52fe6a 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TempLoggingDirectoryTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TempLoggingDirectoryTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; @UsingTestProperties -public class TempLoggingDirectoryTest { +class TempLoggingDirectoryTest { private static final Pattern PER_CLASS_PATH = Pattern.compile("TempLoggingDirectoryTest\\d+"); private static final Path PER_TEST_PATH = Paths.get("testInjectedFields"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TestPropertySourceTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TestPropertySourceTest.java index 0b8783413d8..4e659e175ff 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TestPropertySourceTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/test/junit/TestPropertySourceTest.java @@ -23,13 +23,13 @@ import org.junit.jupiter.api.Test; @UsingTestProperties -public class TestPropertySourceTest { +class TestPropertySourceTest { private static TestProperties staticProperties; private TestProperties instanceProperties; @Test - public void testInjectedFields() { + void testInjectedFields() { assertThat(staticProperties).isNotNull(); assertThat(instanceProperties).isNotNull(); @@ -43,13 +43,13 @@ public void testInjectedFields() { } @Test - public void testInjectedParameter(final TestProperties paramProperties) { + void testInjectedParameter(final TestProperties paramProperties) { assertThat(paramProperties).isEqualTo(instanceProperties); } @Test @SetTestProperty(key = "log4j2.testSetTestProperty", value = "true") - public void testSetTestProperty() { + void testSetTestProperty() { final PropertiesUtil env = PropertiesUtil.getProperties(); assertThat(env.getBooleanProperty("log4j2.testSetTestProperty")).isTrue(); } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/CharsTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/CharsTest.java index 55b27736f8b..cca365710fe 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/CharsTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/CharsTest.java @@ -24,17 +24,17 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -public class CharsTest { +class CharsTest { @ParameterizedTest @ValueSource(ints = {-1, 16, 400, -1, 16, 400}) - public void invalidDigitReturnsNullCharacter(final int invalidDigit) { + void invalidDigitReturnsNullCharacter(final int invalidDigit) { assertAll( () -> assertEquals('\0', Chars.getUpperCaseHex(invalidDigit)), () -> assertEquals('\0', Chars.getLowerCaseHex(invalidDigit))); } @Test - public void validDigitReturnsProperCharacter() { + void validDigitReturnsProperCharacter() { final char[] expectedLower = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; final char[] expectedUpper = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; assertAll(IntStream.range(0, 16) diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ConstantsTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ConstantsTest.java index d96f2ab8bac..8735b0d1d00 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ConstantsTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ConstantsTest.java @@ -20,10 +20,10 @@ import org.junit.jupiter.api.Test; -public class ConstantsTest { +class ConstantsTest { @Test - public void testJdkVersionDetection() { + void testJdkVersionDetection() { assertEquals(1, Constants.getMajorVersion("1.1.2")); assertEquals(8, Constants.getMajorVersion("1.8.2")); assertEquals(9, Constants.getMajorVersion("9.1.1")); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceTest.java index 219721b6d16..83f11e852b1 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/EnvironmentPropertySourceTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class EnvironmentPropertySourceTest { +class EnvironmentPropertySourceTest { private final PropertySource source = new EnvironmentPropertySource(); @@ -40,7 +40,7 @@ public static Object[][] data() { @ParameterizedTest @MethodSource("data") - public void testNormalFormFollowsEnvironmentVariableConventions( + void testNormalFormFollowsEnvironmentVariableConventions( final CharSequence expected, final List tokens) { assertEquals(expected, source.getNormalForm(tokens)); } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LambdaUtilTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LambdaUtilTest.java index fa33a9972cb..1632afaae9b 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LambdaUtilTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LambdaUtilTest.java @@ -28,36 +28,36 @@ /** * Tests the LambdaUtil class. */ -public class LambdaUtilTest { +class LambdaUtilTest { @Test - public void testGetSupplierResultOfSupplier() { + void testGetSupplierResultOfSupplier() { final String expected = "result"; final Object actual = LambdaUtil.get((Supplier) () -> expected); assertSame(expected, actual); } @Test - public void testGetMessageSupplierResultOfSupplier() { + void testGetMessageSupplierResultOfSupplier() { final Message expected = new SimpleMessage("hi"); final Message actual = LambdaUtil.get(() -> expected); assertSame(expected, actual); } @Test - public void testGetSupplierReturnsNullIfSupplierNull() { + void testGetSupplierReturnsNullIfSupplierNull() { final Object actual = LambdaUtil.get((Supplier) null); assertNull(actual); } @Test - public void testGetMessageSupplierReturnsNullIfSupplierNull() { - final Object actual = LambdaUtil.get((MessageSupplier) null); + void testGetMessageSupplierReturnsNullIfSupplierNull() { + final Object actual = LambdaUtil.get(null); assertNull(actual); } @Test - public void testGetSupplierExceptionIfSupplierThrowsException() { + void testGetSupplierExceptionIfSupplierThrowsException() { assertThrows( RuntimeException.class, () -> LambdaUtil.get((Supplier) () -> { @@ -66,7 +66,7 @@ public void testGetSupplierExceptionIfSupplierThrowsException() { } @Test - public void testGetMessageSupplierExceptionIfSupplierThrowsException() { + void testGetMessageSupplierExceptionIfSupplierThrowsException() { assertThrows( RuntimeException.class, () -> LambdaUtil.get(() -> { @@ -75,7 +75,7 @@ public void testGetMessageSupplierExceptionIfSupplierThrowsException() { } @Test - public void testGetAllReturnsResultOfSuppliers() { + void testGetAllReturnsResultOfSuppliers() { final String expected1 = "result1"; final Supplier function1 = () -> expected1; final String expected2 = "result2"; @@ -89,13 +89,13 @@ public void testGetAllReturnsResultOfSuppliers() { } @Test - public void testGetAllReturnsNullArrayIfSupplierArrayNull() { + void testGetAllReturnsNullArrayIfSupplierArrayNull() { final Object[] actual = LambdaUtil.getAll((Supplier[]) null); assertNull(actual); } @Test - public void testGetAllReturnsNullElementsIfSupplierArrayContainsNulls() { + void testGetAllReturnsNullElementsIfSupplierArrayContainsNulls() { final Supplier[] functions = new Supplier[3]; final Object[] actual = LambdaUtil.getAll(functions); assertEquals(actual.length, functions.length); @@ -105,7 +105,7 @@ public void testGetAllReturnsNullElementsIfSupplierArrayContainsNulls() { } @Test - public void testGetAllThrowsExceptionIfAnyOfTheSuppliersThrowsException() { + void testGetAllThrowsExceptionIfAnyOfTheSuppliersThrowsException() { final Supplier function1 = () -> "abc"; final Supplier function2 = () -> { throw new RuntimeException(); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LegacyPropertiesCompatibilityTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LegacyPropertiesCompatibilityTest.java index aebf91f4bb1..40afae1d3ce 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LegacyPropertiesCompatibilityTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/LegacyPropertiesCompatibilityTest.java @@ -22,7 +22,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class LegacyPropertiesCompatibilityTest { +class LegacyPropertiesCompatibilityTest { public static Object[][] data() { return new Object[][] { @@ -84,7 +84,7 @@ public static Object[][] data() { @ParameterizedTest @MethodSource("data") - public void compareNewWithOldName(final String newName, final String oldName) { + void compareNewWithOldName(final String newName, final String oldName) { final List newTokens = PropertySource.Util.tokenize(newName); final List oldTokens = PropertySource.Util.tokenize(oldName); assertEquals(oldTokens, newTokens); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Log4jCharsetsPropertiesTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Log4jCharsetsPropertiesTest.java index 6a50052acc5..20d03654bcd 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Log4jCharsetsPropertiesTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Log4jCharsetsPropertiesTest.java @@ -24,13 +24,13 @@ import java.util.ResourceBundle; import org.junit.jupiter.api.Test; -public class Log4jCharsetsPropertiesTest { +class Log4jCharsetsPropertiesTest { /** * Tests that we can load all mappings. */ @Test - public void testLoadAll() { + void testLoadAll() { final ResourceBundle resourceBundle = PropertiesUtil.getCharsetsResourceBundle(); final Enumeration keys = resourceBundle.getKeys(); while (keys.hasMoreElements()) { diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ProcessIdUtilTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ProcessIdUtilTest.java index 351fcd0d3fb..0460d3a47bd 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ProcessIdUtilTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ProcessIdUtilTest.java @@ -20,11 +20,11 @@ import org.junit.jupiter.api.Test; -public class ProcessIdUtilTest { +class ProcessIdUtilTest { @Test - public void processIdTest() { + void processIdTest() { final String processId = ProcessIdUtil.getProcessId(); - assertNotEquals(processId, ProcessIdUtil.DEFAULT_PROCESSID, "ProcessId is default"); + assertNotEquals(ProcessIdUtil.DEFAULT_PROCESSID, processId, "ProcessId is default"); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesPropertySourceTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesPropertySourceTest.java index f3c69b3d296..bf82ed2b3a2 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesPropertySourceTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesPropertySourceTest.java @@ -16,7 +16,7 @@ */ package org.apache.logging.log4j.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collections; @@ -25,7 +25,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class PropertiesPropertySourceTest { +class PropertiesPropertySourceTest { private final PropertySource source = new PropertiesPropertySource(new Properties()); @@ -41,7 +41,7 @@ public static Object[][] data() { @ParameterizedTest @MethodSource("data") - public void testNormalFormFollowsCamelCaseConventions(final String expected, final List tokens) { + void testNormalFormFollowsCamelCaseConventions(final String expected, final List tokens) { assertEquals(expected, source.getNormalForm(tokens)); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesUtilOrderTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesUtilOrderTest.java index 662bfcd1cc0..3e07998606d 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesUtilOrderTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertiesUtilOrderTest.java @@ -70,7 +70,7 @@ public boolean containsProperty(final String key) { private final Properties properties = new Properties(); @BeforeEach - public void setUp() throws Exception { + void setUp() throws Exception { try (final InputStream is = ClassLoader.getSystemResourceAsStream("PropertiesUtilOrderTest.properties")) { properties.load(is); } @@ -102,9 +102,9 @@ void testOrderOfNormalizedProperties(final EnvironmentVariables env, final Syste final PropertiesUtil util = new PropertiesUtil(properties); // Same result for both a legacy property and a normalized property assertFalse(util.hasProperty("Log4jNormalizedProperty")); - assertEquals(null, util.getStringProperty("Log4jNormalizedProperty")); + assertNull(util.getStringProperty("Log4jNormalizedProperty")); assertFalse(util.hasProperty("log4j2.normalizedProperty")); - assertEquals(null, util.getStringProperty("log4j2.normalizedProperty")); + assertNull(util.getStringProperty("log4j2.normalizedProperty")); properties.setProperty("log4j2.normalizedProperty", "props.normalized"); assertTrue(util.hasProperty("Log4jNormalizedProperty")); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceCamelCaseTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceCamelCaseTest.java index 824c7f3771d..ebc659a470a 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceCamelCaseTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceCamelCaseTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class PropertySourceCamelCaseTest { +class PropertySourceCamelCaseTest { public static Object[][] data() { return new Object[][] { @@ -37,7 +37,7 @@ public static Object[][] data() { @ParameterizedTest @MethodSource("data") - public void testJoinAsCamelCase(final CharSequence expected, final List tokens) { + void testJoinAsCamelCase(final CharSequence expected, final List tokens) { assertEquals(expected, PropertySource.Util.joinAsCamelCase(tokens)); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceTokenizerTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceTokenizerTest.java index dba8c8f172c..ac19573f547 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceTokenizerTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/PropertySourceTokenizerTest.java @@ -24,7 +24,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class PropertySourceTokenizerTest { +class PropertySourceTokenizerTest { public static Object[][] data() { return new Object[][] { @@ -52,7 +52,7 @@ public static Object[][] data() { @ParameterizedTest @MethodSource("data") - public void testTokenize(final String value, final List expectedTokens) { + void testTokenize(final String value, final List expectedTokens) { final List tokens = PropertySource.Util.tokenize(value); assertEquals(expectedTokens, tokens); } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java index 8ca74a0bee6..927d6e3e772 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/ServiceLoaderUtilTest.java @@ -35,12 +35,12 @@ import org.apache.logging.log4j.test.junit.UsingStatusListener; import org.junit.jupiter.api.Test; -public class ServiceLoaderUtilTest { +class ServiceLoaderUtilTest { private static final Logger LOGGER = StatusLogger.getLogger(); @Test - public void testServiceResolution() { + void testServiceResolution() { final List services = new ArrayList<>(); ServiceLoaderUtil.safeStream( BetterService.class, @@ -63,7 +63,7 @@ public void testServiceResolution() { @Test @UsingStatusListener - public void testBrokenServiceFile(final ListStatusListener listener) { + void testBrokenServiceFile(final ListStatusListener listener) { final List services = new ArrayList<>(); assertDoesNotThrow(() -> ServiceLoaderUtil.safeStream( Service.class, @@ -85,7 +85,7 @@ public void testBrokenServiceFile(final ListStatusListener listener) { } @Test - public void testOsgiUnavailable() { + void testOsgiUnavailable() { // OSGI classes are present... assertDoesNotThrow(() -> Class.forName("org.osgi.framework.FrameworkUtil")); // ...but we don't run in an OSGI container diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SortedArrayStringMapTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SortedArrayStringMapTest.java index 164ae85f3f7..e5709a6a547 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SortedArrayStringMapTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SortedArrayStringMapTest.java @@ -45,26 +45,26 @@ /** * Tests the SortedArrayStringMap class. */ -public class SortedArrayStringMapTest { +class SortedArrayStringMapTest { @Test - public void testConstructorDisallowsNegativeCapacity() { + void testConstructorDisallowsNegativeCapacity() { assertThrows(IllegalArgumentException.class, () -> new SortedArrayStringMap(-1)); } @Test - public void testConstructorAllowsZeroCapacity() { + void testConstructorAllowsZeroCapacity() { final SortedArrayStringMap sortedArrayStringMap = new SortedArrayStringMap(0); assertEquals(0, sortedArrayStringMap.size()); } @Test - public void testConstructorIgnoresNull() { + void testConstructorIgnoresNull() { assertEquals(0, new SortedArrayStringMap((SortedArrayStringMap) null).size()); } @Test - public void testConstructorNonStringKeys() { + void testConstructorNonStringKeys() { final Map map = new HashMap<>(1); map.put(Long.MAX_VALUE, 1); map.put(null, null); @@ -74,7 +74,7 @@ public void testConstructorNonStringKeys() { } @Test - public void testToString() { + void testToString() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -83,7 +83,7 @@ public void testToString() { } @Test - public void testSerialization() throws Exception { + void testSerialization() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", null); // null may be treated differently @@ -95,7 +95,7 @@ public void testSerialization() throws Exception { } @Test - public void testSerializationOfEmptyMap() throws Exception { + void testSerializationOfEmptyMap() { final SortedArrayStringMap original = new SortedArrayStringMap(); final byte[] binary = serialize(original); final SortedArrayStringMap copy = deserialize(binary); @@ -103,7 +103,7 @@ public void testSerializationOfEmptyMap() throws Exception { } @Test - public void testSerializationOfNonSerializableValue() throws Exception { + void testSerializationOfNonSerializableValue() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -120,7 +120,7 @@ public void testSerializationOfNonSerializableValue() throws Exception { } @Test - public void testDeserializationOfUnknownClass() throws Exception { + void testDeserializationOfUnknownClass() throws Exception { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("serializableButNotInClasspathOfDeserializer", new org.junit.runner.Result()); @@ -189,7 +189,7 @@ private String createClassPath(final Class cls) throws Exception { } @Test - public void testPutAll() { + void testPutAll() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -210,7 +210,7 @@ public void testPutAll() { } @Test - public void testPutAll_overwritesSameKeys2() { + void testPutAll_overwritesSameKeys2() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -236,7 +236,7 @@ public void testPutAll_overwritesSameKeys2() { } @Test - public void testPutAll_nullKeyInLargeOriginal() { + void testPutAll_nullKeyInLargeOriginal() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -261,7 +261,7 @@ public void testPutAll_nullKeyInLargeOriginal() { } @Test - public void testPutAll_nullKeyInSmallOriginal() { + void testPutAll_nullKeyInSmallOriginal() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -284,7 +284,7 @@ public void testPutAll_nullKeyInSmallOriginal() { } @Test - public void testPutAll_nullKeyInSmallAdditional() { + void testPutAll_nullKeyInSmallAdditional() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -309,7 +309,7 @@ public void testPutAll_nullKeyInSmallAdditional() { } @Test - public void testPutAll_nullKeyInLargeAdditional() { + void testPutAll_nullKeyInLargeAdditional() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -332,7 +332,7 @@ public void testPutAll_nullKeyInLargeAdditional() { } @Test - public void testPutAll_nullKeyInBoth_LargeOriginal() { + void testPutAll_nullKeyInBoth_LargeOriginal() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -358,7 +358,7 @@ public void testPutAll_nullKeyInBoth_LargeOriginal() { } @Test - public void testPutAll_nullKeyInBoth_SmallOriginal() { + void testPutAll_nullKeyInBoth_SmallOriginal() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -382,7 +382,7 @@ public void testPutAll_nullKeyInBoth_SmallOriginal() { } @Test - public void testPutAll_overwritesSameKeys1() { + void testPutAll_overwritesSameKeys1() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -404,13 +404,13 @@ public void testPutAll_overwritesSameKeys1() { } @Test - public void testEquals() { + void testEquals() { final SortedArrayStringMap original = new SortedArrayStringMap(); final SortedArrayStringMap other = new SortedArrayStringMap(); assertEquals(other, original, "Empty maps are equal"); assertEquals(other.hashCode(), original.hashCode(), "Empty maps have equal hashcode"); - assertNotEquals(original, "Object other than SortedArrayStringMap"); + assertNotEquals("Object other than SortedArrayStringMap", original); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -445,7 +445,7 @@ public void testEquals() { } @Test - public void testToMap() { + void testToMap() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -462,7 +462,7 @@ public void testToMap() { } @Test - public void testPutAll_KeepsExistingValues() { + void testPutAll_KeepsExistingValues() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); @@ -492,7 +492,7 @@ public void testPutAll_KeepsExistingValues() { } @Test - public void testPutAll_sizePowerOfTwo() { + void testPutAll_sizePowerOfTwo() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); @@ -527,7 +527,7 @@ public void testPutAll_sizePowerOfTwo() { } @Test - public void testPutAll_largeAddition() { + void testPutAll_largeAddition() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue(null, "nullVal"); original.putValue("a", "aaa"); @@ -555,7 +555,7 @@ public void testPutAll_largeAddition() { } @Test - public void testPutAllSelfDoesNotModify() { + void testPutAllSelfDoesNotModify() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); @@ -571,7 +571,7 @@ public void testPutAllSelfDoesNotModify() { } @Test - public void testConcurrentModificationBiConsumerPut() { + void testConcurrentModificationBiConsumerPut() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows( @@ -580,7 +580,7 @@ public void testConcurrentModificationBiConsumerPut() { } @Test - public void testConcurrentModificationBiConsumerPutValue() { + void testConcurrentModificationBiConsumerPutValue() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows( @@ -589,21 +589,21 @@ public void testConcurrentModificationBiConsumerPutValue() { } @Test - public void testConcurrentModificationBiConsumerRemove() { + void testConcurrentModificationBiConsumerRemove() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows(ConcurrentModificationException.class, () -> original.forEach((s, o) -> original.remove("a"))); } @Test - public void testConcurrentModificationBiConsumerClear() { + void testConcurrentModificationBiConsumerClear() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows(ConcurrentModificationException.class, () -> original.forEach((s, o) -> original.clear())); } @Test - public void testConcurrentModificationTriConsumerPut() { + void testConcurrentModificationTriConsumerPut() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows( @@ -612,7 +612,7 @@ public void testConcurrentModificationTriConsumerPut() { } @Test - public void testConcurrentModificationTriConsumerPutValue() { + void testConcurrentModificationTriConsumerPutValue() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows( @@ -621,7 +621,7 @@ public void testConcurrentModificationTriConsumerPutValue() { } @Test - public void testConcurrentModificationTriConsumerRemove() { + void testConcurrentModificationTriConsumerRemove() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows( @@ -630,7 +630,7 @@ public void testConcurrentModificationTriConsumerRemove() { } @Test - public void testConcurrentModificationTriConsumerClear() { + void testConcurrentModificationTriConsumerClear() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); assertThrows( @@ -638,12 +638,12 @@ public void testConcurrentModificationTriConsumerClear() { } @Test - public void testInitiallyNotFrozen() { + void testInitiallyNotFrozen() { assertFalse(new SortedArrayStringMap().isFrozen()); } @Test - public void testIsFrozenAfterCallingFreeze() { + void testIsFrozenAfterCallingFreeze() { final SortedArrayStringMap original = new SortedArrayStringMap(); assertFalse(original.isFrozen(), "before freeze"); original.freeze(); @@ -651,14 +651,14 @@ public void testIsFrozenAfterCallingFreeze() { } @Test - public void testFreezeProhibitsPutValue() { + void testFreezeProhibitsPutValue() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.freeze(); assertThrows(UnsupportedOperationException.class, () -> original.putValue("a", "aaa")); } @Test - public void testFreezeProhibitsRemove() { + void testFreezeProhibitsRemove() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("b", "bbb"); original.freeze(); @@ -668,7 +668,7 @@ public void testFreezeProhibitsRemove() { } @Test - public void testFreezeAllowsRemoveOfNonExistingKey() { + void testFreezeAllowsRemoveOfNonExistingKey() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("b", "bbb"); original.freeze(); @@ -676,14 +676,14 @@ public void testFreezeAllowsRemoveOfNonExistingKey() { } @Test - public void testFreezeAllowsRemoveIfEmpty() { + void testFreezeAllowsRemoveIfEmpty() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.freeze(); assertDoesNotThrow(() -> original.remove("a")); } @Test - public void testFreezeProhibitsClear() { + void testFreezeProhibitsClear() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "aaa"); original.freeze(); @@ -691,14 +691,14 @@ public void testFreezeProhibitsClear() { } @Test - public void testFreezeAllowsClearIfEmpty() { + void testFreezeAllowsClearIfEmpty() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.freeze(); assertDoesNotThrow(original::clear); } @Test - public void testPutInsertsInAlphabeticOrder() { + void testPutInsertsInAlphabeticOrder() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -723,7 +723,7 @@ public void testPutInsertsInAlphabeticOrder() { } @Test - public void testPutValueInsertsInAlphabeticOrder() { + void testPutValueInsertsInAlphabeticOrder() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -748,7 +748,7 @@ public void testPutValueInsertsInAlphabeticOrder() { } @Test - public void testNullKeysAllowed() { + void testNullKeysAllowed() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -776,7 +776,7 @@ public void testNullKeysAllowed() { } @Test - public void testNullKeysCopiedToAsMap() { + void testNullKeysCopiedToAsMap() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -815,7 +815,7 @@ public void testNullKeysCopiedToAsMap() { } @Test - public void testRemove() { + void testRemove() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); assertEquals(1, original.size()); @@ -831,7 +831,7 @@ public void testRemove() { } @Test - public void testRemoveNullsOutRemovedSlot() throws Exception { + void testRemoveNullsOutRemovedSlot() throws Exception { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("b", "bvalue"); @@ -851,7 +851,7 @@ public void testRemoveNullsOutRemovedSlot() throws Exception { } @Test - public void testRemoveWhenFull() { + void testRemoveWhenFull() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("b", "bvalue"); @@ -861,7 +861,7 @@ public void testRemoveWhenFull() { } @Test - public void testNullValuesArePreserved() { + void testNullValuesArePreserved() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); assertEquals(1, original.size()); @@ -877,7 +877,7 @@ public void testNullValuesArePreserved() { } @Test - public void testGet() { + void testGet() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -895,7 +895,7 @@ public void testGet() { } @Test - public void testGetValue_GetValueAt() { + void testGetValue_GetValueAt() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -922,7 +922,7 @@ public void testGetValue_GetValueAt() { } @Test - public void testClear() throws Exception { + void testClear() throws Exception { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -940,7 +940,7 @@ public void testClear() throws Exception { } @Test - public void testIndexOfKey() { + void testIndexOfKey() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); assertEquals(0, original.indexOfKey("a")); @@ -977,7 +977,7 @@ public void testIndexOfKey() { } @Test - public void testContainsKey() { + void testContainsKey() { final SortedArrayStringMap original = new SortedArrayStringMap(); assertFalse(original.containsKey("a"), "a"); assertFalse(original.containsKey("B"), "B"); @@ -1010,7 +1010,7 @@ public void testContainsKey() { } @Test - public void testGetValueAt() { + void testGetValueAt() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); assertEquals("a", original.getKeyAt(0)); @@ -1032,7 +1032,7 @@ public void testGetValueAt() { } @Test - public void testSizeAndIsEmpty() { + void testSizeAndIsEmpty() { final SortedArrayStringMap original = new SortedArrayStringMap(); assertEquals(0, original.size()); assertTrue(original.isEmpty(), "initial"); @@ -1063,7 +1063,7 @@ public void testSizeAndIsEmpty() { } @Test - public void testForEachBiConsumer() { + void testForEachBiConsumer() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -1095,7 +1095,7 @@ static class State { }; @Test - public void testForEachTriConsumer() { + void testForEachTriConsumer() { final SortedArrayStringMap original = new SortedArrayStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java index b4d240d942c..e65755bba12 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorTestIT.java @@ -16,12 +16,13 @@ */ package org.apache.logging.log4j.util; +import static org.junit.jupiter.api.Assertions.assertSame; + import java.security.Permission; import java.util.Deque; import org.apache.logging.log4j.test.junit.SecurityManagerTestRule; import org.junit.Rule; import org.junit.Test; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.parallel.ResourceLock; /** @@ -57,6 +58,6 @@ public void checkPermission(final Permission permission) { public void testGetCurrentStacktraceSlowPath() { final StackLocator stackLocator = StackLocator.getInstance(); final Deque> classes = stackLocator.getCurrentStackTrace(); - Assertions.assertSame(StackLocator.class, classes.getFirst()); + assertSame(StackLocator.class, classes.getFirst()); } } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java index 0b96b8e970e..549e1c9c26f 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StackLocatorUtilTest.java @@ -31,11 +31,11 @@ /** * Tests {@link StackLocatorUtil}. */ -public class StackLocatorUtilTest { +class StackLocatorUtilTest { @Test @EnabledOnJre(JRE.JAVA_8) - public void testStackTraceEquivalence() throws Exception { + void testStackTraceEquivalence() throws Exception { // Frame 8 is a hidden frame and does not show in the stacktrace for (int i = 1; i < 8; i++) { final Class expected = (Class) Class.forName("sun.reflect.Reflection") @@ -50,26 +50,26 @@ public void testStackTraceEquivalence() throws Exception { } @Test - public void testGetCallerClass() throws Exception { + void testGetCallerClass() { final Class expected = StackLocatorUtilTest.class; final Class actual = StackLocatorUtil.getCallerClass(1); assertSame(expected, actual); } @Test - public void testGetCallerClassLoader() throws Exception { + void testGetCallerClassLoader() { assertSame(StackLocatorUtilTest.class.getClassLoader(), StackLocatorUtil.getCallerClassLoader(1)); } @Test - public void testGetCallerClassNameViaStackTrace() throws Exception { + void testGetCallerClassNameViaStackTrace() throws Exception { final Class expected = StackLocatorUtilTest.class; final Class actual = Class.forName(new Throwable().getStackTrace()[0].getClassName()); assertSame(expected, actual); } @Test - public void testGetCurrentStackTrace() throws Exception { + void testGetCurrentStackTrace() { final Deque> classes = StackLocatorUtil.getCurrentStackTrace(); final Stack> reversed = new Stack<>(); reversed.ensureCapacity(classes.size()); @@ -84,7 +84,7 @@ public void testGetCurrentStackTrace() throws Exception { } @Test - public void testTopElementInStackTrace() { + void testTopElementInStackTrace() { final StackLocator stackLocator = StackLocator.getInstance(); final Deque> classes = stackLocator.getCurrentStackTrace(); // Removing private class in "PrivateSecurityManagerStackTraceUtil" @@ -93,7 +93,7 @@ public void testTopElementInStackTrace() { } @Test - public void testGetCallerClassViaName() throws Exception { + void testGetCallerClassViaName() { final Class expected = TestMethodTestDescriptor.class; final Class actual = StackLocatorUtil.getCallerClass("org.junit.platform.engine.support.hierarchical.ThrowableCollector"); @@ -103,7 +103,7 @@ public void testGetCallerClassViaName() throws Exception { } @Test - public void testGetCallerClassViaAnchorClass() throws Exception { + void testGetCallerClassViaAnchorClass() { final Class expected = TestMethodTestDescriptor.class; final Class actual = StackLocatorUtil.getCallerClass(ThrowableCollector.class); // if this test fails in the future, it's probably because of a JUnit upgrade; check the new stack trace and @@ -112,7 +112,7 @@ public void testGetCallerClassViaAnchorClass() throws Exception { } @Test - public void testLocateClass() { + void testLocateClass() { final ClassLocator locator = new ClassLocator(); final Class clazz = locator.locateClass(); assertNotNull(clazz, "Could note locate class"); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringBuildersTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringBuildersTest.java index 72cea26c2ba..8722dd33e42 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringBuildersTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringBuildersTest.java @@ -24,9 +24,9 @@ /** * Tests the StringBuilders class. */ -public class StringBuildersTest { +class StringBuildersTest { @Test - public void trimToMaxSize() { + void trimToMaxSize() { final StringBuilder sb = new StringBuilder(); final char[] value = new char[4 * 1024]; sb.append(value); @@ -37,7 +37,7 @@ public void trimToMaxSize() { } @Test - public void trimToMaxSizeWithLargeCapacity() { + void trimToMaxSizeWithLargeCapacity() { final StringBuilder sb = new StringBuilder(); final char[] value = new char[4 * 1024]; sb.append(value); @@ -49,7 +49,7 @@ public void trimToMaxSizeWithLargeCapacity() { } @Test - public void escapeJsonCharactersCorrectly() { + void escapeJsonCharactersCorrectly() { final String jsonValueNotEscaped = "{\"field\n1\":\"value_1\"}"; final String jsonValueEscaped = "{\\\"field\\n1\\\":\\\"value_1\\\"}"; @@ -68,7 +68,7 @@ public void escapeJsonCharactersCorrectly() { } @Test - public void escapeJsonCharactersISOControl() { + void escapeJsonCharactersISOControl() { final String jsonValueNotEscaped = "{\"field\n1\":\"value" + (char) 0x8F + "_1\"}"; final String jsonValueEscaped = "{\\\"field\\n1\\\":\\\"value\\u008F_1\\\"}"; @@ -80,7 +80,7 @@ public void escapeJsonCharactersISOControl() { } @Test - public void escapeXMLCharactersCorrectly() { + void escapeXMLCharactersCorrectly() { final String xmlValueNotEscaped = "<\"Salt&Peppa'\">"; final String xmlValueEscaped = "<"Salt&Peppa'">"; diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringsTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringsTest.java index d970be499f5..66c9b956a35 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringsTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/StringsTest.java @@ -29,10 +29,10 @@ /** * Tests {@linkStrings}. */ -public class StringsTest { +class StringsTest { @Test - public void testConcat() { + void testConcat() { assertEquals("ab", Strings.concat("a", "b")); assertEquals("a", Strings.concat("a", "")); assertEquals("a", Strings.concat("a", null)); @@ -44,13 +44,13 @@ public void testConcat() { * A sanity test to make sure a typo does not mess up {@link Strings#EMPTY}. */ @Test - public void testEMPTY() { + void testEMPTY() { assertEquals("", Strings.EMPTY); assertEquals(0, Strings.EMPTY.length()); } @Test - public void testIsBlank() { + void testIsBlank() { assertTrue(Strings.isBlank(null)); assertTrue(Strings.isBlank("")); assertTrue(Strings.isBlank(" ")); @@ -61,7 +61,7 @@ public void testIsBlank() { } @Test - public void testIsEmpty() { + void testIsEmpty() { assertTrue(Strings.isEmpty(null)); assertTrue(Strings.isEmpty("")); assertFalse(Strings.isEmpty(" ")); @@ -69,7 +69,7 @@ public void testIsEmpty() { } @Test - public void testJoin() { + void testJoin() { assertNull(Strings.join((Iterable) null, '.')); assertNull(Strings.join((Iterator) null, '.')); assertEquals("", Strings.join((Collections.emptyList()), '.')); @@ -85,7 +85,7 @@ public void testJoin() { } @Test - public void splitList() { + void splitList() { String[] list = Strings.splitList("1, 2, 3"); assertEquals(3, list.length); list = Strings.splitList(""); @@ -95,12 +95,12 @@ public void splitList() { } @Test - public void testQuote() { + void testQuote() { assertEquals("'Q'", Strings.quote("Q")); } @Test - public void testToLowerCase() { + void testToLowerCase() { assertEquals("a", Strings.toRootLowerCase("A")); assertEquals("a", Strings.toRootLowerCase("a")); } diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceTest.java index 374bd6522fb..4aba702bd01 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/SystemPropertiesPropertySourceTest.java @@ -31,7 +31,7 @@ */ @Tag("concurrency") @ResourceLock(Resources.SYSTEM_PROPERTIES) -public class SystemPropertiesPropertySourceTest { +class SystemPropertiesPropertySourceTest { private static final int ITERATIONS = 10000; @@ -48,7 +48,7 @@ public class SystemPropertiesPropertySourceTest { * @throws ExecutionException */ @Test - public void testMultiThreadedAccess() throws InterruptedException, ExecutionException { + void testMultiThreadedAccess() throws InterruptedException, ExecutionException { final ExecutorService threadPool = Executors.newSingleThreadExecutor(); try { final Future future = threadPool.submit(() -> { diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox1Test.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox1Test.java index a0ccf7ce287..2ce60cd0552 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox1Test.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox1Test.java @@ -29,19 +29,19 @@ * Tests the Unbox class. */ @ResourceLock(Resources.SYSTEM_PROPERTIES) -public class Unbox1Test { +class Unbox1Test { @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.clearProperty("log4j.unbox.ringbuffer.size"); } @Test - public void testBoxClaimsItHas32Slots() { + void testBoxClaimsItHas32Slots() { assertEquals(32, Unbox.getRingbufferSize()); } @Test - public void testBoxHas32Slots() { + void testBoxHas32Slots() { final int MAX = 32; final StringBuilder[] probe = new StringBuilder[MAX * 3]; for (int i = 0; i <= probe.length - 8; ) { @@ -63,13 +63,13 @@ public void testBoxHas32Slots() { } @Test - public void testBoxBoolean() { + void testBoxBoolean() { assertEquals("true", Unbox.box(true).toString()); assertEquals("false", Unbox.box(false).toString()); } @Test - public void testBoxByte() { + void testBoxByte() { assertEquals("0", Unbox.box((byte) 0).toString()); assertEquals("1", Unbox.box((byte) 1).toString()); assertEquals("127", Unbox.box((byte) 127).toString()); @@ -78,14 +78,14 @@ public void testBoxByte() { } @Test - public void testBoxChar() { + void testBoxChar() { assertEquals("a", Unbox.box('a').toString()); assertEquals("b", Unbox.box('b').toString()); assertEquals("字", Unbox.box('字').toString()); } @Test - public void testBoxDouble() { + void testBoxDouble() { assertEquals("3.14", Unbox.box(3.14).toString()); assertEquals( Double.toString(Double.MAX_VALUE), Unbox.box(Double.MAX_VALUE).toString()); @@ -94,14 +94,14 @@ public void testBoxDouble() { } @Test - public void testBoxFloat() { + void testBoxFloat() { assertEquals("3.14", Unbox.box(3.14F).toString()); assertEquals(Float.toString(Float.MAX_VALUE), Unbox.box(Float.MAX_VALUE).toString()); assertEquals(Float.toString(Float.MIN_VALUE), Unbox.box(Float.MIN_VALUE).toString()); } @Test - public void testBoxInt() { + void testBoxInt() { assertEquals("0", Unbox.box(0).toString()); assertEquals("1", Unbox.box(1).toString()); assertEquals("127", Unbox.box(127).toString()); @@ -116,7 +116,7 @@ public void testBoxInt() { } @Test - public void testBoxLong() { + void testBoxLong() { assertEquals("0", Unbox.box(0L).toString()); assertEquals("1", Unbox.box(1L).toString()); assertEquals("127", Unbox.box(127L).toString()); @@ -127,7 +127,7 @@ public void testBoxLong() { } @Test - public void testBoxShort() { + void testBoxShort() { assertEquals("0", Unbox.box((short) 0).toString()); assertEquals("1", Unbox.box((short) 1).toString()); assertEquals("127", Unbox.box((short) 127).toString()); @@ -138,7 +138,7 @@ public void testBoxShort() { } @Test - public void testBoxIsThreadLocal() throws Exception { + void testBoxIsThreadLocal() throws Exception { final StringBuilder[] probe = new StringBuilder[16 * 3]; populate(0, probe); final Thread t1 = new Thread(() -> populate(16, probe)); diff --git a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox2ConfigurableTest.java b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox2ConfigurableTest.java index 16853e4c42e..fd0fe73e4af 100644 --- a/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox2ConfigurableTest.java +++ b/log4j-api-test/src/test/java/org/apache/logging/log4j/util/Unbox2ConfigurableTest.java @@ -37,14 +37,14 @@ */ @EnabledIfSystemProperty(named = "test", matches = ".*Unbox2ConfigurableTest.*") @ResourceLock(Resources.SYSTEM_PROPERTIES) -public class Unbox2ConfigurableTest { +class Unbox2ConfigurableTest { @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty("log4j.unbox.ringbuffer.size", "65"); } @AfterAll - public static void afterClass() throws Exception { + static void afterClass() throws Exception { System.clearProperty("log4j.unbox.ringbuffer.size"); // ensure subsequent tests (which assume 32 slots) pass @@ -65,13 +65,13 @@ public static void afterClass() throws Exception { } @Test - public void testBoxConfiguredTo128Slots() { + void testBoxConfiguredTo128Slots() { // next power of 2 that is 65 or more assertEquals(128, Unbox.getRingbufferSize()); } @Test - public void testBoxSuccessfullyConfiguredTo128Slots() { + void testBoxSuccessfullyConfiguredTo128Slots() { final int MAX = 128; final StringBuilder[] probe = new StringBuilder[MAX * 3]; for (int i = 0; i <= probe.length - 8; ) { diff --git a/log4j-cassandra/src/test/java/org/apache/logging/log4j/cassandra/CassandraRule.java b/log4j-cassandra/src/test/java/org/apache/logging/log4j/cassandra/CassandraRule.java index 3505b8b9bb8..8ae051b2a5b 100644 --- a/log4j-cassandra/src/test/java/org/apache/logging/log4j/cassandra/CassandraRule.java +++ b/log4j-cassandra/src/test/java/org/apache/logging/log4j/cassandra/CassandraRule.java @@ -77,7 +77,7 @@ protected void before() throws Throwable { Files.copy(getClass().getResourceAsStream("/cassandra.yaml"), config); System.setProperty("cassandra.native_transport_port", "0"); System.setProperty("cassandra.storage_port", "0"); - System.setProperty("cassandra.config", "file:" + config.toString()); + System.setProperty("cassandra.config", "file:" + config); System.setProperty("cassandra.storagedir", root.toString()); System.setProperty("cassandra-foreground", "true"); // prevents Cassandra from closing stdout/stderr THREAD_FACTORY.newThread(embeddedCassandra).start(); @@ -166,7 +166,7 @@ public InetSocketAddress getNativeSocket() { serversField.setAccessible(true); @SuppressWarnings("unchecked") final Collection servers = (Collection) serversField.get(nativeService); - if (servers.size() > 0) { + if (!servers.isEmpty()) { final Server server = servers.iterator().next(); final Field trackerField = Server.class.getDeclaredField("connectionTracker"); trackerField.setAccessible(true); diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/FilterPerformanceComparison.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/FilterPerformanceComparison.java index 4495ed3defa..761121341a4 100644 --- a/log4j-core-its/src/test/java/org/apache/logging/log4j/FilterPerformanceComparison.java +++ b/log4j-core-its/src/test/java/org/apache/logging/log4j/FilterPerformanceComparison.java @@ -20,19 +20,18 @@ import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.test.categories.PerformanceTests; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.slf4j.MDC; /** * */ -@Category(PerformanceTests.class) -public class FilterPerformanceComparison { +@Tag("PerformanceTests") +class FilterPerformanceComparison { private final Logger logger = LogManager.getLogger(FilterPerformanceComparison.class.getName()); private final org.slf4j.Logger logbacklogger = org.slf4j.LoggerFactory.getLogger(FilterPerformanceComparison.class); @@ -47,30 +46,30 @@ public class FilterPerformanceComparison { private static final String LOGBACK_CONF = "logback.configurationFile"; - @BeforeClass - public static void setupClass() { + @BeforeAll + static void setupClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); System.setProperty(LOGBACK_CONF, LOGBACK_CONFIG); } - @AfterClass - public static void cleanupClass() { + @AfterAll + static void cleanupClass() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); System.clearProperty(LOGBACK_CONF); } - @After - public void after() { + @AfterEach + void after() { ThreadContext.clearAll(); } @Test - public void testPerformanceEmptyContext() throws Exception { - testPerformance(Collections.emptyMap()); + void testPerformanceEmptyContext() throws Exception { + testPerformance(Collections.emptyMap()); } @Test - public void testPerformanceNonEmptyContext() throws Exception { + void testPerformanceNonEmptyContext() throws Exception { testPerformance(createNonEmptyContextData()); } @@ -88,7 +87,7 @@ private static void putContextData(final Map contextData) { } } - private void testPerformance(final Map contextData) throws Exception { + private void testPerformance(final Map contextData) { putContextData(contextData); Target.LOGBACK.timedLoop(logger, logbacklogger, WARMUP); Target.LOG4J2.timedLoop(logger, logbacklogger, WARMUP); @@ -109,12 +108,12 @@ private void testPerformance(final Map contextData) throws Excep } @Test - public void testThreadsEmptyContext() throws Exception { - testThreads(Collections.emptyMap()); + void testThreadsEmptyContext() throws Exception { + testThreads(Collections.emptyMap()); } @Test - public void testThreadsNonEmptyContext() throws Exception { + void testThreadsNonEmptyContext() throws Exception { testThreads(createNonEmptyContextData()); } diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceComparison.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceComparison.java index ce79919801d..93ce3350f57 100644 --- a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceComparison.java +++ b/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceComparison.java @@ -25,18 +25,17 @@ import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.test.categories.PerformanceTests; import org.apache.logging.log4j.core.test.util.Profiler; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Use this class to analyze performance between Log4j and other logging frameworks. */ -@Category(PerformanceTests.class) -public class PerformanceComparison { +@Tag("PerformanceTests") +class PerformanceComparison { private final Logger logger = LogManager.getLogger(PerformanceComparison.class.getName()); private final org.slf4j.Logger logbacklogger = org.slf4j.LoggerFactory.getLogger(PerformanceComparison.class); @@ -54,15 +53,15 @@ public class PerformanceComparison { private static final String LOGBACK_CONF = "logback.configurationFile"; private static final String LOG4J_CONF = "log4j.configuration"; - @BeforeClass - public static void setupClass() { + @BeforeAll + static void setupClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); System.setProperty(LOGBACK_CONF, LOGBACK_CONFIG); System.setProperty(LOG4J_CONF, LOG4J_CONFIG); } - @AfterClass - public static void cleanupClass() { + @AfterAll + static void cleanupClass() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); System.clearProperty(LOGBACK_CONF); System.clearProperty(LOG4J_CONF); @@ -72,7 +71,7 @@ public static void cleanupClass() { } @Test - public void testPerformance() throws Exception { + void testPerformance() { log4j(WARMUP); logback(WARMUP); diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceRun.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceRun.java index ac344b21dca..253b8f70cba 100644 --- a/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceRun.java +++ b/log4j-core-its/src/test/java/org/apache/logging/log4j/PerformanceRun.java @@ -50,7 +50,7 @@ public class PerformanceRun { private static final int COUNT = 1000000; @Test - public void testPerformance() throws Exception { + public void testPerformance() { System.out.println("Starting Log4j 2.0"); final long result3 = log4j2(COUNT); diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/SimplePerfTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/SimplePerfTest.java index c84aaf9a4ed..e3c1c7beb03 100644 --- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/SimplePerfTest.java +++ b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/SimplePerfTest.java @@ -16,24 +16,23 @@ */ package org.apache.logging.log4j.core; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Random; 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.DefaultConfiguration; -import org.apache.logging.log4j.core.test.categories.PerformanceTests; import org.apache.logging.log4j.util.Timer; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * */ -@Category(PerformanceTests.class) -public class SimplePerfTest { +@Tag("PerformanceTests") +class SimplePerfTest { private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(SimplePerfTest.class.getName()); private volatile Level lvl = Level.DEBUG; @@ -44,8 +43,8 @@ public class SimplePerfTest { private static int RAND_SIZE = 250; private static int[] values = new int[RAND_SIZE]; - @BeforeClass - public static void setupClass() { + @BeforeAll + static void setupClass() { final Configuration config = LoggerContext.getContext().getConfiguration(); @@ -66,11 +65,11 @@ public static void setupClass() { timer.stop(); maxTime = timer.getElapsedNanoTime(); System.gc(); - System.out.println(timer.toString()); + System.out.println(timer); } @Test - public void debugDisabled() throws Exception { + void debugDisabled() throws Exception { System.gc(); Thread.sleep(100); final Timer timer = new Timer("DebugDisabled", LOOP_CNT); @@ -79,12 +78,12 @@ public void debugDisabled() throws Exception { logger.isDebugEnabled(); } timer.stop(); - System.out.println(timer.toString()); - assertTrue("Timer exceeded max time of " + maxTime, maxTime > timer.getElapsedNanoTime()); + System.out.println(timer); + assertTrue(maxTime > timer.getElapsedNanoTime(), "Timer exceeded max time of " + maxTime); } @Test - public void debugDisabledByLevel() throws Exception { + void debugDisabledByLevel() throws Exception { System.gc(); Thread.sleep(100); final Timer timer = new Timer("IsEnabled", LOOP_CNT); @@ -93,12 +92,12 @@ public void debugDisabledByLevel() throws Exception { logger.isEnabled(Level.DEBUG); } timer.stop(); - System.out.println(timer.toString()); - assertTrue("Timer exceeded max time of " + maxTime, maxTime > timer.getElapsedNanoTime()); + System.out.println(timer); + assertTrue(maxTime > timer.getElapsedNanoTime(), "Timer exceeded max time of " + maxTime); } @Test - public void debugLogger() throws Exception { + void debugLogger() throws Exception { System.gc(); Thread.sleep(100); final Timer timer = new Timer("DebugLogger", LOOP_CNT); @@ -108,8 +107,8 @@ public void debugLogger() throws Exception { logger.debug(msg); } timer.stop(); - System.out.println(timer.toString()); - assertTrue("Timer exceeded max time of " + maxTime, maxTime > timer.getElapsedNanoTime()); + System.out.println(timer); + assertTrue(maxTime > timer.getElapsedNanoTime(), "Timer exceeded max time of " + maxTime); } /* @Test diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedPerfTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedPerfTest.java index fa4f00b6911..c3590118521 100644 --- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedPerfTest.java +++ b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedPerfTest.java @@ -20,16 +20,15 @@ import java.util.concurrent.Executors; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.test.categories.PerformanceTests; import org.apache.logging.log4j.util.Timer; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * */ -@Category(PerformanceTests.class) -public class ThreadedPerfTest { +@Tag("PerformanceTests") +class ThreadedPerfTest { private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(ThreadedPerfTest.class.getName()); @@ -38,7 +37,7 @@ public class ThreadedPerfTest { private static final int THREADS = 10; @Test - public void debugDisabled() { + void debugDisabled() { final Timer timer = new Timer("DebugDisabled", LOOP_CNT * THREADS); final Runnable runnable = new DebugDisabledRunnable(); final ExecutorService pool = Executors.newFixedThreadPool(THREADS); @@ -48,11 +47,11 @@ public void debugDisabled() { } pool.shutdown(); timer.stop(); - System.out.println(timer.toString()); + System.out.println(timer); } @Test - public void debugLogger() { + void debugLogger() { final Timer timer = new Timer("DebugLogger", LOOP_CNT * THREADS); final Runnable runnable = new DebugLoggerRunnable(); final ExecutorService pool = Executors.newFixedThreadPool(THREADS); @@ -62,7 +61,7 @@ public void debugLogger() { } pool.shutdown(); timer.stop(); - System.out.println(timer.toString()); + System.out.println(timer); } public static class DebugDisabledRunnable implements Runnable { diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java index 1ef9c78703c..ce8a7d83543 100644 --- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java +++ b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/ThreadedTest.java @@ -22,18 +22,17 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.test.categories.PerformanceTests; import org.apache.logging.log4j.core.test.junit.LoggerContextRule; 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 org.junit.rules.RuleChain; import org.junit.runners.model.Statement; /** * */ -@Category(PerformanceTests.class) +@Tag("PerformanceTests") public class ThreadedTest { private static final String DIR = "target/threaded"; private static final String CONFIG = "log4j-threaded.xml"; @@ -61,7 +60,7 @@ public void evaluate() throws Throwable { .around(context); @Test - public void testDeadlock() throws Exception { + void testDeadlock() throws Exception { final ExecutorService pool = Executors.newFixedThreadPool(THREADS * 2); final State state = new State(); for (int count = 0; count < THREADS; ++count) { diff --git a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestDriver.java b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestDriver.java index ea5b453cacb..e7620864b9b 100644 --- a/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestDriver.java +++ b/log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/PerfTestDriver.java @@ -18,7 +18,6 @@ import java.io.BufferedReader; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; @@ -36,7 +35,7 @@ public class PerfTestDriver { private static final String DEFAULT_WAIT_STRATEGY = "Block"; - static enum WaitStrategy { + enum WaitStrategy { Sleep, Yield, Block; @@ -203,14 +202,14 @@ public String toString() { } } - static enum Runner { + enum Runner { Log4j12(RunLog4j1.class), // Log4j2(RunLog4j2.class), // Logback(RunLogback.class); private final Class implementationClass; - private Runner(final Class cls) { + Runner(final Class cls) { this.implementationClass = cls; } } @@ -306,7 +305,7 @@ private static void add( } private static void runPerfTests(final String[] args, final List tests) - throws IOException, InterruptedException, FileNotFoundException { + throws IOException, InterruptedException { final String java = args.length > 0 ? args[0] : "java"; final int repeat = args.length > 1 ? Integers.parseInt(args[1]) : 5; int x = 0; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/FormatterLoggerManualExample.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/FormatterLoggerManualExample.java index 54c7c50101e..0f12ad168f4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/FormatterLoggerManualExample.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/FormatterLoggerManualExample.java @@ -40,7 +40,7 @@ String getName() { */ public static void main(final String[] args) { try (final LoggerContext ctx = Configurator.initialize( - FormatterLoggerManualExample.class.getName(), "target/test-classes/log4j2-console.xml"); ) { + FormatterLoggerManualExample.class.getName(), "target/test-classes/log4j2-console.xml")) { final User user = new User(); logger.debug("User %s with birthday %s", user.getName(), user.getBirthdayCalendar()); logger.debug("User %1$s with birthday %2$tm %2$te, %2$tY", user.getName(), user.getBirthdayCalendar()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInJsonTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInJsonTest.java index eab2c568a2e..07e10805d4d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInJsonTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInJsonTest.java @@ -18,11 +18,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper; -import org.apache.logging.log4j.core.test.categories.Layouts; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; -@Category(Layouts.Json.class) -public class MarkerMixInJsonTest extends MarkerMixInTest { +@Tag("Layouts.Json") +class MarkerMixInJsonTest extends MarkerMixInTest { @Override protected ObjectMapper newObjectMapper() { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInTest.java index e21c229a93d..00175a393f6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInTest.java @@ -16,28 +16,31 @@ */ package org.apache.logging.log4j; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import java.io.IOException; import org.apache.logging.log4j.MarkerManager.Log4jMarker; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests {@link MarkerMixIn}. * * This class is in this package to let {@link Log4jMarker} have the least visibility. */ -public abstract class MarkerMixInTest { +abstract class MarkerMixInTest { private ObjectReader reader; private ObjectWriter writer; - @Before - public void setUp() { + @BeforeEach + void setUp() { final ObjectMapper log4jObjectMapper = newObjectMapper(); writer = log4jObjectMapper.writer(); reader = log4jObjectMapper.readerFor(Log4jMarker.class); @@ -47,23 +50,23 @@ public void setUp() { protected abstract ObjectMapper newObjectMapper(); @Test - public void testNameOnly() throws IOException { + void testNameOnly() throws IOException { final Marker expected = MarkerManager.getMarker("A"); final String str = writeValueAsString(expected); - Assert.assertFalse(str.contains("parents")); + assertFalse(str.contains("parents")); final Marker actual = reader.readValue(str); - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } @Test - public void testOneParent() throws IOException { + void testOneParent() throws IOException { final Marker expected = MarkerManager.getMarker("A"); final Marker parent = MarkerManager.getMarker("PARENT_MARKER"); expected.addParents(parent); final String str = writeValueAsString(expected); - Assert.assertTrue(str.contains("PARENT_MARKER")); + assertTrue(str.contains("PARENT_MARKER")); final Marker actual = reader.readValue(str); - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } /** @@ -78,16 +81,16 @@ private String writeValueAsString(final Marker expected) throws JsonProcessingEx } @Test - public void testTwoParents() throws IOException { + void testTwoParents() throws IOException { final Marker expected = MarkerManager.getMarker("A"); final Marker parent1 = MarkerManager.getMarker("PARENT_MARKER1"); final Marker parent2 = MarkerManager.getMarker("PARENT_MARKER2"); expected.addParents(parent1); expected.addParents(parent2); final String str = writeValueAsString(expected); - Assert.assertTrue(str.contains("PARENT_MARKER1")); - Assert.assertTrue(str.contains("PARENT_MARKER2")); + assertTrue(str.contains("PARENT_MARKER1")); + assertTrue(str.contains("PARENT_MARKER2")); final Marker actual = reader.readValue(str); - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInXmlTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInXmlTest.java index 3eb88253c94..70aa1e5a44a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInXmlTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInXmlTest.java @@ -18,11 +18,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.core.jackson.Log4jXmlObjectMapper; -import org.apache.logging.log4j.core.test.categories.Layouts; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; -@Category(Layouts.Xml.class) -public class MarkerMixInXmlTest extends MarkerMixInTest { +@Tag("Layouts.Xml") +class MarkerMixInXmlTest extends MarkerMixInTest { @Override protected ObjectMapper newObjectMapper() { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInYamlTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInYamlTest.java index 2f1d28b9132..1f9297fc301 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInYamlTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/MarkerMixInYamlTest.java @@ -18,11 +18,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.core.jackson.Log4jYamlObjectMapper; -import org.apache.logging.log4j.core.test.categories.Layouts; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; -@Category(Layouts.Yaml.class) -public class MarkerMixInYamlTest extends MarkerMixInTest { +@Tag("Layouts.Yaml") +class MarkerMixInYamlTest extends MarkerMixInTest { @Override protected ObjectMapper newObjectMapper() { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java index 6e7840bc027..fbbcf7b1e31 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelJsonTest.java @@ -29,7 +29,7 @@ @Tag("json") @LoggerContextSource("log4j-reference-level.json") -public class AppenderRefLevelJsonTest { +class AppenderRefLevelJsonTest { private final ListAppender app1; private final ListAppender app2; @@ -51,7 +51,7 @@ public AppenderRefLevelJsonTest( } @Test - public void logger1() { + void logger1() { logger1.traceEntry(); logger1.debug("debug message"); logger1.error("Test Message"); @@ -63,7 +63,7 @@ public void logger1() { } @Test - public void logger2() { + void logger2() { logger2.traceEntry(); logger2.debug("debug message"); logger2.error("Test Message"); @@ -75,7 +75,7 @@ public void logger2() { } @Test - public void logger3() { + void logger3() { logger3.traceEntry(); logger3.debug(testMarker, "debug message"); logger3.error("Test Message"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java index c2a2f4f9778..f47f2cdf6c6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/AppenderRefLevelTest.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-reference-level.xml") -public class AppenderRefLevelTest { +class AppenderRefLevelTest { private final ListAppender app1; private final ListAppender app2; @@ -49,7 +49,7 @@ public AppenderRefLevelTest( Marker testMarker = MarkerManager.getMarker("TEST"); @Test - public void logger1() { + void logger1() { logger1.traceEntry(); logger1.debug("debug message"); logger1.error("Test Message"); @@ -63,7 +63,7 @@ public void logger1() { } @Test - public void logger2() { + void logger2() { logger2.traceEntry(); logger2.debug("debug message"); logger2.error("Test Message"); @@ -71,13 +71,13 @@ public void logger2() { logger2.warn("warn Message"); logger2.traceExit(); List events = app1.getEvents(); - assertEquals(events.size(), 2, "Incorrect number of events. Expected 2, actual " + events.size()); + assertEquals(2, events.size(), "Incorrect number of events. Expected 2, actual " + events.size()); events = app2.getEvents(); - assertEquals(events.size(), 4, "Incorrect number of events. Expected 4, actual " + events.size()); + assertEquals(4, events.size(), "Incorrect number of events. Expected 4, actual " + events.size()); } @Test - public void logger3() { + void logger3() { logger3.traceEntry(); logger3.debug(testMarker, "debug message"); logger3.error("Test Message"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java index cc1e127bac7..12fd307d276 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/BasicLoggingTest.java @@ -22,10 +22,10 @@ import org.junit.jupiter.api.Test; @Tag("smoke") -public class BasicLoggingTest { +class BasicLoggingTest { @Test - public void test1() { + void test1() { final Logger logger = LogManager.getLogger(BasicLoggingTest.class.getName()); logger.debug("debug not set"); logger.error("Test message"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java index 42633eb0c5c..f29bb5d61ca 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CollectionLoggingTest.java @@ -44,7 +44,7 @@ public CollectionLoggingTest(@Named("List") final ListAppender app) { @Test @ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceAccessMode.READ) - public void testSystemProperties(final LoggerContext context) { + void testSystemProperties(final LoggerContext context) { final Logger logger = context.getLogger(CollectionLoggingTest.class.getName()); logger.error(System.getProperties()); // logger.error(new MapMessage(System.getProperties())); @@ -53,7 +53,7 @@ public void testSystemProperties(final LoggerContext context) { @Test @ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceAccessMode.READ) - public void testSimpleMap(final LoggerContext context) { + void testSimpleMap(final LoggerContext context) { final Logger logger = context.getLogger(CollectionLoggingTest.class.getName()); logger.error(System.getProperties()); final Map map = new HashMap<>(); @@ -65,14 +65,14 @@ public void testSimpleMap(final LoggerContext context) { } @Test - public void testNetworkInterfaces(final LoggerContext context) throws SocketException { + 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(final LoggerContext context) { + 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-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java index 6fd84d9281b..8bcbb90ce04 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsOverrideTest.java @@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-customLevels.xml") -public class CustomLevelsOverrideTest { +class CustomLevelsOverrideTest { private final ListAppender listAppender; private final Level warnLevel; @@ -46,7 +46,7 @@ public CustomLevelsOverrideTest(final LoggerContext context, @Named("List1") fin } @Test - public void testCustomLevelInts() { + void testCustomLevelInts() { // assertEquals(350, warnLevel.intLevel()); // assertEquals(450, infoLevel.intLevel()); // assertEquals(550, debugLevel.intLevel()); @@ -56,21 +56,21 @@ public void testCustomLevelInts() { } @Test - public void testCustomLevelPresence() { + void testCustomLevelPresence() { assertNotNull(warnLevel); assertNotNull(infoLevel); assertNotNull(debugLevel); } @Test - public void testCustomLevelVsStdLevel() { + void testCustomLevelVsStdLevel() { assertEquals(Level.WARN, warnLevel); assertEquals(Level.INFO, infoLevel); assertEquals(Level.DEBUG, debugLevel); } @Test - public void testLog() { + void testLog() { assertThat(listAppender.getEvents(), hasSize(0)); logger.debug("Hello, {}", "World"); assertThat(listAppender.getEvents(), hasSize(1)); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java index da5ad43883b..fb32835d2be 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-customLevels.xml") -public class CustomLevelsTest { +class CustomLevelsTest { private final ListAppender listAppender; private final Level diagLevel; @@ -45,21 +45,21 @@ public CustomLevelsTest(final LoggerContext context, @Named("List1") final ListA } @Test - public void testCustomLevelInts() { + void testCustomLevelInts() { assertEquals(350, diagLevel.intLevel()); assertEquals(450, noticeLevel.intLevel()); assertEquals(550, verboseLevel.intLevel()); } @Test - public void testCustomLevelPresence() { + void testCustomLevelPresence() { assertNotNull(diagLevel); assertNotNull(noticeLevel); assertNotNull(verboseLevel); } @Test - public void testLog() { + void testLog() { assertThat(listAppender.getEvents(), hasSize(0)); logger.debug("Hello, {}", "World"); assertThat(listAppender.getEvents(), hasSize(1)); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java index a3eecb85970..f4bcacdce03 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/CustomLevelsWithFiltersTest.java @@ -31,19 +31,19 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-customLevelsWithFilters.xml") -public class CustomLevelsWithFiltersTest { +class CustomLevelsWithFiltersTest { private Level infom1Level; private Level infop1Level; @BeforeEach - public void before() { + void before() { infom1Level = Level.getLevel("INFOM1"); infop1Level = Level.getLevel("INFOP1"); } @Test - public void testConfiguration(final Configuration configuration, @Named("info") final FileAppender appender) { + void testConfiguration(final Configuration configuration, @Named("info") final FileAppender appender) { assertNotNull(configuration); assertNotNull(appender); final CompositeFilter compFilter = (CompositeFilter) appender.getFilter(); @@ -62,13 +62,13 @@ public void testConfiguration(final Configuration configuration, @Named("info") } @Test - public void testCustomLevelInts() { + void testCustomLevelInts() { assertEquals(399, infom1Level.intLevel()); assertEquals(401, infop1Level.intLevel()); } @Test - public void testCustomLevelPresence() { + void testCustomLevelPresence() { assertNotNull(infom1Level); assertNotNull(infop1Level); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java index b5ef7147741..87a2c9c9ec7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/DeadlockTest.java @@ -22,10 +22,10 @@ @LoggerContextSource("log4j-deadlock.xml") @Tag("concurrency") -public class DeadlockTest { +class DeadlockTest { @Test - public void deadlockOnReconfigure(final LoggerContext context) { + void deadlockOnReconfigure(final LoggerContext context) { context.reconfigure(); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java index 4b712de351e..8e30e081dea 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ExtendedLevelTest.java @@ -30,7 +30,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-customLevel.xml") -public class ExtendedLevelTest { +class ExtendedLevelTest { private final ListAppender list1; private final ListAppender list2; @@ -41,7 +41,7 @@ public ExtendedLevelTest(@Named("List1") final ListAppender list1, @Named("List2 } @Test - public void testLevelLogging(final LoggerContext context) { + 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"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java index 2a8d641041a..8cbcb9f986d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeAsynchronousLoggingTest.java @@ -28,10 +28,10 @@ */ @Tag("allocation") @Tag("functional") -public class GcFreeAsynchronousLoggingTest { +class GcFreeAsynchronousLoggingTest { @Test - public void testNoAllocationDuringSteadyStateLogging() throws Throwable { + void testNoAllocationDuringSteadyStateLogging() throws Throwable { GcFreeLoggingTestUtil.runTest(getClass()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAsyncLoggingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAsyncLoggingTest.java index e74d5553e8c..b540fe67151 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAsyncLoggingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeMixedSyncAsyncLoggingTest.java @@ -27,10 +27,10 @@ */ @Tag("allocation") @Tag("functional") -public class GcFreeMixedSyncAsyncLoggingTest { +class GcFreeMixedSyncAsyncLoggingTest { @Test - public void testNoAllocationDuringSteadyStateLogging() throws Throwable { + void testNoAllocationDuringSteadyStateLogging() throws Throwable { GcFreeLoggingTestUtil.runTest(getClass()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java index 5e785379dd6..4d61acc5ace 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/GcFreeSynchronousLoggingTest.java @@ -27,10 +27,10 @@ */ @Tag("allocation") @Tag("functional") -public class GcFreeSynchronousLoggingTest { +class GcFreeSynchronousLoggingTest { @Test - public void testNoAllocationDuringSteadyStateLogging() throws Throwable { + void testNoAllocationDuringSteadyStateLogging() throws Throwable { GcFreeLoggingTestUtil.runTest(getClass()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/HostNameTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/HostNameTest.java index 65407d07174..af904074a10 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/HostNameTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/HostNameTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-test2.xml") -public class HostNameTest { +class HostNameTest { private final ListAppender host; private final RollingFileAppender hostFile; @@ -44,7 +44,7 @@ public HostNameTest( } @Test - public void testHostname(final LoggerContext context) { + 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 msgs = host.getMessages(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java index 050bdad76cd..20b574e8a41 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LateConfigTest.java @@ -17,10 +17,10 @@ package org.apache.logging.log4j.core; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.URI; import java.nio.file.Path; @@ -36,7 +36,7 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class LateConfigTest { +class LateConfigTest { private static final String CONFIG = "/log4j-test1.xml"; private static LoggerContext context; @@ -45,28 +45,28 @@ public class LateConfigTest { private static Path loggingPath; @BeforeAll - public static void setupClass() { + static void setupClass() { context = LoggerContext.getContext(false); } @AfterAll - public static void tearDownClass() { + static void tearDownClass() { Configurator.shutdown(context); StatusLogger.getLogger().reset(); } @Test - public void testReconfiguration() throws Exception { + void testReconfiguration() throws Exception { final Configuration cfg = context.getConfiguration(); assertNotNull(cfg, "No configuration"); - assertTrue(cfg instanceof DefaultConfiguration, "Not set to default configuration"); + assertInstanceOf(DefaultConfiguration.class, cfg, "Not set to default configuration"); final URI configLocation = LateConfigTest.class.getResource(CONFIG).toURI(); final LoggerContext loggerContext = LoggerContext.getContext(null, false, configLocation); assertNotNull(loggerContext, "No Logger Context"); assertThat(loggingPath.resolve("test-xml.log")).exists(); final Configuration newConfig = loggerContext.getConfiguration(); assertNotSame(cfg, newConfig, "Configuration not reset"); - assertTrue(newConfig instanceof XmlConfiguration, "Reconfiguration failed"); + assertInstanceOf(XmlConfiguration.class, newConfig, "Reconfiguration failed"); context = LoggerContext.getContext(false); final Configuration sameConfig = context.getConfiguration(); assertSame(newConfig, sameConfig, "Configuration should not have been reset"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LevelTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LevelTest.java index 55ad0ede1b8..e2c292b7307 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LevelTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LevelTest.java @@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-Level.xml") -public class LevelTest { +class LevelTest { private final ListAppender listAll; private final ListAppender listTrace; @@ -77,7 +77,7 @@ private static class Expected { } @Test - public void testLevelLogging(final LoggerContext context) { + void testLevelLogging(final LoggerContext context) { final Marker marker = MarkerManager.getMarker("marker"); final Message msg = new ObjectMessage("msg"); final Throwable t = new Throwable("test"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java index 191a822f2fc..95418cabfcb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/Log4j1222Test.java @@ -16,7 +16,7 @@ */ package org.apache.logging.log4j.core; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -28,10 +28,10 @@ * Tests logging during shutdown. */ @Tag("functional") -public class Log4j1222Test { +class Log4j1222Test { @Test - public void homepageRendersSuccessfully() { + void homepageRendersSuccessfully() { System.setProperty("log4j.configurationFile", "log4j2-console.xml"); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); } @@ -50,7 +50,10 @@ public void run() { private void trigger() { Holder.LOGGER.info("Attempt to trigger"); - assertTrue("Logger is of type " + Holder.LOGGER.getClass().getName(), Holder.LOGGER instanceof TestLogger); + assertInstanceOf( + TestLogger.class, + Holder.LOGGER, + "Logger is of type " + Holder.LOGGER.getClass().getName()); if (((TestLogger) Holder.LOGGER).getEntries().isEmpty()) { System.out.println("Logger contains no messages"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LogEventTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LogEventTest.java index ec462b1f4d9..10aeeb5b3b0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LogEventTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LogEventTest.java @@ -34,13 +34,13 @@ /** * */ -public class LogEventTest { +class LogEventTest { private static final Message MESSAGE = new SimpleMessage("This is a test"); private static final TestClass TESTER = new TestClass(); @Test - public void testSerialization() throws Exception { + void testSerialization() throws Exception { final LogEvent event1 = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // .setLoggerFqcn("org.apache.logging.log4j.core.Logger") // @@ -66,7 +66,7 @@ public void testSerialization() throws Exception { } @Test - public void testNanoTimeIsNotSerialized1() throws Exception { + void testNanoTimeIsNotSerialized1() { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // .setLoggerFqcn("org.apache.logging.log4j.core.Logger") // @@ -85,7 +85,7 @@ public void testNanoTimeIsNotSerialized1() throws Exception { } @Test - public void testNanoTimeIsNotSerialized2() throws Exception { + void testNanoTimeIsNotSerialized2() { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // .setLoggerFqcn("org.apache.logging.log4j.core.Logger") // @@ -104,7 +104,7 @@ public void testNanoTimeIsNotSerialized2() throws Exception { @Test @Disabled - public void testEquals() { + void testEquals() { final LogEvent event1 = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // .setLoggerFqcn("org.apache.logging.log4j.core.Logger") // @@ -128,7 +128,7 @@ public void testEquals() { } @Test - public void testLocation() { + void testLocation() { final StackTraceElement ste = TESTER.getEventSource(this.getClass().getName()); assertNotNull(ste, "No StackTraceElement"); assertEquals(this.getClass().getName(), ste.getClassName(), "Incorrect event"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java index fffac674b7a..e23dcfbea02 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerDateTest.java @@ -34,7 +34,7 @@ public LoggerDateTest(@Named("File") final FileAppender fileApp) { } @Test - public void testFileName() { + void testFileName() { final String name = fileApp.getFileName(); final int year = Calendar.getInstance().get(Calendar.YEAR); assertTrue(name.contains(Integer.toString(year)), "Date was not substituted: " + name); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerTest.java index 258c41de705..bcd8d7bd26f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerTest.java @@ -58,7 +58,7 @@ import org.junit.jupiter.api.TestInfo; @LoggerContextSource(value = LoggerTest.CONFIG, reconfigure = ReconfigurationPolicy.AFTER_EACH) -public class LoggerTest { +class LoggerTest { static final String CONFIG = "log4j-test2.xml"; @@ -117,7 +117,7 @@ private void assertEventCount(final List events, final int expected) { } @Test - public void basicFlow() { + void basicFlow() { logger.traceEntry(); logger.traceExit(); final List events = app.getEvents(); @@ -125,7 +125,7 @@ public void basicFlow() { } @Test - public void builder() { + void builder() { logger.atDebug().withLocation().log("Hello"); final Marker marker = MarkerManager.getMarker("test"); logger.atError().withMarker(marker).log("Hello {}", "John"); @@ -143,7 +143,7 @@ public void builder() { } @Test - public void catching() { + void catching() { try { throw new NullPointerException(); } catch (final Exception e) { @@ -154,14 +154,14 @@ public void catching() { } @Test - public void debug() { + void debug() { logger.debug("Debug message"); final List events = app.getEvents(); assertEventCount(events, 1); } @Test - public void debugChangeLevel_ForClass() { + void debugChangeLevel_ForClass() { loggerClass.debug("Debug message 1"); assertEventCount(app.getEvents(), 1); Configurator.setLevel(LoggerTest.class, Level.OFF); @@ -173,7 +173,7 @@ public void debugChangeLevel_ForClass() { } @Test - public void debugChangeLevel_ForLogger() { + void debugChangeLevel_ForLogger() { logger.debug("Debug message 1"); assertEventCount(app.getEvents(), 1); Configurator.setLevel(logger, Level.OFF); @@ -185,7 +185,7 @@ public void debugChangeLevel_ForLogger() { } @Test - public void debugChangeLevel_ForLoggerName() { + void debugChangeLevel_ForLoggerName() { logger.debug("Debug message 1"); assertEventCount(app.getEvents(), 1); Configurator.setLevel(logger.getName(), Level.OFF); @@ -197,7 +197,7 @@ public void debugChangeLevel_ForLoggerName() { } @Test - public void debugChangeLevelAllChildrenLoggers() { + void debugChangeLevelAllChildrenLoggers() { // Use logger AND child loggers logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 child"); @@ -216,7 +216,7 @@ public void debugChangeLevelAllChildrenLoggers() { } @Test - public void debugChangeLevelChildLogger_ForLogger() { + void debugChangeLevelChildLogger_ForLogger() { // Use logger AND child loggers logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 child"); @@ -235,7 +235,7 @@ public void debugChangeLevelChildLogger_ForLogger() { } @Test - public void debugChangeLevelChildLogger_ForLoggerName() { + void debugChangeLevelChildLogger_ForLoggerName() { // Use logger AND child loggers logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 child"); @@ -254,7 +254,7 @@ public void debugChangeLevelChildLogger_ForLoggerName() { } @Test - public void debugChangeLevelName_ForLoggerName() { + void debugChangeLevelName_ForLoggerName() { logger.debug("Debug message 1"); assertEventCount(app.getEvents(), 1); Configurator.setLevel(logger.getName(), Level.OFF.name()); @@ -266,7 +266,7 @@ public void debugChangeLevelName_ForLoggerName() { } @Test - public void debugChangeLevelNameChildLogger_ForLoggerName() { + void debugChangeLevelNameChildLogger_ForLoggerName() { // Use logger AND child loggers logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 child"); @@ -285,7 +285,7 @@ public void debugChangeLevelNameChildLogger_ForLoggerName() { } @Test - public void debugChangeLevelNameChildLoggers_ForLoggerName(final LoggerContext context) { + void debugChangeLevelNameChildLoggers_ForLoggerName(final LoggerContext context) { final org.apache.logging.log4j.Logger loggerChild = context.getLogger(logger.getName() + ".child"); // Use logger AND loggerChild logger.debug("Debug message 1"); @@ -303,7 +303,7 @@ public void debugChangeLevelNameChildLoggers_ForLoggerName(final LoggerContext c } @Test - public void debugChangeLevelsChildLoggers_ForLogger(final LoggerContext context) { + void debugChangeLevelsChildLoggers_ForLogger(final LoggerContext context) { final org.apache.logging.log4j.Logger loggerChild = context.getLogger(logger.getName() + ".child"); // Use logger AND loggerChild logger.debug("Debug message 1"); @@ -321,7 +321,7 @@ public void debugChangeLevelsChildLoggers_ForLogger(final LoggerContext context) } @Test - public void debugChangeLevelsChildLoggers_ForLoggerName(final LoggerContext context) { + void debugChangeLevelsChildLoggers_ForLoggerName(final LoggerContext context) { final org.apache.logging.log4j.Logger loggerChild = context.getLogger(logger.getName() + ".child"); // Use logger AND loggerChild logger.debug("Debug message 1"); @@ -339,7 +339,7 @@ public void debugChangeLevelsChildLoggers_ForLoggerName(final LoggerContext cont } @Test - public void debugChangeLevelsMap() { + void debugChangeLevelsMap() { logger.debug("Debug message 1"); assertEventCount(app.getEvents(), 1); final Map map = new HashMap<>(); @@ -354,7 +354,7 @@ public void debugChangeLevelsMap() { } @Test - public void debugChangeLevelsMapChildLoggers() { + void debugChangeLevelsMapChildLoggers() { logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 C"); loggerGrandchild.debug("Debug message 1 GC"); @@ -379,7 +379,7 @@ public void debugChangeLevelsMapChildLoggers() { } @Test - public void debugChangeRootLevel() { + void debugChangeRootLevel() { logger.debug("Debug message 1"); assertEventCount(app.getEvents(), 1); Configurator.setRootLevel(Level.OFF); @@ -391,21 +391,21 @@ public void debugChangeRootLevel() { } @Test - public void debugObject() { + void debugObject() { logger.debug(new Date()); final List events = app.getEvents(); assertEventCount(events, 1); } @Test - public void debugWithParms() { + void debugWithParms() { logger.debug("Hello, {}", "World"); final List events = app.getEvents(); assertEventCount(events, 1); } @Test - public void getLogger_String_MessageFactoryMismatch(final TestInfo testInfo) { + void getLogger_String_MessageFactoryMismatch(final TestInfo testInfo) { final Logger testLogger = testMessageFactoryMismatch( testInfo.getTestMethod().map(Method::getName).orElseThrow(AssertionError::new), StringFormatterMessageFactory.INSTANCE, @@ -419,7 +419,7 @@ public void getLogger_String_MessageFactoryMismatch(final TestInfo testInfo) { } @Test - public void getLogger_String_MessageFactoryMismatchNull(final TestInfo testInfo) { + void getLogger_String_MessageFactoryMismatchNull(final TestInfo testInfo) { final Logger testLogger = testMessageFactoryMismatch( testInfo.getTestMethod().map(Method::getName).orElseThrow(AssertionError::new), StringFormatterMessageFactory.INSTANCE, @@ -433,7 +433,7 @@ public void getLogger_String_MessageFactoryMismatchNull(final TestInfo testInfo) } @Test - public void mdc() { + void mdc() { ThreadContext.put("TestYear", "2010"); logger.debug("Debug message"); ThreadContext.clearMap(); @@ -443,7 +443,7 @@ public void mdc() { } @Test - public void paramWithExceptionTest() throws Exception { + void paramWithExceptionTest() { logger.error("Throwing with parameters {}", "TestParam", new NullPointerException("Test Exception")); final List events = app.getEvents(); assertNotNull(events, "Log event list not returned"); @@ -458,7 +458,7 @@ public void paramWithExceptionTest() throws Exception { } @Test - public void simpleFlow() { + void simpleFlow() { logger.entry(CONFIG); logger.traceExit(0); final List events = app.getEvents(); @@ -466,7 +466,7 @@ public void simpleFlow() { } @Test - public void simpleFlowDepreacted() { + void simpleFlowDepreacted() { logger.entry(CONFIG); logger.exit(0); final List events = app.getEvents(); @@ -474,7 +474,7 @@ public void simpleFlowDepreacted() { } @Test - public void structuredData() { + void structuredData() { ThreadContext.put("loginId", "JohnDoe"); ThreadContext.put("ipAddress", "192.168.0.120"); ThreadContext.put("locale", Locale.US.getDisplayName()); @@ -489,7 +489,7 @@ public void structuredData() { } @Test - public void testAdditivity(final LoggerContext context) throws Exception { + void testAdditivity(final LoggerContext context) { final Logger localLogger = context.getLogger("org.apache.test"); localLogger.error("Test parent additivity"); final List events = app.getEvents(); @@ -497,7 +497,7 @@ public void testAdditivity(final LoggerContext context) throws Exception { } @Test - public void testImpliedThrowable(final LoggerContext context) { + 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 msgs = host.getMessages(); @@ -507,21 +507,21 @@ public void testImpliedThrowable(final LoggerContext context) { } @Test - public void testLevelInheritance(final LoggerContext context) throws Exception { + void testLevelInheritance(final LoggerContext context) { 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); + assertEquals("org.apache.logging.log4j.core.LoggerTest", loggerConfig.getName()); + assertEquals(Level.DEBUG, loggerConfig.getLevel()); final Logger localLogger = context.getLogger("org.apache.logging.log4j.core.LoggerTest"); assertSame( - localLogger.getLevel(), Level.DEBUG, + localLogger.getLevel(), "Incorrect level - expected DEBUG, actual " + localLogger.getLevel()); } @Test - public void testReconfiguration(final LoggerContext context) throws Exception { + 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); @@ -545,7 +545,7 @@ public void testReconfiguration(final LoggerContext context) throws Exception { } @Test - public void testSuppressedThrowable(final LoggerContext context) { + 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 msgs = noThrown.getMessages(); @@ -555,7 +555,7 @@ public void testSuppressedThrowable(final LoggerContext context) { } @Test - public void throwing() { + void throwing() { logger.throwing(new IllegalArgumentException("Test Exception")); final List events = app.getEvents(); assertEventCount(events, 1); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java index 538e72c0fc1..d84bd9f0b51 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LoggerUpdateTest.java @@ -30,7 +30,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-test2.xml") -public class LoggerUpdateTest { +class LoggerUpdateTest { private final ListAppender app; @@ -39,7 +39,7 @@ public LoggerUpdateTest(@Named("List") final ListAppender app) { } @Test - public void resetLevel(final LoggerContext context) { + void resetLevel(final LoggerContext context) { final org.apache.logging.log4j.Logger logger = context.getLogger("com.apache.test"); logger.traceEntry(); List events = app.getEvents(); @@ -59,7 +59,7 @@ public void resetLevel(final LoggerContext context) { } @Test - public void testUpdateLoggersPropertyListeners(final LoggerContext context) throws Exception { + void testUpdateLoggersPropertyListeners(final LoggerContext context) { context.addPropertyChangeListener(evt -> { assertEquals(LoggerContext.PROPERTY_CONFIG, evt.getPropertyName()); assertSame(context, evt.getSource()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LookupTest.java index d9147160185..ce41afd2ed8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/LookupTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -26,13 +27,13 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-lookup.xml") -public class LookupTest { +class LookupTest { @Test - public void testHostname(@Named final ConsoleAppender console) { + void testHostname(@Named final ConsoleAppender console) { final Layout layout = console.getLayout(); assertNotNull(layout, "No Layout"); - assertTrue(layout instanceof PatternLayout, "Layout is not a PatternLayout"); + assertInstanceOf(PatternLayout.class, layout, "Layout is not a PatternLayout"); final String pattern = ((PatternLayout) layout).getConversionPattern(); assertNotNull(pattern, "No conversion pattern"); assertTrue( diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternResolverDoesNotEvaluateThreadContextTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternResolverDoesNotEvaluateThreadContextTest.java index 9bfd6fd38fd..20eef664356 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternResolverDoesNotEvaluateThreadContextTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternResolverDoesNotEvaluateThreadContextTest.java @@ -47,7 +47,7 @@ public void testNoUserSet() { final Logger logger = context.getLogger(getClass()); logger.info("This is a test"); final List messages = listAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages returned"); + assertTrue(messages != null && !messages.isEmpty(), "No messages returned"); final String message = messages.get(0); assertEquals( "INFO org.apache.logging.log4j.core." @@ -60,7 +60,7 @@ public void testMessageIsNotLookedUp() { final Logger logger = context.getLogger(getClass()); logger.info("This is a ${upper:test}"); final List messages = listAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages returned"); + assertTrue(messages != null && !messages.isEmpty(), "No messages returned"); final String message = messages.get(0); assertEquals( "INFO org.apache.logging.log4j.core." @@ -78,7 +78,7 @@ public void testUser() { ThreadContext.remove(PARAMETER); } final List messages = listAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages returned"); + assertTrue(messages != null && !messages.isEmpty(), "No messages returned"); final String message = messages.get(0); assertEquals( "INFO org.apache.logging.log4j.core." @@ -96,7 +96,7 @@ public void testUserIsLookup() { ThreadContext.remove(PARAMETER); } final List messages = listAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages returned"); + assertTrue(messages != null && !messages.isEmpty(), "No messages returned"); final String message = messages.get(0); assertEquals( "INFO org.apache.logging.log4j.core." @@ -114,7 +114,7 @@ public void testUserHasLookup() { ThreadContext.remove(PARAMETER); } final List messages = listAppender.getMessages(); - assertTrue(messages != null && messages.size() > 0, "No messages returned"); + assertTrue(messages != null && !messages.isEmpty(), "No messages returned"); final String message = messages.get(0); assertEquals( "INFO org.apache.logging.log4j.core." diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java index 42913d50c34..827c39f97b7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternSelectorTest.java @@ -31,12 +31,12 @@ @SetSystemProperty(key = Constants.SCRIPT_LANGUAGES, value = "bsh, Javascript") @LoggerContextSource("log4j-patternSelector.xml") -public class PatternSelectorTest { +class PatternSelectorTest { private static final int CURRENT_LINE = 36; @Test - public void testMarkerPatternSelector(@Named("List") final ListAppender app) { + void testMarkerPatternSelector(@Named("List") final ListAppender app) { final org.apache.logging.log4j.Logger logger = LogManager.getLogger("TestMarkerPatternSelector"); logger.traceEntry(); logger.info("Hello World"); @@ -57,7 +57,7 @@ public void testMarkerPatternSelector(@Named("List") final ListAppender app) { } @Test - public void testScriptPatternSelector(@Named("List2") final ListAppender app) { + 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(); @@ -85,7 +85,7 @@ public void testScriptPatternSelector(@Named("List2") final ListAppender app) { } @Test - public void testJavaScriptPatternSelector(@Named("List3") final ListAppender app) { + 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(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternVariableResolverTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternVariableResolverTest.java index a0ff3f5ebf8..4b4c0739c7e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternVariableResolverTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PatternVariableResolverTest.java @@ -46,7 +46,7 @@ public void testFileName() { final Logger logger = context.getLogger(PatternVariableResolverTest.class); logger.info("This is a test"); final List messages = listAppender.getMessages(); - assertTrue("No messages returned", messages != null && messages.size() > 0); + assertTrue("No messages returned", messages != null && !messages.isEmpty()); final String message = messages.get(0); System.out.println(message); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java index e160c9d81f9..4a4bf8dba0a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/PropertiesFileConfigTest.java @@ -45,7 +45,7 @@ void clear(@Named("List") final ListAppender appender) { } @Test - public void testReconfiguration(final LoggerContext context) throws Exception { + void testReconfiguration(final LoggerContext context) throws Exception { final Configuration oldConfig = context.getConfiguration(); final int MONITOR_INTERVAL_SECONDS = 5; final File file = new File(CONFIG); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java index 49cdf037bb4..559a5d6e3e6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ReusableParameterizedMessageMemoryLeakTest.java @@ -22,10 +22,10 @@ import org.apache.logging.log4j.message.ReusableMessageFactory; import org.junit.jupiter.api.Test; -public class ReusableParameterizedMessageMemoryLeakTest { +class ReusableParameterizedMessageMemoryLeakTest { @Test - public void parameters_should_be_garbage_collected() throws Exception { + void parameters_should_be_garbage_collected() throws Exception { awaitGarbageCollection(() -> { final ParameterObject parameter = new ParameterObject("paramValue"); final ReusableMessage message = diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java index 13e84e82176..889d702fec0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownDisabledTest.java @@ -23,10 +23,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-test3.xml") -public class ShutdownDisabledTest { +class ShutdownDisabledTest { @Test - public void testShutdownFlag(final Configuration config) { + void testShutdownFlag(final Configuration config) { assertFalse(config.isShutdownHookEnabled(), "Shutdown hook is enabled"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java index a1774d73c9a..66855a51c74 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/ShutdownTimeoutConfigurationTest.java @@ -23,10 +23,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-test-shutdownTimeout.xml") -public class ShutdownTimeoutConfigurationTest { +class ShutdownTimeoutConfigurationTest { @Test - public void testShutdownFlag(final Configuration config) { + void testShutdownFlag(final Configuration config) { assertEquals(5000, config.getShutdownTimeoutMillis()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java index 1378f28ffe3..0bd00104b17 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/StrictXmlConfigTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-strict1.xml") -public class StrictXmlConfigTest { +class StrictXmlConfigTest { org.apache.logging.log4j.Logger logger; private ListAppender app; @@ -42,7 +42,7 @@ public StrictXmlConfigTest(final LoggerContext context, @Named("List") final Lis } @Test - public void basicFlow() { + void basicFlow() { final EntryMessage entry = logger.traceEntry(); logger.traceExit(entry); final List events = app.getEvents(); @@ -50,7 +50,7 @@ public void basicFlow() { } @Test - public void basicFlowDeprecated() { + void basicFlowDeprecated() { logger.traceEntry(); logger.traceExit(); final List events = app.getEvents(); @@ -58,7 +58,7 @@ public void basicFlowDeprecated() { } @Test - public void simpleFlow() { + void simpleFlow() { logger.traceEntry(); logger.traceExit(0); final List events = app.getEvents(); @@ -66,14 +66,14 @@ public void simpleFlow() { } @Test - public void throwing() { + void throwing() { logger.throwing(new IllegalArgumentException("Test Exception")); final List events = app.getEvents(); assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size()); } @Test - public void catching() { + void catching() { try { throw new NullPointerException(); } catch (final Exception e) { @@ -84,28 +84,28 @@ public void catching() { } @Test - public void debug() { + void debug() { logger.debug("Debug message"); final List events = app.getEvents(); assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size()); } @Test - public void debugObject() { + void debugObject() { logger.debug(new Date()); final List events = app.getEvents(); assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size()); } @Test - public void debugWithParms() { + void debugWithParms() { logger.debug("Hello, {}", "World"); final List events = app.getEvents(); assertEquals(1, events.size(), "Incorrect number of events. Expected 1, actual " + events.size()); } @Test - public void mdc() { + void mdc() { ThreadContext.put("TestYear", "2010"); logger.debug("Debug message"); ThreadContext.clearMap(); @@ -115,7 +115,7 @@ public void mdc() { } @Test - public void structuredData() { + void structuredData() { ThreadContext.put("loginId", "JohnDoe"); ThreadContext.put("ipAddress", "192.168.0.120"); ThreadContext.put("locale", Locale.US.getDisplayName()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java index 0ad1907264d..d06e1d63d08 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/TimestampMessageTest.java @@ -43,7 +43,7 @@ *

*/ @LoggerContextSource("log4j2-744.xml") -public class TimestampMessageTest { +class TimestampMessageTest { private ListAppender app; public TimestampMessageTest(@Named("List") final ListAppender app) { @@ -51,18 +51,18 @@ public TimestampMessageTest(@Named("List") final ListAppender app) { } @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty(ClockFactory.PROPERTY_NAME, PoisonClock.class.getName()); } @AfterAll - public static void afterClass() throws IllegalAccessException { + static void afterClass() throws IllegalAccessException { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); ClockFactoryTest.resetClocks(); } @Test - public void testTimestampMessage(final LoggerContext context) { + void testTimestampMessage(final LoggerContext context) { final Logger log = context.getLogger("TimestampMessageTest"); log.info((Message) new TimeMsg("Message with embedded timestamp", 123456789000L)); final List msgs = app.getMessages(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/XmlEvents.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/XmlEvents.java index c91ffb220fb..15e8856c473 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/XmlEvents.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/XmlEvents.java @@ -27,10 +27,10 @@ @LoggerContextSource("xml-events.xml") @Disabled("TODO") -public class XmlEvents { +class XmlEvents { @Test - public void testEvents() { + void testEvents() { ThreadContext.put("loginId", "JohnDoe"); ThreadContext.put("ipAddress", "192.168.0.120"); ThreadContext.put("locale", Locale.US.getDisplayName()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AbstractAppenderBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AbstractAppenderBuilderTest.java index bec17bef216..6035ea1425d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AbstractAppenderBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AbstractAppenderBuilderTest.java @@ -22,10 +22,10 @@ import org.apache.logging.log4j.core.config.DefaultConfiguration; import org.junit.jupiter.api.Test; -public class AbstractAppenderBuilderTest { +class AbstractAppenderBuilderTest { @Test - public void testDefaultLayoutLeak() { + void testDefaultLayoutLeak() { final int expected = AbstractManager.getManagerCount(); final Configuration configuration = new DefaultConfiguration(); final ConsoleAppender appender = ConsoleAppender.newBuilder() diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderQueueFullPolicyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderQueueFullPolicyTest.java index 4c9021df83d..f0a84f1f4dc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderQueueFullPolicyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderQueueFullPolicyTest.java @@ -42,7 +42,7 @@ * */ @LoggerContextSource("log4j-asynch-queue-full.xml") -public class AsyncAppenderQueueFullPolicyTest { +class AsyncAppenderQueueFullPolicyTest { private final BlockingAppender blockingAppender; private final AsyncAppender asyncAppender; @@ -61,13 +61,13 @@ public AsyncAppenderQueueFullPolicyTest( } @AfterEach - public void after() { + void after() { blockingAppender.running = false; policy.queueFull.set(0L); } @Test - public void testRouter() throws Exception { + void testRouter() { final Logger logger = LogManager.getLogger(AsyncAppenderQueueFullPolicyTest.class); assertEquals(4, asyncAppender.getQueueCapacity()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderTest.java index e693d2ca15f..ed0c6bc24a3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/AsyncAppenderTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -37,7 +38,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; -public class AsyncAppenderTest { +class AsyncAppenderTest { static void exceptionTest(final LoggerContext context) throws InterruptedException { assertNotNull(context); @@ -78,14 +79,14 @@ static void rewriteTest(final LoggerContext context) throws InterruptedException @Test @LoggerContextSource("BlockingQueueFactory-ArrayBlockingQueue.xml") - public void testArrayBlockingQueue(final LoggerContext context) throws InterruptedException { + void testArrayBlockingQueue(final LoggerContext context) throws InterruptedException { rewriteTest(context); exceptionTest(context); } @Test @LoggerContextSource("log4j-asynch.xml") - public void testDefaultAsyncAppenderConfig(final LoggerContext context) throws InterruptedException { + void testDefaultAsyncAppenderConfig(final LoggerContext context) throws InterruptedException { rewriteTest(context); exceptionTest(context); @@ -101,14 +102,14 @@ public void testDefaultAsyncAppenderConfig(final LoggerContext context) throws I @Test @Tag("disruptor") @LoggerContextSource("BlockingQueueFactory-DisruptorBlockingQueue.xml") - public void testDisruptorBlockingQueue(final LoggerContext context) throws InterruptedException { + void testDisruptorBlockingQueue(final LoggerContext context) throws InterruptedException { rewriteTest(context); exceptionTest(context); } @Test @LoggerContextSource("log4j-asynch.xml") - public void testGetAppenderRefStrings(final LoggerContext context) throws InterruptedException { + void testGetAppenderRefStrings(final LoggerContext context) { final AsyncAppender appender = context.getConfiguration().getAppender("Async"); assertArrayEquals(new String[] {"List"}, appender.getAppenderRefStrings()); assertNotSame(appender.getAppenderRefStrings(), appender.getAppenderRefStrings()); @@ -116,18 +117,18 @@ public void testGetAppenderRefStrings(final LoggerContext context) throws Interr @Test @LoggerContextSource("log4j-asynch.xml") - public void testGetAppenders(final LoggerContext context) throws InterruptedException { + void testGetAppenders(final LoggerContext context) { final AsyncAppender appender = context.getConfiguration().getAppender("Async"); final List appenders = appender.getAppenders(); assertEquals(1, appenders.size()); final Appender listAppender = appenders.get(0); assertEquals("List", listAppender.getName()); - assertTrue(listAppender instanceof ListAppender); + assertInstanceOf(ListAppender.class, listAppender); } @Test @LoggerContextSource("log4j-asynch.xml") - public void testGetErrorRef(final LoggerContext context) throws InterruptedException { + void testGetErrorRef(final LoggerContext context) { final AsyncAppender appender = context.getConfiguration().getAppender("Async"); assertEquals("STDOUT", appender.getErrorRef()); } @@ -135,21 +136,21 @@ public void testGetErrorRef(final LoggerContext context) throws InterruptedExcep @Test @Tag("jctools") @LoggerContextSource("BlockingQueueFactory-JCToolsBlockingQueue.xml") - public void testJcToolsBlockingQueue(final LoggerContext context) throws InterruptedException { + void testJcToolsBlockingQueue(final LoggerContext context) throws InterruptedException { rewriteTest(context); exceptionTest(context); } @Test @LoggerContextSource("BlockingQueueFactory-LinkedTransferQueue.xml") - public void testLinkedTransferQueue(final LoggerContext context) throws InterruptedException { + void testLinkedTransferQueue(final LoggerContext context) throws InterruptedException { rewriteTest(context); exceptionTest(context); } @Test @LoggerContextSource("log4j-asynch-no-location.xml") - public void testNoLocationInformation(final LoggerContext context, @Named("List") final ListAppender appender) + void testNoLocationInformation(final LoggerContext context, @Named("List") final ListAppender appender) throws InterruptedException { final ExtendedLogger logger = context.getLogger(getClass()); logger.error("This is a test"); @@ -169,7 +170,7 @@ public void testNoLocationInformation(final LoggerContext context, @Named("List" @Test @Timeout(5) @LoggerContextSource("log4j-asynch-shutdownTimeout.xml") - public void testShutdownTimeout(final LoggerContext context) { + void testShutdownTimeout(final LoggerContext context) { context.getLogger("Logger").info("This is a test"); context.stop(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiStyleLayoutMain.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiStyleLayoutMain.java index 2ef1c52c9fa..83a6e8632cc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiStyleLayoutMain.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiStyleLayoutMain.java @@ -21,7 +21,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configurator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Shows how to use ANSI escape codes to color messages. Each message is printed to the console in color, but the rest @@ -39,7 +39,7 @@ * * */ -public class ConsoleAppenderAnsiStyleLayoutMain { +class ConsoleAppenderAnsiStyleLayoutMain { public static void main(final String[] args) { new ConsoleAppenderAnsiStyleLayoutMain().test(args); @@ -49,7 +49,7 @@ public static void main(final String[] args) { * This is a @Test method to make it easy to run from a command line with {@code mvn -Dtest=FQCN test} */ @Test - public void test() { + void test() { test(null); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiXExceptionMain.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiXExceptionMain.java index ee062add98e..88abec63f87 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiXExceptionMain.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiXExceptionMain.java @@ -22,7 +22,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configurator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Shows how to use ANSI escape codes to color messages. Each message is printed to the console in color, but the rest @@ -42,7 +42,7 @@ * * */ -public class ConsoleAppenderAnsiXExceptionMain { +class ConsoleAppenderAnsiXExceptionMain { public static void main(final String[] args) { new ConsoleAppenderAnsiXExceptionMain().test(args); @@ -52,7 +52,7 @@ public static void main(final String[] args) { * This is a @Test method to make it easy to run from a command line with {@code mvn -Dtest=FQCN test} */ @Test - public void test() { + void test() { test(null); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderBuilderTest.java index dae67a50fdf..10ab22436f3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderBuilderTest.java @@ -26,13 +26,13 @@ import org.apache.logging.log4j.core.layout.PatternLayout; import org.junit.jupiter.api.Test; -public class ConsoleAppenderBuilderTest { +class ConsoleAppenderBuilderTest { /** * Tests https://issues.apache.org/jira/browse/LOG4J2-1620 */ @Test - public void testDefaultImmediateFlush() { + void testDefaultImmediateFlush() { assertTrue(ConsoleAppender.newBuilder().isImmediateFlush()); } @@ -42,7 +42,7 @@ public void testDefaultImmediateFlush() { * Tested with Oracle 7 and 8 and IBM Java 8. */ @Test - public void testDefaultLayoutDefaultCharset() { + void testDefaultLayoutDefaultCharset() { final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("test").build(); final PatternLayout layout = (PatternLayout) appender.getLayout(); @@ -56,7 +56,7 @@ public void testDefaultLayoutDefaultCharset() { * Tests https://issues.apache.org/jira/browse/LOG4J2-2441 */ @Test - public void testSetNullErrorHandlerIsNotAllowed() { + void testSetNullErrorHandlerIsNotAllowed() { final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("test").build(); final ErrorHandler handler = appender.getHandler(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderTest.java index 1d8171233b2..87b4a5077a9 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderTest.java @@ -44,17 +44,17 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class ConsoleAppenderTest { +class ConsoleAppenderTest { private static final String LOG4J_SKIP_JANSI = "log4j.skipJansi"; @AfterAll - public static void afterClass() { + static void afterClass() { System.clearProperty(LOG4J_SKIP_JANSI); } @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty(LOG4J_SKIP_JANSI, "true"); } @@ -64,7 +64,7 @@ public static void beforeClass() { PrintStream psMock; @BeforeEach - public void before() { + void before() { System.setProperty(LOG4J_SKIP_JANSI, "true"); baos = new ByteArrayOutputStream(); } @@ -120,12 +120,12 @@ private void testConsoleStreamManagerDoesNotClose( } @Test - public void testFollowSystemErr() { + void testFollowSystemErr() { testFollowSystemPrintStream(System.err, Target.SYSTEM_ERR, SystemSetter.SYSTEM_ERR); } @Test - public void testFollowSystemOut() { + void testFollowSystemOut() { testFollowSystemPrintStream(System.out, Target.SYSTEM_OUT, SystemSetter.SYSTEM_OUT); } @@ -164,12 +164,12 @@ private void testFollowSystemPrintStream( } @Test - public void testSystemErrStreamManagerDoesNotClose() { + void testSystemErrStreamManagerDoesNotClose() { testConsoleStreamManagerDoesNotClose(System.err, Target.SYSTEM_ERR, SystemSetter.SYSTEM_ERR); } @Test - public void testSystemOutStreamManagerDoesNotClose() { + void testSystemOutStreamManagerDoesNotClose() { testConsoleStreamManagerDoesNotClose(System.out, Target.SYSTEM_OUT, SystemSetter.SYSTEM_OUT); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverAppenderTest.java index 9770771b8c7..efba39b0b97 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverAppenderTest.java @@ -48,37 +48,37 @@ public FailoverAppenderTest( } @AfterEach - public void tearDown() throws Exception { + void tearDown() { app.clear(); } @Test - public void testFailover() { + void testFailover() { logger.error("This is a test"); List events = app.getEvents(); assertNotNull(events); - assertEquals(events.size(), 1, "Incorrect number of events. Should be 1 is " + events.size()); + assertEquals(1, events.size(), "Incorrect number of events. Should be 1 is " + events.size()); app.clear(); logger.error("This is a test"); events = app.getEvents(); assertNotNull(events); - assertEquals(events.size(), 1, "Incorrect number of events. Should be 1 is " + events.size()); + assertEquals(1, events.size(), "Incorrect number of events. Should be 1 is " + events.size()); } @Test - public void testRecovery() throws Exception { + void testRecovery() throws Exception { onceLogger.error("Fail once"); onceLogger.error("Fail again"); List events = app.getEvents(); assertNotNull(events); - assertEquals(events.size(), 2, "Incorrect number of events. Should be 2 is " + events.size()); + assertEquals(2, events.size(), "Incorrect number of events. Should be 2 is " + events.size()); app.clear(); Thread.sleep(1100); onceLogger.error("Fail after recovery interval"); onceLogger.error("Second log message"); events = app.getEvents(); - assertEquals(events.size(), 0, "Did not recover"); + assertEquals(0, events.size(), "Did not recover"); events = foApp.drainEvents(); - assertEquals(events.size(), 2, "Incorrect number of events in primary appender"); + assertEquals(2, events.size(), "Incorrect number of events in primary appender"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverFailedPrimaryAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverFailedPrimaryAppenderTest.java index 6ef641c8b90..9c39204b166 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverFailedPrimaryAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FailoverFailedPrimaryAppenderTest.java @@ -43,15 +43,15 @@ public class FailoverFailedPrimaryAppenderTest { public static LoggerContextRule init = new LoggerContextRule("log4j-failover.xml"); @Before - public void setUp() throws Exception { + public void setUp() { app = init.getListAppender("List"); - foApp = (FailOnceAppender) init.getAppender("Once"); + foApp = init.getAppender("Once"); logger = init.getLogger("LoggerTest"); onceLogger = init.getLogger("Once"); } @After - public void tearDown() throws Exception { + public void tearDown() { if (app != null) { app.clear(); } @@ -62,12 +62,12 @@ public void testFailover() { logger.error("This is a test"); List events = app.getEvents(); assertNotNull(events); - assertEquals("Incorrect number of events. Should be 1 is " + events.size(), events.size(), 1); + assertEquals("Incorrect number of events. Should be 1 is " + events.size(), 1, events.size()); app.clear(); logger.error("This is a test"); events = app.getEvents(); assertNotNull(events); - assertEquals("Incorrect number of events. Should be 1 is " + events.size(), events.size(), 1); + assertEquals("Incorrect number of events. Should be 1 is " + events.size(), 1, events.size()); } @Test @@ -76,14 +76,14 @@ public void testRecovery() throws Exception { onceLogger.error("Fail again"); List events = app.getEvents(); assertNotNull(events); - assertEquals("Incorrect number of events. Should be 2 is " + events.size(), events.size(), 2); + assertEquals("Incorrect number of events. Should be 2 is " + events.size(), 2, events.size()); app.clear(); Thread.sleep(1100); onceLogger.error("Fail after recovery interval"); onceLogger.error("Second log message"); events = app.getEvents(); - assertEquals("Did not recover", events.size(), 0); + assertEquals("Did not recover", 0, events.size()); events = foApp.drainEvents(); - assertEquals("Incorrect number of events in primary appender", events.size(), 2); + assertEquals("Incorrect number of events in primary appender", 2, events.size()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderBuilderTest.java index 904ef088cc1..718349e1f3c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderBuilderTest.java @@ -16,12 +16,12 @@ */ package org.apache.logging.log4j.core.appender; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.status.StatusData; @@ -29,13 +29,13 @@ import org.apache.logging.log4j.status.StatusLogger; import org.junit.jupiter.api.Test; -public class FileAppenderBuilderTest { +class FileAppenderBuilderTest { /** * Tests https://issues.apache.org/jira/browse/LOG4J2-1620 */ @Test - public void testDefaultImmediateFlush() { + void testDefaultImmediateFlush() { assertTrue(FileAppender.newBuilder().isImmediateFlush()); } @@ -44,12 +44,12 @@ public void testDefaultImmediateFlush() { * {@code null}. */ @Test - public void testConstraints() { + void testConstraints() { final AtomicInteger counter = new AtomicInteger(); final StatusListener listener = new StatusListener() { @Override - public void close() throws IOException {} + public void close() {} @Override public void log(final StatusData data) { @@ -79,7 +79,7 @@ public Level getStatusLevel() { .withFileName("target/FileAppenderBuilderTest.log") .build(); assertNotNull(appender); - assertTrue(counter.get() == 0); + assertEquals(0, counter.get()); } catch (NullPointerException e) { // thrown if no filename is provided fail(e); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderPermissionsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderPermissionsTest.java index 1db2eee7eb3..1ebf7cbacf3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderPermissionsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderPermissionsTest.java @@ -53,19 +53,19 @@ * Tests {@link FileAppender}. */ @CleanUpDirectories(FileAppenderPermissionsTest.DIR) -public class FileAppenderPermissionsTest { +class FileAppenderPermissionsTest { static final String DIR = "target/permissions1"; @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty("log4j2.debug", "true"); assumeTrue(FileUtils.isFilePosixAttributeViewSupported()); } @ParameterizedTest @CsvSource({"rwxrwxrwx,true,2", "rw-r--r--,false,3", "rw-------,true,4", "rw-rw----,false,5"}) - public void testFilePermissionsAPI(final String filePermissions, final boolean createOnDemand, final int fileIndex) + void testFilePermissionsAPI(final String filePermissions, final boolean createOnDemand, final int fileIndex) throws Exception { final File file = new File(DIR, "AppenderTest-" + fileIndex + ".log"); final Path path = file.toPath(); @@ -91,7 +91,7 @@ public void testFilePermissionsAPI(final String filePermissions, final boolean c assertNotEquals(createOnDemand, Files.exists(path)); long curLen = file.length(); long prevLen = curLen; - assertEquals(curLen, 0, "File length: " + curLen); + assertEquals(0, curLen, "File length: " + curLen); for (int i = 0; i < 100; ++i) { final LogEvent event = Log4jLogEvent.newBuilder() .setLoggerName("TestLogger") // @@ -121,7 +121,7 @@ public void testFilePermissionsAPI(final String filePermissions, final boolean c @ParameterizedTest @CsvSource({"rwxrwxrwx,2", "rw-r--r--,3", "rw-------,4", "rw-rw----,5"}) - public void testFileUserGroupAPI(final String filePermissions, final int fileIndex) throws Exception { + void testFileUserGroupAPI(final String filePermissions, final int fileIndex) throws Exception { final File file = new File(DIR, "AppenderTest-" + (1000 + fileIndex) + ".log"); final Path path = file.toPath(); final String user = findAUser(); @@ -151,7 +151,7 @@ public void testFileUserGroupAPI(final String filePermissions, final int fileInd assertTrue(appender.isStarted(), "Appender did not start"); long curLen = file.length(); long prevLen = curLen; - assertEquals(curLen, 0, file + " File length: " + curLen); + assertEquals(0, curLen, file + " File length: " + curLen); for (int i = 0; i < 100; ++i) { final LogEvent event = Log4jLogEvent.newBuilder() .setLoggerName("TestLogger") // @@ -209,7 +209,7 @@ public static String findAGroup(final String user) throws IOException { } } - private static String findAUser() throws IOException { + private static String findAUser() { // On jenkins build within ubuntu, it is not possible to chmod to another user return System.getProperty("user.name"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java index c645c3516e3..07221c2c811 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/FileAppenderTest.java @@ -52,20 +52,20 @@ * Tests {@link FileAppender}. */ @CleanUpFiles(FileAppenderTest.FILE_NAME) -public class FileAppenderTest { +class FileAppenderTest { static final String FILE_NAME = "target/fileAppenderTest.log"; private static final Path PATH = Paths.get(FILE_NAME); private static final int THREADS = 2; @AfterAll - public static void cleanupClass() { + static void cleanupClass() { assertFalse(AbstractManager.hasManager(FILE_NAME), "Manager for " + FILE_NAME + " not removed"); } @ParameterizedTest @ValueSource(booleans = {false, true}) - public void testAppender(final boolean createOnDemand) throws Exception { + void testAppender(final boolean createOnDemand) throws Exception { final int logEventCount = 1; writer(false, logEventCount, "test", createOnDemand, false); verifyFile(logEventCount); @@ -73,7 +73,7 @@ public void testAppender(final boolean createOnDemand) throws Exception { @ParameterizedTest @ValueSource(booleans = {false, true}) - public void testLazyCreate(final boolean createOnDemand) throws Exception { + void testLazyCreate(final boolean createOnDemand) { final Layout layout = createPatternLayout(); // @formatter:off final FileAppender appender = FileAppender.newBuilder() @@ -106,7 +106,7 @@ private static PatternLayout createPatternLayout() { @ParameterizedTest @ValueSource(booleans = {false, true}) - public void testSmallestBufferSize(final boolean createOnDemand) throws Exception { + void testSmallestBufferSize(final boolean createOnDemand) throws Exception { final Layout layout = createPatternLayout(); // @formatter:off final FileAppender appender = FileAppender.newBuilder() @@ -154,7 +154,7 @@ public void testSmallestBufferSize(final boolean createOnDemand) throws Exceptio @ParameterizedTest @ValueSource(booleans = {false, true}) - public void testLockingAppender(final boolean createOnDemand) throws Exception { + void testLockingAppender(final boolean createOnDemand) throws Exception { final int logEventCount = 1; writer(true, logEventCount, "test", createOnDemand, false); verifyFile(logEventCount); @@ -162,13 +162,12 @@ public void testLockingAppender(final boolean createOnDemand) throws Exception { @ParameterizedTest @ValueSource(booleans = {false, true}) - public void testMultipleAppenderThreads(final boolean createOnDemand) throws Exception { + void testMultipleAppenderThreads(final boolean createOnDemand) throws Exception { testMultipleLockingAppenderThreads(false, THREADS, createOnDemand); } private void testMultipleLockingAppenderThreads( - final boolean lock, final int threadCount, final boolean createOnDemand) - throws InterruptedException, Exception { + final boolean lock, final int threadCount, final boolean createOnDemand) throws Exception { final ExecutorService threadPool = Executors.newFixedThreadPool(threadCount); final AtomicReference throwableRef = new AtomicReference<>(); final int logEventCount = 100; @@ -193,14 +192,14 @@ private void testMultipleLockingAppenderThreads( @ParameterizedTest @ValueSource(booleans = {false, true}) - public void testMultipleLockingAppenders(final boolean createOnDemand) throws Exception { + void testMultipleLockingAppenders(final boolean createOnDemand) throws Exception { testMultipleLockingAppenderThreads(true, THREADS, createOnDemand); } @ParameterizedTest @ValueSource(booleans = {false, true}) @Disabled - public void testMultipleVMs(final boolean createOnDemand) throws Exception { + void testMultipleVMs(final boolean createOnDemand) throws Exception { final String classPath = System.getProperty("java.class.path"); final int logEventCount = 10; final int processCount = 3; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderTest.java index 1719f15cba9..a4df56e5074 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/HttpAppenderTest.java @@ -26,7 +26,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.junit5.WireMockExtension; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/InMemoryAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/InMemoryAppenderTest.java index bdc95ceef32..4bc0c53b765 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/InMemoryAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/InMemoryAppenderTest.java @@ -31,10 +31,10 @@ import org.apache.logging.log4j.util.Strings; import org.junit.jupiter.api.Test; -public class InMemoryAppenderTest { +class InMemoryAppenderTest { @Test - public void testAppender() { + void testAppender() { final Layout layout = PatternLayout.createDefaultLayout(); final boolean writeHeader = true; final InMemoryAppender app = new InMemoryAppender("test", layout, null, false, writeHeader); @@ -43,7 +43,7 @@ public void testAppender() { } @Test - public void testHeaderRequested() { + void testHeaderRequested() { final PatternLayout layout = PatternLayout.newBuilder().withHeader("HEADERHEADER").build(); final boolean writeHeader = true; @@ -53,7 +53,7 @@ public void testHeaderRequested() { } @Test - public void testHeaderSuppressed() { + void testHeaderSuppressed() { final PatternLayout layout = PatternLayout.newBuilder().withHeader("HEADERHEADER").build(); final boolean writeHeader = false; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/JsonCompleteFileAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/JsonCompleteFileAppenderTest.java index fa8666af1c3..4d1befb11d4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/JsonCompleteFileAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/JsonCompleteFileAppenderTest.java @@ -16,10 +16,11 @@ */ package org.apache.logging.log4j.core.appender; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import org.apache.logging.log4j.Logger; @@ -83,7 +84,7 @@ public void testFlushAtEndOfBatch() throws Exception { logger.error(logMsg, new IllegalArgumentException("badarg")); this.loggerContextRule.getLoggerContext().stop(); // stops async thread - final List lines = Files.readAllLines(logFile.toPath(), Charset.forName("UTF8")); + final List lines = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8); final String[] expected = { "[", // equals @@ -106,6 +107,6 @@ public void testFlushAtEndOfBatch() throws Exception { line.contains(expected[i])); } final String location = "testFlushAtEndOfBatch"; - assertTrue("no location", !lines.get(0).contains(location)); + assertFalse("no location", lines.get(0).contains(location)); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileAppenderTest.java index 8937864d0c7..f4ca62e9ab2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileAppenderTest.java @@ -46,11 +46,11 @@ "target/MemoryMappedFileAppenderRemapTest.log", "target/MemoryMappedFileAppenderLocationTest.log" }) -public class MemoryMappedFileAppenderTest { +class MemoryMappedFileAppenderTest { @Test @LoggerContextSource("MemoryMappedFileAppenderTest.xml") - public void testMemMapBasics(final LoggerContext context) throws Exception { + void testMemMapBasics(final LoggerContext context) throws Exception { final Logger log = context.getLogger(getClass()); final Path logFile = Paths.get("target", "MemoryMappedFileAppenderTest.log"); try { @@ -71,7 +71,7 @@ public void testMemMapBasics(final LoggerContext context) throws Exception { @Test @LoggerContextSource("MemoryMappedFileAppenderRemapTest.xml") - public void testMemMapExtendsIfNeeded(final LoggerContext context) throws Exception { + void testMemMapExtendsIfNeeded(final LoggerContext context) throws Exception { final Logger log = context.getLogger(getClass()); final Path logFile = Paths.get("target", "MemoryMappedFileAppenderRemapTest.log"); final char[] text = new char[256]; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileManagerTest.java index f0d21994439..2a442f6ea70 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileManagerTest.java @@ -33,13 +33,13 @@ * * @since 2.1 */ -public class MemoryMappedFileManagerTest { +class MemoryMappedFileManagerTest { @TempDir File tempDir; @Test - public void testRemapAfterInitialMapSizeExceeded() throws IOException { + void testRemapAfterInitialMapSizeExceeded() throws IOException { final int mapSize = 64; // very small, on purpose final File file = new File(tempDir, "memory-mapped-file.bin"); @@ -65,7 +65,7 @@ public void testRemapAfterInitialMapSizeExceeded() throws IOException { } @Test - public void testAppendDoesNotOverwriteExistingFile() throws IOException { + void testAppendDoesNotOverwriteExistingFile() throws IOException { final File file = new File(tempDir, "memory-mapped-file.bin"); final int initialLength = 4 * 1024; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamAppenderTest.java index 3082425be09..ed09bc11d86 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamAppenderTest.java @@ -16,10 +16,14 @@ */ package org.apache.logging.log4j.core.appender; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; -import java.sql.SQLException; +import java.lang.reflect.Method; +import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.Appender; @@ -27,23 +31,21 @@ import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.filter.NoMarkerFilter; import org.apache.logging.log4j.core.layout.PatternLayout; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; /** * Tests {@link OutputStreamAppender}. */ -public class OutputStreamAppenderTest { +class OutputStreamAppenderTest { private static final String TEST_MSG = "FOO ERROR"; - @Rule - public TestName testName = new TestName(); + public String testName; private String getName(final OutputStream out) { - return out.getClass().getSimpleName() + "." + testName.getMethodName(); + return out.getClass().getSimpleName() + "." + testName; } /** @@ -61,19 +63,19 @@ private void addAppender(final OutputStream outputStream, final String outputStr } @Test - public void testBuildFilter() { + void testBuildFilter() { final NoMarkerFilter filter = NoMarkerFilter.newBuilder().build(); // @formatter:off final OutputStreamAppender.Builder builder = OutputStreamAppender.newBuilder().setName("test").setFilter(filter); // @formatter:on - Assert.assertEquals(filter, builder.getFilter()); + assertEquals(filter, builder.getFilter()); final OutputStreamAppender appender = builder.build(); - Assert.assertEquals(filter, appender.getFilter()); + assertEquals(filter, appender.getFilter()); } @Test - public void testOutputStreamAppenderToBufferedOutputStream() throws SQLException { + void testOutputStreamAppenderToBufferedOutputStream() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final OutputStream os = new BufferedOutputStream(out); final String name = getName(out); @@ -81,18 +83,18 @@ public void testOutputStreamAppenderToBufferedOutputStream() throws SQLException addAppender(os, name); logger.error(TEST_MSG); final String actual = out.toString(); - Assert.assertTrue(actual, actual.contains(TEST_MSG)); + assertTrue(actual.contains(TEST_MSG), actual); } @Test - public void testOutputStreamAppenderToByteArrayOutputStream() throws SQLException { + void testOutputStreamAppenderToByteArrayOutputStream() { final OutputStream out = new ByteArrayOutputStream(); final String name = getName(out); final Logger logger = LogManager.getLogger(name); addAppender(out, name); logger.error(TEST_MSG); final String actual = out.toString(); - Assert.assertTrue(actual, actual.contains(TEST_MSG)); + assertTrue(actual.contains(TEST_MSG), actual); } /** @@ -101,7 +103,7 @@ public void testOutputStreamAppenderToByteArrayOutputStream() throws SQLExceptio * new Writer appender. */ @Test - public void testUpdatePatternWithFileAppender() { + void testUpdatePatternWithFileAppender() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); // @formatter:off @@ -120,4 +122,10 @@ public void testUpdatePatternWithFileAppender() { ConfigurationTestUtils.updateLoggers(appender, config); LogManager.getLogger().error("FOO MSG"); } + + @BeforeEach + public void setup(TestInfo testInfo) { + Optional testMethod = testInfo.getTestMethod(); + testMethod.ifPresent(method -> this.testName = method.getName()); + } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamManagerTest.java index c5e25a15c66..64c0a08dbe1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/OutputStreamManagerTest.java @@ -62,7 +62,7 @@ void narrow(final LoggerContext context) { } @Test - public void testOutputStreamAppenderFlushClearsBufferOnException() { + void testOutputStreamAppenderFlushClearsBufferOnException() { final IOException exception = new IOException(); final OutputStream throwingOutputStream = new OutputStream() { @Override @@ -79,7 +79,7 @@ public void write(final int b) throws IOException { outputStreamManager.getByteBuffer().put((byte) 0); } - assertEquals(outputStreamManager.getByteBuffer().remaining(), 1); + assertEquals(1, outputStreamManager.getByteBuffer().remaining()); final AppenderLoggingException appenderLoggingException = assertThrows( AppenderLoggingException.class, diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileAppenderTest.java index b240958379a..0371bbdb2ae 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileAppenderTest.java @@ -18,8 +18,8 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import java.io.BufferedReader; import java.io.File; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileManagerTest.java index 4c8b0af078a..fa8ccae5d50 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/RandomAccessFileManagerTest.java @@ -31,7 +31,7 @@ /** * Tests the RandomAccessFileManager class. */ -public class RandomAccessFileManagerTest { +class RandomAccessFileManagerTest { @TempDir File tempDir; @@ -41,7 +41,7 @@ public class RandomAccessFileManagerTest { * {@link org.apache.logging.log4j.core.appender.RandomAccessFileManager#writeBytes(byte[], int, int)}. */ @Test - public void testWrite_multiplesOfBufferSize() throws IOException { + void testWrite_multiplesOfBufferSize() throws IOException { final File file = new File(tempDir, "testWrite_multiplesOfBufferSize.bin"); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.getInstance(); @@ -63,7 +63,7 @@ public void testWrite_multiplesOfBufferSize() throws IOException { * . */ @Test - public void testWrite_dataExceedingBufferSize() throws IOException { + void testWrite_dataExceedingBufferSize() throws IOException { final File file = new File(tempDir, "testWrite_dataExceedingBufferSize.bin"); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.getInstance(); @@ -82,7 +82,7 @@ public void testWrite_dataExceedingBufferSize() throws IOException { } @Test - public void testConfigurableBufferSize() throws IOException { + void testConfigurableBufferSize() throws IOException { final File file = new File(tempDir, "testConfigurableBufferSize.bin"); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.getInstance(); @@ -98,7 +98,7 @@ public void testConfigurableBufferSize() throws IOException { } @Test - public void testWrite_dataExceedingMinBufferSize() throws IOException { + void testWrite_dataExceedingMinBufferSize() throws IOException { final File file = new File(tempDir, "testWrite_dataExceedingMinBufferSize.bin"); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.getInstance(); @@ -118,7 +118,7 @@ public void testWrite_dataExceedingMinBufferSize() throws IOException { } @Test - public void testAppendDoesNotOverwriteExistingFile() throws IOException { + void testAppendDoesNotOverwriteExistingFile() throws IOException { final boolean isAppend = true; final File file = new File(tempDir, "testAppendDoesNotOverwriteExistingFile.bin"); assertEquals(0, file.length()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ReconfigureAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ReconfigureAppenderTest.java index bd649ff5bb5..688ac302044 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ReconfigureAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ReconfigureAppenderTest.java @@ -32,11 +32,11 @@ import org.apache.logging.log4j.core.util.Builder; import org.junit.jupiter.api.Test; -public class ReconfigureAppenderTest { +class ReconfigureAppenderTest { private RollingFileAppender appender; @Test - public void addAndRemoveAppenderTest() { + void addAndRemoveAppenderTest() { // this will create a rolling file appender and add it to the logger // of this class. The file manager is created for the first time. // see AbstractManager.getManager(...). diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ScriptAppenderSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ScriptAppenderSelectorTest.java index 0b8c8c6cb56..99545656641 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ScriptAppenderSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ScriptAppenderSelectorTest.java @@ -31,7 +31,7 @@ import org.junitpioneer.jupiter.SetSystemProperty; @SetSystemProperty(key = Constants.SCRIPT_LANGUAGES, value = "Groovy, Javascript") -public class ScriptAppenderSelectorTest { +class ScriptAppenderSelectorTest { @Test @LoggerContextSource("log4j-appender-selector-javascript.xml") diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SmtpAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SmtpAppenderTest.java index f1ac50d8f2f..1ad3d8f8d2d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SmtpAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SmtpAppenderTest.java @@ -16,12 +16,13 @@ */ package org.apache.logging.log4j.core.appender; -import static org.junit.Assert.assertArrayEquals; -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 static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Iterator; import javax.mail.Address; @@ -35,19 +36,18 @@ import org.apache.logging.log4j.core.net.MimeMessageBuilder; import org.apache.logging.log4j.core.net.SmtpManager; import org.apache.logging.log4j.core.test.AvailablePortFinder; -import org.apache.logging.log4j.core.test.categories.Appenders; import org.apache.logging.log4j.core.test.smtp.SimpleSmtpServer; import org.apache.logging.log4j.core.test.smtp.SmtpMessage; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(Appenders.Smtp.class) -public class SmtpAppenderTest { +@Tag("Smtp") +class SmtpAppenderTest { private static final String HOST = "localhost"; @Test - public void testMessageFactorySetFrom() throws MessagingException { + void testMessageFactorySetFrom() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String address = "testing@example.com"; @@ -67,7 +67,7 @@ public void testMessageFactorySetFrom() throws MessagingException { } @Test - public void testMessageFactorySetReplyTo() throws MessagingException { + void testMessageFactorySetReplyTo() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String addresses = "testing1@example.com,testing2@example.com"; @@ -81,7 +81,7 @@ public void testMessageFactorySetReplyTo() throws MessagingException { } @Test - public void testMessageFactorySetRecipients() throws MessagingException { + void testMessageFactorySetRecipients() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String addresses = "testing1@example.com,testing2@example.com"; @@ -95,7 +95,7 @@ public void testMessageFactorySetRecipients() throws MessagingException { } @Test - public void testMessageFactorySetSubject() throws MessagingException { + void testMessageFactorySetSubject() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String subject = "Test Subject"; @@ -109,7 +109,7 @@ public void testMessageFactorySetSubject() throws MessagingException { } @Test - public void testDelivery() { + void testDelivery() { final String subjectKey = getClass().getName(); final String subjectValue = "SubjectValue1"; ThreadContext.put(subjectKey, subjectValue); @@ -127,7 +127,7 @@ public void testDelivery() { .setBufferSize(3) .build(); assertNotNull(appender); - assertTrue(appender.getManager() instanceof SmtpManager); + assertInstanceOf(SmtpManager.class, appender.getManager()); appender.start(); final LoggerContext context = LoggerContext.getContext(); @@ -146,7 +146,7 @@ public void testDelivery() { root.error("Error message #2"); server.stop(); - assertTrue(server.getReceivedEmailSize() == 2); + assertEquals(2, server.getReceivedEmailSize()); final Iterator messages = server.getReceivedEmail(); final SmtpMessage email = messages.next(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBuilderTest.java index e79579444e3..e67b2f2d65e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderBuilderTest.java @@ -20,13 +20,13 @@ import org.junit.jupiter.api.Test; -public class SocketAppenderBuilderTest { +class SocketAppenderBuilderTest { /** * Tests https://issues.apache.org/jira/browse/LOG4J2-1620 */ @Test - public void testDefaultImmediateFlush() { + void testDefaultImmediateFlush() { assertTrue( SocketAppender.newBuilder().isImmediateFlush(), "Regression of LOG4J2-1620: default value for immediateFlush should be true"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderReconnectTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderReconnectTest.java index 503b2b1e1ad..619749eacf2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderReconnectTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderReconnectTest.java @@ -55,7 +55,7 @@ /** * Tests reconnection support of {@link org.apache.logging.log4j.core.appender.SocketAppender}. */ -public class SocketAppenderReconnectTest { +class SocketAppenderReconnectTest { private static final String CLASS_NAME = SocketAppenderReconnectTest.class.getSimpleName(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSocketOptionsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSocketOptionsTest.java index 76453658539..7988c3fbd8c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSocketOptionsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSocketOptionsTest.java @@ -86,10 +86,10 @@ public void testSocketOptions() throws IOException { Assert.assertEquals(12345, socketOptions.getSoLinger().intValue()); Assert.assertEquals(54321, socketOptions.getSoTimeout().intValue()); // Test live socket - Assert.assertEquals(false, socket.getKeepAlive()); - Assert.assertEquals(false, socket.getOOBInline()); - Assert.assertEquals(false, socket.getReuseAddress()); - Assert.assertEquals(false, socket.getTcpNoDelay()); + Assert.assertFalse(socket.getKeepAlive()); + Assert.assertFalse(socket.getOOBInline()); + Assert.assertFalse(socket.getReuseAddress()); + Assert.assertFalse(socket.getTcpNoDelay()); // Assert.assertEquals(10000, socket.getReceiveBufferSize()); // This settings changes while we are running, so we cannot assert it. // Assert.assertEquals(8000, socket.getSendBufferSize()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSslSocketOptionsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSslSocketOptionsTest.java index 5e68fd776ce..0167194c7b1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSslSocketOptionsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderSslSocketOptionsTest.java @@ -40,7 +40,7 @@ import org.junit.jupiter.api.io.CleanupMode; import org.junit.jupiter.api.io.TempDir; -public class SocketAppenderSslSocketOptionsTest { +class SocketAppenderSslSocketOptionsTest { private static final String APPENDER_NAME = "TestSocket"; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderTest.java index b330f7d4d43..3eaad6533f1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SocketAppenderTest.java @@ -16,17 +16,16 @@ */ package org.apache.logging.log4j.core.appender; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; -import java.io.Serializable; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.ServerSocket; @@ -41,7 +40,6 @@ import org.apache.logging.log4j.LoggingException; import org.apache.logging.log4j.ThreadContext; import org.apache.logging.log4j.core.Appender; -import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; @@ -52,17 +50,16 @@ import org.apache.logging.log4j.core.test.AvailablePortFinder; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.core.util.Throwables; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * */ -public class SocketAppenderTest { +class SocketAppenderTest { private static final int PORT = AvailablePortFinder.getNextAvailable(); private static final int DYN_PORT = AvailablePortFinder.getNextAvailable(); @@ -74,8 +71,8 @@ public class SocketAppenderTest { private final LoggerContext context = LoggerContext.getContext(); private final Logger logger = context.getLogger(SocketAppenderTest.class.getName()); - @BeforeClass - public static void setupClass() throws Exception { + @BeforeAll + static void setupClass() throws Exception { tcpServer = new TcpSocketTestServer(PORT); tcpServer.start(); udpServer = new UdpSocketTestServer(); @@ -84,15 +81,15 @@ public static void setupClass() throws Exception { ThreadContext.clearAll(); } - @AfterClass - public static void cleanupClass() { + @AfterAll + static void cleanupClass() { tcpServer.shutdown(); udpServer.shutdown(); ThreadContext.clearAll(); } - @After - public void teardown() { + @AfterEach + void teardown() { ThreadContext.clearAll(); removeAndStopAppenders(); reset(); @@ -113,13 +110,13 @@ static void reset() { } @Test - public void testTcpAppender1() throws Exception { + void testTcpAppender1() throws Exception { testTcpAppender(tcpServer, logger, Constants.ENCODER_BYTE_BUFFER_SIZE); } @Test - @Ignore("WIP Bug when this method runs after testTcpAppender1()") - public void testTcpAppender2() throws Exception { + @Disabled("WIP Bug when this method runs after testTcpAppender1()") + void testTcpAppender2() throws Exception { testTcpAppender(tcpServer, logger, Constants.ENCODER_BYTE_BUFFER_SIZE); } @@ -133,12 +130,11 @@ static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logge .setName("test") .setImmediateFail(false) .setBufferSize(bufferSize) - .setLayout((Layout) - JsonLayout.newBuilder().setProperties(true).build()) + .setLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); - Assert.assertEquals(bufferSize, appender.getManager().getByteBuffer().capacity()); + assertEquals(bufferSize, appender.getManager().getByteBuffer().capacity()); // set appender on root and set level to debug logger.addAppender(appender); @@ -160,29 +156,28 @@ static void testTcpAppender(final TcpSocketTestServer tcpTestServer, final Logge } Thread.sleep(250); LogEvent event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS); - assertNotNull("No event retrieved", event); - assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a test message")); - assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 0); + assertNotNull(event, "No event retrieved"); + assertEquals("This is a test message", event.getMessage().getFormattedMessage(), "Incorrect event"); + assertTrue(tcpTestServer.getCount() > 0, "Message not delivered via TCP"); assertEquals(expectedUuidStr, event.getContextData().getValue(tcKey)); event = tcpTestServer.getQueue().poll(3, TimeUnit.SECONDS); - assertNotNull("No event retrieved", event); - assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("Throwing an exception")); - assertTrue("Message not delivered via TCP", tcpTestServer.getCount() > 1); + assertNotNull(event, "No event retrieved"); + assertEquals("Throwing an exception", event.getMessage().getFormattedMessage(), "Incorrect event"); + assertTrue(tcpTestServer.getCount() > 1, "Message not delivered via TCP"); assertEquals(expectedUuidStr, event.getContextStack().pop()); assertNotNull(event.getThrownProxy()); assertEquals(expectedExMsg, event.getThrownProxy().getMessage()); } @Test - public void testDefaultProtocol() throws Exception { + void testDefaultProtocol() { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .setPort(tcpServer.getLocalPort()) .setReconnectDelayMillis(-1) .setName("test") .setImmediateFail(false) - .setLayout((Layout) - JsonLayout.newBuilder().setProperties(true).build()) + .setLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on assertNotNull(appender); @@ -190,7 +185,7 @@ public void testDefaultProtocol() throws Exception { } @Test - public void testUdpAppender() throws Exception { + void testUdpAppender() throws Exception { try { udpServer.latch.await(); } catch (final InterruptedException ex) { @@ -204,8 +199,7 @@ public void testUdpAppender() throws Exception { .setReconnectDelayMillis(-1) .setName("test") .setImmediateFail(false) - .setLayout((Layout) - JsonLayout.newBuilder().setProperties(true).build()) + .setLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); @@ -216,13 +210,13 @@ public void testUdpAppender() throws Exception { logger.setLevel(Level.DEBUG); logger.debug("This is a udp message"); final LogEvent event = udpServer.getQueue().poll(3, TimeUnit.SECONDS); - assertNotNull("No event retrieved", event); - assertTrue("Incorrect event", event.getMessage().getFormattedMessage().equals("This is a udp message")); - assertTrue("Message not delivered via UDP", udpServer.getCount() > 0); + assertNotNull(event, "No event retrieved"); + assertEquals("This is a udp message", event.getMessage().getFormattedMessage(), "Incorrect event"); + assertTrue(udpServer.getCount() > 0, "Message not delivered via UDP"); } @Test - public void testTcpAppenderDeadlock() throws Exception { + void testTcpAppenderDeadlock() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() @@ -231,8 +225,7 @@ public void testTcpAppenderDeadlock() throws Exception { .setReconnectDelayMillis(100) .setName("test") .setImmediateFail(false) - .setLayout((Layout) - JsonLayout.newBuilder().setProperties(true).build()) + .setLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); @@ -248,14 +241,14 @@ public void testTcpAppenderDeadlock() throws Exception { logger.debug("This message is written because a deadlock never."); final LogEvent event = tcpSocketServer.getQueue().poll(3, TimeUnit.SECONDS); - assertNotNull("No event retrieved", event); + assertNotNull(event, "No event retrieved"); } finally { tcpSocketServer.shutdown(); } } @Test - public void testTcpAppenderNoWait() throws Exception { + void testTcpAppenderNoWait() { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .setHost("localhost") @@ -264,8 +257,7 @@ public void testTcpAppenderNoWait() throws Exception { .setName("test") .setImmediateFail(false) .setIgnoreExceptions(false) - .setLayout((Layout) - JsonLayout.newBuilder().setProperties(true).build()) + .setLayout(JsonLayout.newBuilder().setProperties(true).build()) .build(); // @formatter:on appender.start(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SyslogAppenderTestBase.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SyslogAppenderTestBase.java index 4de3e69d298..5af62582bf2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SyslogAppenderTestBase.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/SyslogAppenderTestBase.java @@ -16,9 +16,10 @@ */ package org.apache.logging.log4j.core.appender; -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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.Serializable; import java.util.ArrayList; @@ -40,11 +41,10 @@ import org.apache.logging.log4j.message.StructuredDataMessage; import org.apache.logging.log4j.test.junit.UsingStatusListener; import org.apache.logging.log4j.util.Strings; -import org.junit.Assert; import org.junit.jupiter.api.BeforeAll; @UsingStatusListener -public abstract class SyslogAppenderTestBase { +abstract class SyslogAppenderTestBase { protected static final String line1 = "TestApp - Audit [Transfer@18060 Amount=\"200.00\" FromAccount=\"123457\" ToAccount=\"123456\"]" + "[RequestContext@18060 ipAddress=\"192.168.0.120\" loginId=\"JohnDoe\"] Transfer Complete"; @@ -57,7 +57,7 @@ public abstract class SyslogAppenderTestBase { protected boolean includeNewLine = true; @BeforeAll - public static void setupClass() throws Exception { + public static void setupClass() { LoggerContext.getContext().reconfigure(); } @@ -110,26 +110,26 @@ protected void sendInfoStructuredMessage() { protected void checkTheNumberOfSentAndReceivedMessages() throws InterruptedException { assertEquals( - "The number of received messages should be equal with the number of sent messages", sentMessages.size(), - getReceivedMessages(DEFAULT_TIMEOUT_IN_MS).size()); + getReceivedMessages(DEFAULT_TIMEOUT_IN_MS).size(), + "The number of received messages should be equal with the number of sent messages"); } protected void checkTheEqualityOfSentAndReceivedMessages(final Level expectedLevel) throws InterruptedException { final List receivedMessages = getReceivedMessages(DEFAULT_TIMEOUT_IN_MS); - assertNotNull("No messages received", receivedMessages); + assertNotNull(receivedMessages, "No messages received"); for (int i = 0; i < receivedMessages.size(); i++) { final String receivedMessage = receivedMessages.get(i); final String sentMessage = sentMessages.get(i); final String suffix = includeNewLine ? "\n" : Strings.EMPTY; assertTrue( - "Incorrect message received: " + receivedMessage, - receivedMessage.endsWith(sentMessage + suffix) || receivedMessage.contains(sentMessage)); + receivedMessage.endsWith(sentMessage + suffix) || receivedMessage.contains(sentMessage), + "Incorrect message received: " + receivedMessage); final int expectedPriority = Priority.getPriority(getExpectedFacility(), expectedLevel); assertTrue( - "Expected facility " + expectedPriority + " in message " + receivedMessage, - receivedMessage.startsWith("<" + expectedPriority + ">")); + receivedMessage.startsWith("<" + expectedPriority + ">"), + "Expected facility " + expectedPriority + " in message " + receivedMessage); } } @@ -166,15 +166,15 @@ protected void validate(final SyslogAppender syslogAppender) { } else if (layout instanceof Rfc5424Layout) { validate((Rfc5424Layout) layout); } else { - Assert.fail("Unexpected layout: " + layout); + fail("Unexpected layout: " + layout); } } protected void validate(final Rfc5424Layout layout) { - Assert.assertEquals(getExpectedFacility(), layout.getFacility()); + assertEquals(getExpectedFacility(), layout.getFacility()); } protected void validate(final SyslogLayout layout) { - Assert.assertEquals(getExpectedFacility(), layout.getFacility()); + assertEquals(getExpectedFacility(), layout.getFacility()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogAppenderTest.java index 7294e038ba3..b18673e4be2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogAppenderTest.java @@ -33,7 +33,7 @@ import org.apache.logging.log4j.core.test.net.ssl.TlsSyslogTestUtil; import org.junit.jupiter.api.Test; -public class TlsSyslogAppenderTest extends SyslogAppenderTest { +class TlsSyslogAppenderTest extends SyslogAppenderTest { private SSLServerSocketFactory serverSocketFactory; private SslConfiguration sslConfiguration; @@ -44,7 +44,7 @@ public TlsSyslogAppenderTest() throws StoreConfigurationException { } @Test - public void sendLargeLegacyBsdMessageOverTls() throws IOException, InterruptedException { + void sendLargeLegacyBsdMessageOverTls() throws IOException, InterruptedException { final String prefix = "BEGIN"; initTlsTestEnvironment(1, TlsSyslogMessageFormat.LEGACY_BSD); @@ -55,7 +55,7 @@ public void sendLargeLegacyBsdMessageOverTls() throws IOException, InterruptedEx } @Test - public void sendLegacyBsdMessagesOverTls() throws IOException, InterruptedException { + void sendLegacyBsdMessagesOverTls() throws IOException, InterruptedException { final int numberOfMessages = 100; initTlsTestEnvironment(numberOfMessages, TlsSyslogMessageFormat.LEGACY_BSD); final List generatedMessages = @@ -64,14 +64,14 @@ public void sendLegacyBsdMessagesOverTls() throws IOException, InterruptedExcept } @Test - public void sendStructuredMessageOverTls() throws InterruptedException, IOException { + void sendStructuredMessageOverTls() throws InterruptedException, IOException { initTlsTestEnvironment(1, TlsSyslogMessageFormat.SYSLOG); sendAndCheckStructuredMessage(); } @Test - public void sendStructuredMessagesOverTls() throws IOException, InterruptedException { + void sendStructuredMessagesOverTls() throws IOException, InterruptedException { final int numberOfMessages = 100; initTlsTestEnvironment(numberOfMessages, TlsSyslogMessageFormat.SYSLOG); sendAndCheckStructuredMessages(numberOfMessages); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogFrameTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogFrameTest.java index 670431d5c79..653718d0bf0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogFrameTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/TlsSyslogFrameTest.java @@ -23,11 +23,11 @@ import org.apache.logging.log4j.util.Chars; import org.junit.jupiter.api.Test; -public class TlsSyslogFrameTest { +class TlsSyslogFrameTest { private static final String TEST_MESSAGE = "The quick brown fox jumps over the lazy dog"; @Test - public void equals() { + void equals() { final TlsSyslogFrame first = new TlsSyslogFrame(TEST_MESSAGE); final TlsSyslogFrame second = new TlsSyslogFrame(TEST_MESSAGE); assertEquals(first, second); @@ -35,7 +35,7 @@ public void equals() { } @Test - public void notEquals() { + void notEquals() { final TlsSyslogFrame first = new TlsSyslogFrame("A message"); final TlsSyslogFrame second = new TlsSyslogFrame("B message"); assertNotEquals(first, second); @@ -43,7 +43,7 @@ public void notEquals() { } @Test - public void testToString() { + void testToString() { final TlsSyslogFrame frame = new TlsSyslogFrame(TEST_MESSAGE); final int length = TEST_MESSAGE.getBytes(StandardCharsets.UTF_8).length; final String expected = Integer.toString(length) + Chars.SPACE + TEST_MESSAGE; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/WriterAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/WriterAppenderTest.java index e813ee456eb..37e715216a1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/WriterAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/WriterAppenderTest.java @@ -39,7 +39,7 @@ /** * Tests {@link WriterAppender}. */ -public class WriterAppenderTest { +class WriterAppenderTest { private static final String TEST_MSG = "FOO ERROR"; @@ -83,31 +83,31 @@ private void addAppender(final Writer writer, final String writerName) { } @Test - public void testWriterAppenderToCharArrayWriter() { + void testWriterAppenderToCharArrayWriter() { test(new CharArrayWriter()); } @Test - public void testWriterAppenderToOutputStreamWriter() { + void testWriterAppenderToOutputStreamWriter() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Writer writer = new OutputStreamWriter(out); test(out, writer); } @Test - public void testWriterAppenderToPrintWriter() { + void testWriterAppenderToPrintWriter() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Writer writer = new PrintWriter(out); test(out, writer); } @Test - public void testWriterAppenderToStringWriter() { + void testWriterAppenderToStringWriter() { test(new StringWriter()); } @Test - public void testBuilder() { + void testBuilder() { // This should compile WriterAppender.newBuilder() .setTarget(new StringWriter()) diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderTest.java index f39e40ace3d..731ee7ffa8d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderTest.java @@ -16,8 +16,10 @@ */ package org.apache.logging.log4j.core.appender; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -26,24 +28,23 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.Layouts; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Tests a "compact" XML file, no extra spaces or end of lines. */ -@Category(Layouts.Xml.class) -public class XmlCompactFileAppenderTest { +@Tag("Layouts.Xml") +class XmlCompactFileAppenderTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "XmlCompactFileAppenderTest.xml"); } @Test - public void testFlushAtEndOfBatch() throws Exception { + void testFlushAtEndOfBatch() throws Exception { final File file = new File("target", "XmlCompactFileAppenderTest.log"); file.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); @@ -57,23 +58,23 @@ public void testFlushAtEndOfBatch() throws Exception { } finally { file.delete(); } - assertNotNull("line1", line1); + assertNotNull(line1, "line1"); final String msg1 = ""; - assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.contains(msg1)); + assertTrue(line1.contains(msg1), "line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']'); final String msg2 = ""; - assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg2 + ']', line1.contains(msg2)); + assertTrue(line1.contains(msg2), "line1 incorrect: [" + line1 + "], does not contain: [" + msg2 + ']'); final String msg3 = ""; - assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1)); + assertEquals("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', msg1, line1); assertNotNull("line2", line2); final String msg2 = ""; - assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2)); + assertEquals("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', msg2, line2); assertNotNull("line3", line3); final String msg3 = "\n" + 0, // "\n"; }; - final List lines1 = Files.readAllLines(logFile.toPath(), Charset.forName("UTF-8")); + final List lines1 = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8); assertEquals("number of lines", indentations.length, lines1.size()); for (int i = 0; i < indentations.length; i++) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java index ab2a44380d6..ad186d21129 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java @@ -16,34 +16,34 @@ */ package org.apache.logging.log4j.core.appender; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.Layouts; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Tests a "complete" XML file a.k.a. a well-formed XML file. */ -@Category(Layouts.Xml.class) -public class XmlFileAppenderTest { +@Tag("Layouts.Xml") +class XmlFileAppenderTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "XmlFileAppenderTest.xml"); } @Test - public void testFlushAtEndOfBatch() throws Exception { + void testFlushAtEndOfBatch() throws Exception { final File file = new File("target", "XmlFileAppenderTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); @@ -52,7 +52,7 @@ public void testFlushAtEndOfBatch() throws Exception { log.info(logMsg); CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread - final List lines = Files.readAllLines(file.toPath(), Charset.forName("UTF8")); + final List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); file.delete(); final String[] expect = { @@ -65,11 +65,11 @@ public void testFlushAtEndOfBatch() throws Exception { for (int i = 0; i < expect.length; i++) { assertTrue( - "Expected line " + i + " to contain " + expect[i] + " but got: " + lines.get(i), - lines.get(i).contains(expect[i])); + lines.get(i).contains(expect[i]), + "Expected line " + i + " to contain " + expect[i] + " but got: " + lines.get(i)); } final String location = "testFlushAtEndOfBatch"; - assertTrue("no location", !lines.get(0).contains(location)); + assertFalse(lines.get(0).contains(location), "no location"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseAppenderTest.java index 8ede2cdc3e4..fdf2df70843 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseAppenderTest.java @@ -26,7 +26,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; -import java.io.Serializable; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.LogEvent; @@ -74,12 +73,12 @@ public void testAppend() { appender.append(event1); then(manager).should().isBuffered(); - then(manager).should().writeThrough(same(event1), (Serializable) isNull()); + then(manager).should().writeThrough(same(event1), isNull()); reset(manager); appender.append(event2); then(manager).should().isBuffered(); - then(manager).should().writeThrough(same(event2), (Serializable) isNull()); + then(manager).should().writeThrough(same(event2), isNull()); reset(manager); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseManagerTest.java index 2af9990f65e..38fad66231c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/AbstractDatabaseManagerTest.java @@ -16,9 +16,9 @@ */ package org.apache.logging.log4j.core.appender.db; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.then; @@ -31,9 +31,9 @@ import java.io.Serializable; import org.apache.logging.log4j.core.LogEvent; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AbstractDatabaseManagerTest { +class AbstractDatabaseManagerTest { // this stub is provided because mocking constructors is hard private static class StubDatabaseManager extends AbstractDatabaseManager { @@ -52,12 +52,12 @@ protected void connectAndStart() { } @Override - protected boolean shutdownInternal() throws Exception { + protected boolean shutdownInternal() { return true; } @Override - protected void startupInternal() throws Exception { + protected void startupInternal() { // noop } @@ -74,7 +74,7 @@ public void setUp(final String name, final int buffer) { } @Test - public void testBuffering01() throws Exception { + void testBuffering01() throws Exception { setUp("name", 0); final LogEvent event1 = mock(LogEvent.class); @@ -86,35 +86,35 @@ public void testBuffering01() throws Exception { reset(manager); manager.write(event1, null); - then(manager).should().writeThrough(same(event1), (Serializable) isNull()); + then(manager).should().writeThrough(same(event1), isNull()); then(manager).should().connectAndStart(); then(manager).should().isBuffered(); - then(manager).should().writeInternal(same(event1), (Serializable) isNull()); + then(manager).should().writeInternal(same(event1), isNull()); then(manager).should().commitAndClose(); then(manager).shouldHaveNoMoreInteractions(); reset(manager); manager.write(event2, null); - then(manager).should().writeThrough(same(event2), (Serializable) isNull()); + then(manager).should().writeThrough(same(event2), isNull()); then(manager).should().connectAndStart(); then(manager).should().isBuffered(); - then(manager).should().writeInternal(same(event2), (Serializable) isNull()); + then(manager).should().writeInternal(same(event2), isNull()); then(manager).should().commitAndClose(); then(manager).shouldHaveNoMoreInteractions(); reset(manager); manager.write(event3, null); - then(manager).should().writeThrough(same(event3), (Serializable) isNull()); + then(manager).should().writeThrough(same(event3), isNull()); then(manager).should().connectAndStart(); then(manager).should().isBuffered(); - then(manager).should().writeInternal(same(event3), (Serializable) isNull()); + then(manager).should().writeInternal(same(event3), isNull()); then(manager).should().commitAndClose(); then(manager).shouldHaveNoMoreInteractions(); reset(manager); } @Test - public void testBuffering02() throws Exception { + void testBuffering02() throws Exception { setUp("name", 4); final LogEvent event1 = mock(LogEvent.class); @@ -142,20 +142,20 @@ public void testBuffering02() throws Exception { then(manager).should().connectAndStart(); verify(manager, times(5)).isBuffered(); // 4 + 1 in flush() - then(manager).should().writeInternal(same(event1copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event1copy), isNull()); then(manager).should().buffer(event1); - then(manager).should().writeInternal(same(event2copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event2copy), isNull()); then(manager).should().buffer(event2); - then(manager).should().writeInternal(same(event3copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event3copy), isNull()); then(manager).should().buffer(event3); - then(manager).should().writeInternal(same(event4copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event4copy), isNull()); then(manager).should().buffer(event4); then(manager).should().commitAndClose(); then(manager).shouldHaveNoMoreInteractions(); } @Test - public void testBuffering03() throws Exception { + void testBuffering03() throws Exception { setUp("name", 10); final LogEvent event1 = mock(LogEvent.class); @@ -180,18 +180,18 @@ public void testBuffering03() throws Exception { then(manager).should().connectAndStart(); verify(manager, times(4)).isBuffered(); - then(manager).should().writeInternal(same(event1copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event1copy), isNull()); then(manager).should().buffer(event1); - then(manager).should().writeInternal(same(event2copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event2copy), isNull()); then(manager).should().buffer(event2); - then(manager).should().writeInternal(same(event3copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event3copy), isNull()); then(manager).should().buffer(event3); then(manager).should().commitAndClose(); then(manager).shouldHaveNoMoreInteractions(); } @Test - public void testBuffering04() throws Exception { + void testBuffering04() throws Exception { setUp("name", 10); final LogEvent event1 = mock(LogEvent.class); @@ -216,11 +216,11 @@ public void testBuffering04() throws Exception { then(manager).should().connectAndStart(); verify(manager, times(4)).isBuffered(); - then(manager).should().writeInternal(same(event1copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event1copy), isNull()); then(manager).should().buffer(event1); - then(manager).should().writeInternal(same(event2copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event2copy), isNull()); then(manager).should().buffer(event2); - then(manager).should().writeInternal(same(event3copy), (Serializable) isNull()); + then(manager).should().writeInternal(same(event3copy), isNull()); then(manager).should().buffer(event3); then(manager).should().commitAndClose(); then(manager).should().shutdownInternal(); @@ -228,48 +228,48 @@ public void testBuffering04() throws Exception { } @Test - public void testStartupShutdown01() throws Exception { + void testStartupShutdown01() throws Exception { setUp("testName01", 0); - assertEquals("The name is not correct.", "testName01", manager.getName()); - assertFalse("The manager should not have started.", manager.isRunning()); + assertEquals("testName01", manager.getName(), "The name is not correct."); + assertFalse(manager.isRunning(), "The manager should not have started."); manager.startup(); then(manager).should().startupInternal(); - assertTrue("The manager should be running now.", manager.isRunning()); + assertTrue(manager.isRunning(), "The manager should be running now."); manager.shutdown(); then(manager).should().shutdownInternal(); - assertFalse("The manager should not be running anymore.", manager.isRunning()); + assertFalse(manager.isRunning(), "The manager should not be running anymore."); } @Test - public void testStartupShutdown02() throws Exception { + void testStartupShutdown02() throws Exception { setUp("anotherName02", 0); - assertEquals("The name is not correct.", "anotherName02", manager.getName()); - assertFalse("The manager should not have started.", manager.isRunning()); + assertEquals("anotherName02", manager.getName(), "The name is not correct."); + assertFalse(manager.isRunning(), "The manager should not have started."); manager.startup(); then(manager).should().startupInternal(); - assertTrue("The manager should be running now.", manager.isRunning()); + assertTrue(manager.isRunning(), "The manager should be running now."); manager.releaseSub(-1, null); then(manager).should().shutdownInternal(); - assertFalse("The manager should not be running anymore.", manager.isRunning()); + assertFalse(manager.isRunning(), "The manager should not be running anymore."); } @Test - public void testToString01() { + void testToString01() { setUp("someName01", 0); - assertEquals("The string is not correct.", "someName01", manager.toString()); + assertEquals("someName01", manager.toString(), "The string is not correct."); } @Test - public void testToString02() { + void testToString02() { setUp("bufferSize=12, anotherKey02=coolValue02", 12); - assertEquals("The string is not correct.", "bufferSize=12, anotherKey02=coolValue02", manager.toString()); + assertEquals("bufferSize=12, anotherKey02=coolValue02", manager.toString(), "The string is not correct."); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/AbstractJdbcDataSourceTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/AbstractJdbcDataSourceTest.java index fad3411bbba..4167bdc678c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/AbstractJdbcDataSourceTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/AbstractJdbcDataSourceTest.java @@ -26,12 +26,12 @@ public abstract class AbstractJdbcDataSourceTest { @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.clearProperty("log4j2.enableJndiJdbc"); } @BeforeClass - public static void beforeClass() throws Exception { + public static void beforeClass() { System.setProperty("log4j2.enableJndiJdbc", "true"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/ColumnConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/ColumnConfigTest.java index af816eb47b4..a27e5ce9adb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/ColumnConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/ColumnConfigTest.java @@ -16,76 +16,76 @@ */ package org.apache.logging.log4j.core.appender.db.jdbc; -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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.logging.log4j.util.Strings; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ColumnConfigTest { +class ColumnConfigTest { @Test - public void testNullNameNoConfig() { + void testNullNameNoConfig() { final ColumnConfig config = ColumnConfig.newBuilder().setPattern("%l").build(); - assertNull("The result should be null.", config); + assertNull(config, "The result should be null."); } @Test - public void testPatternAndLiteralNoConfig() { + void testPatternAndLiteralNoConfig() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col") .setPattern("%l") .setLiteral("literal") .build(); - assertNull("The result should be null.", config); + assertNull(config, "The result should be null."); } @Test - public void testPatternAndDateNoConfig() { + void testPatternAndDateNoConfig() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col") .setPattern("%l") .setEventTimestamp(true) .build(); - assertNull("The result should be null.", config); + assertNull(config, "The result should be null."); } @Test - public void testLiteralAndDateNoConfig() { + void testLiteralAndDateNoConfig() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col") .setLiteral("literal") .setEventTimestamp(true) .build(); - assertNull("The result should be null.", config); + assertNull(config, "The result should be null."); } @Test - public void testNoSettingNoConfig01() { + void testNoSettingNoConfig01() { final ColumnConfig config = ColumnConfig.newBuilder().setName("col").build(); - assertNull("The result should be null.", config); + assertNull(config, "The result should be null."); } @Test - public void testNoSettingNoConfig02() { + void testNoSettingNoConfig02() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col") .setEventTimestamp(false) .build(); - assertNull("The result should be null.", config); + assertNull(config, "The result should be null."); } @Test - public void testNoSettingNoConfig03() { + void testNoSettingNoConfig03() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col") .setPattern(Strings.EMPTY) @@ -93,25 +93,25 @@ public void testNoSettingNoConfig03() { .setEventTimestamp(false) .build(); - assertNull("The result should be null.", config); + assertNull(config, "The result should be null."); } @Test - public void testDateColumn01() { + void testDateColumn01() { final ColumnConfig config = ColumnConfig.newBuilder().setName("col").setEventTimestamp(true).build(); - assertNotNull("The result should not be null.", config); - assertEquals("The column name is not correct.", "col", config.getColumnName()); - assertNull("The pattern should be null.", config.getLayout()); - assertNull("The literal value should be null.", config.getLiteralValue()); - assertTrue("The timestamp flag should be true.", config.isEventTimestamp()); - assertFalse("The unicode flag should be false.", config.isUnicode()); - assertFalse("The clob flag should be false.", config.isClob()); + assertNotNull(config, "The result should not be null."); + assertEquals("col", config.getColumnName(), "The column name is not correct."); + assertNull(config.getLayout(), "The pattern should be null."); + assertNull(config.getLiteralValue(), "The literal value should be null."); + assertTrue(config.isEventTimestamp(), "The timestamp flag should be true."); + assertFalse(config.isUnicode(), "The unicode flag should be false."); + assertFalse(config.isClob(), "The clob flag should be false."); } @Test - public void testDateColumn02() { + void testDateColumn02() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col2") .setEventTimestamp(true) @@ -119,32 +119,32 @@ public void testDateColumn02() { .setClob(true) .build(); - assertNotNull("The result should not be null.", config); - assertEquals("The column name is not correct.", "col2", config.getColumnName()); - assertNull("The pattern should be null.", config.getLayout()); - assertNull("The literal value should be null.", config.getLiteralValue()); - assertTrue("The timestamp flag should be true.", config.isEventTimestamp()); - assertFalse("The unicode flag should be false.", config.isUnicode()); - assertFalse("The clob flag should be false.", config.isClob()); + assertNotNull(config, "The result should not be null."); + assertEquals("col2", config.getColumnName(), "The column name is not correct."); + assertNull(config.getLayout(), "The pattern should be null."); + assertNull(config.getLiteralValue(), "The literal value should be null."); + assertTrue(config.isEventTimestamp(), "The timestamp flag should be true."); + assertFalse(config.isUnicode(), "The unicode flag should be false."); + assertFalse(config.isClob(), "The clob flag should be false."); } @Test - public void testPatternColumn01() { + void testPatternColumn01() { final ColumnConfig config = ColumnConfig.newBuilder().setName("col").setPattern("%l").build(); - assertNotNull("The result should not be null.", config); - assertEquals("The column name is not correct.", "col", config.getColumnName()); - assertNotNull("The pattern should not be null.", config.getLayout()); - assertEquals("The pattern is not correct.", "%l", config.getLayout().toString()); - assertNull("The literal value should be null.", config.getLiteralValue()); - assertFalse("The timestamp flag should be false.", config.isEventTimestamp()); - assertTrue("The unicode flag should be true.", config.isUnicode()); - assertFalse("The clob flag should be false.", config.isClob()); + assertNotNull(config, "The result should not be null."); + assertEquals("col", config.getColumnName(), "The column name is not correct."); + assertNotNull(config.getLayout(), "The pattern should not be null."); + assertEquals("%l", config.getLayout().toString(), "The pattern is not correct."); + assertNull(config.getLiteralValue(), "The literal value should be null."); + assertFalse(config.isEventTimestamp(), "The timestamp flag should be false."); + assertTrue(config.isUnicode(), "The unicode flag should be true."); + assertFalse(config.isClob(), "The clob flag should be false."); } @Test - public void testPatternColumn02() { + void testPatternColumn02() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col2") .setPattern("%X{id} %level") @@ -154,21 +154,18 @@ public void testPatternColumn02() { .setClob(true) .build(); - assertNotNull("The result should not be null.", config); - assertEquals("The column name is not correct.", "col2", config.getColumnName()); - assertNotNull("The pattern should not be null.", config.getLayout()); - assertEquals( - "The pattern is not correct.", - "%X{id} %level", - config.getLayout().toString()); - assertNull("The literal value should be null.", config.getLiteralValue()); - assertFalse("The timestamp flag should be false.", config.isEventTimestamp()); - assertFalse("The unicode flag should be false.", config.isUnicode()); - assertTrue("The clob flag should be true.", config.isClob()); + assertNotNull(config, "The result should not be null."); + assertEquals("col2", config.getColumnName(), "The column name is not correct."); + assertNotNull(config.getLayout(), "The pattern should not be null."); + assertEquals("%X{id} %level", config.getLayout().toString(), "The pattern is not correct."); + assertNull(config.getLiteralValue(), "The literal value should be null."); + assertFalse(config.isEventTimestamp(), "The timestamp flag should be false."); + assertFalse(config.isUnicode(), "The unicode flag should be false."); + assertTrue(config.isClob(), "The clob flag should be true."); } @Test - public void testPatternColumn03() { + void testPatternColumn03() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col3") .setPattern("%X{id} %level") @@ -178,38 +175,35 @@ public void testPatternColumn03() { .setClob(false) .build(); - assertNotNull("The result should not be null.", config); - assertEquals("The column name is not correct.", "col3", config.getColumnName()); - assertNotNull("The pattern should not be null.", config.getLayout()); - assertEquals( - "The pattern is not correct.", - "%X{id} %level", - config.getLayout().toString()); - assertNull("The literal value should be null.", config.getLiteralValue()); - assertFalse("The timestamp flag should be false.", config.isEventTimestamp()); - assertTrue("The unicode flag should be true.", config.isUnicode()); - assertFalse("The clob flag should be false.", config.isClob()); + assertNotNull(config, "The result should not be null."); + assertEquals("col3", config.getColumnName(), "The column name is not correct."); + assertNotNull(config.getLayout(), "The pattern should not be null."); + assertEquals("%X{id} %level", config.getLayout().toString(), "The pattern is not correct."); + assertNull(config.getLiteralValue(), "The literal value should be null."); + assertFalse(config.isEventTimestamp(), "The timestamp flag should be false."); + assertTrue(config.isUnicode(), "The unicode flag should be true."); + assertFalse(config.isClob(), "The clob flag should be false."); } @Test - public void testLiteralColumn01() { + void testLiteralColumn01() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col") .setLiteral("literalValue01") .build(); - assertNotNull("The result should not be null.", config); - assertEquals("The column name is not correct.", "col", config.getColumnName()); - assertNull("The pattern should be null.", config.getLayout()); - assertNotNull("The literal value should be null.", config.getLiteralValue()); - assertEquals("The literal value is not correct.", "literalValue01", config.getLiteralValue()); - assertFalse("The timestamp flag should be false.", config.isEventTimestamp()); - assertFalse("The unicode flag should be false.", config.isUnicode()); - assertFalse("The clob flag should be false.", config.isClob()); + assertNotNull(config, "The result should not be null."); + assertEquals("col", config.getColumnName(), "The column name is not correct."); + assertNull(config.getLayout(), "The pattern should be null."); + assertNotNull(config.getLiteralValue(), "The literal value should be null."); + assertEquals("literalValue01", config.getLiteralValue(), "The literal value is not correct."); + assertFalse(config.isEventTimestamp(), "The timestamp flag should be false."); + assertFalse(config.isUnicode(), "The unicode flag should be false."); + assertFalse(config.isClob(), "The clob flag should be false."); } @Test - public void testLiteralColumn02() { + void testLiteralColumn02() { final ColumnConfig config = ColumnConfig.newBuilder() .setName("col2") .setLiteral("USER1.MY_SEQUENCE.NEXT") @@ -217,13 +211,13 @@ public void testLiteralColumn02() { .setClob(true) .build(); - assertNotNull("The result should not be null.", config); - assertEquals("The column name is not correct.", "col2", config.getColumnName()); - assertNull("The pattern should be null.", config.getLayout()); - assertNotNull("The literal value should be null.", config.getLiteralValue()); - assertEquals("The literal value is not correct.", "USER1.MY_SEQUENCE.NEXT", config.getLiteralValue()); - assertFalse("The timestamp flag should be false.", config.isEventTimestamp()); - assertFalse("The unicode flag should be false.", config.isUnicode()); - assertFalse("The clob flag should be false.", config.isClob()); + assertNotNull(config, "The result should not be null."); + assertEquals("col2", config.getColumnName(), "The column name is not correct."); + assertNull(config.getLayout(), "The pattern should be null."); + assertNotNull(config.getLiteralValue(), "The literal value should be null."); + assertEquals("USER1.MY_SEQUENCE.NEXT", config.getLiteralValue(), "The literal value is not correct."); + assertFalse(config.isEventTimestamp(), "The timestamp flag should be false."); + assertFalse(config.isUnicode(), "The unicode flag should be false."); + assertFalse(config.isClob(), "The clob flag should be false."); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcAppenderStringSubstitutionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcAppenderStringSubstitutionTest.java index 3578e1a9788..693aa835797 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcAppenderStringSubstitutionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/JdbcAppenderStringSubstitutionTest.java @@ -41,7 +41,7 @@ public static void afterClass() { new LoggerContextRule("org/apache/logging/log4j/core/appender/db/jdbc/log4j2-jdbc-string-substitution.xml"); @Test - public void test() throws Exception { + public void test() { final JdbcAppender appender = rule.getAppender("databaseAppender", JdbcAppender.class); Assert.assertNotNull(appender); final JdbcDatabaseManager manager = appender.getManager(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/JmsAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/JmsAppenderTest.java index ce16f06df14..5507c33075b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/JmsAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/JmsAppenderTest.java @@ -83,12 +83,12 @@ public class JmsAppenderTest { public RuleChain rules = RuleChain.outerRule(jndiRule).around(ctx); @AfterClass - public static void afterClass() throws Exception { + public static void afterClass() { System.clearProperty("log4j2.enableJndiJms"); } @BeforeClass - public static void beforeClass() throws Exception { + public static void beforeClass() { System.setProperty("log4j2.enableJndiJms", "true"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqAppenderTest.java index 57ac558b189..9bd516daa48 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqAppenderTest.java @@ -51,7 +51,7 @@ @Timeout(value = 20, unit = TimeUnit.SECONDS) @UsingStatusListener @LoggerContextSource(value = "JeroMqAppenderTest.xml", timeout = 60) -public class JeroMqAppenderTest { +class JeroMqAppenderTest { private static final Logger LOGGER = StatusLogger.getLogger(); @@ -60,14 +60,14 @@ public class JeroMqAppenderTest { private static final int DEFAULT_TIMEOUT_MS = 5000; @Test - public void testAppenderLifeCycle() throws Exception { + void testAppenderLifeCycle() { // do nothing to make sure the appender starts and stops without // locking up resources. assertNotNull(JeroMqManager.getContext()); } @Test - public void testClientServer(@Named(APPENDER_NAME) final JeroMqAppender appender, final LoggerContext ctx) + void testClientServer(@Named(APPENDER_NAME) final JeroMqAppender appender, final LoggerContext ctx) throws Exception { addLoggingFilter(appender); final Logger logger = ctx.getLogger(getClass()); @@ -106,7 +106,7 @@ public void testClientServer(@Named(APPENDER_NAME) final JeroMqAppender appender } @Test - public void testMultiThreadedServer(@Named(APPENDER_NAME) final JeroMqAppender appender, final LoggerContext ctx) + void testMultiThreadedServer(@Named(APPENDER_NAME) final JeroMqAppender appender, final LoggerContext ctx) throws Exception { addLoggingFilter(appender); final Logger logger = ctx.getLogger(getClass()); @@ -159,7 +159,7 @@ public void testMultiThreadedServer(@Named(APPENDER_NAME) final JeroMqAppender a } @Test - public void testServerOnly(@Named(APPENDER_NAME) final JeroMqAppender appender, final LoggerContext ctx) { + void testServerOnly(@Named(APPENDER_NAME) final JeroMqAppender appender, final LoggerContext ctx) { addLoggingFilter(appender); final Logger logger = ctx.getLogger(getClass()); appender.resetSendRcs(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqTestClient.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqTestClient.java index 5ae48f6c186..c40514e93b9 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqTestClient.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/jeromq/JeroMqTestClient.java @@ -42,7 +42,7 @@ class JeroMqTestClient implements Callable> { } @Override - public List call() throws Exception { + public List call() { try (final ZMQ.Socket subscriber = context.socket(SocketType.SUB)) { LOGGER.info("Starting JeroMqTestClient."); subscriber.connect(endpoint); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderCloseTimeoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderCloseTimeoutTest.java index b150e9f5ec7..3a54a91d0ab 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderCloseTimeoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderCloseTimeoutTest.java @@ -66,7 +66,7 @@ public void close(final long timeout, final TimeUnit timeUnit) { }; @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { KafkaManager.producerFactory = config -> kafka; } @@ -74,12 +74,12 @@ public static void setUpClass() throws Exception { public LoggerContextRule ctx = new LoggerContextRule("KafkaAppenderCloseTimeoutTest.xml"); @Before - public void setUp() throws Exception { + public void setUp() { kafka.clear(); } @Test(timeout = 2000) - public void testClose() throws Exception { + public void testClose() { final Appender appender = ctx.getRequiredAppender("KafkaAppender"); appender.stop(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderTest.java index ac69d2e9445..ef8c24edf00 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaAppenderTest.java @@ -75,7 +75,6 @@ public synchronized Future send(final ProducerRecord kafka; } @@ -110,12 +109,12 @@ public static void setUpClass() throws Exception { public LoggerContextRule ctx = new LoggerContextRule("KafkaAppenderTest.xml"); @Before - public void setUp() throws Exception { + public void setUp() { kafka.clear(); } @Test - public void testAppendWithLayout() throws Exception { + public void testAppendWithLayout() { final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithLayout"); appender.append(createLogEvent()); final List> history = kafka.history(); @@ -128,7 +127,7 @@ public void testAppendWithLayout() throws Exception { } @Test - public void testAppendWithSerializedLayout() throws Exception { + public void testAppendWithSerializedLayout() { final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithSerializedLayout"); final LogEvent logEvent = createLogEvent(); appender.append(logEvent); @@ -144,7 +143,7 @@ public void testAppendWithSerializedLayout() throws Exception { } @Test - public void testAsyncAppend() throws Exception { + public void testAsyncAppend() { final Appender appender = ctx.getRequiredAppender("AsyncKafkaAppender"); appender.append(createLogEvent()); final List> history = kafka.history(); @@ -157,7 +156,7 @@ public void testAsyncAppend() throws Exception { } @Test - public void testAppendWithKey() throws Exception { + public void testAppendWithKey() { final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKey"); final LogEvent logEvent = createLogEvent(); appender.append(logEvent); @@ -173,7 +172,7 @@ public void testAppendWithKey() throws Exception { } @Test - public void testAppendWithKeyLookup() throws Exception { + public void testAppendWithKeyLookup() { final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKeyLookup"); final LogEvent logEvent = createLogEvent(); final Date date = new Date(); @@ -208,7 +207,7 @@ public void testAppendWithRetryCount() { } @Test - public void testAppenderNoEventTimestamp() throws Exception { + public void testAppenderNoEventTimestamp() { final Appender appender = ctx.getRequiredAppender("KafkaAppenderNoEventTimestamp"); final LogEvent logEvent = createLogEvent(); appender.append(logEvent); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManagerProducerThreadLeakTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManagerProducerThreadLeakTest.java index 3982a6e0653..9e4b6b14a79 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManagerProducerThreadLeakTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManagerProducerThreadLeakTest.java @@ -16,12 +16,11 @@ */ package org.apache.logging.log4j.core.appender.mom.kafka; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.test.categories.Appenders; import org.apache.logging.log4j.core.test.junit.LoggerContextSource; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -30,7 +29,7 @@ * * @see LOG4J2-2916 */ -@Category(Appenders.Kafka.class) +@Tag("Appenders.Kafka") @LoggerContextSource("KafkaManagerProducerThreadLeakTest.xml") class KafkaManagerProducerThreadLeakTest { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/nosql/NoSqlAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/nosql/NoSqlAppenderTest.java index 496415f9ca8..c3e33ffaf64 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/nosql/NoSqlAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/nosql/NoSqlAppenderTest.java @@ -16,51 +16,51 @@ */ package org.apache.logging.log4j.core.appender.nosql; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class NoSqlAppenderTest { +@ExtendWith(MockitoExtension.class) +class NoSqlAppenderTest { @Mock private NoSqlProvider provider; @Test - public void testNoProvider() { + void testNoProvider() { final NoSqlAppender appender = NoSqlAppender.createAppender("myName01", null, null, null, null); - assertNull("The appender should be null.", appender); + assertNull(appender, "The appender should be null."); } @Test - public void testProvider() { + void testProvider() { final NoSqlAppender appender = NoSqlAppender.createAppender("myName01", null, null, null, provider); - assertNotNull("The appender should not be null.", appender); + assertNotNull(appender, "The appender should not be null."); assertEquals( - "The toString value is not correct.", "myName01{ manager=noSqlManager{ description=myName01, bufferSize=0, provider=" + provider + " } }", - appender.toString()); + appender.toString(), + "The toString value is not correct."); appender.stop(); } @Test - public void testProviderBuffer() { + void testProviderBuffer() { final NoSqlAppender appender = NoSqlAppender.createAppender("anotherName02", null, null, "25", provider); - assertNotNull("The appender should not be null.", appender); + assertNotNull(appender, "The appender should not be null."); assertEquals( - "The toString value is not correct.", "anotherName02{ manager=noSqlManager{ description=anotherName02, bufferSize=25, provider=" + provider + " } }", - appender.toString()); + appender.toString(), + "The toString value is not correct."); appender.stop(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java index 89c4e2eb448..69f67c82d91 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/LoggerNameLevelRewritePolicyTest.java @@ -30,10 +30,10 @@ * * @since 2.4 */ -public class LoggerNameLevelRewritePolicyTest { +class LoggerNameLevelRewritePolicyTest { @Test - public void testUpdate() { + void testUpdate() { final KeyValuePair[] rewrite = new KeyValuePair[] {new KeyValuePair("INFO", "DEBUG"), new KeyValuePair("WARN", "INFO")}; final String loggerNameRewrite = "com.foo.bar"; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/MapRewritePolicyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/MapRewritePolicyTest.java index cf59e7ad3d4..5401b8317e0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/MapRewritePolicyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/MapRewritePolicyTest.java @@ -40,14 +40,14 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class MapRewritePolicyTest { +class MapRewritePolicyTest { private static final StringMap stringMap = ContextDataFactory.createContextData(); private static Map map = new HashMap<>(); private static KeyValuePair[] rewrite; private static LogEvent logEvent0, logEvent1, logEvent2, logEvent3; @BeforeAll - public static void setupClass() { + static void setupClass() { stringMap.putValue("test1", "one"); stringMap.putValue("test2", "two"); map = stringMap.toMap(); @@ -91,7 +91,7 @@ public static void setupClass() { } @Test - public void addTest() { + void addTest() { final MapRewritePolicy addPolicy = MapRewritePolicy.createPolicy("Add", rewrite); LogEvent rewritten = addPolicy.rewrite(logEvent0); compareLogEvents(logEvent0, rewritten); @@ -111,7 +111,7 @@ public void addTest() { } @Test - public void updateTest() { + void updateTest() { final MapRewritePolicy updatePolicy = MapRewritePolicy.createPolicy("Update", rewrite); LogEvent rewritten = updatePolicy.rewrite(logEvent0); compareLogEvents(logEvent0, rewritten); @@ -131,7 +131,7 @@ public void updateTest() { } @Test - public void defaultIsAdd() { + void defaultIsAdd() { final MapRewritePolicy addPolicy = MapRewritePolicy.createPolicy(null, rewrite); LogEvent rewritten = addPolicy.rewrite(logEvent0); compareLogEvents(logEvent0, rewritten); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/RewriteAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/RewriteAppenderTest.java index 16ce2793a9f..226b1952c3b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/RewriteAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rewrite/RewriteAppenderTest.java @@ -41,7 +41,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-rewrite.xml") -public class RewriteAppenderTest { +class RewriteAppenderTest { private final ListAppender app; private final ListAppender app2; @@ -51,7 +51,7 @@ public RewriteAppenderTest(@Named("List") final ListAppender app, @Named("List2" } @Test - public void rewriteTest() { + void rewriteTest() { final StructuredDataMessage msg = new StructuredDataMessage("Test", "This is a test", "Service"); msg.put("Key1", "Value1"); msg.put("Key2", "Value2"); @@ -70,19 +70,19 @@ public void rewriteTest() { } @Test - public void testProperties(final LoggerContext context) { + void testProperties(final LoggerContext context) { final Logger logger = context.getLogger(RewriteAppenderTest.class); logger.debug("Test properties rewrite"); final List list = app2.getMessages(); assertThat(list, hasSize(1)); assertThat(list.get(0), not(containsString("{user.dir}"))); assertNotNull(list, "No events generated"); - assertEquals(list.size(), 1, "Incorrect number of events. Expected 1, got " + list.size()); + assertEquals(1, list.size(), "Incorrect number of events. Expected 1, got " + list.size()); assertFalse(list.get(0).contains("{user."), "Did not resolve user name"); } @Test - public void testFilter(final LoggerContext context) { + void testFilter(final LoggerContext context) { StructuredDataMessage msg = new StructuredDataMessage("Test", "This is a test", "Service"); msg.put("Key1", "Value2"); msg.put("Key2", "Value1"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/CronTriggeringPolicyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/CronTriggeringPolicyTest.java index d967c4cdeaa..1b6fc7edd80 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/CronTriggeringPolicyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/CronTriggeringPolicyTest.java @@ -26,7 +26,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class CronTriggeringPolicyTest { +class CronTriggeringPolicyTest { private static final String CRON_EXPRESSION = "0 0 0 * * ?"; @@ -37,7 +37,7 @@ public class CronTriggeringPolicyTest { // public CleanFiles cleanFiles = new CleanFiles("testcmd1.log", "testcmd2.log", "testcmd3.log"); @BeforeEach - public void before() { + void before() { configuration = new NullConfiguration(); } @@ -68,7 +68,7 @@ private void testBuilder() { * true. */ @Test - public void testBuilderOnce() { + void testBuilderOnce() { testBuilder(); } @@ -76,7 +76,7 @@ public void testBuilderOnce() { * Tests LOG4J2-1740 Add CronTriggeringPolicy programmatically leads to NPE */ @Test - public void testLoggerContextAndBuilder() { + void testLoggerContextAndBuilder() { Configurator.initialize(configuration); testBuilder(); } @@ -85,7 +85,7 @@ public void testLoggerContextAndBuilder() { * Tests LOG4J2-1740 Add CronTriggeringPolicy programmatically leads to NPE */ @Test - public void testRollingRandomAccessFileAppender() { + void testRollingRandomAccessFileAppender() { // @formatter:off RollingRandomAccessFileAppender.newBuilder() .setName("test2") @@ -103,7 +103,7 @@ public void testRollingRandomAccessFileAppender() { * true. */ @Test - public void testBuilderSequence() { + void testBuilderSequence() { testBuilder(); testBuilder(); } @@ -139,12 +139,12 @@ private void testFactoryMethod() { * true. */ @Test - public void testFactoryMethodOnce() { + void testFactoryMethodOnce() { testFactoryMethod(); } @Test - public void testFactoryMethodSequence() { + void testFactoryMethodSequence() { testFactoryMethod(); testFactoryMethod(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/EligibleFilesTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/EligibleFilesTest.java index ec3600d9e6a..e0b7c487f2e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/EligibleFilesTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/EligibleFilesTest.java @@ -17,7 +17,7 @@ package org.apache.logging.log4j.core.appender.rolling; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.nio.file.Path; import java.util.Map; @@ -27,24 +27,24 @@ /** * Test getEligibleFiles method. */ -public class EligibleFilesTest { +class EligibleFilesTest { @Test - public void runTest() throws Exception { + void runTest() { final String path = "target/test-classes/rolloverPath/log4j.txt.20170112_09-" + NotANumber.VALUE + ".gz"; final TestRolloverStrategy strategy = new TestRolloverStrategy(); final Map files = strategy.findFilesInPath(path); - assertTrue(files.size() > 0, "No files found"); + assertFalse(files.isEmpty(), "No files found"); assertEquals(30, files.size(), "Incorrect number of files found. Should be 30, was " + files.size()); } @Test - public void runTestWithPlusCharacter() throws Exception { + void runTestWithPlusCharacter() { final String path = "target/test-classes/rolloverPath/log4j.20211028T194500+0200." + NotANumber.VALUE + ".log.gz"; final TestRolloverStrategy strategy = new TestRolloverStrategy(); final Map files = strategy.findFilesWithPlusInPath(path); - assertTrue(files.size() > 0, "No files found"); + assertFalse(files.isEmpty(), "No files found"); assertEquals(30, files.size(), "Incorrect number of files found. Should be 30, was " + files.size()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/FileSizeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/FileSizeTest.java index beca4274495..9d48e6492cb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/FileSizeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/FileSizeTest.java @@ -24,7 +24,7 @@ /** * Tests {@link FileSize}. */ -public class FileSizeTest { +class FileSizeTest { @ParameterizedTest(name = "[{index}] \"{0}\" -> {1}") @CsvSource( diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/OnStartupTriggeringPolicyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/OnStartupTriggeringPolicyTest.java index ef769ff5841..74820472375 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/OnStartupTriggeringPolicyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/OnStartupTriggeringPolicyTest.java @@ -42,7 +42,7 @@ /** * Tests {@link OnStartupTriggeringPolicy}. */ -public class OnStartupTriggeringPolicyTest { +class OnStartupTriggeringPolicyTest { private static final String TARGET_PATTERN = "/test1-%d{MM-dd-yyyy}-%i.log"; private static final String TEST_DATA = "Hello world!"; @@ -52,7 +52,7 @@ public class OnStartupTriggeringPolicyTest { Path tempDir; @Test - public void testPolicy() throws Exception { + void testPolicy() throws Exception { final Configuration configuration = new DefaultConfiguration(); final Path target = tempDir.resolve("testfile"); final long timeStamp = Instant.now().minus(Duration.ofDays(1)).toEpochMilli(); @@ -114,9 +114,9 @@ public void testPolicy() throws Exception { try (final Stream contents = Files.list(tempDir)) { files = contents.map(Path::toString).collect(Collectors.joining(", ", "[", "]")); } - assertTrue(Files.exists(target), target.toString() + ", files = " + files); + assertTrue(Files.exists(target), target + ", files = " + files); assertEquals(0, Files.size(target), target.toString()); - assertTrue(Files.exists(rolled), "Missing: " + rolled.toString() + ", files on disk = " + files); + assertTrue(Files.exists(rolled), "Missing: " + rolled + ", files on disk = " + files); assertEquals(size, Files.size(rolled), rolled.toString()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessorTest.java index ee333d6fe42..36341b77474 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/PatternProcessorTest.java @@ -36,7 +36,7 @@ /** * Tests the PatternProcessor class. */ -public class PatternProcessorTest { +class PatternProcessorTest { private static Instant parseLocalDateTime(final String text) { return LocalDateTime.parse(text).atZone(ZoneId.systemDefault()).toInstant(); @@ -44,7 +44,7 @@ private static Instant parseLocalDateTime(final String text) { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testDontInterpretBackslashAsEscape() { + void testDontInterpretBackslashAsEscape() { final PatternProcessor pp = new PatternProcessor("c:\\test\\new/app-%d{HH-mm-ss}.log"); final Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 16); @@ -58,7 +58,7 @@ public void testDontInterpretBackslashAsEscape() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeHourlyReturnsFirstMinuteOfNextHour() { + void testGetNextTimeHourlyReturnsFirstMinuteOfNextHour() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd-HH}.log.gz"); final Instant initial = parseLocalDateTime("2014-03-04T10:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -69,7 +69,7 @@ public void testGetNextTimeHourlyReturnsFirstMinuteOfNextHour() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeHourlyReturnsFirstMinuteOfNextHour2() { + void testGetNextTimeHourlyReturnsFirstMinuteOfNextHour2() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd-HH}.log.gz"); final Instant initial = parseLocalDateTime("2014-03-04T23:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -80,7 +80,7 @@ public void testGetNextTimeHourlyReturnsFirstMinuteOfNextHour2() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeHourlyReturnsFirstMinuteOfNextHourDstStart() { + void testGetNextTimeHourlyReturnsFirstMinuteOfNextHourDstStart() { // America/Chicago 2014 - DST start - Mar 9 02:00 // during winter GMT-6 // during summer GMT-5 @@ -96,7 +96,7 @@ public void testGetNextTimeHourlyReturnsFirstMinuteOfNextHourDstStart() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeHourlyReturnsFirstMinuteOfHourAfterNextHourDstEnd() { + void testGetNextTimeHourlyReturnsFirstMinuteOfHourAfterNextHourDstEnd() { // America/Chicago 2014 - DST end - Nov 2 02:00 // during summer GMT-5 // during winter GMT-6 @@ -113,7 +113,7 @@ public void testGetNextTimeHourlyReturnsFirstMinuteOfHourAfterNextHourDstEnd() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeHourlyReturnsFirstMinuteOfNextYear() { + void testGetNextTimeHourlyReturnsFirstMinuteOfNextYear() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd-HH}.log.gz"); final Instant initial = parseLocalDateTime("2015-12-31T23:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -124,7 +124,7 @@ public void testGetNextTimeHourlyReturnsFirstMinuteOfNextYear() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeMillisecondlyReturnsNextMillisec() { + void testGetNextTimeMillisecondlyReturnsNextMillisec() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd-HH-mm-ss.SSS}.log.gz"); final Instant initial = parseLocalDateTime("2014-03-04T10:31:53.123"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -135,7 +135,7 @@ public void testGetNextTimeMillisecondlyReturnsNextMillisec() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeMinutelyReturnsFirstSecondOfNextMinute() { + void testGetNextTimeMinutelyReturnsFirstSecondOfNextMinute() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd-HH-mm}.log.gz"); final Instant initial = parseLocalDateTime("2014-03-04T10:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -146,7 +146,7 @@ public void testGetNextTimeMinutelyReturnsFirstSecondOfNextMinute() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth() { + void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM}.log.gz"); final Instant initial = parseLocalDateTime("2014-10-15T10:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -157,7 +157,7 @@ public void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth2() { + void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth2() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM}.log.gz"); final Instant initial = parseLocalDateTime("2014-01-31T10:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -169,7 +169,7 @@ public void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth2() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth3() { + void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth3() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM}.log.gz"); final Instant initial = parseLocalDateTime("2014-12-31T10:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -181,7 +181,7 @@ public void testGetNextTimeMonthlyReturnsFirstDayOfNextMonth3() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeMonthlyReturnsFirstDayOfNextYear() { + void testGetNextTimeMonthlyReturnsFirstDayOfNextYear() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM}.log.gz"); final Instant initial = parseLocalDateTime("2015-12-28T00:00:00"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -193,7 +193,7 @@ public void testGetNextTimeMonthlyReturnsFirstDayOfNextYear() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeSecondlyReturnsFirstMillisecOfNextSecond() { + void testGetNextTimeSecondlyReturnsFirstMillisecOfNextSecond() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd-HH-mm-ss}.log.gz"); final Instant initial = parseLocalDateTime("2014-03-04T10:31:53.123"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -204,7 +204,7 @@ public void testGetNextTimeSecondlyReturnsFirstMillisecOfNextSecond() { @Test @ResourceLock(Resources.LOCALE) - public void testGetNextTimeWeeklyReturnsFirstDayOfNextWeek_FRANCE() { + void testGetNextTimeWeeklyReturnsFirstDayOfNextWeek_FRANCE() { final Locale old = Locale.getDefault(); Locale.setDefault(Locale.FRANCE); // force 1st day of the week to be Monday @@ -222,7 +222,7 @@ public void testGetNextTimeWeeklyReturnsFirstDayOfNextWeek_FRANCE() { @Test @ResourceLock(Resources.LOCALE) - public void testGetNextTimeWeeklyReturnsFirstDayOfNextWeek_US() { + void testGetNextTimeWeeklyReturnsFirstDayOfNextWeek_US() { final Locale old = Locale.getDefault(); Locale.setDefault(Locale.US); // force 1st day of the week to be Sunday @@ -243,7 +243,7 @@ public void testGetNextTimeWeeklyReturnsFirstDayOfNextWeek_US() { */ @Test @ResourceLock(Resources.LOCALE) - public void testGetNextTimeWeeklyReturnsFirstWeekInYear_US() { + void testGetNextTimeWeeklyReturnsFirstWeekInYear_US() { final Locale old = Locale.getDefault(); Locale.setDefault(Locale.US); // force 1st day of the week to be Sunday try { @@ -260,7 +260,7 @@ public void testGetNextTimeWeeklyReturnsFirstWeekInYear_US() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeDailyReturnsFirstHourOfNextDay() { + void testGetNextTimeDailyReturnsFirstHourOfNextDay() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd}.log.gz"); final Instant initial = parseLocalDateTime("2014-03-04T02:31:59"); final long actual = pp.getNextTime(initial.toEpochMilli(), 1, false); @@ -271,7 +271,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDay() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption1() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption1() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd}{GMT-6}.log.gz"); final Instant initial = OffsetDateTime.parse("2014-03-04T02:31:59-06:00").toInstant(); @@ -285,7 +285,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption1 @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) @ResourceLock(value = Resources.TIME_ZONE) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption2() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption2() { final TimeZone old = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT+10")); // default is ignored if pattern contains timezone try { @@ -305,7 +305,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption2 @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) @ResourceLock(value = Resources.TIME_ZONE) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption3() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption3() { final TimeZone old = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT-10")); // default is ignored if pattern contains timezone try { @@ -324,7 +324,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDayHonoringTimeZoneOption3 @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstJan() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayDstJan() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd}{America/Chicago}.log.gz"); final Instant initial = OffsetDateTime.parse("2014-01-04T00:31:59-06:00").toInstant(); @@ -337,7 +337,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstJan() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstJun() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayDstJun() { final PatternProcessor pp = new PatternProcessor("logs/app-%d{yyyy-MM-dd}{America/Chicago}.log.gz"); final Instant initial = OffsetDateTime.parse("2014-06-04T00:31:59-05:00").toInstant(); @@ -350,7 +350,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstJun() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstStart() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayDstStart() { // America/Chicago 2014 - DST start - Mar 9 02:00 // during winter GMT-6 // during summer GMT-5 @@ -366,7 +366,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstStart() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstEnd() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayDstEnd() { // America/Chicago 2014 - DST end - Nov 2 02:00 // during summer GMT-5 // during winter GMT-6 @@ -383,7 +383,7 @@ public void testGetNextTimeDailyReturnsFirstHourOfNextDayDstEnd() { @Test @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) @ResourceLock(value = Resources.TIME_ZONE) - public void testGetNextTimeDailyReturnsFirstHourOfNextDayInGmtIfZoneIsInvalid() { + void testGetNextTimeDailyReturnsFirstHourOfNextDayInGmtIfZoneIsInvalid() { final TimeZone old = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT-10")); // default is ignored even if timezone option invalid try { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RandomRollingAppenderOnStartupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RandomRollingAppenderOnStartupTest.java index 324a9af1258..6ed7c13e945 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RandomRollingAppenderOnStartupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RandomRollingAppenderOnStartupTest.java @@ -16,7 +16,7 @@ */ package org.apache.logging.log4j.core.appender.rolling; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; import java.nio.file.DirectoryStream; import java.nio.file.Files; @@ -61,7 +61,7 @@ public RandomRollingAppenderOnStartupTest(final String configFile) { } @Before - public void setUp() throws Exception { + public void setUp() { this.logger = this.loggerContextRule.getLogger(RandomRollingAppenderOnStartupTest.class.getName()); } @@ -86,9 +86,10 @@ public static void afterClass() throws Exception { size = Files.size(path); } else { final long fileSize = Files.size(path); - assertTrue( + assertEquals( "Expected size: " + size + " Size of " + path.getFileName() + ": " + fileSize, - size == fileSize); + size, + fileSize); } Files.delete(path); } @@ -97,7 +98,7 @@ public static void afterClass() throws Exception { } @Test - public void testAppender() throws Exception { + public void testAppender() { for (int i = 0; i < 100; ++i) { logger.debug("This is test message number " + i); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCountTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCountTest.java index 5294953a18a..e8bd5a9e8aa 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCountTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCountTest.java @@ -57,7 +57,7 @@ public RollingAppenderCountTest() { } @Before - public void setUp() throws Exception { + public void setUp() { this.logger = this.loggerContextRule.getLogger("LogTest"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeLookupTest.java index c878ec3520c..509cf831227 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeLookupTest.java @@ -18,11 +18,11 @@ import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; @@ -53,7 +53,7 @@ public class RollingAppenderCronAndSizeLookupTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderCronAndSizeLookupTest.class.getName()); } @@ -79,7 +79,7 @@ public void testAppender() throws Exception { String previous = ""; for (final File file : files) { final String actual = file.getName(); - if (previous.length() == 0) { + if (previous.isEmpty()) { previous = actual; } else { assertNotSame("File names snould not be equal", previous, actual); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeTest.java index f40daa0b8aa..973ae70a85f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronAndSizeTest.java @@ -18,11 +18,11 @@ import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; @@ -53,7 +53,7 @@ public class RollingAppenderCronAndSizeTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderCronAndSizeTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnStartupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnStartupTest.java index 3f3cd56eb9c..822d756034e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnStartupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnStartupTest.java @@ -16,9 +16,9 @@ */ package org.apache.logging.log4j.core.appender.rolling; -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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileOutputStream; @@ -31,14 +31,14 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configurator; -import org.junit.Test; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * */ -public class RollingAppenderCronOnStartupTest { +class RollingAppenderCronOnStartupTest { private static final String CONFIG = "log4j-rolling-cron-onStartup.xml"; private static final String DIR = "target/rolling-cron-onStartup"; @@ -48,7 +48,7 @@ public class RollingAppenderCronOnStartupTest { private LoggerContext context; @AfterAll - public static void after() { + static void after() { final File dir = new File(DIR); if (dir.exists()) { cleanDir(dir); @@ -57,14 +57,14 @@ public static void after() { } @AfterEach - public void afterEach() { + void afterEach() { if (context != null) { context.stop(); } } @Test - public void testAppender() throws Exception { + void testAppender() throws Exception { final File dir = new File(DIR); if (dir.exists()) { cleanDir(dir); @@ -80,18 +80,18 @@ public void testAppender() throws Exception { ps = new PrintStream(new FileOutputStream(rolled)); ps.println("This is a line 1"); ps.close(); - assertTrue("Log file does not exist", file.exists()); - assertTrue("Log file does not exist", rolled.exists()); + assertTrue(file.exists(), "Log file does not exist"); + assertTrue(rolled.exists(), "Log file does not exist"); final LoggerContext lc = Configurator.initialize("Test", CONFIG); final Logger logger = lc.getLogger(RollingAppenderCronOnStartupTest.class); logger.info("This is line 3"); final File[] files = dir.listFiles(); - assertNotNull("No files", files); - assertEquals("Unexpected number of files. Expected 2 but found " + files.length, 2, files.length); + assertNotNull(files, "No files"); + assertEquals(2, files.length, "Unexpected number of files. Expected 2 but found " + files.length); List lines = Files.readAllLines(file.toPath()); - assertEquals("Unexpected number of lines. Expected 2: Actual: " + lines.size(), 2, lines.size()); + assertEquals(2, lines.size(), "Unexpected number of lines. Expected 2: Actual: " + lines.size()); lines = Files.readAllLines(rolled.toPath()); - assertEquals("Unexpected number of lines. Expected 1: Actual: " + lines.size(), 1, lines.size()); + assertEquals(1, lines.size(), "Unexpected number of lines. Expected 1: Actual: " + lines.size()); } private static void cleanDir(final File dir) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java index 68d3a5987bb..bab06818acc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertTrue; import java.io.File; +import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; @@ -60,14 +61,16 @@ public class RollingAppenderCronOnceADayTest { @BeforeClass public static void beforeClass() throws Exception { final Path src = FileSystems.getDefault().getPath(TARGET_TEST_CLASSES, CONFIG); - String content = new String(Files.readAllBytes(src), UTF_8); + String content = new String(Files.readAllBytes(src), StandardCharsets.UTF_8); final Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, CRON_DELAY); remainingTime = cal.getTimeInMillis() - System.currentTimeMillis(); cronExpression = String.format( "%d %d %d * * ?", cal.get(Calendar.SECOND), cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY)); content = content.replace("@CRON_EXPR@", cronExpression); - Files.write(FileSystems.getDefault().getPath(TARGET_TEST_CLASSES, CONFIG_TARGET), content.getBytes(UTF_8)); + Files.write( + FileSystems.getDefault().getPath(TARGET_TEST_CLASSES, CONFIG_TARGET), + content.getBytes(StandardCharsets.UTF_8)); StatusLogger.getLogger().debug("Cron expression will be " + cronExpression + " in " + remainingTime + "ms"); } @@ -84,7 +87,7 @@ public void testAppender() throws Exception { assertTrue("Log file does not exist", file.exists()); logger.debug("This is test message number 1, waiting for rolling"); - final RollingFileAppender app = (RollingFileAppender) + final RollingFileAppender app = loggerContextRule.getLoggerContext().getConfiguration().getAppender("RollingFile"); final TriggeringPolicy policy = app.getManager().getTriggeringPolicy(); assertNotNull("No triggering policy", policy); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronTest.java index 8f3d4c95364..0130de1e481 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronTest.java @@ -20,6 +20,7 @@ import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -94,12 +95,12 @@ public void testAppender() throws Exception { logger.debug("Adding new event {}", i); } Thread.sleep(1000); - final RollingFileAppender app = (RollingFileAppender) + final RollingFileAppender app = loggerContextRule.getLoggerContext().getConfiguration().getAppender("RollingFile"); final TriggeringPolicy policy = app.getManager().getTriggeringPolicy(); assertNotNull("No triggering policy", policy); assertTrue("Incorrect policy type", policy instanceof CronTriggeringPolicy); final CronExpression expression = ((CronTriggeringPolicy) policy).getCronExpression(); - assertTrue("Incorrect triggering policy", expression.getCronExpression().equals("* * * ? * *")); + assertEquals("Incorrect triggering policy", "* * * ? * *", expression.getCronExpression()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDeleteScriptTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDeleteScriptTest.java index 82cd6152a65..c65c2114b30 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDeleteScriptTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDeleteScriptTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core.appender.rolling; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; @@ -70,7 +71,7 @@ public void testAppender() throws Exception { assertTrue(file.getName() + " ends with '.log'", file.getName().endsWith(".log")); final String strIndex = file.getName().substring(5, file.getName().indexOf('.')); final int index = Integers.parseInt(strIndex); - assertTrue(file + " should have odd index", index % 2 == 1); + assertEquals(file + " should have odd index", 1, index % 2); } } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWrite1906Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWrite1906Test.java index 22e76e9615f..dab76cab14a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWrite1906Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWrite1906Test.java @@ -18,17 +18,16 @@ import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; -import java.io.IOException; import java.util.List; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; @@ -60,12 +59,12 @@ public class RollingAppenderDirectWrite1906Test { private Logger logger; @BeforeClass - public static void setupClass() throws Exception { + public static void setupClass() { StatusLogger.getLogger().registerListener(new NoopStatusListener()); } @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderDirectWrite1906Test.class.getName()); } @@ -124,6 +123,6 @@ public Level getStatusLevel() { } @Override - public void close() throws IOException {} + public void close() {} } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteStartupSizeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteStartupSizeTest.java index 92562cf4182..47ab9404efd 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteStartupSizeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteStartupSizeTest.java @@ -59,7 +59,7 @@ public static void beforeClass() throws Exception { } @Test - public void testRollingFileAppenderWithReconfigure() throws Exception { + public void testRollingFileAppenderWithReconfigure() { final RollingFileAppender rfAppender = loggerContextRule.getRequiredAppender("RollingFile", RollingFileAppender.class); final RollingFileManager manager = rfAppender.getManager(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTempCompressedFilePatternTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTempCompressedFilePatternTest.java index c092b2834fe..087fb7aefa4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTempCompressedFilePatternTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTempCompressedFilePatternTest.java @@ -40,7 +40,7 @@ */ @UsingStatusListener @DisabledOnOs(value = OS.MAC, disabledReason = "FileWatcher is not fast enough on macOS for this test") -public class RollingAppenderDirectWriteTempCompressedFilePatternTest { +class RollingAppenderDirectWriteTempCompressedFilePatternTest { private final String PATTERN = "test-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d+\\.log\\.gz"; private final Pattern FILE_PATTERN = Pattern.compile(PATTERN); @@ -51,7 +51,7 @@ public class RollingAppenderDirectWriteTempCompressedFilePatternTest { @Test @LoggerContextSource - public void testAppender(final LoggerContext ctx) throws Exception { + void testAppender(final LoggerContext ctx) throws Exception { final Logger logger = ctx.getLogger(getClass()); try (final WatchService watcher = FileSystems.getDefault().newWatchService()) { WatchKey key = loggingPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTest.java index 4a34ca917c6..f28b6268cb8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteTest.java @@ -36,7 +36,7 @@ import org.junit.jupiter.api.Test; @UsingStatusListener -public class RollingAppenderDirectWriteTest { +class RollingAppenderDirectWriteTest { private final Pattern FILE_PATTERN = Pattern.compile("test-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d+\\.log(\\.gz)?"); private final Pattern LINE_PATTERN = Pattern.compile("This is test message number \\d+\\."); @@ -46,7 +46,7 @@ public class RollingAppenderDirectWriteTest { @Test @LoggerContextSource - public void testAppender(final LoggerContext ctx) throws Exception { + void testAppender(final LoggerContext ctx) throws Exception { final Logger logger = ctx.getLogger(getClass()); final int count = 100; for (int i = 0; i < count; ++i) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithFilenameTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithFilenameTest.java index c445e747f48..530c65c1fbd 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithFilenameTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithFilenameTest.java @@ -44,12 +44,12 @@ public class RollingAppenderDirectWriteWithFilenameTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderDirectWriteWithFilenameTest.class.getName()); } @Test - public void testAppender() throws Exception { + public void testAppender() { final File dir = new File(DIR); assertFalse("Directory created", dir.exists()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithHtmlLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithHtmlLayoutTest.java index 598aa9dbd0f..887bee97e59 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithHtmlLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithHtmlLayoutTest.java @@ -18,11 +18,11 @@ import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithReconfigureTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithReconfigureTest.java index 61af172b7ab..f27ca883d3c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithReconfigureTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderDirectWriteWithReconfigureTest.java @@ -16,10 +16,10 @@ */ package org.apache.logging.log4j.core.appender.rolling; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; @@ -53,7 +53,7 @@ public class RollingAppenderDirectWriteWithReconfigureTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderDirectWriteWithReconfigureTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderNoUnconditionalDeleteTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderNoUnconditionalDeleteTest.java index 8070312323b..803a898c20e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderNoUnconditionalDeleteTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderNoUnconditionalDeleteTest.java @@ -64,7 +64,7 @@ public RollingAppenderNoUnconditionalDeleteTest(final String configFile, final S } @Before - public void setUp() throws Exception { + public void setUp() { this.logger = this.loggerContextRule.getLogger(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartup2Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartup2Test.java index 5158cb912f6..7dba6fcfddf 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartup2Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartup2Test.java @@ -16,11 +16,13 @@ */ package org.apache.logging.log4j.core.appender.rolling; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; @@ -33,15 +35,14 @@ import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.DefaultConfiguration; import org.apache.logging.log4j.core.util.datetime.FastDateFormat; -import org.junit.AfterClass; -import org.junit.Assert; -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.Test; /** * */ -public class RollingAppenderOnStartup2Test { +class RollingAppenderOnStartup2Test { private static final String DIR = "target/rollOnStartup"; private static final String TARGET_FILE = DIR + "/orchestrator.log"; @@ -50,8 +51,8 @@ public class RollingAppenderOnStartup2Test { private static final String ROLLED_FILE_SUFFIX = "-1.log.gz"; private static final String TEST_DATA = "Hello world!"; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeAll + static void beforeClass() throws Exception { if (Files.exists(Paths.get("target/rollOnStartup"))) { try (final DirectoryStream directoryStream = Files.newDirectoryStream(Paths.get(DIR))) { for (final Path path : directoryStream) { @@ -64,14 +65,14 @@ public static void beforeClass() throws Exception { // System.setProperty("log4j2.StatusLogger.level", "trace"); final Configuration configuration = new DefaultConfiguration(); final Path target = Paths.get(TARGET_FILE); - Assert.assertFalse(Files.exists(target)); + assertFalse(Files.exists(target)); target.toFile().getParentFile().mkdirs(); final long timeStamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24); final String expectedDate = formatter.format(timeStamp); final String rolledFileName = ROLLED_FILE_PREFIX + expectedDate + ROLLED_FILE_SUFFIX; final Path rolled = Paths.get(rolledFileName); final long copied; - try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes("UTF-8"))) { + try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes(StandardCharsets.UTF_8))) { copied = Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING); } final long size = Files.size(target); @@ -83,8 +84,8 @@ public static void beforeClass() throws Exception { System.setProperty("log4j.configurationFile", "log4j-rollOnStartup.json"); } - @AfterClass - public static void afterClass() throws Exception { + @AfterAll + static void afterClass() { final long size = 0; /* try (DirectoryStream directoryStream = Files.newDirectoryStream(Paths.get(DIR))) { for (final Path path : directoryStream) { @@ -102,7 +103,7 @@ public static void afterClass() throws Exception { } @Test - public void testAppender() throws Exception { + void testAppender() { final Logger logger = LogManager.getLogger(RollingAppenderOnStartup2Test.class); for (int i = 0; i < 10; ++i) { logger.debug("This is test message number " + i); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupDirectTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupDirectTest.java index ea5d42dde8e..aa7e4a51063 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupDirectTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupDirectTest.java @@ -16,8 +16,9 @@ */ package org.apache.logging.log4j.core.appender.rolling; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.nio.file.DirectoryStream; @@ -35,14 +36,14 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configurator; -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.Test; /** * */ -public class RollingAppenderOnStartupDirectTest { +class RollingAppenderOnStartupDirectTest { private static final String SOURCE = "src/test/resources/__files"; private static final String DIR = "target/onStartup"; @@ -54,8 +55,8 @@ public class RollingAppenderOnStartupDirectTest { private static LoggerContext loggerContext; - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeAll + static void beforeClass() throws Exception { if (Files.exists(Paths.get("target/onStartup"))) { try (final DirectoryStream directoryStream = Files.newDirectoryStream(Paths.get(DIR))) { for (final Path path : directoryStream) { @@ -73,7 +74,7 @@ public static void beforeClass() throws Exception { } @Test - public void performTest() throws Exception { + void performTest() throws Exception { loggerContext = Configurator.initialize("Test", CONFIG); final Logger logger = loggerContext.getLogger(RollingAppenderOnStartupDirectTest.class); for (int i = 3; i < 10; ++i) { @@ -85,18 +86,19 @@ public void performTest() throws Exception { ++fileCount; if (path.toFile().getName().startsWith(ROLLED)) { final List lines = Files.readAllLines(path); - assertTrue("No messages in " + path.toFile().getName(), lines.size() > 0); + assertFalse( + lines.isEmpty(), "No messages in " + path.toFile().getName()); assertTrue( - "Missing message for " + path.toFile().getName(), - lines.get(0).startsWith(PREFIX)); + lines.get(0).startsWith(PREFIX), + "Missing message for " + path.toFile().getName()); } } } - assertEquals("File did not roll", 2, fileCount); + assertEquals(2, fileCount, "File did not roll"); } - @AfterClass - public static void afterClass() throws Exception { + @AfterAll + static void afterClass() throws Exception { Configurator.shutdown(loggerContext); try (final DirectoryStream directoryStream = Files.newDirectoryStream(Paths.get(DIR))) { for (final Path path : directoryStream) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupTest.java index 3e419755c8c..a65513050f0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderOnStartupTest.java @@ -16,7 +16,8 @@ */ package org.apache.logging.log4j.core.appender.rolling; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.nio.file.DirectoryStream; @@ -38,7 +39,7 @@ import org.junit.jupiter.api.Test; @UsingStatusListener -public class RollingAppenderOnStartupTest { +class RollingAppenderOnStartupTest { private static final String SOURCE = "src/test/resources/__files"; private static final String FILENAME = "onStartup.log"; @@ -49,7 +50,7 @@ public class RollingAppenderOnStartupTest { private static Path loggingPath; @BeforeAll - public static void setup() throws Exception { + static void setup() throws Exception { final Path target = loggingPath.resolve(FILENAME); Files.copy(Paths.get(SOURCE, FILENAME), target, StandardCopyOption.REPLACE_EXISTING); final FileTime newTime = FileTime.from(Instant.now().minus(1, ChronoUnit.DAYS)); @@ -70,7 +71,7 @@ public static void setup() throws Exception { @Test @LoggerContextSource - public void performTest(final LoggerContext loggerContext) throws Exception { + void performTest(final LoggerContext loggerContext) throws Exception { boolean rolled = false; final Logger logger = loggerContext.getLogger(RollingAppenderOnStartupTest.class); for (int i = 3; i < 10; ++i) { @@ -81,13 +82,14 @@ public void performTest(final LoggerContext loggerContext) throws Exception { if (path.toFile().getName().startsWith(ROLLED)) { rolled = true; final List lines = Files.readAllLines(path); - assertTrue("No messages in " + path.toFile().getName(), lines.size() > 0); + assertFalse( + lines.isEmpty(), "No messages in " + path.toFile().getName()); assertTrue( - "Missing message for " + path.toFile().getName(), - lines.get(0).startsWith(PREFIX + "1")); + lines.get(0).startsWith(PREFIX + "1"), + "Missing message for " + path.toFile().getName()); } } } - assertTrue("File did not roll", rolled); + assertTrue(rolled, "File did not roll"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderReconfigureTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderReconfigureTest.java index ae25790e1c8..8e6a300a28d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderReconfigureTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderReconfigureTest.java @@ -34,7 +34,7 @@ * LOG4J2-1725. */ @UsingStatusListener -public class RollingAppenderReconfigureTest { +class RollingAppenderReconfigureTest { private static final URL CONFIG = RollingAppenderReconfigureTest.class.getResource("RollingAppenderReconfigureTest.xml"); @@ -45,7 +45,7 @@ public class RollingAppenderReconfigureTest { @Test @LoggerContextSource - public void testReconfigure(final LoggerContext context) throws Exception { + void testReconfigure(final LoggerContext context) throws Exception { final Logger logger = context.getLogger(getClass()); for (int i = 0; i < 500; ++i) { logger.debug("This is test message number {}", i); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeCompressPermissionsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeCompressPermissionsTest.java index e8ebb09cf6a..98bc0989b7a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeCompressPermissionsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeCompressPermissionsTest.java @@ -57,7 +57,7 @@ public static void beforeClass() { } @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderSizeCompressPermissionsTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeMaxWidthTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeMaxWidthTest.java index 449d60d1251..4b49a59f120 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeMaxWidthTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeMaxWidthTest.java @@ -96,7 +96,7 @@ public RollingAppenderSizeMaxWidthTest(final LoggerContextRule loggerContextRule } @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderSizeMaxWidthTest.class.getName()); final RollingFileAppender app = (RollingFileAppender) loggerContextRule.getRequiredAppender("RollingFile"); app.getManager().addRolloverListener(this); @@ -133,7 +133,7 @@ public void setUp() throws Exception { } @Test - public void testAppender() throws Exception { + public void testAppender() { if (minWidth > 0) { assertTrue("min must be greater than or equal to the minimum width", min > -powerOfTen(minWidth)); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeNoCompressTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeNoCompressTest.java index b60ca743612..3906a4c79f6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeNoCompressTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeNoCompressTest.java @@ -39,7 +39,7 @@ * LOG4J2-1804. */ @UsingStatusListener -public class RollingAppenderSizeNoCompressTest { +class RollingAppenderSizeNoCompressTest { private static final Logger LOGGER = StatusLogger.getLogger(); @@ -48,7 +48,7 @@ public class RollingAppenderSizeNoCompressTest { @Test @LoggerContextSource - public void testAppender(final LoggerContext context) throws Exception { + void testAppender(final LoggerContext context) throws Exception { final Logger logger = context.getLogger(getClass()); final List messages = new ArrayList<>(); for (int i = 0; i < 1000; ++i) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeTest.java index b5559f16dbb..dc245af3058 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeTest.java @@ -46,7 +46,7 @@ import org.junit.jupiter.params.provider.MethodSource; @UsingStatusListener -public class RollingAppenderSizeTest { +class RollingAppenderSizeTest { private static long DEFAULT_SHUTDOWN_MS = 500; @@ -90,7 +90,7 @@ private static LogEvent createEvent(final String pattern, final Object p0) { @ParameterizedTest @MethodSource("parameters") - public void testIsCreateOnDemand(final String fileExtension, final boolean createOnDemand) throws IOException { + void testIsCreateOnDemand(final String fileExtension, final boolean createOnDemand) throws IOException { final Path extensionFolder = loggingPath.resolve(fileExtension); RollingFileAppender appender = null; try { @@ -106,7 +106,7 @@ public void testIsCreateOnDemand(final String fileExtension, final boolean creat @ParameterizedTest @MethodSource("parameters") - public void testAppender(final String fileExtension, final boolean createOnDemand) throws Exception { + void testAppender(final String fileExtension, final boolean createOnDemand) throws Exception { final Path extensionFolder = loggingPath.resolve(fileExtension); RollingFileAppender appender = null; try { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeWithTimeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeWithTimeTest.java index 66fed65dc90..abe97560e82 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeWithTimeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeWithTimeTest.java @@ -53,7 +53,7 @@ public class RollingAppenderSizeWithTimeTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderSizeWithTimeTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTempCompressedFilePatternTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTempCompressedFilePatternTest.java index 929a073ad85..579768097f2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTempCompressedFilePatternTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTempCompressedFilePatternTest.java @@ -51,7 +51,7 @@ * LOG4J2-1766. */ @UsingStatusListener -public class RollingAppenderTempCompressedFilePatternTest { +class RollingAppenderTempCompressedFilePatternTest { private static Logger LOGGER = StatusLogger.getLogger(); @@ -61,7 +61,7 @@ public class RollingAppenderTempCompressedFilePatternTest { @Test @DisabledOnOs(value = OS.MAC, disabledReason = "FileWatcher isn't fast enough to work properly.") @LoggerContextSource - public void testAppender(final LoggerContext context) throws Exception { + void testAppender(final LoggerContext context) throws Exception { final Logger logger = context.getLogger(getClass()); final Path logsDir = loggingPath.resolve("logs"); final Path tmpDir = loggingPath.resolve("tmp"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeDirectTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeDirectTest.java index 15b45603f91..31c04d39091 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeDirectTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeDirectTest.java @@ -18,10 +18,10 @@ import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; @@ -50,7 +50,7 @@ public class RollingAppenderTimeAndSizeDirectTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderTimeAndSizeDirectTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeTest.java index 2ec3084657b..a04471dcac1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderTimeAndSizeTest.java @@ -18,12 +18,12 @@ import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; 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.Assert.assertTrue; import java.io.File; @@ -56,7 +56,7 @@ public class RollingAppenderTimeAndSizeTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderTimeAndSizeTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderUncompressedTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderUncompressedTest.java index 6fc45949b86..66568da524f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderUncompressedTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderUncompressedTest.java @@ -58,7 +58,7 @@ public static void cleanupClass() { } @Test - public void testAppender() throws Exception { + public void testAppender() { for (int i = 0; i < 100; ++i) { logger.debug("This is test message number " + i); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingDirectSize3490Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingDirectSize3490Test.java index bf5be0d9180..d4b6bb5d6f7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingDirectSize3490Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingDirectSize3490Test.java @@ -36,7 +36,7 @@ * This test attempts to validate that logging rolls after the max files are already written * will succeed on a restart. */ -public class RollingDirectSize3490Test implements RolloverListener { +class RollingDirectSize3490Test implements RolloverListener { private static final String CONFIG = "log4j-rolling-3490.xml"; private static final String[] set1 = {"This is file 1"}; @@ -48,7 +48,7 @@ public class RollingDirectSize3490Test implements RolloverListener { private boolean rolloverTriggered = false; @BeforeAll - public static void clean() throws Exception { + static void clean() { final File dir = new File(DIR); if (dir.exists()) { final File[] files = dir.listFiles(); @@ -62,7 +62,7 @@ public static void clean() throws Exception { } @Test - public void rolloverTest() throws Exception { + void rolloverTest() throws Exception { final File parent = new File(DIR); parent.mkdirs(); final Path app1 = new File(parent, "app-21.log").toPath(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderAccessTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderAccessTest.java index 4d963f6e211..44a88a7c45f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderAccessTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderAccessTest.java @@ -16,15 +16,16 @@ */ package org.apache.logging.log4j.core.appender.rolling; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.io.IOException; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.RollingFileAppender; import org.apache.logging.log4j.core.config.Configuration; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RollingFileAppenderAccessTest { +class RollingFileAppenderAccessTest { /** * Not a real test, just make sure we can compile access to the typed manager. @@ -32,7 +33,7 @@ public class RollingFileAppenderAccessTest { * @throws IOException */ @Test - public void testAccessManagerWithBuilder() throws IOException { + void testAccessManagerWithBuilder() throws IOException { try (final LoggerContext ctx = LoggerContext.getContext(false)) { final Configuration config = ctx.getConfiguration(); final File file = File.createTempFile("RollingFileAppenderAccessTest", ".tmp"); @@ -49,8 +50,8 @@ public void testAccessManagerWithBuilder() throws IOException { final RollingFileManager manager = appender.getManager(); // Since the RolloverStrategy and TriggeringPolicy are immutable, we could also use generics to type their // access. - Assert.assertNotNull(manager.getRolloverStrategy()); - Assert.assertNotNull(manager.getTriggeringPolicy()); + assertNotNull(manager.getRolloverStrategy()); + assertNotNull(manager.getTriggeringPolicy()); } } @@ -60,7 +61,7 @@ public void testAccessManagerWithBuilder() throws IOException { * @throws IOException */ @Test - public void testAccessManagerWithStrings() throws IOException { + void testAccessManagerWithStrings() throws IOException { try (final LoggerContext ctx = LoggerContext.getContext(false)) { final Configuration config = ctx.getConfiguration(); final File file = File.createTempFile("RollingFileAppenderAccessTest", ".tmp"); @@ -84,8 +85,8 @@ public void testAccessManagerWithStrings() throws IOException { final RollingFileManager manager = appender.getManager(); // Since the RolloverStrategy and TriggeringPolicy are immutable, we could also use generics to type their // access. - Assert.assertNotNull(manager.getRolloverStrategy()); - Assert.assertNotNull(manager.getTriggeringPolicy()); + assertNotNull(manager.getRolloverStrategy()); + assertNotNull(manager.getTriggeringPolicy()); } } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderBuilderTest.java index ec2bf42cca7..d739c978d07 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderBuilderTest.java @@ -16,17 +16,18 @@ */ package org.apache.logging.log4j.core.appender.rolling; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.logging.log4j.core.appender.RollingFileAppender; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RollingFileAppenderBuilderTest { +class RollingFileAppenderBuilderTest { /** * Tests https://issues.apache.org/jira/browse/LOG4J2-1620 */ @Test - public void testDefaultImmediateFlush() { - Assert.assertTrue(RollingFileAppender.newBuilder().isImmediateFlush()); + void testDefaultImmediateFlush() { + assertTrue(RollingFileAppender.newBuilder().isImmediateFlush()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderInterruptedThreadTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderInterruptedThreadTest.java index 156c85e8f0c..6a568a66fe2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderInterruptedThreadTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderInterruptedThreadTest.java @@ -16,8 +16,10 @@ */ package org.apache.logging.log4j.core.appender.rolling; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertTrue; import java.io.File; import org.apache.logging.log4j.Level; @@ -31,7 +33,6 @@ import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; import org.apache.logging.log4j.core.test.junit.CleanFolders; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -80,14 +81,14 @@ public void tearDown() { public void testRolloverInInterruptedThread() { final Logger logger = loggerContext.getLogger(getClass().getName()); - Assert.assertThat(logger.getAppenders().values(), hasItem(instanceOf(RollingFileAppender.class))); + assertThat(logger.getAppenders().values(), hasItem(instanceOf(RollingFileAppender.class))); logger.info("Sending logging event 1"); // send first event to initialize rollover system Thread.currentThread().interrupt(); // mark thread as interrupted logger.info("Sending logging event 2"); // send second event to trigger rotation, expecting 2 files in result - Assert.assertTrue(new File(ROLLING_APPENDER_FILES_DIR, "file-1.log").exists()); - Assert.assertTrue(new File(ROLLING_APPENDER_FILES_DIR, "file-2.log").exists()); + assertTrue(new File(ROLLING_APPENDER_FILES_DIR, "file-1.log").exists()); + assertTrue(new File(ROLLING_APPENDER_FILES_DIR, "file-2.log").exists()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderLayoutTest.java index 48c0942a1f2..7ac285ee90d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderLayoutTest.java @@ -16,17 +16,18 @@ */ package org.apache.logging.log4j.core.appender.rolling; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.logging.log4j.core.appender.RollingFileAppender; import org.apache.logging.log4j.core.config.DefaultConfiguration; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RollingFileAppenderLayoutTest { +class RollingFileAppenderLayoutTest { @Test - public void testDefaultLayout() throws Exception { + void testDefaultLayout() { // @formatter:off - Assert.assertNotNull(RollingFileAppender.newBuilder() + assertNotNull(RollingFileAppender.newBuilder() .setName(RollingFileAppenderLayoutTest.class.getName()) .setConfiguration(new DefaultConfiguration()) .withFileName("log.txt") diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderUpdateDataTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderUpdateDataTest.java index b50d83efa3e..2f63c19e34e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderUpdateDataTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileAppenderUpdateDataTest.java @@ -16,6 +16,10 @@ */ package org.apache.logging.log4j.core.appender.rolling; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; @@ -25,14 +29,13 @@ import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory; import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * Tests LOG4J2-2009 Rolling appender managers broken on pattern/policy reconfiguration */ -public class RollingFileAppenderUpdateDataTest { +class RollingFileAppenderUpdateDataTest { private ConfigurationBuilder buildConfigA() { return buildConfigurationBuilder("target/rolling-update-date/foo.log.%i"); @@ -64,8 +67,8 @@ private ConfigurationBuilder buildConfigurationBuilder(final private LoggerContext loggerContext1 = null; private LoggerContext loggerContext2 = null; - @After - public void after() { + @AfterEach + void after() { if (loggerContext1 != null) { loggerContext1.close(); loggerContext1 = null; @@ -77,7 +80,7 @@ public void after() { } @Test - public void testClosingLoggerContext() { + void testClosingLoggerContext() { // initial config with indexed rollover try (final LoggerContext loggerContext1 = Configurator.initialize(buildConfigA().build())) { @@ -92,20 +95,20 @@ public void testClosingLoggerContext() { } @Test - public void testNotClosingLoggerContext() { + void testNotClosingLoggerContext() { // initial config with indexed rollover loggerContext1 = Configurator.initialize(buildConfigA().build()); validateAppender(loggerContext1, "target/rolling-update-date/foo.log.%i"); // rebuild config with date based rollover loggerContext2 = Configurator.initialize(buildConfigB().build()); - Assert.assertNotNull("No LoggerContext", loggerContext2); - Assert.assertTrue("Expected same logger context to be returned", loggerContext1 == loggerContext2); + assertNotNull(loggerContext2, "No LoggerContext"); + assertSame(loggerContext1, loggerContext2, "Expected same logger context to be returned"); validateAppender(loggerContext1, "target/rolling-update-date/foo.log.%i"); } @Test - public void testReconfigure() { + void testReconfigure() { // initial config with indexed rollover loggerContext1 = Configurator.initialize(buildConfigA().build()); validateAppender(loggerContext1, "target/rolling-update-date/foo.log.%i"); @@ -117,8 +120,8 @@ public void testReconfigure() { private void validateAppender(final LoggerContext loggerContext, final String expectedFilePattern) { final RollingFileAppender appender = loggerContext.getConfiguration().getAppender("fooAppender"); - Assert.assertNotNull(appender); - Assert.assertEquals(expectedFilePattern, appender.getFilePattern()); + assertNotNull(appender); + assertEquals(expectedFilePattern, appender.getFilePattern()); LogManager.getLogger("root").info("just to show it works."); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManagerTest.java index 325b859f6f1..dfa94c3ffe7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManagerTest.java @@ -16,11 +16,11 @@ */ package org.apache.logging.log4j.core.appender.rolling; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.File; @@ -40,10 +40,10 @@ import org.apache.logging.log4j.core.layout.PatternLayout; import org.apache.logging.log4j.core.lookup.StrSubstitutor; import org.apache.logging.log4j.core.util.IOUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junitpioneer.jupiter.Issue; -public class RollingFileManagerTest { +class RollingFileManagerTest { /** * Test the RollingFileManager with a custom DirectFileRolloverStrategy @@ -51,7 +51,7 @@ public class RollingFileManagerTest { * @throws IOException */ @Test - public void testCustomDirectFileRolloverStrategy() throws IOException { + void testCustomDirectFileRolloverStrategy() throws IOException { class CustomDirectFileRolloverStrategy extends AbstractRolloverStrategy implements DirectFileRolloverStrategy { final File file; @@ -105,7 +105,7 @@ public RolloverDescription rollover(final RollingFileManager manager) throws Sec * Test that a synchronous action failure does not cause a rollover. Addresses Issue #1445. */ @Test - public void testSynchronousActionFailure() throws IOException { + void testSynchronousActionFailure() throws IOException { class FailingSynchronousAction extends AbstractAction { @Override public boolean execute() { @@ -158,7 +158,7 @@ public RolloverDescription rollover(final RollingFileManager manager) throws Sec @Test @Issue("https://github.com/apache/logging-log4j2/issues/1645") - public void testCreateParentDir() { + void testCreateParentDir() { final Configuration configuration = new NullConfiguration(); final RollingFileManager manager = RollingFileManager.getFileManager( null, @@ -192,7 +192,7 @@ public void testCreateParentDir() { @Test @Issue("https://github.com/apache/logging-log4j2/issues/2592") - public void testRolloverOfDeletedFile() throws IOException { + void testRolloverOfDeletedFile() throws IOException { final File file = File.createTempFile("testRolloverOfDeletedFile", "log"); file.deleteOnExit(); final String testContent = "Test"; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingNewDirectoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingNewDirectoryTest.java index 157be9b57f0..e720a33ea0f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingNewDirectoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingNewDirectoryTest.java @@ -44,7 +44,7 @@ public class RollingNewDirectoryTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingNewDirectoryTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManagerTest.java index 55e0c20961a..e3aba8f2583 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAccessFileManagerTest.java @@ -20,13 +20,13 @@ import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasLength; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.isEmpty; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.lastModified; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; -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.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileOutputStream; @@ -45,19 +45,19 @@ import org.apache.logging.log4j.core.util.FileUtils; import org.apache.logging.log4j.core.util.NullOutputStream; import org.apache.logging.log4j.util.Strings; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the RollingRandomAccessFileManager class. */ -public class RollingRandomAccessFileManagerTest { +class RollingRandomAccessFileManagerTest { /** * Test method for * {@link org.apache.logging.log4j.core.appender.rolling.RollingRandomAccessFileManager#writeBytes(byte[], int, int)} */ @Test - public void testWrite_multiplesOfBufferSize() throws IOException { + void testWrite_multiplesOfBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { @@ -102,7 +102,7 @@ public void testWrite_multiplesOfBufferSize() throws IOException { * {@link org.apache.logging.log4j.core.appender.rolling.RollingRandomAccessFileManager#writeBytes(byte[], int, int)} . */ @Test - public void testWrite_dataExceedingBufferSize() throws IOException { + void testWrite_dataExceedingBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { @@ -144,7 +144,7 @@ public void testWrite_dataExceedingBufferSize() throws IOException { } @Test - public void testConfigurableBufferSize() throws IOException { + void testConfigurableBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { @@ -183,7 +183,7 @@ public void testConfigurableBufferSize() throws IOException { } @Test - public void testAppendDoesNotOverwriteExistingFile() throws IOException { + void testAppendDoesNotOverwriteExistingFile() throws IOException { final boolean isAppend = true; final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); @@ -224,7 +224,7 @@ public void testAppendDoesNotOverwriteExistingFile() throws IOException { } @Test - public void testFileTimeBasedOnSystemClockWhenAppendIsFalse() throws IOException { + void testFileTimeBasedOnSystemClockWhenAppendIsFalse() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); LockSupport.parkNanos(1000000); // 1 millisec @@ -255,7 +255,7 @@ public void testFileTimeBasedOnSystemClockWhenAppendIsFalse() throws IOException } @Test - public void testFileTimeBasedOnFileModifiedTimeWhenAppendIsTrue() throws IOException { + void testFileTimeBasedOnFileModifiedTimeWhenAppendIsTrue() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); LockSupport.parkNanos(1000000); // 1 millisec @@ -282,7 +282,7 @@ public void testFileTimeBasedOnFileModifiedTimeWhenAppendIsTrue() throws IOExcep } @Test - public void testRolloverRetainsFileAttributes() throws Exception { + void testRolloverRetainsFileAttributes() throws Exception { // Short-circuit if host doesn't support file attributes. if (!FileUtils.isFilePosixAttributeViewSupported()) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteAndSwitchDirectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteAndSwitchDirectorTest.java index 5099aa5d04b..ceb6faacfed 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteAndSwitchDirectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteAndSwitchDirectorTest.java @@ -27,12 +27,12 @@ import org.junit.jupiter.api.Test; @CleanUpDirectories(RollingRandomAppenderDirectWriteAndSwitchDirectorTest.DIR) -public class RollingRandomAppenderDirectWriteAndSwitchDirectorTest { +class RollingRandomAppenderDirectWriteAndSwitchDirectorTest { public static final String DIR = "target/rolling-random-direct-switch-director"; @Test @LoggerContextSource(value = "log4j-rolling-random-direct-switch-director.xml", timeout = 10) - public void testAppender(final LoggerContext context) throws Exception { + void testAppender(final LoggerContext context) throws Exception { final Logger logger = context.getLogger(RollingRandomAppenderDirectWriteAndSwitchDirectorTest.class.getName()); final LocalTime start = LocalTime.now(); LocalTime end; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteTest.java index 6489bec0fbb..d74a0637bd2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteTest.java @@ -18,10 +18,10 @@ import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that; import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.hasItemInArray; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; @@ -50,7 +50,7 @@ public class RollingRandomAppenderDirectWriteTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingRandomAppenderDirectWriteTest.class.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteWithFilenameTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteWithFilenameTest.java index cea54269cb8..8ae8e94eb34 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteWithFilenameTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingRandomAppenderDirectWriteWithFilenameTest.java @@ -44,12 +44,12 @@ public class RollingRandomAppenderDirectWriteWithFilenameTest { private Logger logger; @Before - public void setUp() throws Exception { + public void setUp() { this.logger = loggerContextRule.getLogger(RollingRandomAppenderDirectWriteWithFilenameTest.class.getName()); } @Test - public void testAppender() throws Exception { + public void testAppender() { final File dir = new File(DIR); assertFalse("Directory created", dir.exists()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverFilePatternTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverFilePatternTest.java index ed23f414d83..15b6a18ff71 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverFilePatternTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverFilePatternTest.java @@ -16,21 +16,21 @@ */ package org.apache.logging.log4j.core.appender.rolling; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.regex.Matcher; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test getEligibleFiles method. */ -public class RolloverFilePatternTest { +class RolloverFilePatternTest { @Test - public void testFilePatternWithoutPadding() throws Exception { + void testFilePatternWithoutPadding() { final Matcher matcher = AbstractRolloverStrategy.PATTERN_COUNTER.matcher("target/logs/test-%i.log.gz"); assertTrue(matcher.find()); assertNull(matcher.group("ZEROPAD")); @@ -38,7 +38,7 @@ public void testFilePatternWithoutPadding() throws Exception { } @Test - public void testFilePatternWithSpacePadding() throws Exception { + void testFilePatternWithSpacePadding() { final Matcher matcher = AbstractRolloverStrategy.PATTERN_COUNTER.matcher("target/logs/test-%3i.log.gz"); assertTrue(matcher.find()); assertNull(matcher.group("ZEROPAD")); @@ -46,7 +46,7 @@ public void testFilePatternWithSpacePadding() throws Exception { } @Test - public void testFilePatternWithZeroPadding() throws Exception { + void testFilePatternWithZeroPadding() { final Matcher matcher = AbstractRolloverStrategy.PATTERN_COUNTER.matcher("target/logs/test-%03i.log.gz"); assertTrue(matcher.find()); assertEquals("0", matcher.group("ZEROPAD")); @@ -54,7 +54,7 @@ public void testFilePatternWithZeroPadding() throws Exception { } @Test - public void testFilePatternUnmatched() throws Exception { + void testFilePatternUnmatched() { final Matcher matcher = AbstractRolloverStrategy.PATTERN_COUNTER.matcher("target/logs/test-%n.log.gz"); assertFalse(matcher.find()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverWithPaddingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverWithPaddingTest.java index 72905b33a81..d31ecf5ec00 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverWithPaddingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RolloverWithPaddingTest.java @@ -38,7 +38,7 @@ * Tests that zero-padding in rolled files works correctly. */ @UsingStatusListener -public class RolloverWithPaddingTest { +class RolloverWithPaddingTest { private static final String[] EXPECTED_FILES = { "rollingtest.log", "test-001.log", "test-002.log", "test-003.log", "test-004.log", "test-005.log" @@ -50,7 +50,7 @@ public class RolloverWithPaddingTest { @Test @LoggerContextSource - public void testPadding(final LoggerContext context) throws Exception { + void testPadding(final LoggerContext context) throws Exception { final Logger logger = context.getLogger(getClass()); for (int i = 0; i < 10; ++i) { // 30 chars per message: each message triggers a rollover @@ -64,7 +64,7 @@ public void testPadding(final LoggerContext context) throws Exception { @Test @LoggerContextSource - public void testOldFileDeleted(final LoggerContext context) throws Exception { + void testOldFileDeleted(final LoggerContext context) throws Exception { final Logger logger = context.getLogger(getClass()); // Prepare directory for (int i = 1; i <= 5; i++) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/Bzip2CompressActionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/Bzip2CompressActionTest.java index a3119c8bd80..0907ef1e8d5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/Bzip2CompressActionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/Bzip2CompressActionTest.java @@ -34,20 +34,20 @@ /** * Tests Bzip2CompressAction. */ -public class Bzip2CompressActionTest { +class Bzip2CompressActionTest { @Test - public void testConstructorDisallowsNullSource() { + void testConstructorDisallowsNullSource() { assertThrows(NullPointerException.class, () -> new CommonsCompressAction("bzip2", null, new File("any"), true)); } @Test - public void testConstructorDisallowsNullDestination() { + void testConstructorDisallowsNullDestination() { assertThrows(NullPointerException.class, () -> new CommonsCompressAction("bzip2", new File("any"), null, true)); } @Test - public void testExecuteReturnsFalseIfSourceDoesNotExist() throws IOException { + void testExecuteReturnsFalseIfSourceDoesNotExist() throws IOException { File source = new File("any"); while (source.exists()) { source = new File(source.getName() + Math.random()); @@ -57,7 +57,7 @@ public void testExecuteReturnsFalseIfSourceDoesNotExist() throws IOException { } @Test - public void testExecuteCompressesSourceFileToDestinationFile(@TempDir final File tempDir) throws IOException { + void testExecuteCompressesSourceFileToDestinationFile(@TempDir final File tempDir) throws IOException { final String LINE1 = "Here is line 1. Random text: ABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n"; final String LINE2 = "Here is line 2. Random text: ABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n"; final String LINE3 = "Here is line 3. Random text: ABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n"; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java index d57f4513f17..06548d5b2c1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeleteActionTest.java @@ -36,7 +36,7 @@ /** * Tests the {@code DeleteAction} class. */ -public class DeleteActionTest { +class DeleteActionTest { private static DeleteAction createAnyFilter( final String path, final boolean followLinks, final int maxDepth, final boolean testMode) { @@ -57,7 +57,7 @@ private static DeleteAction create( } @Test - public void testGetBasePathResolvesLookups() { + void testGetBasePathResolvesLookups() { final DeleteAction delete = createAnyFilter("${sys:user.home}/a/b/c", false, 1, false); final Path actual = delete.getBasePath(); @@ -67,31 +67,31 @@ public void testGetBasePathResolvesLookups() { } @Test - public void testGetBasePathStringReturnsOriginalParam() { + void testGetBasePathStringReturnsOriginalParam() { final DeleteAction delete = createAnyFilter("${sys:user.home}/a/b/c", false, 1, false); assertEquals("${sys:user.home}/a/b/c", delete.getBasePathString()); } @Test - public void testGetMaxDepthReturnsConstructorValue() { + void testGetMaxDepthReturnsConstructorValue() { final DeleteAction delete = createAnyFilter("any", false, 23, false); assertEquals(23, delete.getMaxDepth()); } @Test - public void testGetOptionsReturnsEmptySetIfNotFollowingLinks() { + void testGetOptionsReturnsEmptySetIfNotFollowingLinks() { final DeleteAction delete = createAnyFilter("any", false, 0, false); assertEquals(Collections.emptySet(), delete.getOptions()); } @Test - public void testGetOptionsReturnsSetWithFollowLinksIfFollowingLinks() { + void testGetOptionsReturnsSetWithFollowLinksIfFollowingLinks() { final DeleteAction delete = createAnyFilter("any", true, 0, false); assertEquals(EnumSet.of(FileVisitOption.FOLLOW_LINKS), delete.getOptions()); } @Test - public void testGetFiltersReturnsConstructorValue() { + void testGetFiltersReturnsConstructorValue() { final PathCondition[] filters = {new FixedCondition(true), new FixedCondition(false)}; final DeleteAction delete = create("any", true, 0, false, filters); @@ -99,14 +99,14 @@ public void testGetFiltersReturnsConstructorValue() { } @Test - public void testCreateFileVisitorReturnsDeletingVisitor() { + void testCreateFileVisitorReturnsDeletingVisitor() { final DeleteAction delete = createAnyFilter("any", true, 0, false); final FileVisitor visitor = delete.createFileVisitor(delete.getBasePath(), delete.getPathConditions()); assertThat(visitor, instanceOf(DeletingVisitor.class)); } @Test - public void testCreateFileVisitorTestModeIsActionTestMode() { + void testCreateFileVisitorTestModeIsActionTestMode() { final DeleteAction delete = createAnyFilter("any", true, 0, false); assertFalse(delete.isTestMode()); final FileVisitor visitor = delete.createFileVisitor(delete.getBasePath(), delete.getPathConditions()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeletingVisitorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeletingVisitorTest.java index 5e0d2a84786..871f92789ae 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeletingVisitorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeletingVisitorTest.java @@ -37,7 +37,7 @@ /** * Tests the {@code DeletingVisitor} class. */ -public class DeletingVisitorTest { +class DeletingVisitorTest { /** * Modifies {@code DeletingVisitor} for testing: instead of actually deleting a file, it adds the path to a list for * later verification. @@ -51,13 +51,13 @@ public DeletingVisitorHelper( } @Override - protected void delete(final Path file) throws IOException { + protected void delete(final Path file) { deleted.add(file); // overrides and stores path instead of deleting } } @Test - public void testAcceptedFilesAreDeleted() throws IOException { + void testAcceptedFilesAreDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final DeletingVisitorHelper visitor = @@ -69,7 +69,7 @@ public void testAcceptedFilesAreDeleted() throws IOException { } @Test - public void testRejectedFilesAreNotDeleted() throws IOException { + void testRejectedFilesAreNotDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition REJECT_ALL = new FixedCondition(false); final DeletingVisitorHelper visitor = @@ -81,7 +81,7 @@ public void testRejectedFilesAreNotDeleted() throws IOException { } @Test - public void testAllFiltersMustAcceptOrFileIsNotDeleted() throws IOException { + void testAllFiltersMustAcceptOrFileIsNotDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final FixedCondition REJECT_ALL = new FixedCondition(false); @@ -94,7 +94,7 @@ public void testAllFiltersMustAcceptOrFileIsNotDeleted() throws IOException { } @Test - public void testIfAllFiltersAcceptFileIsDeleted() throws IOException { + void testIfAllFiltersAcceptFileIsDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final List filters = Arrays.asList(ACCEPT_ALL, ACCEPT_ALL, ACCEPT_ALL); @@ -106,7 +106,7 @@ public void testIfAllFiltersAcceptFileIsDeleted() throws IOException { } @Test - public void testInTestModeFileIsNotDeletedEvenIfAllFiltersAccept() throws IOException { + void testInTestModeFileIsNotDeletedEvenIfAllFiltersAccept() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final List filters = Arrays.asList(ACCEPT_ALL, ACCEPT_ALL, ACCEPT_ALL); @@ -118,7 +118,7 @@ public void testInTestModeFileIsNotDeletedEvenIfAllFiltersAccept() throws IOExce } @Test - public void testVisitFileRelativizesAgainstBase() throws IOException { + void testVisitFileRelativizesAgainstBase() throws IOException { final PathCondition filter = new PathCondition() { @@ -140,7 +140,7 @@ public void beforeFileTreeWalk() {} } @Test - public void testNoSuchFileFailure() throws IOException { + void testNoSuchFileFailure() throws IOException { final DeletingVisitorHelper visitor = new DeletingVisitorHelper(Paths.get("/a/b/c"), Collections.emptyList(), true); assertEquals( @@ -149,7 +149,7 @@ public void testNoSuchFileFailure() throws IOException { } @Test - public void testIOException() { + void testIOException() { final DeletingVisitorHelper visitor = new DeletingVisitorHelper(Paths.get("/a/b/c"), Collections.emptyList(), true); final IOException exception = new IOException(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DurationTest.java index 75d05c1be87..c66b937d322 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DurationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DurationTest.java @@ -25,42 +25,42 @@ /** * Tests the Duration class. */ -public class DurationTest { +class DurationTest { @Test - public void testParseFailsIfNullText() { + void testParseFailsIfNullText() { assertThrows(NullPointerException.class, () -> Duration.parse(null)); } @Test - public void testParseFailsIfInvalidPattern() { + void testParseFailsIfInvalidPattern() { assertThrows(IllegalArgumentException.class, () -> Duration.parse("abc")); } @Test - public void testParseFailsIfSectionsOutOfOrder() { + void testParseFailsIfSectionsOutOfOrder() { assertThrows(IllegalArgumentException.class, () -> Duration.parse("P4DT2M1S3H")); } @Test - public void testParseFailsIfTButMissingTime() { + void testParseFailsIfTButMissingTime() { assertThrows(IllegalArgumentException.class, () -> Duration.parse("P1dT")); } @Test - public void testParseIsCaseInsensitive() { + void testParseIsCaseInsensitive() { assertEquals("P4DT3H2M1S", Duration.parse("p4dt3h2m1s").toString()); } @Test - public void testParseAllowsOverflows() { + void testParseAllowsOverflows() { assertEquals(1000 * 70, Duration.parse("PT70S").toMillis()); assertEquals(1000 * 70 * 60, Duration.parse("PT70M").toMillis()); assertEquals(1000 * 25 * 60 * 60, Duration.parse("PT25H").toMillis()); } @Test - public void testToMillis() { + void testToMillis() { assertEquals(0, Duration.ZERO.toMillis()); assertEquals(1000, Duration.parse("PT1S").toMillis()); assertEquals(1000 * 2 * 60, Duration.parse("PT2M").toMillis()); @@ -71,7 +71,7 @@ public void testToMillis() { } @Test - public void testToString() { + void testToString() { assertEquals("PT0S", Duration.ZERO.toString()); assertEquals("PT1S", Duration.parse("PT1S").toString()); assertEquals("PT2M1S", Duration.parse("PT2M1S").toString()); @@ -80,7 +80,7 @@ public void testToString() { } @Test - public void testPrefixPNotRequired() { + void testPrefixPNotRequired() { assertEquals("PT1S", Duration.parse("T1S").toString()); assertEquals("PT2M1S", Duration.parse("T2M1S").toString()); assertEquals("PT3H2M1S", Duration.parse("T3H2M1S").toString()); @@ -88,7 +88,7 @@ public void testPrefixPNotRequired() { } @Test - public void testInfixTNotRequired() { + void testInfixTNotRequired() { assertEquals("PT1S", Duration.parse("P1S").toString()); assertEquals("PT2M1S", Duration.parse("P2M1S").toString()); assertEquals("PT3H2M1S", Duration.parse("P3H2M1S").toString()); @@ -96,7 +96,7 @@ public void testInfixTNotRequired() { } @Test - public void testPrefixPAndInfixTNotRequired() { + void testPrefixPAndInfixTNotRequired() { assertEquals("PT1S", Duration.parse("1S").toString()); assertEquals("PT2M1S", Duration.parse("2M1S").toString()); assertEquals("PT3H2M1S", Duration.parse("3H2M1S").toString()); @@ -104,7 +104,7 @@ public void testPrefixPAndInfixTNotRequired() { } @Test - public void testCompareTo() { + void testCompareTo() { assertEquals(-1, Duration.parse("PT1S").compareTo(Duration.parse("PT2S"))); assertEquals(-1, Duration.parse("PT1M").compareTo(Duration.parse("PT2M"))); assertEquals(-1, Duration.parse("PT1H").compareTo(Duration.parse("PT2H"))); @@ -128,7 +128,7 @@ public void testCompareTo() { } @Test - public void testEquals() { + void testEquals() { assertNotEquals(Duration.parse("PT1S"), (Duration.parse("PT2S"))); assertNotEquals(Duration.parse("PT1M"), (Duration.parse("PT2M"))); assertNotEquals(Duration.parse("PT1H"), (Duration.parse("PT2H"))); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileRenameActionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileRenameActionTest.java index 7309e6e7ccf..9b179441db5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileRenameActionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileRenameActionTest.java @@ -24,18 +24,18 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -public class FileRenameActionTest { +class FileRenameActionTest { static File tempDir = new File("./target"); @AfterEach - public void cleanup() { + void cleanup() { final File file = new File(tempDir, "newFile.log"); file.delete(); } @Test - public void testRename1() throws Exception { + void testRename1() throws Exception { final File file = new File(tempDir, "fileRename.log"); try (final PrintStream pos = new PrintStream(file)) { for (int i = 0; i < 100; ++i) { @@ -52,7 +52,7 @@ public void testRename1() throws Exception { } @Test - public void testEmpty() throws Exception { + void testEmpty() throws Exception { final File file = new File(tempDir, "fileRename.log"); try (final PrintStream pos = new PrintStream(file)) { // do nothing @@ -67,7 +67,7 @@ public void testEmpty() throws Exception { } @Test - public void testRenameEmpty() throws Exception { + void testRenameEmpty() throws Exception { final File file = new File(tempDir, "fileRename.log"); try (final PrintStream pos = new PrintStream(file)) { // do nothing @@ -82,7 +82,7 @@ public void testRenameEmpty() throws Exception { } @Test - public void testNoParent() throws Exception { + void testNoParent() throws Exception { final File file = new File("fileRename.log"); try (final PrintStream pos = new PrintStream(file)) { for (int i = 0; i < 100; ++i) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileSizeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileSizeTest.java index b0da9d6d00b..729a5d2e858 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileSizeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/FileSizeTest.java @@ -24,16 +24,16 @@ import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.api.parallel.Resources; -public class FileSizeTest { +class FileSizeTest { @Test - public void testParse() { + void testParse() { assertEquals(5 * 1024, FileSize.parse("5k", 0)); } @Test @ResourceLock(Resources.LOCALE) - public void testParseInEurope() { + void testParseInEurope() { // Caveat: Breaks the ability for this test to run in parallel with other tests :( final Locale previousDefault = Locale.getDefault(); try { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileCountTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileCountTest.java index e94f2b5edd1..84120c63d53 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileCountTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileCountTest.java @@ -25,16 +25,16 @@ /** * Tests the IfAccumulatedFileCount class. */ -public class IfAccumulatedFileCountTest { +class IfAccumulatedFileCountTest { @Test - public void testGetThresholdCount() { + void testGetThresholdCount() { assertEquals(123, IfAccumulatedFileCount.createFileCountCondition(123).getThresholdCount()); assertEquals(456, IfAccumulatedFileCount.createFileCountCondition(456).getThresholdCount()); } @Test - public void testAccept() { + void testAccept() { final int[] counts = {3, 5, 9}; for (final int count : counts) { final IfAccumulatedFileCount condition = IfAccumulatedFileCount.createFileCountCondition(count); @@ -49,7 +49,7 @@ public void testAccept() { } @Test - public void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { + void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { final CountingCondition counter = new CountingCondition(true); final IfAccumulatedFileCount condition = IfAccumulatedFileCount.createFileCountCondition(3, counter); @@ -65,7 +65,7 @@ public void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { } @Test - public void testBeforeTreeWalk() { + void testBeforeTreeWalk() { final CountingCondition counter = new CountingCondition(true); final IfAccumulatedFileCount filter = IfAccumulatedFileCount.createFileCountCondition(30, counter, counter, counter); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileSizeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileSizeTest.java index 0605842a7e1..08fa6aa98d8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileSizeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAccumulatedFileSizeTest.java @@ -26,10 +26,10 @@ /** * Tests the IfAccumulatedFileSize class. */ -public class IfAccumulatedFileSizeTest { +class IfAccumulatedFileSizeTest { @Test - public void testGetThresholdBytes() { + void testGetThresholdBytes() { assertEquals(2, create("2B").getThresholdBytes()); assertEquals(3, create("3 B").getThresholdBytes()); assertEquals(2 * 1024, create("2KB").getThresholdBytes()); @@ -47,7 +47,7 @@ private static IfAccumulatedFileSize create(final String size) { } @Test - public void testNotAcceptOnExactMatch() { + void testNotAcceptOnExactMatch() { final String[] sizes = {"2KB", "3MB", "4GB", "5TB"}; for (final String size : sizes) { final IfAccumulatedFileSize condition = IfAccumulatedFileSize.createFileSizeCondition(size); @@ -58,7 +58,7 @@ public void testNotAcceptOnExactMatch() { } @Test - public void testAcceptIfExceedThreshold() { + void testAcceptIfExceedThreshold() { final String[] sizes = {"2KB", "3MB", "4GB", "5TB"}; for (final String size : sizes) { final IfAccumulatedFileSize condition = IfAccumulatedFileSize.createFileSizeCondition(size); @@ -69,7 +69,7 @@ public void testAcceptIfExceedThreshold() { } @Test - public void testNotAcceptIfBelowThreshold() { + void testNotAcceptIfBelowThreshold() { final String[] sizes = {"2KB", "3MB", "4GB", "5TB"}; for (final String size : sizes) { final IfAccumulatedFileSize condition = IfAccumulatedFileSize.createFileSizeCondition(size); @@ -80,7 +80,7 @@ public void testNotAcceptIfBelowThreshold() { } @Test - public void testAcceptOnceThresholdExceeded() { + void testAcceptOnceThresholdExceeded() { final DummyFileAttributes attribs = new DummyFileAttributes(); final String[] sizes = {"2KB", "3MB", "4GB", "5TB"}; for (final String size : sizes) { @@ -96,7 +96,7 @@ public void testAcceptOnceThresholdExceeded() { } @Test - public void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { + void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { final CountingCondition counter = new CountingCondition(true); final IfAccumulatedFileSize condition = IfAccumulatedFileSize.createFileSizeCondition("2KB", counter); final DummyFileAttributes attribs = new DummyFileAttributes(); @@ -123,7 +123,7 @@ public void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { } @Test - public void testBeforeTreeWalk() { + void testBeforeTreeWalk() { final CountingCondition counter = new CountingCondition(true); final IfAccumulatedFileSize filter = IfAccumulatedFileSize.createFileSizeCondition("2GB", counter, counter, counter); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAnyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAnyTest.java index 7ed92516851..9fea2f12986 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAnyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfAnyTest.java @@ -42,7 +42,7 @@ class IfAnyTest { @Test - public void test() { + void test() { final PathCondition TRUE = new FixedCondition(true); final PathCondition FALSE = new FixedCondition(false); assertTrue(IfAny.createOrCondition(TRUE, TRUE).accept(null, null, null)); @@ -52,12 +52,12 @@ public void test() { } @Test - public void testEmptyIsFalse() { + void testEmptyIsFalse() { assertFalse(IfAny.createOrCondition().accept(null, null, null)); } @Test - public void testBeforeTreeWalk() { + void testBeforeTreeWalk() { final CountingCondition counter = new CountingCondition(true); final IfAny or = IfAny.createOrCondition(counter, counter, counter); or.beforeFileTreeWalk(); @@ -65,14 +65,14 @@ public void testBeforeTreeWalk() { } @Test - public void testCreateOrConditionCalledProgrammaticallyThrowsNPEWhenComponentsNotSpecified() { + void testCreateOrConditionCalledProgrammaticallyThrowsNPEWhenComponentsNotSpecified() { PathCondition[] components = null; assertThrows(NullPointerException.class, () -> IfAny.createOrCondition(components)); } @ParameterizedTest @ValueSource(strings = "No components provided for IfAny") - public void testCreateOrConditionCalledByPluginBuilderReturnsNullAndLogsMessageWhenComponentsNotSpecified( + void testCreateOrConditionCalledByPluginBuilderReturnsNullAndLogsMessageWhenComponentsNotSpecified( final String expectedMessage) { final PluginEntry nullEntry = null; final PluginType type = new PluginType<>(nullEntry, IfAny.class, "Dummy"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfFileNameTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfFileNameTest.java index d307a37cde7..8fe68f5c334 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfFileNameTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfFileNameTest.java @@ -25,22 +25,22 @@ import java.nio.file.Paths; import org.junit.jupiter.api.Test; -public class IfFileNameTest { +class IfFileNameTest { @Test - public void testCreateNameConditionFailsIfBothRegexAndPathAreNull() { + void testCreateNameConditionFailsIfBothRegexAndPathAreNull() { assertThrows(IllegalArgumentException.class, () -> IfFileName.createNameCondition(null, null)); } @Test - public void testCreateNameConditionAcceptsIfEitherRegexOrPathOrBothAreNonNull() { + void testCreateNameConditionAcceptsIfEitherRegexOrPathOrBothAreNonNull() { IfFileName.createNameCondition("bar", null); IfFileName.createNameCondition(null, "foo"); IfFileName.createNameCondition("bar", "foo"); } @Test - public void testGetSyntaxAndPattern() { + void testGetSyntaxAndPattern() { assertEquals("glob:path", IfFileName.createNameCondition("path", null).getSyntaxAndPattern()); assertEquals( "glob:path", IfFileName.createNameCondition("glob:path", null).getSyntaxAndPattern()); @@ -50,7 +50,7 @@ public void testGetSyntaxAndPattern() { } @Test - public void testAcceptUsesPathPatternIfExists() { + void testAcceptUsesPathPatternIfExists() { final IfFileName filter = IfFileName.createNameCondition("path", "regex"); final Path relativePath = Paths.get("path"); assertTrue(filter.accept(null, relativePath, null)); @@ -60,7 +60,7 @@ public void testAcceptUsesPathPatternIfExists() { } @Test - public void testAcceptUsesRegexIfNoPathPatternExists() { + void testAcceptUsesRegexIfNoPathPatternExists() { final IfFileName regexFilter = IfFileName.createNameCondition(null, "regex"); final Path pathMatchingRegex = Paths.get("regex"); assertTrue(regexFilter.accept(null, pathMatchingRegex, null)); @@ -70,7 +70,7 @@ public void testAcceptUsesRegexIfNoPathPatternExists() { } @Test - public void testAcceptIgnoresBasePathAndAttributes() { + void testAcceptIgnoresBasePathAndAttributes() { final IfFileName pathFilter = IfFileName.createNameCondition("path", null); final Path relativePath = Paths.get("path"); assertTrue(pathFilter.accept(null, relativePath, null)); @@ -81,7 +81,7 @@ public void testAcceptIgnoresBasePathAndAttributes() { } @Test - public void testAcceptCallsNestedConditionsOnlyIfPathAccepted1() { + void testAcceptCallsNestedConditionsOnlyIfPathAccepted1() { final CountingCondition counter = new CountingCondition(true); final IfFileName regexFilter = IfFileName.createNameCondition(null, "regex", counter); final Path pathMatchingRegex = Paths.get("regex"); @@ -103,7 +103,7 @@ public void testAcceptCallsNestedConditionsOnlyIfPathAccepted1() { } @Test - public void testAcceptCallsNestedConditionsOnlyIfPathAccepted2() { + void testAcceptCallsNestedConditionsOnlyIfPathAccepted2() { final CountingCondition counter = new CountingCondition(true); final IfFileName globFilter = IfFileName.createNameCondition("glob", null, counter); final Path pathMatchingGlob = Paths.get("glob"); @@ -125,7 +125,7 @@ public void testAcceptCallsNestedConditionsOnlyIfPathAccepted2() { } @Test - public void testBeforeTreeWalk() { + void testBeforeTreeWalk() { final CountingCondition counter = new CountingCondition(true); final IfFileName pathFilter = IfFileName.createNameCondition("path", null, counter, counter, counter); pathFilter.beforeFileTreeWalk(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfLastModifiedTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfLastModifiedTest.java index 22bf04e43f1..41a758fe5c5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfLastModifiedTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfLastModifiedTest.java @@ -45,7 +45,7 @@ class IfLastModifiedTest { @Test - public void testAcceptsIfFileAgeEqualToDuration() { + void testAcceptsIfFileAgeEqualToDuration() { final IfLastModified filter = IfLastModified.newBuilder().setAge(Duration.parse("PT33S")).build(); final DummyFileAttributes attrs = new DummyFileAttributes(); @@ -55,7 +55,7 @@ public void testAcceptsIfFileAgeEqualToDuration() { } @Test - public void testAcceptsIfFileAgeExceedsDuration() { + void testAcceptsIfFileAgeExceedsDuration() { final IfLastModified filter = IfLastModified.newBuilder().setAge(Duration.parse("PT33S")).build(); final DummyFileAttributes attrs = new DummyFileAttributes(); @@ -65,7 +65,7 @@ public void testAcceptsIfFileAgeExceedsDuration() { } @Test - public void testDoesNotAcceptIfFileAgeLessThanDuration() { + void testDoesNotAcceptIfFileAgeLessThanDuration() { final IfLastModified filter = IfLastModified.newBuilder().setAge(Duration.parse("PT33S")).build(); final DummyFileAttributes attrs = new DummyFileAttributes(); @@ -75,7 +75,7 @@ public void testDoesNotAcceptIfFileAgeLessThanDuration() { } @Test - public void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { + void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { final CountingCondition counter = new CountingCondition(true); final IfLastModified filter = IfLastModified.newBuilder() .setAge(Duration.parse("PT33S")) @@ -103,7 +103,7 @@ public void testAcceptCallsNestedConditionsOnlyIfPathAccepted() { } @Test - public void testBeforeTreeWalk() { + void testBeforeTreeWalk() { final CountingCondition counter = new CountingCondition(true); final IfLastModified filter = IfLastModified.newBuilder() .setAge(Duration.parse("PT33S")) @@ -114,7 +114,7 @@ public void testBeforeTreeWalk() { } @Test - public void testCreateAgeConditionCalledProgrammaticallyThrowsNPEWhenAgeIsNotSpecified() { + void testCreateAgeConditionCalledProgrammaticallyThrowsNPEWhenAgeIsNotSpecified() { Duration age = null; assertThrows( NullPointerException.class, () -> IfLastModified.newBuilder().setAge(age)); @@ -122,7 +122,7 @@ public void testCreateAgeConditionCalledProgrammaticallyThrowsNPEWhenAgeIsNotSpe @ParameterizedTest @ValueSource(strings = "No age provided for IfLastModified") - public void testCreateAgeConditionCalledByPluginBuilderReturnsNullAndLogsMessageWhenAgeIsNotSpecified( + void testCreateAgeConditionCalledByPluginBuilderReturnsNullAndLogsMessageWhenAgeIsNotSpecified( final String expectedMessage) { final PluginEntry nullEntry = null; final PluginType type = new PluginType<>(nullEntry, IfLastModified.class, "Dummy"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfNotTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfNotTest.java index 2398fb2a501..43637e4d4e2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfNotTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/IfNotTest.java @@ -42,7 +42,7 @@ class IfNotTest { @Test - public void test() { + void test() { assertTrue(new FixedCondition(true).accept(null, null, null)); assertFalse(IfNot.createNotCondition(new FixedCondition(true)).accept(null, null, null)); @@ -51,13 +51,13 @@ public void test() { } @Test - public void testEmptyIsFalse() { + void testEmptyIsFalse() { assertThrows( NullPointerException.class, () -> IfNot.createNotCondition(null).accept(null, null, null)); } @Test - public void testBeforeTreeWalk() { + void testBeforeTreeWalk() { final CountingCondition counter = new CountingCondition(true); final IfNot not = IfNot.createNotCondition(counter); not.beforeFileTreeWalk(); @@ -65,14 +65,14 @@ public void testBeforeTreeWalk() { } @Test - public void testCreateNotConditionCalledProgrammaticallyThrowsNPEWhenToNegateIsNotSpecified() { + void testCreateNotConditionCalledProgrammaticallyThrowsNPEWhenToNegateIsNotSpecified() { PathCondition toNegate = null; assertThrows(NullPointerException.class, () -> IfNot.createNotCondition(toNegate)); } @ParameterizedTest @ValueSource(strings = "No condition provided for IfNot") - public void testCreateNotConditionCalledByPluginBuilderReturnsNullAndLogsMessageWhenToNegateIsNotSpecified( + void testCreateNotConditionCalledByPluginBuilderReturnsNullAndLogsMessageWhenToNegateIsNotSpecified( final String expectedMessage) { final PluginEntry nullEntry = null; final PluginType type = new PluginType<>(nullEntry, IfNot.class, "Dummy"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathConditionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathConditionTest.java index 823258c2080..5b735c2bd2b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathConditionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathConditionTest.java @@ -16,19 +16,19 @@ */ package org.apache.logging.log4j.core.appender.rolling.action; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; -public class PathConditionTest { +class PathConditionTest { private static final PathCondition[] EMPTY_FIXTURE = {}; private static final PathCondition[] NULL_FIXTURE = null; @Test - public void testCopy() { + void testCopy() { assertArrayEquals(EMPTY_FIXTURE, PathCondition.copy(NULL_FIXTURE)); assertArrayEquals(EMPTY_FIXTURE, PathCondition.copy(EMPTY_FIXTURE)); assertArrayEquals(EMPTY_FIXTURE, PathCondition.copy(PathCondition.EMPTY_ARRAY)); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathSortByModificationTimeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathSortByModificationTimeTest.java index 8c023998550..5e3abad830f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathSortByModificationTimeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/PathSortByModificationTimeTest.java @@ -29,20 +29,20 @@ /** * Tests the {@code PathSortByModificationTime} class. */ -public class PathSortByModificationTimeTest { +class PathSortByModificationTimeTest { /** * Test method for * {@link org.apache.logging.log4j.core.appender.rolling.action.PathSortByModificationTime#isRecentFirst()}. */ @Test - public void testIsRecentFirstReturnsConstructorValue() { + void testIsRecentFirstReturnsConstructorValue() { assertTrue(((PathSortByModificationTime) PathSortByModificationTime.createSorter(true)).isRecentFirst()); assertFalse(((PathSortByModificationTime) PathSortByModificationTime.createSorter(false)).isRecentFirst()); } @Test - public void testCompareRecentFirst() { + void testCompareRecentFirst() { final PathSorter sorter = PathSortByModificationTime.createSorter(true); final Path p1 = Paths.get("aaa"); final Path p2 = Paths.get("bbb"); @@ -65,7 +65,7 @@ public void testCompareRecentFirst() { } @Test - public void testCompareRecentLast() { + void testCompareRecentLast() { final PathSorter sorter = PathSortByModificationTime.createSorter(false); final Path p1 = Paths.get("aaa"); final Path p2 = Paths.get("bbb"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/ScriptConditionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/ScriptConditionTest.java index fcbc287a960..2361202f7ff 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/ScriptConditionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/ScriptConditionTest.java @@ -38,34 +38,34 @@ * Tests the ScriptCondition class. */ @SetSystemProperty(key = Constants.SCRIPT_LANGUAGES, value = "js, javascript, groovy") -public class ScriptConditionTest { +class ScriptConditionTest { @Test - public void testConstructorDisallowsNullScript() { + void testConstructorDisallowsNullScript() { assertNull(ScriptCondition.createCondition(null, new DefaultConfiguration())); } @Test - public void testConstructorDisallowsNullConfig() { + void testConstructorDisallowsNullConfig() { assertThrows( NullPointerException.class, () -> ScriptCondition.createCondition(new Script("test", "js", "print('hi')"), null)); } @Test - public void testCreateConditionReturnsNullForNullScript() { + void testCreateConditionReturnsNullForNullScript() { assertNull(ScriptCondition.createCondition(null, new DefaultConfiguration())); } @Test - public void testCreateConditionDisallowsNullConfig() { + void testCreateConditionDisallowsNullConfig() { assertThrows( NullPointerException.class, () -> ScriptCondition.createCondition(new Script("test", "js", "print('hi')"), null)); } @Test - public void testSelectFilesToDelete() { + void testSelectFilesToDelete() { final Configuration config = new DefaultConfiguration(); config.initialize(); // creates the ScriptManager @@ -78,7 +78,7 @@ public void testSelectFilesToDelete() { } @Test - public void testSelectFilesToDelete2() { + void testSelectFilesToDelete2() { final Configuration config = new DefaultConfiguration(); config.initialize(); // creates the ScriptManager @@ -101,7 +101,7 @@ public void testSelectFilesToDelete2() { @Test @Tag("groovy") - public void testSelectFilesToDelete3() { + void testSelectFilesToDelete3() { final Configuration config = new DefaultConfiguration(); config.initialize(); // creates the ScriptManager diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/SortingVisitorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/SortingVisitorTest.java index 29ab4089b36..a6e854525ae 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/SortingVisitorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/SortingVisitorTest.java @@ -39,7 +39,7 @@ /** * Tests the SortingVisitor class. */ -public class SortingVisitorTest { +class SortingVisitorTest { @TempDir Path base; @@ -49,7 +49,7 @@ public class SortingVisitorTest { private Path ccc; @BeforeEach - public void setUp() throws Exception { + void setUp() throws Exception { aaa = Files.createFile(base.resolve("aaa")); bbb = Files.createFile(base.resolve("bbb")); ccc = Files.createFile(base.resolve("ccc")); @@ -62,7 +62,7 @@ public void setUp() throws Exception { } @Test - public void testRecentFirst() throws Exception { + void testRecentFirst() throws Exception { final SortingVisitor visitor = new SortingVisitor(new PathSortByModificationTime(true)); final Set options = Collections.emptySet(); Files.walkFileTree(base, options, 1, visitor); @@ -76,7 +76,7 @@ public void testRecentFirst() throws Exception { } @Test - public void testRecentLast() throws Exception { + void testRecentLast() throws Exception { final SortingVisitor visitor = new SortingVisitor(new PathSortByModificationTime(false)); final Set options = Collections.emptySet(); Files.walkFileTree(base, options, 1, visitor); @@ -90,7 +90,7 @@ public void testRecentLast() throws Exception { } @Test - public void testNoSuchFileFailure() throws IOException { + void testNoSuchFileFailure() throws IOException { final SortingVisitor visitor = new SortingVisitor(new PathSortByModificationTime(false)); assertSame( FileVisitResult.CONTINUE, @@ -98,7 +98,7 @@ public void testNoSuchFileFailure() throws IOException { } @Test - public void testIOException() { + void testIOException() { final SortingVisitor visitor = new SortingVisitor(new PathSortByModificationTime(false)); final IOException exception = new IOException(); assertSame( diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppender2Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppender2Test.java index 2b53e9e6ce7..f57db401175 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppender2Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppender2Test.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core.appender.routing; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -47,7 +48,7 @@ public void routingTest() { EventLogger.logEvent(msg); final List list = loggerContextRule.getListAppender("List").getEvents(); assertNotNull("No events generated", list); - assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1); + assertEquals("Incorrect number of events. Expected 1, got " + list.size(), 1, list.size()); msg = new StructuredDataMessage("Test", "This is a test", "Unknown"); EventLogger.logEvent(msg); final File file = new File(LOG_FILENAME); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppenderTest.java index b4dcf13494f..886848078c5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/JsonRoutingAppenderTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core.appender.routing; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -47,7 +48,7 @@ public void routingTest() { EventLogger.logEvent(msg); final List list = loggerContextRule.getListAppender("List").getEvents(); assertNotNull("No events generated", list); - assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1); + assertEquals("Incorrect number of events. Expected 1, got " + list.size(), 1, list.size()); msg = new StructuredDataMessage("Test", "This is a test", "Unknown"); EventLogger.logEvent(msg); final File file = new File(LOG_FILENAME); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/PropertiesRoutingAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/PropertiesRoutingAppenderTest.java index 8c39e5ce852..76c68ed7849 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/PropertiesRoutingAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/PropertiesRoutingAppenderTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core.appender.routing; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -49,12 +50,12 @@ public class PropertiesRoutingAppenderTest { public RuleChain rules = loggerContextRule.withCleanFilesRule(UNKNOWN_LOG_FILE, ALERT_LOG_FILE, ACTIVITY_LOG_FILE); @Before - public void setUp() throws Exception { + public void setUp() { this.app = this.loggerContextRule.getListAppender("List"); } @After - public void tearDown() throws Exception { + public void tearDown() { this.app.clear(); this.loggerContextRule.getLoggerContext().stop(); } @@ -65,7 +66,7 @@ public void routingTest() { EventLogger.logEvent(msg); final List list = app.getEvents(); assertNotNull("No events generated", list); - assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1); + assertEquals("Incorrect number of events. Expected 1, got " + list.size(), 1, list.size()); msg = new StructuredDataMessage("Test", "This is a test", "Alert"); EventLogger.logEvent(msg); File file = new File(ALERT_LOG_FILE); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender2767Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender2767Test.java index f1f1a588b15..63666788982 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender2767Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender2767Test.java @@ -45,10 +45,10 @@ public class RoutingAppender2767Test { public RuleChain rules = loggerContextRule.withCleanFilesRule(ACTIVITY_LOG_FILE); @Before - public void setUp() throws Exception {} + public void setUp() {} @After - public void tearDown() throws Exception { + public void tearDown() { this.loggerContextRule.getLoggerContext().stop(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender3350Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender3350Test.java index e2ad0871bdc..cbacf056b84 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender3350Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppender3350Test.java @@ -43,7 +43,7 @@ public class RoutingAppender3350Test { public RuleChain rules = loggerContextRule.withCleanFilesRule(LOG_FILE); @After - public void tearDown() throws Exception { + public void tearDown() { this.loggerContextRule.getLoggerContext().stop(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderKeyLookupEvaluationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderKeyLookupEvaluationTest.java index f38013658b7..e44ffc0eaed 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderKeyLookupEvaluationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderKeyLookupEvaluationTest.java @@ -38,13 +38,13 @@ public class RoutingAppenderKeyLookupEvaluationTest { public final LoggerContextRule loggerContextRule = new LoggerContextRule(CONFIG); @Before - public void setUp() throws Exception { + public void setUp() { ThreadContext.remove(KEY); this.app = this.loggerContextRule.getListAppender("List"); } @After - public void tearDown() throws Exception { + public void tearDown() { this.app.clear(); this.loggerContextRule.getLoggerContext().stop(); ThreadContext.remove(KEY); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderTest.java index d69912f9215..eaaa3255e39 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core.appender.routing; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -49,12 +50,12 @@ public class RoutingAppenderTest { public RuleChain rules = loggerContextRule.withCleanFilesRule(UNKNOWN_LOG_FILE, ALERT_LOG_FILE, ACTIVITY_LOG_FILE); @Before - public void setUp() throws Exception { + public void setUp() { this.app = this.loggerContextRule.getListAppender("List"); } @After - public void tearDown() throws Exception { + public void tearDown() { this.app.clear(); this.loggerContextRule.getLoggerContext().stop(); } @@ -65,7 +66,7 @@ public void routingTest() { EventLogger.logEvent(msg); final List list = app.getEvents(); assertNotNull("No events generated", list); - assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1); + assertEquals("Incorrect number of events. Expected 1, got " + list.size(), 1, list.size()); msg = new StructuredDataMessage("Test", "This is a test", "Alert"); EventLogger.logEvent(msg); File file = new File(ALERT_LOG_FILE); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithJndiTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithJndiTest.java index aa951efbb8e..0d7f8d83009 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithJndiTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithJndiTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core.appender.routing; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -59,7 +60,7 @@ private static Map initBindings() { } @Before - public void before() throws NamingException { + public void before() { listAppender1 = RoutingAppenderWithJndiTest.loggerContextRule.getListAppender("List1"); listAppender2 = RoutingAppenderWithJndiTest.loggerContextRule.getListAppender("List2"); } @@ -91,10 +92,11 @@ public void routingTest() throws NamingException { msg = new StructuredDataMessage("Test", "This is a message from Application1", "Context"); EventLogger.logEvent(msg); assertNotNull("No events generated", listAppender1.getEvents()); - assertTrue( + assertEquals( "Incorrect number of events. Expected 1, got " + listAppender1.getEvents().size(), - listAppender1.getEvents().size() == 1); + 1, + listAppender1.getEvents().size()); // now set jndi resource to Application2 context.rebind(JNDI_CONTEXT_NAME, "Application2"); @@ -102,26 +104,30 @@ public void routingTest() throws NamingException { msg = new StructuredDataMessage("Test", "This is a message from Application2", "Context"); EventLogger.logEvent(msg); assertNotNull("No events generated", listAppender2.getEvents()); - assertTrue( + assertEquals( "Incorrect number of events. Expected 1, got " + listAppender2.getEvents().size(), - listAppender2.getEvents().size() == 1); - assertTrue( + 1, + listAppender2.getEvents().size()); + assertEquals( "Incorrect number of events. Expected 1, got " + listAppender1.getEvents().size(), - listAppender1.getEvents().size() == 1); + 1, + listAppender1.getEvents().size()); msg = new StructuredDataMessage("Test", "This is another message from Application2", "Context"); EventLogger.logEvent(msg); assertNotNull("No events generated", listAppender2.getEvents()); - assertTrue( + assertEquals( "Incorrect number of events. Expected 2, got " + listAppender2.getEvents().size(), - listAppender2.getEvents().size() == 2); - assertTrue( + 2, + listAppender2.getEvents().size()); + assertEquals( "Incorrect number of events. Expected 1, got " + listAppender1.getEvents().size(), - listAppender1.getEvents().size() == 1); + 1, + listAppender1.getEvents().size()); // now set jndi resource to Application3. // The context name, 'Application3', will be used as log file name by the default route. diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithPurgingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithPurgingTest.java index f0b760dab5b..9d40d070e2b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithPurgingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingAppenderWithPurgingTest.java @@ -60,7 +60,7 @@ public class RoutingAppenderWithPurgingTest { IDLE_LOG_FILE1, IDLE_LOG_FILE2, IDLE_LOG_FILE3, MANUAL_LOG_FILE1, MANUAL_LOG_FILE2, MANUAL_LOG_FILE3); @Before - public void setUp() throws Exception { + public void setUp() { this.app = this.loggerContextRule.getListAppender("List"); this.routingAppenderIdle = this.loggerContextRule.getRequiredAppender("RoutingPurgeIdle", RoutingAppender.class); @@ -71,7 +71,7 @@ public void setUp() throws Exception { } @After - public void tearDown() throws Exception { + public void tearDown() { this.app.clear(); this.loggerContextRule.getLoggerContext().stop(); } @@ -82,7 +82,7 @@ public void routingTest() throws InterruptedException { EventLogger.logEvent(msg); final List list = app.getEvents(); assertNotNull("No events generated", list); - assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1); + assertEquals("Incorrect number of events. Expected 1, got " + list.size(), 1, list.size()); msg = new StructuredDataMessage("2", "This is a test 2", "Service"); EventLogger.logEvent(msg); msg = new StructuredDataMessage("3", "This is a test 3", "Service"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingDefaultAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingDefaultAppenderTest.java index 4d0c7ce3a8a..91eca1321f0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingDefaultAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/routing/RoutingDefaultAppenderTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.core.appender.routing; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -46,7 +47,7 @@ public void routingTest() { EventLogger.logEvent(msg); final List list = loggerContextRule.getListAppender("List").getEvents(); assertNotNull("No events generated", list); - assertTrue("Incorrect number of events. Expected 1, got " + list.size(), list.size() == 1); + assertEquals("Incorrect number of events. Expected 1, got " + list.size(), 1, list.size()); msg = new StructuredDataMessage("Test", "This is a test", "Alert"); EventLogger.logEvent(msg); final File file = new File(LOG_FILE); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncAppenderExceptionHandlingTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncAppenderExceptionHandlingTest.java index db9fad8e88b..430739b225f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncAppenderExceptionHandlingTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncAppenderExceptionHandlingTest.java @@ -16,6 +16,10 @@ */ package org.apache.logging.log4j.core.async; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -30,7 +34,6 @@ import org.apache.logging.log4j.core.test.appender.FailOnceAppender; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.util.Strings; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -74,18 +77,18 @@ void AsyncAppender_should_not_stop_on_appender_failures(final String throwableCl // Stop the AsyncAppender to drain the queued events. final Configuration configuration = loggerContext.getConfiguration(); final AsyncAppender asyncAppender = configuration.getAppender("Async"); - Assertions.assertNotNull(asyncAppender, "couldn't obtain the FailOnceAppender"); + assertNotNull(asyncAppender, "couldn't obtain the FailOnceAppender"); asyncAppender.stop(); // Verify the logged message. final FailOnceAppender failOnceAppender = configuration.getAppender("FailOnce"); - Assertions.assertNotNull(failOnceAppender, "couldn't obtain the FailOnceAppender"); - Assertions.assertTrue(failOnceAppender.isFailed(), "FailOnceAppender hasn't failed yet"); + assertNotNull(failOnceAppender, "couldn't obtain the FailOnceAppender"); + assertTrue(failOnceAppender.isFailed(), "FailOnceAppender hasn't failed yet"); final List accumulatedMessages = failOnceAppender.drainEvents().stream() .map(LogEvent::getMessage) .map(Message::getFormattedMessage) .collect(Collectors.toList()); - Assertions.assertEquals(Collections.singletonList(lastLogMessage), accumulatedMessages); + assertEquals(Collections.singletonList(lastLogMessage), accumulatedMessages); } finally { System.setProperty(throwableClassNamePropertyName, Strings.EMPTY); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerArgumentFreedOnErrorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerArgumentFreedOnErrorTest.java index 7dd54b7f761..9a4c9c7c8f6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerArgumentFreedOnErrorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerArgumentFreedOnErrorTest.java @@ -20,16 +20,16 @@ import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.test.junit.UsingStatusListener; import org.apache.logging.log4j.util.StringBuilderFormattable; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junitpioneer.jupiter.SetSystemProperty; -@Category(AsyncLoggers.class) +@Tag(Tags.ASYNC_LOGGERS) class AsyncLoggerArgumentFreedOnErrorTest { /** diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerClassLoadDeadlockTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerClassLoadDeadlockTest.java index 2cec75e28ba..7a5301e757e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerClassLoadDeadlockTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerClassLoadDeadlockTest.java @@ -16,31 +16,34 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; /** * Test class loading deadlock condition from the LOG4J2-1457 */ -@Category(AsyncLoggers.class) -public class AsyncLoggerClassLoadDeadlockTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerClassLoadDeadlockTest { static final int RING_BUFFER_SIZE = 128; - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); System.setProperty("AsyncLogger.RingBufferSize", String.valueOf(RING_BUFFER_SIZE)); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConsoleTest.xml"); } - @Test(timeout = 30000) - public void testClassLoaderDeadlock() throws Exception { + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + void testClassLoaderDeadlock() { // touch the class so static init will be called final AsyncLoggerClassLoadDeadlock temp = new AsyncLoggerClassLoadDeadlock(); assertNotNull(temp); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigAutoFlushTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigAutoFlushTest.java index a2e909ac93a..d79ec54848e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigAutoFlushTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigAutoFlushTest.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -26,23 +26,23 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerConfigAutoFlushTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerConfigAutoFlushTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigAutoFlushTest.xml"); } @Test - public void testFlushAtEndOfBatch() throws Exception { + void testFlushAtEndOfBatch() throws Exception { final File file = new File("target", "AsyncLoggerConfigAutoFlushTest.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"); final String msg = "Message flushed with immediate flush=false"; @@ -52,7 +52,7 @@ public void testFlushAtEndOfBatch() throws Exception { final String line1 = reader.readLine(); reader.close(); file.delete(); - assertNotNull("line1", line1); - assertTrue("line1 correct", line1.contains(msg)); + assertNotNull(line1, "line1"); + assertTrue(line1.contains(msg), "line1 correct"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigErrorOnFormat.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigErrorOnFormat.java index 58020a8115d..b137fdba80a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigErrorOnFormat.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigErrorOnFormat.java @@ -16,10 +16,10 @@ */ package org.apache.logging.log4j.core.async; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -29,35 +29,35 @@ import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.impl.DefaultLogEventFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.message.AsynchronouslyFormattable; import org.apache.logging.log4j.message.Message; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerConfigErrorOnFormat { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerConfigErrorOnFormat { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty("log4j2.enableThreadlocals", "true"); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigErrorOnFormat.xml"); // Log4jLogEvent.toString invokes message.toString System.setProperty("log4j2.logEventFactory", DefaultLogEventFactory.class.getName()); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.clearProperty("log4j2.enableThreadlocals"); System.clearProperty("log4j2.logEventFactory"); } @Test - public void testError() throws Exception { + void testError() throws Exception { final File file = new File("target", "AsyncLoggerConfigErrorOnFormat.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"); log.info(new ThrowsErrorOnFormatMessage()); @@ -71,7 +71,7 @@ public void testError() throws Exception { file.delete(); assertThat(line1, containsString("Second message")); - assertNull("Expected only one line", line2); + assertNull(line2, "Expected only one line"); } @AsynchronouslyFormattable // Shouldn't call getFormattedMessage early diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest.java index ef15d5fe45a..77643204302 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest.java @@ -48,7 +48,7 @@ @Tag(Tags.ASYNC_LOGGERS) @UsingStatusListener -public class AsyncLoggerConfigTest { +class AsyncLoggerConfigTest { private static final String FQCN = AsyncLoggerConfigTest.class.getName(); @@ -57,7 +57,7 @@ public class AsyncLoggerConfigTest { @Test @LoggerContextSource - public void testAdditivity(final LoggerContext context) throws Exception { + void testAdditivity(final LoggerContext context) throws Exception { final Path file = loggingPath.resolve("AsyncLoggerConfigTest.log"); assertThat(file).isEmptyFile(); @@ -79,7 +79,7 @@ public void testAdditivity(final LoggerContext context) throws Exception { } @Test - public void testIncludeLocationDefaultsToFalse() { + void testIncludeLocationDefaultsToFalse() { final Configuration configuration = new NullConfiguration(); final LoggerConfig rootLoggerConfig = RootLogger.newAsyncRootBuilder().withConfig(configuration).build(); @@ -93,7 +93,7 @@ public void testIncludeLocationDefaultsToFalse() { } @Test - public void testSingleFilterInvocation() { + void testSingleFilterInvocation() { final Configuration configuration = new NullConfiguration(); final Filter filter = mock(Filter.class); final LoggerConfig config = AsyncLoggerConfig.newAsyncBuilder() diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest2.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest2.java index 4b5fdcf8531..1de174cfd29 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest2.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest2.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -27,18 +27,18 @@ import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerConfigTest2 { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerConfigTest2 { @Test - public void testConsecutiveReconfigure() throws Exception { + void testConsecutiveReconfigure() throws Exception { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest2.xml"); final File file = new File("target", "AsyncLoggerConfigTest2.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"); final String msg = "Message before reconfig"; @@ -57,9 +57,9 @@ public void testConsecutiveReconfigure() throws Exception { final String line2 = reader.readLine(); reader.close(); file.delete(); - assertNotNull("line1", line1); - assertNotNull("line2", line2); - assertTrue("line1 " + line1, line1.contains(msg)); - assertTrue("line2 " + line2, line2.contains(msg2)); + assertNotNull(line1, "line1"); + assertNotNull(line2, "line2"); + assertTrue(line1.contains(msg), "line1 " + line1); + assertTrue(line2.contains(msg2), "line2 " + line2); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigUseAfterShutdownTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigUseAfterShutdownTest.java index 04f653ceeff..6fe6cc2c5ec 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigUseAfterShutdownTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigUseAfterShutdownTest.java @@ -21,23 +21,23 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.spi.AbstractLogger; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerConfigUseAfterShutdownTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerConfigUseAfterShutdownTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest.xml"); } @Test - public void testNoErrorIfLogAfterShutdown() throws Exception { + void testNoErrorIfLogAfterShutdown() { final Logger log = LogManager.getLogger("com.foo.Bar"); log.info("some message"); CoreLoggerContexts.stopLoggerContext(); // stop async thread diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigWithAsyncEnabledTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigWithAsyncEnabledTest.java index aca4f73456a..0c060d3cb5e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigWithAsyncEnabledTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigWithAsyncEnabledTest.java @@ -16,9 +16,9 @@ */ package org.apache.logging.log4j.core.async; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -27,33 +27,33 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerConfigWithAsyncEnabledTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerConfigWithAsyncEnabledTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty("log4j2.enableThreadlocals", "true"); System.setProperty("log4j2.contextSelector", AsyncLoggerContextSelector.class.getCanonicalName()); // Reuse the configuration from AsyncLoggerConfigTest4 System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest4.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.clearProperty("log4j2.enableThreadlocals"); System.clearProperty("log4j2.contextSelector"); } @Test - public void testParametersAreAvailableToLayout() throws Exception { + void testParametersAreAvailableToLayout() throws Exception { final File file = new File("target", "AsyncLoggerConfigTest4.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"); final String format = "Additive logging: {} for the price of {}!"; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java index bff6099b43c..c82c054ddc6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorInitialStateTest.java @@ -16,17 +16,17 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerContextSelectorInitialStateTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerContextSelectorInitialStateTest { @Test - public void testLoggerContextsListInitiallyEmpty() { + void testLoggerContextsListInitiallyEmpty() { final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector(); assertTrue(selector.getLoggerContexts().isEmpty()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java index c7fbc9c90fa..9079a1a6736 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextSelectorTest.java @@ -16,48 +16,49 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerContextSelectorTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerContextSelectorTest { private static final String FQCN = AsyncLoggerContextSelectorTest.class.getName(); @Test - public void testContextReturnsAsyncLoggerContext() { + void testContextReturnsAsyncLoggerContext() { final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector(); final LoggerContext context = selector.getContext(FQCN, null, false); - assertTrue(context instanceof AsyncLoggerContext); + assertInstanceOf(AsyncLoggerContext.class, context); } @Test - public void testContext2ReturnsAsyncLoggerContext() { + void testContext2ReturnsAsyncLoggerContext() { final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector(); final LoggerContext context = selector.getContext(FQCN, null, false, null); - assertTrue(context instanceof AsyncLoggerContext); + assertInstanceOf(AsyncLoggerContext.class, context); } @Test - public void testLoggerContextsReturnsAsyncLoggerContext() { + void testLoggerContextsReturnsAsyncLoggerContext() { final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector(); selector.getContext(FQCN, null, false); final List list = selector.getLoggerContexts(); assertEquals(1, list.size()); - assertTrue(list.get(0) instanceof AsyncLoggerContext); + assertInstanceOf(AsyncLoggerContext.class, list.get(0)); } @Test - public void testContextNameIsAsyncLoggerContextWithClassHashCode() { + void testContextNameIsAsyncLoggerContextWithClassHashCode() { final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector(); final LoggerContext context = selector.getContext(FQCN, null, false); final int hash = getClass().getClassLoader().hashCode(); @@ -66,7 +67,7 @@ public void testContextNameIsAsyncLoggerContextWithClassHashCode() { } @Test - public void testDependentOnClassLoader() { + void testDependentOnClassLoader() { final AsyncLoggerContextSelector selector = new AsyncLoggerContextSelector(); assertTrue(selector.isClassLoaderDependent()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextTest.java index 82ee87d0123..00bb100d797 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerContextTest.java @@ -20,14 +20,14 @@ import static org.mockito.Mockito.mock; import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.message.MessageFactory; import org.apache.logging.log4j.message.MessageFactory2; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; -@Category(AsyncLoggers.class) +@Tag(Tags.ASYNC_LOGGERS) class AsyncLoggerContextTest { @Test diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerCustomSelectorLocationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerCustomSelectorLocationTest.java index 504b382b11f..a9226ed2c2f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerCustomSelectorLocationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerCustomSelectorLocationTest.java @@ -33,19 +33,19 @@ import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.selector.ContextSelector; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerCustomSelectorLocationTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerCustomSelectorLocationTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { final File file = new File("target", "AsyncLoggerCustomSelectorLocationTest.log"); file.delete(); System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, CustomAsyncContextSelector.class.getName()); @@ -53,13 +53,13 @@ public static void beforeClass() { ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerCustomSelectorLocationTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testCustomAsyncSelectorLocation() throws Exception { + void testCustomAsyncSelectorLocation() throws Exception { final File file = new File("target", "AsyncLoggerCustomSelectorLocationTest.log"); final Logger log = LogManager.getLogger("com.foo.Bar"); final Logger logIncludingLocation = LogManager.getLogger("com.include.location.Bar"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerDefaultLocationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerDefaultLocationTest.java index 32acaab3f07..2a2ec4592f5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerDefaultLocationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerDefaultLocationTest.java @@ -16,10 +16,10 @@ */ package org.apache.logging.log4j.core.async; -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.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -27,29 +27,29 @@ import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.appender.ListAppender; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerDefaultLocationTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerDefaultLocationTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerDefaultLocationTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testAsyncLogWritesToLog() throws Exception { + void testAsyncLogWritesToLog() { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final ListAppender app = context.getConfiguration().getAppender("List"); assertNotNull(app); @@ -59,7 +59,7 @@ public void testAsyncLogWritesToLog() throws Exception { context.stop(); assertEquals(1, app.getEvents().size()); final LogEvent event = app.getEvents().get(0); - assertFalse("includeLocation should be false", event.isIncludeLocation()); - assertNull("Location data should not be present", event.getSource()); + assertFalse(event.isIncludeLocation(), "includeLocation should be false"); + assertNull(event.getSource(), "Location data should not be present"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java index 1c3fdf90714..438d0ef7288 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerEventTranslationExceptionTest.java @@ -26,14 +26,14 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.message.ReusableSimpleMessage; import org.apache.logging.log4j.spi.AbstractLogger; -import org.junit.experimental.categories.Category; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** @@ -43,17 +43,17 @@ * * @see LOG4J2-2816 */ -@Category(AsyncLoggers.class) +@Tag(Tags.ASYNC_LOGGERS) class AsyncLoggerEventTranslationExceptionTest { @BeforeAll - public static void beforeAll() { + static void beforeAll() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty("AsyncLogger.ExceptionHandler", TestExceptionHandler.class.getName()); } @AfterAll - public static void afterAll() { + static void afterAll() { System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR); System.clearProperty("AsyncLogger.ExceptionHandler"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerLocationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerLocationTest.java index 562a4a7d37c..c173a9ac2bc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerLocationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerLocationTest.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -26,19 +26,19 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerLocationTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerLocationTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { final File file = new File("target", "AsyncLoggerLocationTest.log"); file.delete(); @@ -46,13 +46,13 @@ public static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerLocationTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testAsyncLogWritesToLog() throws Exception { + void testAsyncLogWritesToLog() throws Exception { final File file = new File("target", "AsyncLoggerLocationTest.log"); // System.out.println(f.getAbsolutePath()); final Logger log = LogManager.getLogger("com.foo.Bar"); @@ -64,10 +64,10 @@ public void testAsyncLogWritesToLog() throws Exception { final String line1 = reader.readLine(); reader.close(); file.delete(); - assertNotNull("line1", line1); - assertTrue("line1 correct", line1.contains(msg)); + assertNotNull(line1, "line1"); + assertTrue(line1.contains(msg), "line1 correct"); final String location = "testAsyncLogWritesToLog"; - assertTrue("has location", line1.contains(location)); + assertTrue(line1.contains(location), "has location"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerNanoTimeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerNanoTimeTest.java index 617090804e9..ce579bef7aa 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerNanoTimeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerNanoTimeTest.java @@ -16,9 +16,10 @@ */ package org.apache.logging.log4j.core.async; -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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -27,39 +28,39 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.core.util.DummyNanoClock; import org.apache.logging.log4j.core.util.SystemNanoClock; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerNanoTimeTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerNanoTimeTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "NanoTimeToFileTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testAsyncLogUsesNanoTimeClock() throws Exception { + void testAsyncLogUsesNanoTimeClock() throws Exception { final File file = new File("target", "NanoTimeToFileTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); final AsyncLogger log = (AsyncLogger) LogManager.getLogger("com.foo.Bar"); final long before = System.nanoTime(); log.info("Use actual System.nanoTime()"); - assertTrue("using SystemNanoClock", log.getNanoClock() instanceof SystemNanoClock); + assertInstanceOf(SystemNanoClock.class, log.getNanoClock(), "using SystemNanoClock"); final long DUMMYNANOTIME = -53; log.getContext().getConfiguration().setNanoClock(new DummyNanoClock(DUMMYNANOTIME)); @@ -69,7 +70,7 @@ public void testAsyncLogUsesNanoTimeClock() throws Exception { log.updateConfiguration(log.getContext().getConfiguration()); log.info("Use dummy nano clock"); - assertTrue("using SystemNanoClock", log.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, log.getNanoClock(), "using SystemNanoClock"); CoreLoggerContexts.stopLoggerContext(file); // stop async thread @@ -81,13 +82,13 @@ public void testAsyncLogUsesNanoTimeClock() throws Exception { reader.close(); file.delete(); - assertNotNull("line1", line1); - assertNotNull("line2", line2); + assertNotNull(line1, "line1"); + assertNotNull(line2, "line2"); final String[] line1Parts = line1.split(" AND "); assertEquals("Use actual System.nanoTime()", line1Parts[2]); assertEquals(line1Parts[0], line1Parts[1]); final long loggedNanoTime = Long.parseLong(line1Parts[0]); - assertTrue("used system nano time", loggedNanoTime - before < TimeUnit.SECONDS.toNanos(1)); + assertTrue(loggedNanoTime - before < TimeUnit.SECONDS.toNanos(1), "used system nano time"); final String[] line2Parts = line2.split(" AND "); assertEquals("Use dummy nano clock", line2Parts[2]); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java index af4eaf0dd89..ee5db78fadb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTest.java @@ -16,8 +16,10 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -25,37 +27,37 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.core.util.DummyNanoClock; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testAsyncLogWritesToLog() throws Exception { + void testAsyncLogWritesToLog() throws Exception { final File file = new File("target", "AsyncLoggerTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); final AsyncLogger log = (AsyncLogger) LogManager.getLogger("com.foo.Bar"); - assertTrue(log.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, log.getNanoClock()); final String msg = "Async logger msg"; log.info(msg, new InternalError("this is not a real error")); @@ -65,11 +67,11 @@ public void testAsyncLogWritesToLog() throws Exception { final String line1 = reader.readLine(); reader.close(); file.delete(); - assertNotNull("line1", line1); - assertTrue("line1 correct", line1.contains(msg)); + assertNotNull(line1, "line1"); + assertTrue(line1.contains(msg), "line1 correct"); final String location = "testAsyncLogWritesToLog"; - assertTrue("no location", !line1.contains(location)); + assertFalse(line1.contains(location), "no location"); assertTrue(LogManager.getFactory().isClassLoaderDependent()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestCachedThreadName.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestCachedThreadName.java index 2e365fb46fb..aaa6089dd84 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestCachedThreadName.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestCachedThreadName.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -26,30 +26,30 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerTestCachedThreadName { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerTestCachedThreadName { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testAsyncLogUsesCachedThreadName() throws Exception { + void testAsyncLogUsesCachedThreadName() throws Exception { final File file = new File("target", "AsyncLoggerTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); @@ -67,9 +67,9 @@ public void testAsyncLogUsesCachedThreadName() throws Exception { // System.out.println(line2); reader.close(); file.delete(); - assertNotNull("line1", line1); - assertNotNull("line2", line2); - assertTrue("line1", line1.endsWith(" INFO c.f.Bar [main] Async logger msg ")); - assertTrue("line2", line2.endsWith(" INFO c.f.Bar [main] Async logger msg ")); + assertNotNull(line1, "line1"); + assertNotNull(line2, "line2"); + assertTrue(line1.endsWith(" INFO c.f.Bar [main] Async logger msg "), "line1"); + assertTrue(line2.endsWith(" INFO c.f.Bar [main] Async logger msg "), "line2"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestUncachedThreadName.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestUncachedThreadName.java index 10eb49e6d6e..12fa5b07e37 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestUncachedThreadName.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTestUncachedThreadName.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedReader; import java.io.File; @@ -26,31 +26,31 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerTestUncachedThreadName { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerTestUncachedThreadName { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty("AsyncLogger.ThreadNameStrategy", "UNCACHED"); System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testAsyncLogUsesCurrentThreadName() throws Exception { + void testAsyncLogUsesCurrentThreadName() throws Exception { final File file = new File("target", "AsyncLoggerTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); @@ -68,9 +68,9 @@ public void testAsyncLogUsesCurrentThreadName() throws Exception { // System.out.println(line2); reader.close(); file.delete(); - assertNotNull("line1", line1); - assertNotNull("line2", line2); - assertTrue("line1", line1.endsWith(" INFO c.f.Bar [main] Async logger msg ")); - assertTrue("line2", line2.endsWith(" INFO c.f.Bar [MODIFIED-THREADNAME] Async logger msg ")); + assertNotNull(line1, "line1"); + assertNotNull(line2, "line2"); + assertTrue(line1.endsWith(" INFO c.f.Bar [main] Async logger msg "), "line1"); + assertTrue(line2.endsWith(" INFO c.f.Bar [MODIFIED-THREADNAME] Async logger msg "), "line2"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadContextTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadContextTest.java index 93eb835c1c2..d7fc698a957 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadContextTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadContextTest.java @@ -39,7 +39,7 @@ @Tag(Tags.ASYNC_LOGGERS) @UsingTestProperties @UsingStatusListener -public class AsyncLoggerThreadContextTest { +class AsyncLoggerThreadContextTest { private static TestProperties props; @@ -47,13 +47,13 @@ public class AsyncLoggerThreadContextTest { private static Path loggingPath; @BeforeAll - public static void beforeClass() { + static void beforeClass() { props.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); } @Test @LoggerContextSource("AsyncLoggerThreadContextTest.xml") - public void testAsyncLogWritesToLog() throws Exception { + void testAsyncLogWritesToLog() throws Exception { final Path file = loggingPath.resolve("AsyncLoggerTest.log"); ThreadContext.push("stackvalue"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadNameStrategyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadNameStrategyTest.java index 6e1dc7e72a0..c784ac2822a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadNameStrategyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerThreadNameStrategyTest.java @@ -16,56 +16,56 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerThreadNameStrategyTest { - @After - public void after() { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerThreadNameStrategyTest { + @AfterEach + void after() { System.clearProperty("AsyncLogger.ThreadNameStrategy"); } - @Before - public void before() { + @BeforeEach + void before() { System.clearProperty("AsyncLogger.ThreadNameStrategy"); } @Test - public void testDefaultIfNotConfigured() throws Exception { + void testDefaultIfNotConfigured() { final ThreadNameCachingStrategy tns = ThreadNameCachingStrategy.create(); assertSame(ThreadNameCachingStrategy.DEFAULT_STRATEGY, tns); } @Test - public void testDefaultIfInvalidConfig() throws Exception { + void testDefaultIfInvalidConfig() { System.setProperty("AsyncLogger.ThreadNameStrategy", "\\%%InValid "); final ThreadNameCachingStrategy tns = ThreadNameCachingStrategy.create(); assertSame(ThreadNameCachingStrategy.DEFAULT_STRATEGY, tns); } @Test - public void testUseCachedThreadNameIfConfigured() throws Exception { + void testUseCachedThreadNameIfConfigured() { System.setProperty("AsyncLogger.ThreadNameStrategy", "CACHED"); final ThreadNameCachingStrategy tns = ThreadNameCachingStrategy.create(); assertSame(ThreadNameCachingStrategy.CACHED, tns); } @Test - public void testUseUncachedThreadNameIfConfigured() throws Exception { + void testUseUncachedThreadNameIfConfigured() { System.setProperty("AsyncLogger.ThreadNameStrategy", "UNCACHED"); final ThreadNameCachingStrategy tns = ThreadNameCachingStrategy.create(); assertSame(ThreadNameCachingStrategy.UNCACHED, tns); } @Test - public void testUncachedThreadNameStrategyReturnsCurrentThreadName() throws Exception { + void testUncachedThreadNameStrategyReturnsCurrentThreadName() { final String name1 = "MODIFIED-THREADNAME1"; Thread.currentThread().setName(name1); assertEquals(name1, ThreadNameCachingStrategy.UNCACHED.getThreadName()); @@ -76,7 +76,7 @@ public void testUncachedThreadNameStrategyReturnsCurrentThreadName() throws Exce } @Test - public void testCachedThreadNameStrategyReturnsCachedThreadName() throws Exception { + void testCachedThreadNameStrategyReturnsCachedThreadName() { final String original = "Original-ThreadName"; Thread.currentThread().setName(original); assertEquals(original, ThreadNameCachingStrategy.CACHED.getThreadName()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTimestampMessageTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTimestampMessageTest.java index 10fe2320660..3a50eb2ada2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTimestampMessageTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerTimestampMessageTest.java @@ -16,9 +16,9 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.BufferedReader; import java.io.File; @@ -27,7 +27,7 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Clock; import org.apache.logging.log4j.core.util.ClockFactory; import org.apache.logging.log4j.core.util.ClockFactoryTest; @@ -36,10 +36,10 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.message.TimestampMessage; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Confirms that if you log a {@link TimestampMessage} then there are no unnecessary calls to {@link Clock}. @@ -47,24 +47,24 @@ * See LOG4J2-744. *

*/ -@Category(AsyncLoggers.class) -public class AsyncLoggerTimestampMessageTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerTimestampMessageTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerTimestampMessageTest.xml"); System.setProperty(ClockFactory.PROPERTY_NAME, PoisonClock.class.getName()); } - @AfterClass - public static void afterClass() throws IllegalAccessException { + @AfterAll + static void afterClass() throws IllegalAccessException { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); ClockFactoryTest.resetClocks(); } @Test - public void testAsyncLogWritesToLog() throws Exception { + void testAsyncLogWritesToLog() throws Exception { final File file = new File("target", "AsyncLoggerTimestampMessageTest.log"); // System.out.println(f.getAbsolutePath()); @@ -80,7 +80,7 @@ public void testAsyncLogWritesToLog() throws Exception { reader.close(); file.delete(); assertNotNull(line1); - assertTrue("line1 correct", line1.equals("123456789000 Async logger msg with embedded timestamp")); + assertEquals("123456789000 Async logger msg with embedded timestamp", line1, "line1 correct"); } public static class PoisonClock implements Clock { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerUseAfterShutdownTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerUseAfterShutdownTest.java index a7c448bac4b..3c56ad55290 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerUseAfterShutdownTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerUseAfterShutdownTest.java @@ -21,35 +21,35 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.CoreLoggerContexts; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.spi.AbstractLogger; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Test for https://issues.apache.org/jira/browse/LOG4J2-639 */ -@Category(AsyncLoggers.class) -public class AsyncLoggerUseAfterShutdownTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerUseAfterShutdownTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testNoErrorIfLogAfterShutdown() throws Exception { + void testNoErrorIfLogAfterShutdown() { final Logger log = LogManager.getLogger("com.foo.Bar"); final String msg = "Async logger msg"; log.info(msg, new InternalError("this is not a real error")); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncAppenderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncAppenderTest.java index 9a0ed348177..1040b044242 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncAppenderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncAppenderTest.java @@ -37,11 +37,11 @@ key = Constants.LOG4J_CONTEXT_SELECTOR, value = "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector") @UsingStatusListener -public class AsyncLoggersWithAsyncAppenderTest { +class AsyncLoggersWithAsyncAppenderTest { @Test @LoggerContextSource - public void testLoggingWorks(final LoggerContext ctx) throws Exception { + void testLoggingWorks(final LoggerContext ctx) throws Exception { final Logger logger = ctx.getLogger(AsyncLoggersWithAsyncAppenderTest.class); logger.error("This {} a test", "is"); logger.warn("Hello {}!", "world"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncLoggerConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncLoggerConfigTest.java index a4de62f77f0..420406d965c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncLoggerConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggersWithAsyncLoggerConfigTest.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.async; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import java.util.List; import org.apache.logging.log4j.LogManager; @@ -43,12 +43,12 @@ public void testLoggingWorks() throws Exception { Thread.sleep(100); final List list = context.getListAppender("List").getMessages(); assertNotNull("No events generated", list); - assertTrue("Incorrect number of events. Expected 2, got " + list.size(), list.size() == 2); + assertEquals("Incorrect number of events. Expected 2, got " + list.size(), 2, list.size()); String msg = list.get(0); String expected = getClass().getName() + " This is a test"; - assertTrue("Expected " + expected + ", Actual " + msg, expected.equals(msg)); + assertEquals("Expected " + expected + ", Actual " + msg, expected, msg); msg = list.get(1); expected = getClass().getName() + " Hello world!"; - assertTrue("Expected " + expected + ", Actual " + msg, expected.equals(msg)); + assertEquals("Expected " + expected + ", Actual " + msg, expected, msg); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncQueueFullPolicyFactoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncQueueFullPolicyFactoryTest.java index 37f4a77c813..8a21114e6fc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncQueueFullPolicyFactoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncQueueFullPolicyFactoryTest.java @@ -17,36 +17,36 @@ package org.apache.logging.log4j.core.async; import static org.apache.logging.log4j.util.Strings.toRootLowerCase; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Tests the AsyncQueueFullPolicyFactory class. */ -@Category(AsyncLoggers.class) -public class AsyncQueueFullPolicyFactoryTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncQueueFullPolicyFactoryTest { - @Before - @After - public void resetProperties() throws Exception { + @BeforeEach + @AfterEach + void resetProperties() { System.clearProperty(AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER); System.clearProperty(AsyncQueueFullPolicyFactory.PROPERTY_NAME_DISCARDING_THRESHOLD_LEVEL); } @Test - public void testCreateReturnsDefaultRouterByDefault() throws Exception { + void testCreateReturnsDefaultRouterByDefault() { final AsyncQueueFullPolicy router = AsyncQueueFullPolicyFactory.create(); assertEquals(DefaultAsyncQueueFullPolicy.class, router.getClass()); } @Test - public void testCreateReturnsDiscardingRouterIfSpecified() throws Exception { + void testCreateReturnsDiscardingRouterIfSpecified() { System.setProperty( AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER, AsyncQueueFullPolicyFactory.PROPERTY_VALUE_DISCARDING_ASYNC_EVENT_ROUTER); @@ -70,7 +70,7 @@ public void testCreateReturnsDiscardingRouterIfSpecified() throws Exception { } @Test - public void testCreateDiscardingRouterDefaultThresholdLevelInfo() throws Exception { + void testCreateDiscardingRouterDefaultThresholdLevelInfo() { System.setProperty( AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER, AsyncQueueFullPolicyFactory.PROPERTY_VALUE_DISCARDING_ASYNC_EVENT_ROUTER); @@ -80,7 +80,7 @@ public void testCreateDiscardingRouterDefaultThresholdLevelInfo() throws Excepti } @Test - public void testCreateDiscardingRouterCaseInsensitive() { + void testCreateDiscardingRouterCaseInsensitive() { System.setProperty( AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER, toRootLowerCase(AsyncQueueFullPolicyFactory.PROPERTY_VALUE_DISCARDING_ASYNC_EVENT_ROUTER)); @@ -90,7 +90,7 @@ public void testCreateDiscardingRouterCaseInsensitive() { } @Test - public void testCreateDiscardingRouterThresholdLevelCustomizable() throws Exception { + void testCreateDiscardingRouterThresholdLevelCustomizable() { System.setProperty( AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER, AsyncQueueFullPolicyFactory.PROPERTY_VALUE_DISCARDING_ASYNC_EVENT_ROUTER); @@ -114,7 +114,7 @@ public EventRoute getRoute(final long backgroundThreadId, final Level level) { public static class DoesNotImplementInterface {} @Test - public void testCreateReturnsCustomRouterIfSpecified() throws Exception { + void testCreateReturnsCustomRouterIfSpecified() { System.setProperty( AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER, CustomRouterDefaultConstructor.class.getName()); @@ -124,7 +124,7 @@ public void testCreateReturnsCustomRouterIfSpecified() throws Exception { } @Test - public void testCreateReturnsDefaultRouterIfSpecifiedCustomRouterFails() throws Exception { + void testCreateReturnsDefaultRouterIfSpecifiedCustomRouterFails() { System.setProperty( AsyncQueueFullPolicyFactory.PROPERTY_NAME_ASYNC_EVENT_ROUTER, DoesNotImplementInterface.class.getName()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncRootLoggerDefaultLocationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncRootLoggerDefaultLocationTest.java index 8c7ca12e99c..e10c5e36bf5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncRootLoggerDefaultLocationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncRootLoggerDefaultLocationTest.java @@ -16,10 +16,10 @@ */ package org.apache.logging.log4j.core.async; -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.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -27,29 +27,29 @@ import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.test.appender.ListAppender; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncRootLoggerDefaultLocationTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncRootLoggerDefaultLocationTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncRootLoggerDefaultLocationTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testAsyncLogWritesToLog() throws Exception { + void testAsyncLogWritesToLog() { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final ListAppender app = context.getConfiguration().getAppender("List"); assertNotNull(app); @@ -59,7 +59,7 @@ public void testAsyncLogWritesToLog() throws Exception { context.stop(); assertEquals(1, app.getEvents().size()); final LogEvent event = app.getEvents().get(0); - assertFalse("includeLocation should be false", event.isIncludeLocation()); - assertNull("Location data should not be present", event.getSource()); + assertFalse(event.isIncludeLocation(), "includeLocation should be false"); + assertNull(event.getSource(), "Location data should not be present"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigGlobalLoggersTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigGlobalLoggersTest.java index eb7b2e18aeb..ed12038e3d5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigGlobalLoggersTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigGlobalLoggersTest.java @@ -23,33 +23,33 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncWaitStrategyFactoryConfigGlobalLoggersTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncWaitStrategyFactoryConfigGlobalLoggersTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty( ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncWaitStrategyFactoryConfigGlobalLoggerTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR); System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); } - @Ignore("This test succeeds when run individually but fails when run by Surefire with all other tests") + @Disabled("This test succeeds when run individually but fails when run by Surefire with all other tests") @Test - public void testConfigWaitStrategyAndFactory() throws Exception { + void testConfigWaitStrategyAndFactory() { final AsyncLogger logger = (AsyncLogger) LogManager.getLogger("com.foo.Bar"); final LoggerContext context = (LoggerContext) LogManager.getContext(false); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigTest.java index bdc2bad1b14..11072a2e8ba 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryConfigTest.java @@ -17,25 +17,25 @@ package org.apache.logging.log4j.core.async; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import com.lmax.disruptor.WaitStrategy; import com.lmax.disruptor.YieldingWaitStrategy; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.test.appender.ListAppender; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; import org.apache.logging.log4j.core.test.junit.LoggerContextSource; import org.apache.logging.log4j.core.test.junit.Named; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncWaitStrategyFactoryConfigTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncWaitStrategyFactoryConfigTest { @Test @LoggerContextSource("AsyncWaitStrategyFactoryConfigTest.xml") - public void testConfigWaitStrategyFactory(final LoggerContext context) throws Exception { + void testConfigWaitStrategyFactory(final LoggerContext context) { final AsyncWaitStrategyFactory asyncWaitStrategyFactory = context.getConfiguration().getAsyncWaitStrategyFactory(); assertEquals(YieldingWaitStrategyFactory.class, asyncWaitStrategyFactory.getClass()); @@ -46,7 +46,7 @@ public void testConfigWaitStrategyFactory(final LoggerContext context) throws Ex @Test @LoggerContextSource("AsyncWaitStrategyFactoryConfigTest.xml") - public void testWaitStrategy(final LoggerContext context) throws Exception { + void testWaitStrategy(final LoggerContext context) { final org.apache.logging.log4j.Logger logger = context.getRootLogger(); @@ -62,7 +62,7 @@ public void testWaitStrategy(final LoggerContext context) throws Exception { @Test @LoggerContextSource("AsyncWaitStrategyIncorrectFactoryConfigTest.xml") - public void testIncorrectConfigWaitStrategyFactory(final LoggerContext context) throws Exception { + void testIncorrectConfigWaitStrategyFactory(final LoggerContext context) { final AsyncWaitStrategyFactory asyncWaitStrategyFactory = context.getConfiguration().getAsyncWaitStrategyFactory(); assertNull(asyncWaitStrategyFactory); @@ -70,8 +70,8 @@ public void testIncorrectConfigWaitStrategyFactory(final LoggerContext context) @Test @LoggerContextSource("AsyncWaitStrategyIncorrectFactoryConfigTest.xml") - public void testIncorrectWaitStrategyFallsBackToDefault( - @Named("WaitStrategyAppenderList") final ListAppender list1, final LoggerContext context) throws Exception { + void testIncorrectWaitStrategyFallsBackToDefault( + @Named("WaitStrategyAppenderList") final ListAppender list1, final LoggerContext context) { final org.apache.logging.log4j.Logger logger = context.getRootLogger(); final AsyncLoggerConfig loggerConfig = diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryIncorrectConfigGlobalLoggersTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryIncorrectConfigGlobalLoggersTest.java index 9f282de5a95..1d1abdcd4b3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryIncorrectConfigGlobalLoggersTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncWaitStrategyFactoryIncorrectConfigGlobalLoggersTest.java @@ -17,38 +17,38 @@ package org.apache.logging.log4j.core.async; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncWaitStrategyFactoryIncorrectConfigGlobalLoggersTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncWaitStrategyFactoryIncorrectConfigGlobalLoggersTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty( ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncWaitStrategyIncorrectFactoryConfigGlobalLoggerTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR); System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); } @Test - public void testIncorrectConfigWaitStrategyFactory() throws Exception { + void testIncorrectConfigWaitStrategyFactory() throws Exception { final LoggerContext context = (LoggerContext) LogManager.getContext(false); assertThat("context is AsyncLoggerContext", context instanceof AsyncLoggerContext); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/BasicAsyncLoggerContextSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/BasicAsyncLoggerContextSelectorTest.java index 101af9e6493..e645e4637f3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/BasicAsyncLoggerContextSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/BasicAsyncLoggerContextSelectorTest.java @@ -16,87 +16,87 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LifeCycle; import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class BasicAsyncLoggerContextSelectorTest { +@Tag(Tags.ASYNC_LOGGERS) +class BasicAsyncLoggerContextSelectorTest { private static final String FQCN = BasicAsyncLoggerContextSelectorTest.class.getName(); - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BasicAsyncLoggerContextSelector.class.getName()); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR); } @Test - public void testContextReturnsAsyncLoggerContext() { + void testContextReturnsAsyncLoggerContext() { final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector(); final LoggerContext context = selector.getContext(FQCN, null, false); - assertTrue(context instanceof AsyncLoggerContext); + assertInstanceOf(AsyncLoggerContext.class, context); } @Test - public void testContext2ReturnsAsyncLoggerContext() { + void testContext2ReturnsAsyncLoggerContext() { final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector(); final LoggerContext context = selector.getContext(FQCN, null, false, null); - assertTrue(context instanceof AsyncLoggerContext); + assertInstanceOf(AsyncLoggerContext.class, context); } @Test - public void testLoggerContextsReturnsAsyncLoggerContext() { + void testLoggerContextsReturnsAsyncLoggerContext() { final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector(); List list = selector.getLoggerContexts(); assertEquals(1, list.size()); - assertTrue(list.get(0) instanceof AsyncLoggerContext); + assertInstanceOf(AsyncLoggerContext.class, list.get(0)); selector.getContext(FQCN, null, false); list = selector.getLoggerContexts(); assertEquals(1, list.size()); - assertTrue(list.get(0) instanceof AsyncLoggerContext); + assertInstanceOf(AsyncLoggerContext.class, list.get(0)); } @Test - public void testContextNameIsAsyncDefault() { + void testContextNameIsAsyncDefault() { final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector(); final LoggerContext context = selector.getContext(FQCN, null, false); assertEquals("AsyncDefault", context.getName()); } @Test - public void testDependentOnClassLoader() { + void testDependentOnClassLoader() { final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector(); assertFalse(selector.isClassLoaderDependent()); } @Test - public void testFactoryIsNotDependentOnClassLoader() { + void testFactoryIsNotDependentOnClassLoader() { assertFalse(LogManager.getFactory().isClassLoaderDependent()); } @Test - public void testLogManagerShutdown() { + void testLogManagerShutdown() { final LoggerContext context = (LoggerContext) LogManager.getContext(); assertEquals(LifeCycle.State.STARTED, context.getState()); LogManager.shutdown(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DefaultAsyncQueueFullPolicyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DefaultAsyncQueueFullPolicyTest.java index 929267c3182..27548391ab6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DefaultAsyncQueueFullPolicyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DefaultAsyncQueueFullPolicyTest.java @@ -16,18 +16,18 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Tests the DefaultAsyncQueueFullPolicy class. */ -@Category(AsyncLoggers.class) -public class DefaultAsyncQueueFullPolicyTest { +@Tag(Tags.ASYNC_LOGGERS) +class DefaultAsyncQueueFullPolicyTest { private static long currentThreadId() { return Thread.currentThread().getId(); @@ -38,14 +38,14 @@ private static long otherThreadId() { } @Test - public void testGetRouteEnqueuesIfQueueFullAndCalledFromDifferentThread() throws Exception { + void testGetRouteEnqueuesIfQueueFullAndCalledFromDifferentThread() { final DefaultAsyncQueueFullPolicy router = new DefaultAsyncQueueFullPolicy(); assertEquals(EventRoute.ENQUEUE, router.getRoute(otherThreadId(), Level.ALL)); assertEquals(EventRoute.ENQUEUE, router.getRoute(otherThreadId(), Level.OFF)); } @Test - public void testGetRouteSynchronousIfQueueFullAndCalledFromSameThread() throws Exception { + void testGetRouteSynchronousIfQueueFullAndCalledFromSameThread() { final DefaultAsyncQueueFullPolicy router = new DefaultAsyncQueueFullPolicy(); assertEquals(EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), Level.ALL)); assertEquals(EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), Level.OFF)); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DiscardingAsyncQueueFullPolicyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DiscardingAsyncQueueFullPolicyTest.java index 6002e409958..c816cbef4a4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DiscardingAsyncQueueFullPolicyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/DiscardingAsyncQueueFullPolicyTest.java @@ -16,19 +16,20 @@ */ package org.apache.logging.log4j.core.async; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.apache.logging.log4j.core.test.junit.Tags; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Tests the DiscardingAsyncQueueFullPolicy class.. */ -@Category(AsyncLoggers.class) -public class DiscardingAsyncQueueFullPolicyTest { +@Tag(Tags.ASYNC_LOGGERS) +class DiscardingAsyncQueueFullPolicyTest { private static long currentThreadId() { return Thread.currentThread().getId(); @@ -38,83 +39,84 @@ private static long otherThreadId() { return -1; } - @Test(expected = NullPointerException.class) - public void testConstructorDisallowsNullThresholdLevel() { - new DiscardingAsyncQueueFullPolicy(null); + @Test + void testConstructorDisallowsNullThresholdLevel() { + assertThrows(NullPointerException.class, () -> { + new DiscardingAsyncQueueFullPolicy(null); + }); } @Test - public void testThresholdLevelIsConstructorValue() { + void testThresholdLevelIsConstructorValue() { assertSame(Level.ALL, new DiscardingAsyncQueueFullPolicy(Level.ALL).getThresholdLevel()); assertSame(Level.OFF, new DiscardingAsyncQueueFullPolicy(Level.OFF).getThresholdLevel()); assertSame(Level.INFO, new DiscardingAsyncQueueFullPolicy(Level.INFO).getThresholdLevel()); } @Test - public void testGetRouteDiscardsIfThresholdCapacityReachedAndLevelEqualOrLessSpecificThanThreshold() - throws Exception { + void testGetRouteDiscardsIfThresholdCapacityReachedAndLevelEqualOrLessSpecificThanThreshold() { final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN); for (final Level level : new Level[] {Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE, Level.ALL}) { - assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level)); - assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level)); - assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level)); - assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level)); + assertEquals(EventRoute.DISCARD, router.getRoute(currentThreadId(), level), level.name()); + assertEquals(EventRoute.DISCARD, router.getRoute(otherThreadId(), level), level.name()); + assertEquals(EventRoute.DISCARD, router.getRoute(currentThreadId(), level), level.name()); + assertEquals(EventRoute.DISCARD, router.getRoute(otherThreadId(), level), level.name()); } } @Test - public void testGetRouteDiscardsIfQueueFullAndLevelEqualOrLessSpecificThanThreshold() throws Exception { + void testGetRouteDiscardsIfQueueFullAndLevelEqualOrLessSpecificThanThreshold() { final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN); for (final Level level : new Level[] {Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE, Level.ALL}) { - assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(currentThreadId(), level)); - assertEquals(level.name(), EventRoute.DISCARD, router.getRoute(otherThreadId(), level)); + assertEquals(EventRoute.DISCARD, router.getRoute(currentThreadId(), level), level.name()); + assertEquals(EventRoute.DISCARD, router.getRoute(otherThreadId(), level), level.name()); } } @Test - public void testGetRouteEnqueuesIfThresholdCapacityReachedButLevelMoreSpecificThanThreshold() throws Exception { + void testGetRouteEnqueuesIfThresholdCapacityReachedButLevelMoreSpecificThanThreshold() { final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN); for (final Level level : new Level[] {Level.ERROR, Level.FATAL, Level.OFF}) { - assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level)); - assertEquals(level.name(), EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level)); - assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level)); - assertEquals(level.name(), EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level)); + assertEquals(EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level), level.name()); + assertEquals(EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level), level.name()); + assertEquals(EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level), level.name()); + assertEquals(EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level), level.name()); } } @Test - public void testGetRouteEnqueueIfOtherThreadQueueFullAndLevelMoreSpecificThanThreshold() throws Exception { + void testGetRouteEnqueueIfOtherThreadQueueFullAndLevelMoreSpecificThanThreshold() { final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN); for (final Level level : new Level[] {Level.ERROR, Level.FATAL, Level.OFF}) { - assertEquals(level.name(), EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level)); + assertEquals(EventRoute.ENQUEUE, router.getRoute(otherThreadId(), level), level.name()); } } @Test - public void testGetRouteSynchronousIfCurrentThreadQueueFullAndLevelMoreSpecificThanThreshold() throws Exception { + void testGetRouteSynchronousIfCurrentThreadQueueFullAndLevelMoreSpecificThanThreshold() { final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.WARN); for (final Level level : new Level[] {Level.ERROR, Level.FATAL, Level.OFF}) { - assertEquals(level.name(), EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level)); + assertEquals(EventRoute.SYNCHRONOUS, router.getRoute(currentThreadId(), level), level.name()); } } @Test - public void testGetDiscardCount() throws Exception { + void testGetDiscardCount() { final DiscardingAsyncQueueFullPolicy router = new DiscardingAsyncQueueFullPolicy(Level.INFO); - assertEquals("initially", 0, DiscardingAsyncQueueFullPolicy.getDiscardCount(router)); + assertEquals(0, DiscardingAsyncQueueFullPolicy.getDiscardCount(router), "initially"); assertEquals(EventRoute.DISCARD, router.getRoute(-1L, Level.INFO)); - assertEquals("increase", 1, DiscardingAsyncQueueFullPolicy.getDiscardCount(router)); + assertEquals(1, DiscardingAsyncQueueFullPolicy.getDiscardCount(router), "increase"); assertEquals(EventRoute.DISCARD, router.getRoute(-1L, Level.INFO)); - assertEquals("increase", 2, DiscardingAsyncQueueFullPolicy.getDiscardCount(router)); + assertEquals(2, DiscardingAsyncQueueFullPolicy.getDiscardCount(router), "increase"); assertEquals(EventRoute.DISCARD, router.getRoute(-1L, Level.INFO)); - assertEquals("increase", 3, DiscardingAsyncQueueFullPolicy.getDiscardCount(router)); + assertEquals(3, DiscardingAsyncQueueFullPolicy.getDiscardCount(router), "increase"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688AsyncTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688AsyncTest.java index e25184c2672..1d72e8fc8f3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688AsyncTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688AsyncTest.java @@ -62,7 +62,7 @@ public static void afterClass() { private ListAppender listAppender; @Before - public void before() throws Exception { + public void before() { listAppender = context.getListAppender("List"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688Test.java index 7834bbe121b..4e69ab7085a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/Log4j2Jira1688Test.java @@ -61,7 +61,7 @@ public static void afterClass() { private ListAppender listAppender; @Before - public void before() throws Exception { + public void before() { listAppender = context.getListAppender("List"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/QueueFullAsyncLogger3Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/QueueFullAsyncLogger3Test.java index de5d68a5869..10d45ac8a70 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/QueueFullAsyncLogger3Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/QueueFullAsyncLogger3Test.java @@ -45,7 +45,7 @@ @SetTestProperty(key = "log4j2.formatMsgAsync", value = "true") @SetTestProperty(key = "log4j2.asyncQueueFullPolicy", value = "Discard") @Tag(Tags.ASYNC_LOGGERS) -public class QueueFullAsyncLogger3Test extends QueueFullAbstractTest { +class QueueFullAsyncLogger3Test extends QueueFullAbstractTest { @Override protected void checkConfig(final LoggerContext ctx) { @@ -56,7 +56,7 @@ protected void checkConfig(final LoggerContext ctx) { @Test @LoggerContextSource - public void discarded_messages_should_be_garbage_collected( + void discarded_messages_should_be_garbage_collected( final LoggerContext ctx, final @Named(APPENDER_NAME) BlockingAppender blockingAppender) throws InterruptedException { awaitGarbageCollection(() -> { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/RingBufferLogEventTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/RingBufferLogEventTest.java index ffd26bed644..75559f87147 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/RingBufferLogEventTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/RingBufferLogEventTest.java @@ -24,7 +24,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import java.io.IOException; import java.util.Arrays; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; @@ -194,7 +193,7 @@ void testGetMillisReturnsConstructorMillisForNormalMessage() { } @Test - void testSerializationDeserialization() throws IOException, ClassNotFoundException { + void testSerializationDeserialization() { final RingBufferLogEvent evt = new RingBufferLogEvent(); final String loggerName = "logger.name"; final Marker marker = null; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/AdvertiserTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/AdvertiserTest.java index 92cfda340f3..e99cf2fbc25 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/AdvertiserTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/AdvertiserTest.java @@ -30,13 +30,13 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class AdvertiserTest { +class AdvertiserTest { private static final String CONFIG = "log4j-advertiser.xml"; private static final String STATUS_LOG = "target/status.log"; @BeforeAll - public static void setupClass() { + static void setupClass() { final File file = new File(STATUS_LOG); file.delete(); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); @@ -53,7 +53,7 @@ public static void setupClass() { } @AfterAll - public static void cleanupClass() { + static void cleanupClass() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); @@ -91,12 +91,12 @@ private void verifyExpectedEntriesAdvertised(final Map appendersMap = config.getLogger("cat1").getAppenders(); assertEquals( @@ -102,7 +102,7 @@ public void evaluate() throws Throwable { final Filter loggerFilter = config.getLogger("cat1").getFilter(); assertTrue(loggerFilter instanceof RegexFilter); - assertEquals(loggerFilter.getOnMatch(), Filter.Result.DENY); + assertEquals(Filter.Result.DENY, loggerFilter.getOnMatch()); appendersMap = config.getLogger("cat2").getAppenders(); assertEquals( @@ -129,8 +129,8 @@ public void evaluate() throws Throwable { assertEquals( "Expected COMPOSITE_SOURCE for composite configuration but got " + config.getConfigurationSource(), - config.getConfigurationSource(), - ConfigurationSource.COMPOSITE_SOURCE); + ConfigurationSource.COMPOSITE_SOURCE, + config.getConfigurationSource()); } }; runTest(lcr, test); @@ -142,7 +142,7 @@ public void testAttributeCheckWhenMergingConfigurations() { new LoggerContextRule("classpath:log4j-comp-root-loggers.xml,log4j-comp-logger.json"); final Statement test = new Statement() { @Override - public void evaluate() throws Throwable { + public void evaluate() { try { final CompositeConfiguration config = (CompositeConfiguration) lcr.getConfiguration(); Assert.assertNotNull(config); @@ -160,7 +160,7 @@ public void testAttributeMergeForLoggers() { new LoggerContextRule("classpath:log4j-comp-logger-root.xml,log4j-comp-logger-attr-override.json"); final Statement test = new Statement() { @Override - public void evaluate() throws Throwable { + public void evaluate() { final CompositeConfiguration config = (CompositeConfiguration) lcr.getConfiguration(); // Test for Root log level override assertEquals( @@ -197,7 +197,7 @@ public void testMissingConfig() { new LoggerContextRule("classpath:log4j-comp-logger-root.xml,log4j-does-not-exist.json"); final Statement test = new Statement() { @Override - public void evaluate() throws Throwable { + public void evaluate() { final AbstractConfiguration config = (AbstractConfiguration) lcr.getConfiguration(); assertNotNull("No configuration returned", config); // Test for Root log level override @@ -220,7 +220,7 @@ public void testAppenderRefFilterMerge() { new LoggerContextRule("classpath:log4j-comp-logger-ref.xml,log4j-comp-logger-ref.json"); final Statement test = new Statement() { @Override - public void evaluate() throws Throwable { + public void evaluate() { final CompositeConfiguration config = (CompositeConfiguration) lcr.getConfiguration(); final List appenderRefList = diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationFactoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationFactoryTest.java index 5db114e7398..f2d81f13472 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationFactoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationFactoryTest.java @@ -19,6 +19,7 @@ import static org.apache.logging.log4j.util.Unbox.box; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -72,10 +73,10 @@ static void checkConfiguration(final LoggerContext context) { assertEquals(1, logger.filterCount()); final Iterator filterIterator = logger.getFilters(); assertTrue(filterIterator.hasNext()); - assertTrue(filterIterator.next() instanceof ThreadContextMapFilter); + assertInstanceOf(ThreadContextMapFilter.class, filterIterator.next()); final Appender appender = appenders.get(APPENDER_NAME); - assertTrue(appender instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, appender); assertEquals(APPENDER_NAME, appender.getName()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationPropertyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationPropertyTest.java index 718f6fbb8e2..18813ce1d9f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationPropertyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationPropertyTest.java @@ -26,12 +26,12 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class ConfigurationPropertyTest { +class ConfigurationPropertyTest { private LoggerContext loggerContext; @AfterEach - public void afterEach() { + void afterEach() { if (loggerContext != null) { LogManager.shutdown(loggerContext); } @@ -40,7 +40,7 @@ public void afterEach() { } @Test - public void testInitializeFromSystemProperty() { + void testInitializeFromSystemProperty() { System.setProperty("log4j2.configurationFile", "src/test/resources/log4j-list.xml"); loggerContext = (LoggerContext) LogManager.getContext(false); final Configuration configuration = loggerContext.getConfiguration(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationSourceTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationSourceTest.java index 5001ad2d449..3015f4f6271 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationSourceTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfigurationSourceTest.java @@ -81,7 +81,7 @@ void testNoJarFileLeak() throws Exception { } @Test - public void testLoadConfigurationSourceFromJarFile() throws Exception { + void testLoadConfigurationSourceFromJarFile() throws Exception { final Path jarFile = prepareJarConfigURL(tempDir); final URL jarConfigURL = new URL("jar:" + jarFile.toUri().toURL() + "!" + PATH_IN_JAR); final long expectedFdCount = getOpenFileDescriptorCount(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator1Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator1Test.java index be2c6fd1993..e46d4cb3ae7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator1Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator1Test.java @@ -66,7 +66,7 @@ @SetSystemProperty(key = Constants.SCRIPT_LANGUAGES, value = "beanshell, Groovy, Javascript") @Tag("functional") -public class Configurator1Test { +class Configurator1Test { private static final String CONFIG_NAME = "TestConfigurator"; @@ -91,7 +91,7 @@ public class Configurator1Test { }; @AfterEach - public void cleanup() { + void cleanup() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); if (ctx != null) { Configurator.shutdown(ctx); @@ -100,7 +100,7 @@ public void cleanup() { } @Test - public void testInitialize_Name_PathName() throws Exception { + void testInitialize_Name_PathName() { ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-TestConfigurator.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); @@ -116,7 +116,7 @@ public void testInitialize_Name_PathName() throws Exception { } @Test - public void testInitialize_Name_ClassLoader_URI() throws Exception { + void testInitialize_Name_ClassLoader_URI() { ctx = Configurator.initialize( "Test1", null, new File("target/test-classes/log4j2-TestConfigurator.xml").toURI()); LogManager.getLogger("org.apache.test.TestConfigurator"); @@ -133,7 +133,7 @@ public void testInitialize_Name_ClassLoader_URI() throws Exception { } @Test - public void testInitialize_InputStream_File() throws Exception { + void testInitialize_InputStream_File() throws Exception { final File file = new File("target/test-classes/log4j2-TestConfigurator.xml"); final InputStream is = new FileInputStream(file); final ConfigurationSource source = new ConfigurationSource(is, file); @@ -152,7 +152,7 @@ public void testInitialize_InputStream_File() throws Exception { } @Test - public void testInitialize_InputStream_Path() throws Exception { + void testInitialize_InputStream_Path() throws Exception { final Path path = Paths.get("target/test-classes/log4j2-TestConfigurator.xml"); final InputStream is = Files.newInputStream(path); final ConfigurationSource source = new ConfigurationSource(is, path); @@ -171,7 +171,7 @@ public void testInitialize_InputStream_Path() throws Exception { } @Test - public void testInitialize_NullClassLoader_ConfigurationSourceWithInputStream_NoId() throws Exception { + void testInitialize_NullClassLoader_ConfigurationSourceWithInputStream_NoId() throws Exception { final InputStream is = new FileInputStream("target/test-classes/log4j2-TestConfigurator.xml"); final ConfigurationSource source = new ConfigurationSource(is); ctx = Configurator.initialize(null, source); @@ -189,7 +189,7 @@ public void testInitialize_NullClassLoader_ConfigurationSourceWithInputStream_No } @Test - public void testInitialize_Name_LocationName() throws Exception { + void testInitialize_Name_LocationName() { ctx = Configurator.initialize("Test1", "log4j2-TestConfigurator.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); @@ -205,7 +205,7 @@ public void testInitialize_Name_LocationName() throws Exception { } @Test - public void testFromClassPathProperty() throws Exception { + void testFromClassPathProperty() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "classpath:log4j2-TestConfigurator.xml"); ctx = Configurator.initialize("Test1", null); LogManager.getLogger("org.apache.test.TestConfigurator"); @@ -222,7 +222,7 @@ public void testFromClassPathProperty() throws Exception { } @Test - public void testFromClassPathWithClassPathPrefix() throws Exception { + void testFromClassPathWithClassPathPrefix() { ctx = Configurator.initialize("Test1", "classpath:log4j2-TestConfigurator.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); @@ -238,7 +238,7 @@ public void testFromClassPathWithClassPathPrefix() throws Exception { } @Test - public void testFromClassPathWithClassLoaderPrefix() throws Exception { + void testFromClassPathWithClassLoaderPrefix() { ctx = Configurator.initialize("Test1", "classloader:log4j2-TestConfigurator.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); @@ -254,7 +254,7 @@ public void testFromClassPathWithClassLoaderPrefix() throws Exception { } @Test - public void testByName() throws Exception { + void testByName() { ctx = Configurator.initialize("-TestConfigurator", null); LogManager.getLogger("org.apache.test.TestConfigurator"); Configuration config = ctx.getConfiguration(); @@ -270,7 +270,7 @@ public void testByName() throws Exception { } @Test - public void testReconfiguration() throws Exception { + void testReconfiguration() throws Exception { final File file = new File("target/test-classes/log4j2-TestConfigurator.xml"); assertTrue(file.setLastModified(System.currentTimeMillis() - 120000), "setLastModified should have succeeded."); ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-TestConfigurator.xml"); @@ -307,7 +307,7 @@ public void testReconfiguration() throws Exception { } @Test - public void testEnvironment() throws Exception { + void testEnvironment() { ctx = Configurator.initialize("-TestConfigurator", null); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); @@ -327,7 +327,7 @@ public void testEnvironment() throws Exception { } @Test - public void testNoLoggers() throws Exception { + void testNoLoggers() { ctx = Configurator.initialize("Test1", "bad/log4j-loggers.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); @@ -337,7 +337,7 @@ public void testNoLoggers() throws Exception { } @Test - public void testBadStatus() throws Exception { + void testBadStatus() { ctx = Configurator.initialize("Test1", "bad/log4j-status.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); @@ -349,7 +349,7 @@ public void testBadStatus() throws Exception { } @Test - public void testBadFilterParam() throws Exception { + void testBadFilterParam() { ctx = Configurator.initialize("Test1", "bad/log4j-badfilterparam.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); @@ -362,7 +362,7 @@ public void testBadFilterParam() throws Exception { } @Test - public void testNoFilters() throws Exception { + void testNoFilters() { ctx = Configurator.initialize("Test1", "bad/log4j-nofilter.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); @@ -377,7 +377,7 @@ public void testNoFilters() throws Exception { } @Test - public void testBadLayout() throws Exception { + void testBadLayout() { ctx = Configurator.initialize("Test1", "bad/log4j-badlayout.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); @@ -386,14 +386,14 @@ public void testBadLayout() throws Exception { } @Test - public void testBadFileName() throws Exception { + void testBadFileName() { final StringBuilder dir = new StringBuilder("/VeryLongDirectoryName"); for (final String element : CHARS) { dir.append(element); dir.append(toRootUpperCase(element)); } - final String value = FILESEP.equals("/") ? dir.toString() + "/test.log" : "1:/target/bad:file.log"; + final String value = FILESEP.equals("/") ? dir + "/test.log" : "1:/target/bad:file.log"; System.setProperty("testfile", value); ctx = Configurator.initialize("Test1", "bad/log4j-badfilename.xml"); LogManager.getLogger("org.apache.test.TestConfigurator"); @@ -404,7 +404,7 @@ public void testBadFileName() throws Exception { } @Test - public void testBuilder() throws Exception { + void testBuilder() { final ConfigurationBuilder builder = ConfigurationBuilderFactory.newConfigurationBuilder(); builder.setStatusLevel(Level.ERROR); builder.setConfigurationName("BuilderTest"); @@ -429,7 +429,7 @@ public void testBuilder() throws Exception { } @Test - public void testRolling() throws Exception { + void testRolling() { final ConfigurationBuilder builder = ConfigurationBuilderFactory.newConfigurationBuilder(); builder.setStatusLevel(Level.ERROR); @@ -469,7 +469,7 @@ public void testRolling() throws Exception { } @Test - public void testBuilderWithScripts() throws Exception { + void testBuilderWithScripts() { final String script = "if (logEvent.getLoggerName().equals(\"NoLocation\")) {\n" + " return \"NoLocation\";\n" + " } else if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf(\"FLOW\")) {\n" diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator2Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator2Test.java index d1459aea782..55421ce8dfe 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator2Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/Configurator2Test.java @@ -28,22 +28,22 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class Configurator2Test { +class Configurator2Test { @Test - public void testInitializeFromAbsoluteFilePath() { + void testInitializeFromAbsoluteFilePath() { final String path = new File("src/test/resources/log4j-list.xml").getAbsolutePath(); testInitializeFromFilePath(path); } @Test - public void testInitializeFromRelativeFilePath() { + void testInitializeFromRelativeFilePath() { final String path = new File("src/test/resources/log4j-list.xml").toString(); testInitializeFromFilePath(path); } @Test - public void testReconfigure() { + void testReconfigure() { final String path = new File("src/test/resources/log4j-list.xml").getAbsolutePath(); try (final LoggerContext loggerContext = Configurator.initialize(getClass().getName(), null, path)) { @@ -56,7 +56,7 @@ public void testReconfigure() { } @Test - public void testReconfigureFromPath() { + void testReconfigureFromPath() { final String path = new File("src/test/resources/log4j-list.xml").getAbsolutePath(); try (final LoggerContext loggerContext = Configurator.initialize(getClass().getName(), null, path)) { @@ -80,7 +80,7 @@ private void testInitializeFromFilePath(final String path) { * LOG4J2-3631: Configurator uses getName() instead of getCanonicalName(). */ @Test - public void testSetLevelUsesCanonicalName() { + void testSetLevelUsesCanonicalName() { final String path = new File("src/test/resources/log4j-list.xml").getAbsolutePath(); try (final LoggerContext loggerContext = Configurator.initialize(getClass().getName(), null, path)) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorErrorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorErrorTest.java index a558e4992dc..f00d31b4741 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorErrorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorErrorTest.java @@ -26,21 +26,21 @@ import org.junit.jupiter.api.parallel.ResourceLock; @ResourceLock("log4j2.LoggerContextFactory") -public class ConfiguratorErrorTest { +class ConfiguratorErrorTest { @RegisterExtension static final LoggerContextFactoryExtension EXTENSION = new LoggerContextFactoryExtension(SimpleLoggerContextFactory.INSTANCE); @Test - public void testErrorNoClassLoader() { + void testErrorNoClassLoader() { try (final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-config.xml")) { assertNull(ctx, "No LoggerContext should have been returned"); } } @Test - public void testErrorNullClassLoader() { + void testErrorNullClassLoader() { try (final LoggerContext ctx = Configurator.initialize("Test1", null, "target/test-classes/log4j2-config.xml")) { assertNull(ctx, "No LoggerContext should have been returned"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorSetLevelTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorSetLevelTest.java index 3954dda93f9..d5739c021d2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorSetLevelTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ConfiguratorSetLevelTest.java @@ -30,7 +30,7 @@ @Tag("functional") @LoggerContextSource("log4j-set-level.xml") -public class ConfiguratorSetLevelTest { +class ConfiguratorSetLevelTest { private final ListAppender app1; private final LoggerContext loggerContext; @@ -43,7 +43,7 @@ public ConfiguratorSetLevelTest(final LoggerContext context, @Named("LIST1") fin } @Test - public void testSetLevel() { + void testSetLevel() { final Logger logger = loggerContext.getLogger(ConfiguratorSetLevelTest.class); Configurator.setLevel(logger, Level.DEBUG); final LoggerConfig loggerConfig = ((AbstractConfiguration) loggerContext.getConfiguration()) diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/CustomConfigurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/CustomConfigurationTest.java index 927f8257465..d9893b7bc53 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/CustomConfigurationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/CustomConfigurationTest.java @@ -19,7 +19,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertSame; -import java.io.IOException; import java.io.Serializable; import java.nio.file.Path; import org.apache.logging.log4j.Level; @@ -39,7 +38,7 @@ import org.junit.jupiter.api.Test; @UsingStatusListener -public class CustomConfigurationTest { +class CustomConfigurationTest { @TempLoggingDir private static Path loggingPath; @@ -48,14 +47,14 @@ public class CustomConfigurationTest { @SetTestProperty(key = "log4j.level", value = "INFO") @SetTestProperty(key = "log.level", value = "INFO") @LoggerContextSource - public void testConfig(final LoggerContext ctx) throws IOException { + void testConfig(final LoggerContext ctx) { final Path logFile = loggingPath.resolve("test.log"); // don't bother using "error" since that's the default; try another level final Configuration config = ctx.getConfiguration(); assertThat(config).isInstanceOf(XmlConfiguration.class); for (final StatusListener listener : StatusLogger.getLogger().getListeners()) { if (listener instanceof StatusConsoleListener) { - assertSame(listener.getStatusLevel(), Level.INFO); + assertSame(Level.INFO, listener.getStatusLevel()); break; } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/FileOutputTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/FileOutputTest.java index 69dc34b67b9..3e7a7e137f4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/FileOutputTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/FileOutputTest.java @@ -18,7 +18,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import java.io.IOException; import java.nio.file.Path; import org.apache.logging.log4j.core.test.junit.LoggerContextSource; import org.apache.logging.log4j.status.StatusLogger; @@ -28,14 +27,14 @@ /** * Tests the possibility to redirect status logger output to a file. */ -public class FileOutputTest { +class FileOutputTest { @TempLoggingDir private static Path loggingPath; @Test @LoggerContextSource - public void testConfig() throws IOException { + void testConfig() { final Path logFile = loggingPath.resolve("status.log"); assertThat(logFile).exists().isNotEmptyFile(); // Closes the current listeners diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/JiraLog4j2_2134Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/JiraLog4j2_2134Test.java index 0d1b26b2bc4..7f7948c44e8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/JiraLog4j2_2134Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/JiraLog4j2_2134Test.java @@ -33,10 +33,10 @@ @Tag("yaml") @LoggerContextSource("log4j2-2134.yaml") -public class JiraLog4j2_2134Test { +class JiraLog4j2_2134Test { @Test - public void testRefresh() { + void testRefresh() { final Logger log = LogManager.getLogger(this.getClass()); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); @@ -69,7 +69,7 @@ public void testRefresh() { } @Test - public void testRefreshMinimalCodeStart() { + void testRefreshMinimalCodeStart() { final Logger log = LogManager.getLogger(this.getClass()); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); @@ -79,7 +79,7 @@ public void testRefreshMinimalCodeStart() { } @Test - public void testRefreshMinimalCodeStopStart() { + void testRefreshMinimalCodeStopStart() { final Logger log = LogManager.getLogger(this.getClass()); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); ctx.stop(); @@ -89,7 +89,7 @@ public void testRefreshMinimalCodeStopStart() { } @Test - public void testRefreshMinimalCodeStopStartConfig() { + void testRefreshMinimalCodeStopStartConfig() { final Logger log = LogManager.getLogger(this.getClass()); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); @@ -101,7 +101,7 @@ public void testRefreshMinimalCodeStopStartConfig() { @SuppressWarnings("deprecation") @Test - public void testRefreshDeprecatedApis() { + void testRefreshDeprecatedApis() { final Logger log = LogManager.getLogger(this.getClass()); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggerConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggerConfigTest.java index 23ca8ea3779..5098c34ccb3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggerConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggerConfigTest.java @@ -39,7 +39,7 @@ /** * Tests for LoggerConfig. */ -public class LoggerConfigTest { +class LoggerConfigTest { private static final String FQCN = LoggerConfigTest.class.getName(); @@ -50,7 +50,7 @@ private static LoggerConfig createForProperties(final Property[] properties) { @SuppressWarnings({"deprecation"}) @Test - public void testPropertiesWithoutSubstitution() { + void testPropertiesWithoutSubstitution() { assertNull(createForProperties(null).getPropertyList(), "null propertiesList"); final Property[] all = new Property[] { @@ -70,7 +70,7 @@ public void testPropertiesWithoutSubstitution() { } @Test - public void testPropertiesWithSubstitution() { + void testPropertiesWithSubstitution() { final Property[] all = new Property[] { Property.createProperty("key1", "value1-${sys:user.name}"), Property.createProperty("key2", "value2-${sys:user.name}"), @@ -98,7 +98,7 @@ public void testPropertiesWithSubstitution() { } @Test - public void testLevel() { + void testLevel() { final Configuration configuration = new DefaultConfiguration(); final LoggerConfig config1 = LoggerConfig.newBuilder() .withLoggerName("org.apache.logging.log4j.test") @@ -112,14 +112,14 @@ public void testLevel() { .withConfig(configuration) .build(); config1.setParent(config2); - assertEquals(config1.getLevel(), Level.ERROR, "Unexpected Level"); - assertEquals(config1.getExplicitLevel(), Level.ERROR, "Unexpected explicit level"); - assertEquals(config2.getLevel(), Level.ERROR, "Unexpected Level"); + assertEquals(Level.ERROR, config1.getLevel(), "Unexpected Level"); + assertEquals(Level.ERROR, config1.getExplicitLevel(), "Unexpected explicit level"); + assertEquals(Level.ERROR, config2.getLevel(), "Unexpected Level"); assertNull(config2.getExplicitLevel(), "Unexpected explicit level"); } @Test - public void testSingleFilterInvocation() { + void testSingleFilterInvocation() { final Configuration configuration = new NullConfiguration(); final Filter filter = mock(Filter.class); final LoggerConfig config = LoggerConfig.newBuilder() diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggersPluginTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggersPluginTest.java index 70e824937e5..382587b4a8b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggersPluginTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/LoggersPluginTest.java @@ -31,11 +31,11 @@ * Tests LoggersPlugin. */ @SetSystemProperty(key = "log4j2.status.entries", value = "10") -public class LoggersPluginTest { +class LoggersPluginTest { @Test @LoggerContextSource("multipleRootLoggersTest.xml") - public void testEmptyAttribute() { + void testEmptyAttribute() { final Logger logger = LogManager.getLogger(); logger.info("Test"); final StatusData data = StatusLogger.getLogger().getStatusData().get(0); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingLanguageTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingLanguageTest.java index 9018c42acb0..721c0e3090d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingLanguageTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingLanguageTest.java @@ -34,12 +34,12 @@ @SetSystemProperty(key = Constants.SCRIPT_LANGUAGES, value = "beanshell, Javascript") @Tag("functional") -public class MissingLanguageTest { +class MissingLanguageTest { private LoggerContext ctx = null; @AfterEach - public void cleanup() { + void cleanup() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); if (ctx != null) { Configurator.shutdown(ctx); @@ -48,7 +48,7 @@ public void cleanup() { } @org.junit.jupiter.api.Test - public void testBuilderWithScripts() { + void testBuilderWithScripts() { final String script = "if (logEvent.getLoggerName().equals(\"NoLocation\")) {\n" + " return \"NoLocation\";\n" + " } else if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf(\"FLOW\")) {\n" diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingRootLoggerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingRootLoggerTest.java index 1fba7c859fa..13bd9706aa8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingRootLoggerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/MissingRootLoggerTest.java @@ -35,10 +35,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("missingRootLogger.xml") -public class MissingRootLoggerTest { +class MissingRootLoggerTest { @Test - public void testMissingRootLogger(final LoggerContext ctx) throws Exception { + void testMissingRootLogger(final LoggerContext ctx) { final Logger logger = ctx.getLogger("sample.Logger1"); assertTrue(logger.isInfoEnabled(), "Logger should have the INFO level enabled"); assertFalse(logger.isDebugEnabled(), "Logger should have the DEBUG level disabled"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NestedLoggerConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NestedLoggerConfigTest.java index abdcd11303f..46211e4b072 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NestedLoggerConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NestedLoggerConfigTest.java @@ -16,7 +16,7 @@ */ package org.apache.logging.log4j.core.config; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.collect.ImmutableList; import java.io.IOException; @@ -25,29 +25,21 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.xml.XmlConfiguration; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests for LoggerConfig hierarchies. */ -@RunWith(Parameterized.class) -public class NestedLoggerConfigTest { +class NestedLoggerConfigTest { - @Parameterized.Parameters(name = "{0}") - public static List data() throws IOException { + public static List data() { return ImmutableList.of("logger-config/LoggerConfig/", "logger-config/AsyncLoggerConfig/"); } - private final String prefix; - - public NestedLoggerConfigTest(final String prefix) { - this.prefix = prefix; - } - - @Test - public void testInheritParentDefaultLevel() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "{0}") + void testInheritParentDefaultLevel(final String prefix) throws IOException { final Configuration configuration = loadConfiguration(prefix + "default-level.xml"); try { assertEquals(Level.ERROR, configuration.getLoggerConfig("com.foo").getLevel()); @@ -56,8 +48,9 @@ public void testInheritParentDefaultLevel() throws IOException { } } - @Test - public void testInheritParentLevel() throws IOException { + @MethodSource("data") + @ParameterizedTest(name = "{0}") + void testInheritParentLevel(final String prefix) throws IOException { final Configuration configuration = loadConfiguration(prefix + "inherit-level.xml"); try { assertEquals(Level.TRACE, configuration.getLoggerConfig("com.foo").getLevel()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NoLanguagesTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NoLanguagesTest.java index b7bf58961e1..26b69be6d56 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NoLanguagesTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/NoLanguagesTest.java @@ -31,12 +31,12 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class NoLanguagesTest { +class NoLanguagesTest { private LoggerContext ctx = null; @AfterEach - public void cleanup() { + void cleanup() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); if (ctx != null) { Configurator.shutdown(ctx); @@ -45,7 +45,7 @@ public void cleanup() { } @Test - public void testBuilderWithScripts() { + void testBuilderWithScripts() { final String script = "if (logEvent.getLoggerName().equals(\"NoLocation\")) {\n" + " return \"NoLocation\";\n" + " } else if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf(\"FLOW\")) {\n" diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertiesPluginTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertiesPluginTest.java index 4ef1c500a39..bbaa4894abe 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertiesPluginTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertiesPluginTest.java @@ -20,15 +20,15 @@ import org.junit.jupiter.api.Test; -public class PropertiesPluginTest { +class PropertiesPluginTest { @Test - public void testUnescape() { + void testUnescape() { assertEquals("${foo}", PropertiesPlugin.unescape("$${foo}")); } @Test - public void testUnescapeNotEscapedWithDefault() { + void testUnescapeNotEscapedWithDefault() { final String value = "${foo:-bar}"; assertEquals(value, PropertiesPlugin.unescape(value)); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertyTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertyTest.java index 3b13470d160..46539b41cd1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertyTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/PropertyTest.java @@ -35,10 +35,10 @@ * not working */ @LoggerContextSource("configPropertyTest.xml") -public class PropertyTest { +class PropertyTest { @Test - public void testEmptyAttribute(@Named("List") final ListAppender app) throws Exception { + void testEmptyAttribute(@Named("List") final ListAppender app) { final org.apache.logging.log4j.Logger logger = LogManager.getLogger(); logger.info("msg"); @@ -70,7 +70,7 @@ public void testEmptyAttribute(@Named("List") final ListAppender app) throws Exc } @Test - public void testPropertyValues() { + void testPropertyValues() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final StrSubstitutor sub = ctx.getConfiguration().getStrSubstitutor(); // @@ -90,7 +90,7 @@ public void testPropertyValues() { } @Test - public void testLoggerPropertyValues() throws Exception { + void testLoggerPropertyValues() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final List rootLoggerProperties = ctx.getConfiguration().getLoggerConfig(LoggerConfig.ROOT).getPropertyList(); @@ -125,12 +125,12 @@ private static void verifyProperty( } @Test - public void testNullValueIsConvertedToEmptyString() { // LOG4J2-1313 support + void testNullValueIsConvertedToEmptyString() { // LOG4J2-1313 support assertEquals("", Property.createProperty("name", null).getValue()); } @Test - public void testIsValueNeedsLookup() { + void testIsValueNeedsLookup() { assertTrue(Property.createProperty("", "${").isValueNeedsLookup(), "with ${ as value"); assertTrue(Property.createProperty("", "blah${blah").isValueNeedsLookup(), "with ${ in value"); assertFalse(Property.createProperty("", "").isValueNeedsLookup(), "empty value"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationDeadlockTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationDeadlockTest.java index 48cfe679c18..2a595b533fe 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationDeadlockTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationDeadlockTest.java @@ -16,6 +16,9 @@ */ package org.apache.logging.log4j.core.config; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -40,7 +43,6 @@ import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required; import org.apache.logging.log4j.core.test.junit.LoggerContextSource; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; @@ -51,26 +53,26 @@ * @see TestAppender */ @LoggerContextSource("reconfiguration-deadlock.xml") -public class ReconfigurationDeadlockTest { +class ReconfigurationDeadlockTest { private static final int WORKER_COUNT = 100; private ExecutorService executor; @BeforeEach - public void startExecutor() { + void startExecutor() { executor = Executors.newFixedThreadPool(WORKER_COUNT); } @AfterEach - public void stopExecutor() throws InterruptedException { + void stopExecutor() throws InterruptedException { executor.shutdownNow(); final boolean terminated = executor.awaitTermination(30, TimeUnit.SECONDS); - Assertions.assertTrue(terminated, "couldn't terminate the executor"); + assertTrue(terminated, "couldn't terminate the executor"); } @RepeatedTest(100) - public void reconfiguration_should_not_cause_deadlock_for_ongoing_logging() throws Exception { + void reconfiguration_should_not_cause_deadlock_for_ongoing_logging() throws Exception { // Try to update the config file to ensure that we can indeed update it. updateConfigFileModTime(); @@ -88,7 +90,7 @@ public void reconfiguration_should_not_cause_deadlock_for_ongoing_logging() thro final Future workerFuture = workerFutures.get(workerIndex); try { final Object workerResult = workerFuture.get(30, TimeUnit.SECONDS); - Assertions.assertNull(workerResult); + assertNull(workerResult); } catch (final Throwable failure) { final String message = String.format("check for worker %02d/%02d has failed", (workerIndex + 1), WORKER_COUNT); @@ -100,7 +102,7 @@ public void reconfiguration_should_not_cause_deadlock_for_ongoing_logging() thro private static void updateConfigFileModTime() { final File file = new File("target/test-classes/reconfiguration-deadlock.xml"); final boolean fileModified = file.setLastModified(System.currentTimeMillis()); - Assertions.assertTrue(fileModified, "couldn't update file modification time"); + assertTrue(fileModified, "couldn't update file modification time"); } @SuppressWarnings("SameParameterValue") diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationFailureTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationFailureTest.java index fcf4f5c60fa..14df356b901 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationFailureTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/ReconfigurationFailureTest.java @@ -31,23 +31,24 @@ * Performs reconfiguration against bad configurations. * */ -@Disabled // Remove this when LOG4J2-2240 is addressed. -public class ReconfigurationFailureTest { +// Remove this when LOG4J2-2240 is addressed. +@Disabled +class ReconfigurationFailureTest { LoggerContext loggerContext; @BeforeEach - public void setup() { + void setup() { loggerContext = (LoggerContext) LogManager.getContext(); } @AfterEach - public void stopExecutor() throws InterruptedException { + void stopExecutor() { loggerContext.stop(); } @Test - public void setNonExistant() throws Exception { + void setNonExistant() { final URI original = loggerContext.getConfigLocation(); final URI nonExistant = new File("target/file.does.not.exist.xml").toURI(); @@ -56,7 +57,7 @@ public void setNonExistant() throws Exception { } @Test - public void setInvalidXML() throws Exception { + void setInvalidXML() { final URI original = loggerContext.getConfigLocation(); final URI nonExistant = new File("target/InvalidXML.xml").toURI(); @@ -65,7 +66,7 @@ public void setInvalidXML() throws Exception { } @Test - public void setInvalidConfig() throws Exception { + void setInvalidConfig() { final URI original = loggerContext.getConfigLocation(); final URI nonExistant = new File("target/InvalidConfig.xml").toURI(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/BasicArbiterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/BasicArbiterTest.java index 323bf8b64a8..ad898fb95a4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/BasicArbiterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/BasicArbiterTest.java @@ -16,9 +16,9 @@ */ package org.apache.logging.log4j.core.config.arbiters; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; @@ -31,36 +31,36 @@ /** * Tests basic condition processing. */ -public class BasicArbiterTest { +class BasicArbiterTest { static final String CONFIG = "log4j2-arbiters.xml"; static LoggerContext loggerContext = null; @AfterEach - public void after() { + void after() { loggerContext.stop(); loggerContext = null; System.clearProperty("env"); } @Test - public void prodTest() { + void prodTest() { System.setProperty("env", "prod"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ListAppender); + assertInstanceOf(ListAppender.class, app); } @Test - public void devTest() { + void devTest() { System.setProperty("env", "dev"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, app); } @Test @@ -69,7 +69,7 @@ void classArbiterTest() { assertNotNull(loggerContext); Appender app = loggerContext.getConfiguration().getAppender("ShouldExist"); assertNotNull(app); - assertTrue(app instanceof ListAppender); + assertInstanceOf(ListAppender.class, app); app = loggerContext.getConfiguration().getAppender("ShouldNotExist"); assertNull(app); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/EnvironmentArbiterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/EnvironmentArbiterTest.java index 7c13c7a5cd2..ecb5c24d06b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/EnvironmentArbiterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/EnvironmentArbiterTest.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.config.arbiters; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; @@ -30,25 +30,25 @@ /** * Tests system property condition processing. */ -public class EnvironmentArbiterTest { +class EnvironmentArbiterTest { private static final String CONFIG = "log4j2-environmentArbiters.xml"; @Test @SetEnvironmentVariable(key = "ENV", value = "prod") @LoggerContextSource(CONFIG) - public void prodTest(final LoggerContext loggerContext) throws Exception { + void prodTest(final LoggerContext loggerContext) { final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ListAppender); + assertInstanceOf(ListAppender.class, app); } @Test @SetEnvironmentVariable(key = "ENV", value = "dev") @LoggerContextSource(CONFIG) - public void devTest(final LoggerContext loggerContext) throws Exception { + void devTest(final LoggerContext loggerContext) { final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, app); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/ScriptArbiterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/ScriptArbiterTest.java index a15d97d0fe5..50899118c90 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/ScriptArbiterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/ScriptArbiterTest.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.config.arbiters; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; @@ -32,39 +32,39 @@ /** * Tests basic condition processing. */ -public class ScriptArbiterTest { +class ScriptArbiterTest { static final String CONFIG = "log4j2-scriptArbiters.xml"; static LoggerContext loggerContext = null; @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty(Constants.SCRIPT_LANGUAGES, "Groovy, Javascript"); } @AfterEach - public void after() { + void after() { loggerContext.stop(); loggerContext = null; } @Test - public void prodTest() { + void prodTest() { System.setProperty("env", "prod"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ListAppender); + assertInstanceOf(ListAppender.class, app); } @Test - public void devTest() { + void devTest() { System.setProperty("env", "dev"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, app); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SelectArbiterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SelectArbiterTest.java index beff044dc6a..07f1520afd7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SelectArbiterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SelectArbiterTest.java @@ -16,8 +16,8 @@ */ package org.apache.logging.log4j.core.config.arbiters; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; @@ -30,34 +30,34 @@ /** * Tests basic condition processing. */ -public class SelectArbiterTest { +class SelectArbiterTest { static final String CONFIG = "log4j2-selectArbiters.xml"; static LoggerContext loggerContext = null; @AfterEach - public void after() { + void after() { loggerContext.stop(); loggerContext = null; } @Test - public void prodTest() { + void prodTest() { System.setProperty("env", "prod"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ListAppender); + assertInstanceOf(ListAppender.class, app); } @Test - public void devTest() { + void devTest() { System.setProperty("env", "dev"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, app); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SystemPropertyArbiterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SystemPropertyArbiterTest.java index fb3fedb9632..692d9997442 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SystemPropertyArbiterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/arbiters/SystemPropertyArbiterTest.java @@ -16,9 +16,9 @@ */ package org.apache.logging.log4j.core.config.arbiters; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.LoggerContext; @@ -31,36 +31,36 @@ /** * Tests system property condition processing. */ -public class SystemPropertyArbiterTest { +class SystemPropertyArbiterTest { static final String CONFIG = "log4j2-systemPropertyArbiters.xml"; static LoggerContext loggerContext = null; @AfterEach - public void after() { + void after() { loggerContext.stop(); loggerContext = null; System.clearProperty("env"); } @Test - public void prodTest() { + void prodTest() { System.setProperty("env", "prod"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ListAppender); + assertInstanceOf(ListAppender.class, app); } @Test - public void devTest() { + void devTest() { System.setProperty("env", "dev"); loggerContext = Configurator.initialize(null, CONFIG); assertNotNull(loggerContext); final Appender app = loggerContext.getConfiguration().getAppender("Out"); assertNotNull(app); - assertTrue(app instanceof ConsoleAppender); + assertInstanceOf(ConsoleAppender.class, app); } @Test @@ -69,7 +69,7 @@ void classArbiterTest() { assertNotNull(loggerContext); Appender app = loggerContext.getConfiguration().getAppender("ShouldExist"); assertNotNull(app); - assertTrue(app instanceof ListAppender); + assertInstanceOf(ListAppender.class, app); app = loggerContext.getConfiguration().getAppender("ShouldNotExist"); assertNull(app); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationAssemblerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationAssemblerTest.java index 7bcb5437b28..0d6b74f33e6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationAssemblerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationAssemblerTest.java @@ -48,10 +48,10 @@ import org.apache.logging.log4j.core.util.Constants; import org.junit.jupiter.api.Test; -public class ConfigurationAssemblerTest { +class ConfigurationAssemblerTest { @Test - public void testBuildConfiguration() throws Exception { + void testBuildConfiguration() { try { System.setProperty( Constants.LOG4J_CONTEXT_SELECTOR, "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); @@ -68,7 +68,7 @@ public void testBuildConfiguration() throws Exception { } @Test - public void testCustomConfigurationFactory() throws Exception { + void testCustomConfigurationFactory() { try { System.setProperty( ConfigurationFactory.CONFIGURATION_FACTORY_PROPERTY, @@ -88,17 +88,17 @@ private void validate(final Configuration config) { assertNotNull(config.getName()); assertFalse(config.getName().isEmpty()); assertNotNull(config, "No configuration created"); - assertEquals(config.getState(), LifeCycle.State.STARTED, "Incorrect State: " + config.getState()); + assertEquals(LifeCycle.State.STARTED, config.getState(), "Incorrect State: " + config.getState()); final Map appenders = config.getAppenders(); assertNotNull(appenders); - assertEquals(appenders.size(), 2, "Incorrect number of Appenders: " + appenders.size()); + assertEquals(2, appenders.size(), "Incorrect number of Appenders: " + appenders.size()); final KafkaAppender kafkaAppender = (KafkaAppender) appenders.get("Kafka"); final GelfLayout gelfLayout = (GelfLayout) kafkaAppender.getLayout(); final ConsoleAppender consoleAppender = (ConsoleAppender) appenders.get("Stdout"); final PatternLayout patternLayout = (PatternLayout) consoleAppender.getLayout(); final Map loggers = config.getLoggers(); assertNotNull(loggers); - assertEquals(loggers.size(), 2, "Incorrect number of LoggerConfigs: " + loggers.size()); + assertEquals(2, loggers.size(), "Incorrect number of LoggerConfigs: " + loggers.size()); final LoggerConfig rootLoggerConfig = loggers.get(""); assertEquals(Level.ERROR, rootLoggerConfig.getLevel()); assertFalse(rootLoggerConfig.isIncludeLocation()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationBuilderTest.java index 7232d272526..f2dbdf0bc4f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/builder/ConfigurationBuilderTest.java @@ -28,7 +28,7 @@ import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; import org.junit.jupiter.api.Test; -public class ConfigurationBuilderTest { +class ConfigurationBuilderTest { private static final String INDENT = " "; private static final String EOL = System.lineSeparator(); @@ -112,7 +112,7 @@ private void addTestFixtures(final String name, final ConfigurationBuilder builder = ConfigurationBuilderFactory.newConfigurationBuilder(); addTestFixtures("config name", builder); final String xmlConfiguration = builder.toXmlConfiguration(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/DateTypeConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/DateTypeConverterTest.java index dad6b53ffd8..1ccd7d032d9 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/DateTypeConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/DateTypeConverterTest.java @@ -16,26 +16,19 @@ */ package org.apache.logging.log4j.core.config.plugins.convert; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.Time; import java.sql.Timestamp; import java.util.Date; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * */ -@RunWith(Parameterized.class) -public class DateTypeConverterTest { +class DateTypeConverterTest { - private final Class dateClass; - private final long timestamp; - private final Object expected; - - @Parameterized.Parameters public static Object[][] data() { final long millis = System.currentTimeMillis(); return new Object[][] { @@ -46,14 +39,9 @@ public static Object[][] data() { }; } - public DateTypeConverterTest(final Class dateClass, final long timestamp, final Object expected) { - this.dateClass = dateClass; - this.timestamp = timestamp; - this.expected = expected; - } - - @Test - public void testFromMillis() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testFromMillis(final Class dateClass, final long timestamp, final Object expected) { assertEquals(expected, DateTypeConverter.fromMillis(timestamp, dateClass)); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java index b0de4ea7d61..5af8220e11e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverterRegistryTest.java @@ -16,30 +16,32 @@ */ package org.apache.logging.log4j.core.config.plugins.convert; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TypeConverterRegistryTest { +class TypeConverterRegistryTest { - @Test(expected = NullPointerException.class) - public void testFindNullConverter() { - TypeConverterRegistry.getInstance().findCompatibleConverter(null); + @Test + void testFindNullConverter() { + assertThrows(NullPointerException.class, () -> TypeConverterRegistry.getInstance() + .findCompatibleConverter(null)); } @Test - public void testFindBooleanConverter() throws Exception { + void testFindBooleanConverter() throws Exception { final TypeConverter converter = TypeConverterRegistry.getInstance().findCompatibleConverter(Boolean.class); assertNotNull(converter); assertTrue((Boolean) converter.convert("TRUE")); } @Test - public void testFindPrimitiveBooleanConverter() throws Exception { + void testFindPrimitiveBooleanConverter() throws Exception { final TypeConverter converter = TypeConverterRegistry.getInstance().findCompatibleConverter(Boolean.TYPE); assertNotNull(converter); assertTrue((Boolean) converter.convert("tRUe")); @@ -47,7 +49,7 @@ public void testFindPrimitiveBooleanConverter() throws Exception { @SuppressWarnings("unchecked") @Test - public void testFindCharSequenceConverterUsingStringConverter() throws Exception { + void testFindCharSequenceConverterUsingStringConverter() throws Exception { final TypeConverter converter = (TypeConverter) TypeConverterRegistry.getInstance().findCompatibleConverter(CharSequence.class); assertNotNull(converter); @@ -59,7 +61,7 @@ public void testFindCharSequenceConverterUsingStringConverter() throws Exception @SuppressWarnings("unchecked") @Test - public void testFindNumberConverter() throws Exception { + void testFindNumberConverter() { final TypeConverter numberTypeConverter = (TypeConverter) TypeConverterRegistry.getInstance().findCompatibleConverter(Number.class); assertNotNull(numberTypeConverter); @@ -74,7 +76,7 @@ public enum Foo { @SuppressWarnings("unchecked") @Test - public void testFindEnumConverter() throws Exception { + void testFindEnumConverter() throws Exception { final TypeConverter fooTypeConverter = (TypeConverter) TypeConverterRegistry.getInstance().findCompatibleConverter(Foo.class); assertNotNull(fooTypeConverter); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConvertersTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConvertersTest.java index de7741bfb10..1fc961db42d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConvertersTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConvertersTest.java @@ -38,18 +38,15 @@ import org.apache.logging.log4j.core.appender.rolling.action.Duration; import org.apache.logging.log4j.core.layout.GelfLayout; import org.apache.logging.log4j.core.net.Facility; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests {@link TypeConverters}. */ -@RunWith(Parameterized.class) public class TypeConvertersTest { @SuppressWarnings("boxing") - @Parameterized.Parameters public static Collection data() throws Exception { final byte[] byteArray = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 @@ -144,11 +141,11 @@ public static Collection data() throws Exception { {"123", "123".getBytes(Charset.defaultCharset()), null, byte[].class}, {"0xC773218C7EC8EE99", byteArray, null, byte[].class}, {"0xc773218c7ec8ee99", byteArray, null, byte[].class}, - {"Base64:cGxlYXN1cmUu", "pleasure.".getBytes("US-ASCII"), null, byte[].class}, + {"Base64:cGxlYXN1cmUu", "pleasure.".getBytes(StandardCharsets.US_ASCII), null, byte[].class}, // JRE // JRE Charset {"UTF-8", StandardCharsets.UTF_8, null, Charset.class}, - {"ASCII", Charset.forName("ASCII"), "UTF-8", Charset.class}, + {"ASCII", StandardCharsets.US_ASCII, "UTF-8", Charset.class}, {"Not a real charset", StandardCharsets.UTF_8, "UTF-8", Charset.class}, {null, StandardCharsets.UTF_8, "UTF-8", Charset.class}, {null, null, null, Charset.class}, @@ -203,21 +200,9 @@ public static Collection data() throws Exception { }); } - private final String value; - private final Object expected; - private final String defaultValue; - private final Class clazz; - - public TypeConvertersTest( - final String value, final Object expected, final String defaultValue, final Class clazz) { - this.value = value; - this.expected = expected; - this.defaultValue = defaultValue; - this.clazz = clazz; - } - - @Test - public void testConvert() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testConvert(final String value, final Object expected, final String defaultValue, final Class clazz) { final Object actual = TypeConverters.convert(value, clazz, defaultValue); final String assertionMessage = "\nGiven: " + value + "\nDefault: " + defaultValue; assertThat(actual).as(assertionMessage).isEqualTo(expected); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginCacheTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginCacheTest.java index ffd89430c87..c94fd5cb1fc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginCacheTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginCacheTest.java @@ -16,35 +16,32 @@ */ package org.apache.logging.log4j.core.config.plugins.processor; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class PluginCacheTest { +class PluginCacheTest { @Test - public void testOutputIsReproducibleWhenInputOrderingChanges() throws IOException { + void testOutputIsReproducibleWhenInputOrderingChanges() throws IOException { final PluginCache cacheA = new PluginCache(); createCategory(cacheA, "one", Arrays.asList("bravo", "alpha", "charlie")); createCategory(cacheA, "two", Arrays.asList("alpha", "charlie", "bravo")); - assertEquals(cacheA.getAllCategories().size(), 2); - assertEquals(cacheA.getAllCategories().get("one").size(), 3); - assertEquals(cacheA.getAllCategories().get("two").size(), 3); + assertEquals(2, cacheA.getAllCategories().size()); + assertEquals(3, cacheA.getAllCategories().get("one").size()); + assertEquals(3, cacheA.getAllCategories().get("two").size()); final PluginCache cacheB = new PluginCache(); createCategory(cacheB, "two", Arrays.asList("bravo", "alpha", "charlie")); createCategory(cacheB, "one", Arrays.asList("alpha", "charlie", "bravo")); - assertEquals(cacheB.getAllCategories().size(), 2); - assertEquals(cacheB.getAllCategories().get("one").size(), 3); - assertEquals(cacheB.getAllCategories().get("two").size(), 3); + assertEquals(2, cacheB.getAllCategories().size()); + assertEquals(3, cacheB.getAllCategories().get("one").size()); + assertEquals(3, cacheB.getAllCategories().get("two").size()); assertArrayEquals(cacheData(cacheA), cacheData(cacheB)); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginProcessorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginProcessorTest.java index 99798a38c1f..7dfad92ae8b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginProcessorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/processor/PluginProcessorTest.java @@ -17,52 +17,49 @@ package org.apache.logging.log4j.core.config.plugins.processor; import static org.apache.logging.log4j.util.Strings.toRootLowerCase; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.net.URL; import java.util.Enumeration; import java.util.Map; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAliases; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -@RunWith(JUnit4.class) -public class PluginProcessorTest { +class PluginProcessorTest { private static final PluginCache pluginCache = new PluginCache(); private final Plugin p = FakePlugin.class.getAnnotation(Plugin.class); - @BeforeClass - public static void setUpClass() throws Exception { + @BeforeAll + static void setUpClass() throws Exception { final Enumeration resources = PluginProcessor.class.getClassLoader().getResources(PluginProcessor.PLUGIN_CACHE_FILE); pluginCache.loadCacheFiles(resources); } @Test - public void testTestCategoryFound() throws Exception { - assertNotNull("No plugin annotation on FakePlugin.", p); + void testTestCategoryFound() { + assertNotNull(p, "No plugin annotation on FakePlugin."); final Map testCategory = pluginCache.getCategory(p.category()); - assertNotEquals("No plugins were found.", 0, pluginCache.size()); - assertNotNull("The category '" + p.category() + "' was not found.", testCategory); + assertNotEquals(0, pluginCache.size(), "No plugins were found."); + assertNotNull(testCategory, "The category '" + p.category() + "' was not found."); assertFalse(testCategory.isEmpty()); } @Test - public void testFakePluginFoundWithCorrectInformation() throws Exception { + void testFakePluginFoundWithCorrectInformation() { final PluginEntry fake = pluginCache.getCategory(p.category()).get(toRootLowerCase(p.name())); verifyFakePluginEntry(p.name(), fake); } @Test - public void testFakePluginAliasesContainSameInformation() throws Exception { + void testFakePluginAliasesContainSameInformation() { final PluginAliases aliases = FakePlugin.class.getAnnotation(PluginAliases.class); for (final String alias : aliases.value()) { final PluginEntry fake = pluginCache.getCategory(p.category()).get(toRootLowerCase(alias)); @@ -71,7 +68,7 @@ public void testFakePluginAliasesContainSameInformation() throws Exception { } private void verifyFakePluginEntry(final String name, final PluginEntry fake) { - assertNotNull("The plugin '" + toRootLowerCase(name) + "' was not found.", fake); + assertNotNull(fake, "The plugin '" + toRootLowerCase(name) + "' was not found."); assertEquals(FakePlugin.class.getName(), fake.getClassName()); assertEquals(toRootLowerCase(name), fake.getKey()); assertEquals(Plugin.EMPTY, p.elementType()); @@ -81,7 +78,7 @@ private void verifyFakePluginEntry(final String name, final PluginEntry fake) { } @Test - public void testNestedPlugin() throws Exception { + void testNestedPlugin() { final Plugin p = FakePlugin.Nested.class.getAnnotation(Plugin.class); final PluginEntry nested = pluginCache.getCategory(p.category()).get(toRootLowerCase(p.name())); assertNotNull(nested); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java index 815b35894fc..262af0b0350 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java @@ -17,7 +17,7 @@ package org.apache.logging.log4j.core.config.plugins.util; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; @@ -44,7 +44,7 @@ /** * Tests the ResolverUtil class for custom protocol like bundleresource, vfs, vfszip. */ -public class ResolverUtilCustomProtocolTest { +class ResolverUtilCustomProtocolTest { static class NoopURLStreamHandlerFactory implements URLStreamHandlerFactory { @@ -59,7 +59,7 @@ protected URLConnection openConnection(final URL url) { private URLConnection open(final URL url, final Proxy proxy) { return new URLConnection(url) { @Override - public void connect() throws IOException { + public void connect() { // do nothing } }; @@ -141,7 +141,7 @@ public Enumeration getResources(final String name) throws IOException { } @Override - protected Enumeration findResources(final String name) throws IOException { + protected Enumeration findResources(final String name) { return Collections.enumeration(Arrays.asList(findResource(name))); } } @@ -172,41 +172,39 @@ static Stream testExtractedPath() { @ParameterizedTest @MethodSource - public void testExtractedPath(final String urlAsString, final String expected) throws Exception { + void testExtractedPath(final String urlAsString, final String expected) throws Exception { final URL url = new URL(urlAsString); assertThat(new ResolverUtil().extractPath(url)).isEqualTo(expected); } @Test - public void testFindInPackageFromVfsDirectoryURL() throws Exception { + void testFindInPackageFromVfsDirectoryURL() throws Exception { final File tmpDir = new File(DIR, "resolverutil3"); try (final URLClassLoader cl = ResolverUtilTest.compileAndCreateClassLoader(tmpDir, "3")) { final ResolverUtil resolverUtil = new ResolverUtil(); resolverUtil.setClassLoader(new SingleURLClassLoader(new URL("vfs:/" + tmpDir + "/customplugin3/"), cl)); resolverUtil.findInPackage(new PluginTest(), "customplugin3"); + assertEquals(1, resolverUtil.getClasses().size(), "Class not found in packages"); assertEquals( - "Class not found in packages", 1, resolverUtil.getClasses().size()); - assertEquals( - "Unexpected class resolved", cl.loadClass("customplugin3.FixedString3Layout"), - resolverUtil.getClasses().iterator().next()); + resolverUtil.getClasses().iterator().next(), + "Unexpected class resolved"); } } @Test - public void testFindInPackageFromVfsJarURL() throws Exception { + void testFindInPackageFromVfsJarURL() throws Exception { final File tmpDir = new File(DIR, "resolverutil4"); try (final URLClassLoader cl = ResolverUtilTest.compileJarAndCreateClassLoader(tmpDir, "4")) { final ResolverUtil resolverUtil = new ResolverUtil(); resolverUtil.setClassLoader( new SingleURLClassLoader(new URL("vfs:/" + tmpDir + "/customplugin4.jar/customplugin4/"), cl)); resolverUtil.findInPackage(new PluginTest(), "customplugin4"); + assertEquals(1, resolverUtil.getClasses().size(), "Class not found in packages"); assertEquals( - "Class not found in packages", 1, resolverUtil.getClasses().size()); - assertEquals( - "Unexpected class resolved", cl.loadClass("customplugin4.FixedString4Layout"), - resolverUtil.getClasses().iterator().next()); + resolverUtil.getClasses().iterator().next(), + "Unexpected class resolved"); } } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java index 5d20a79a7cf..0ff21e20567 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java @@ -20,7 +20,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; -import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; @@ -46,7 +45,7 @@ /** * Tests the ResolverUtil class. */ -public class ResolverUtilTest { +class ResolverUtilTest { static Stream testExtractedPath() { return Stream.of( @@ -78,13 +77,13 @@ static Stream testExtractedPath() { @ParameterizedTest @MethodSource - public void testExtractedPath(final String urlAsString, final String expected) throws Exception { + void testExtractedPath(final String urlAsString, final String expected) throws Exception { final URL url = new URL(urlAsString); assertThat(new ResolverUtil().extractPath(url)).isEqualTo(expected); } @Test - public void testExtractPathFromJarUrlNotDecodedIfFileExists() throws Exception { + void testExtractPathFromJarUrlNotDecodedIfFileExists() throws Exception { testExtractPathFromJarUrlNotDecodedIfFileExists("/log4j+config+with+plus+characters.xml"); } @@ -100,13 +99,13 @@ private void testExtractPathFromJarUrlNotDecodedIfFileExists(final String existi } @Test - public void testFileFromUriWithSpacesAndPlusCharactersInName() throws Exception { + void testFileFromUriWithSpacesAndPlusCharactersInName() throws Exception { final String existingFile = "/s p a c e s/log4j+config+with+plus+characters.xml"; testExtractPathFromJarUrlNotDecodedIfFileExists(existingFile); } @Test - public void testExtractPathFromFileUrlNotDecodedIfFileExists() throws Exception { + void testExtractPathFromFileUrlNotDecodedIfFileExists() throws Exception { final String existingFile = "/log4j+config+with+plus+characters.xml"; final URL url = ResolverUtilTest.class.getResource(existingFile); assertThat(url).hasProtocol("file"); @@ -115,7 +114,7 @@ public void testExtractPathFromFileUrlNotDecodedIfFileExists() throws Exception } @Test - public void testFindInPackageFromDirectoryPath(final @TempDir File tmpDir) throws Exception { + void testFindInPackageFromDirectoryPath(final @TempDir File tmpDir) throws Exception { try (final URLClassLoader cl = compileAndCreateClassLoader(tmpDir, "1")) { final ResolverUtil resolverUtil = new ResolverUtil(); resolverUtil.setClassLoader(cl); @@ -129,7 +128,7 @@ public void testFindInPackageFromDirectoryPath(final @TempDir File tmpDir) throw } @Test - public void testFindInPackageFromJarPath(final @TempDir File tmpDir) throws Exception { + void testFindInPackageFromJarPath(final @TempDir File tmpDir) throws Exception { try (final URLClassLoader cl = compileJarAndCreateClassLoader(tmpDir, "2")) { final ResolverUtil resolverUtil = new ResolverUtil(); resolverUtil.setClassLoader(cl); @@ -142,8 +141,7 @@ public void testFindInPackageFromJarPath(final @TempDir File tmpDir) throws Exce } } - static URLClassLoader compileJarAndCreateClassLoader(final File tmpDir, final String suffix) - throws IOException, Exception { + static URLClassLoader compileJarAndCreateClassLoader(final File tmpDir, final String suffix) throws Exception { compile(tmpDir, suffix); final File jarFile = new File(tmpDir, "customplugin" + suffix + ".jar"); final URI jarURI = jarFile.toURI(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/RequiredValidatorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/RequiredValidatorTest.java index 33a5ca37d70..9a53b6fced7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/RequiredValidatorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/RequiredValidatorTest.java @@ -29,14 +29,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class RequiredValidatorTest { +class RequiredValidatorTest { private PluginType plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach - public void setUp() throws Exception { + void setUp() { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType) manager.getPluginType("Validator"); @@ -45,7 +45,7 @@ public void setUp() throws Exception { } @Test - public void testNullDefaultValue() throws Exception { + void testNullDefaultValue() { final ValidatingPlugin validatingPlugin = (ValidatingPlugin) new PluginBuilder(plugin) .withConfiguration(new NullConfiguration()) .withConfigurationNode(node) @@ -54,7 +54,7 @@ public void testNullDefaultValue() throws Exception { } @Test - public void testNonNullValue() throws Exception { + void testNonNullValue() { node.getAttributes().put("name", "foo"); final ValidatingPlugin validatingPlugin = (ValidatingPlugin) new PluginBuilder(plugin) .withConfiguration(new NullConfiguration()) diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidHostValidatorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidHostValidatorTest.java index af757064c6e..772c6a62d5f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidHostValidatorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidHostValidatorTest.java @@ -31,14 +31,14 @@ import org.junit.jupiter.api.Test; @StatusLoggerLevel("FATAL") -public class ValidHostValidatorTest { +class ValidHostValidatorTest { private PluginType plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach - public void setUp() throws Exception { + void setUp() { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType) manager.getPluginType("HostAndPort"); @@ -47,12 +47,12 @@ public void setUp() throws Exception { } @Test - public void testNullHost() throws Exception { + void testNullHost() { assertNull(buildPlugin()); } @Test - public void testInvalidIpAddress() throws Exception { + void testInvalidIpAddress() { node.getAttributes().put("host", "256.256.256.256"); node.getAttributes().put("port", "1"); final HostAndPort plugin = buildPlugin(); @@ -60,7 +60,7 @@ public void testInvalidIpAddress() throws Exception { } @Test - public void testLocalhost() throws Exception { + void testLocalhost() { node.getAttributes().put("host", "localhost"); node.getAttributes().put("port", "1"); final HostAndPort hostAndPort = buildPlugin(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidPortValidatorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidPortValidatorTest.java index a4b927b562f..99d4853233c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidPortValidatorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidPortValidatorTest.java @@ -28,13 +28,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ValidPortValidatorTest { +class ValidPortValidatorTest { private PluginType plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach - public void setUp() throws Exception { + void setUp() { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType) manager.getPluginType("HostAndPort"); @@ -44,19 +44,19 @@ public void setUp() throws Exception { } @Test - public void testNegativePort() throws Exception { + void testNegativePort() { node.getAttributes().put("port", "-1"); assertNull(buildPlugin()); } @Test - public void testValidPort() throws Exception { + void testValidPort() { node.getAttributes().put("port", "10"); assertNotNull(buildPlugin()); } @Test - public void testInvalidPort() throws Exception { + void testInvalidPort() { node.getAttributes().put("port", "1234567890"); assertNull(buildPlugin()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithFailoverTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithFailoverTest.java index 7a217392315..d47ba5457c1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithFailoverTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithFailoverTest.java @@ -39,14 +39,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ValidatingPluginWithFailoverTest { +class ValidatingPluginWithFailoverTest { private PluginType plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach - public void setUp() throws Exception { + void setUp() { final PluginManager manager = new PluginManager(Core.CATEGORY_NAME); manager.collectPlugins(); plugin = (PluginType) manager.getPluginType("failover"); @@ -66,7 +66,7 @@ public void setUp() throws Exception { } @Test - public void testDoesNotLog_NoParameterThatMatchesElement_message() { + void testDoesNotLog_NoParameterThatMatchesElement_message() { final StoringStatusListener listener = new StoringStatusListener(); // @formatter:off final PluginBuilder builder = new PluginBuilder(plugin) diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericBuilderTest.java index 25d753aa995..6c6090438ff 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericBuilderTest.java @@ -29,14 +29,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ValidatingPluginWithGenericBuilderTest { +class ValidatingPluginWithGenericBuilderTest { private PluginType plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach - public void setUp() throws Exception { + void setUp() { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType) @@ -46,7 +46,7 @@ public void setUp() throws Exception { } @Test - public void testNullDefaultValue() throws Exception { + void testNullDefaultValue() { final ValidatingPluginWithGenericBuilder validatingPlugin = (ValidatingPluginWithGenericBuilder) new PluginBuilder(plugin) .withConfiguration(new NullConfiguration()) @@ -56,7 +56,7 @@ public void testNullDefaultValue() throws Exception { } @Test - public void testNonNullValue() throws Exception { + void testNonNullValue() { node.getAttributes().put("name", "foo"); final ValidatingPluginWithGenericBuilder validatingPlugin = (ValidatingPluginWithGenericBuilder) new PluginBuilder(plugin) diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericSubclassFoo1BuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericSubclassFoo1BuilderTest.java index 91bcc5b89a2..e3360258b7d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericSubclassFoo1BuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithGenericSubclassFoo1BuilderTest.java @@ -29,14 +29,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ValidatingPluginWithGenericSubclassFoo1BuilderTest { +class ValidatingPluginWithGenericSubclassFoo1BuilderTest { private PluginType plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach - public void setUp() throws Exception { + void setUp() { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType) @@ -46,7 +46,7 @@ public void setUp() throws Exception { } @Test - public void testNullDefaultValue() throws Exception { + void testNullDefaultValue() { final PluginWithGenericSubclassFoo1Builder validatingPlugin = (PluginWithGenericSubclassFoo1Builder) new PluginBuilder(plugin) .withConfiguration(new NullConfiguration()) @@ -56,7 +56,7 @@ public void testNullDefaultValue() throws Exception { } @Test - public void testNonNullValue() throws Exception { + void testNonNullValue() { node.getAttributes().put("thing", "thing1"); node.getAttributes().put("foo1", "foo1"); final PluginWithGenericSubclassFoo1Builder validatingPlugin = diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithTypedBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithTypedBuilderTest.java index caed8b7267f..579be80385e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithTypedBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidatingPluginWithTypedBuilderTest.java @@ -29,14 +29,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ValidatingPluginWithTypedBuilderTest { +class ValidatingPluginWithTypedBuilderTest { private PluginType plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach - public void setUp() throws Exception { + void setUp() { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType) @@ -46,7 +46,7 @@ public void setUp() throws Exception { } @Test - public void testNullDefaultValue() throws Exception { + void testNullDefaultValue() { // @formatter:off final ValidatingPluginWithTypedBuilder validatingPlugin = (ValidatingPluginWithTypedBuilder) new PluginBuilder(plugin) @@ -58,7 +58,7 @@ public void testNullDefaultValue() throws Exception { } @Test - public void testNonNullValue() throws Exception { + void testNonNullValue() { node.getAttributes().put("name", "foo"); // @formatter:off final ValidatingPluginWithTypedBuilder validatingPlugin = diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationTest.java index 5a3329a5b17..181879489ca 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/properties/PropertiesConfigurationTest.java @@ -19,8 +19,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Map; @@ -46,7 +46,7 @@ class PropertiesConfigurationTest { @Test @LoggerContextSource("log4j2-properties.properties") void testPropertiesConfiguration(final Configuration config) { - assertEquals(config.getState(), LifeCycle.State.STARTED, "Incorrect State: " + config.getState()); + assertEquals(LifeCycle.State.STARTED, config.getState(), "Incorrect State: " + config.getState()); final Map appenders = config.getAppenders(); assertNotNull(appenders); assertEquals(1, appenders.size(), "Incorrect number of Appenders: " + appenders.size()); @@ -55,7 +55,7 @@ void testPropertiesConfiguration(final Configuration config) { assertEquals(2, loggers.size(), "Incorrect number of LoggerConfigs: " + loggers.size()); final Filter filter = config.getFilter(); assertNotNull(filter, "No Filter"); - assertTrue(filter instanceof ThresholdFilter, "Not a Threshold Filter"); + assertInstanceOf(ThresholdFilter.class, filter, "Not a Threshold Filter"); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); } @@ -63,13 +63,13 @@ void testPropertiesConfiguration(final Configuration config) { @Test @LoggerContextSource("log4j2-properties-root-only.properties") void testRootLoggerOnly(final Configuration config) { - assertEquals(config.getState(), LifeCycle.State.STARTED, "Incorrect State: " + config.getState()); + assertEquals(LifeCycle.State.STARTED, config.getState(), "Incorrect State: " + config.getState()); final Map appenders = config.getAppenders(); assertNotNull(appenders); - assertEquals(appenders.size(), 1, "Incorrect number of Appenders: " + appenders.size()); + assertEquals(1, appenders.size(), "Incorrect number of Appenders: " + appenders.size()); final Map loggers = config.getLoggers(); assertNotNull(loggers); - assertEquals(loggers.size(), 1, "Incorrect number of LoggerConfigs: " + loggers.size()); + assertEquals(1, loggers.size(), "Incorrect number of LoggerConfigs: " + loggers.size()); final Filter filter = config.getFilter(); assertNotNull(filter, "No Filter"); assertThat(filter, instanceOf(ThresholdFilter.class)); @@ -80,13 +80,13 @@ void testRootLoggerOnly(final Configuration config) { @Test @LoggerContextSource("log4j-rolling.properties") void testRollingFile(final Configuration config) { - assertEquals(config.getState(), LifeCycle.State.STARTED, "Incorrect State: " + config.getState()); + assertEquals(LifeCycle.State.STARTED, config.getState(), "Incorrect State: " + config.getState()); final Map appenders = config.getAppenders(); assertNotNull(appenders); - assertEquals(appenders.size(), 3, "Incorrect number of Appenders: " + appenders.size()); + assertEquals(3, appenders.size(), "Incorrect number of Appenders: " + appenders.size()); final Map loggers = config.getLoggers(); assertNotNull(loggers); - assertEquals(loggers.size(), 2, "Incorrect number of LoggerConfigs: " + loggers.size()); + assertEquals(2, loggers.size(), "Incorrect number of LoggerConfigs: " + loggers.size()); final Filter filter = config.getFilter(); assertNotNull(filter, "No Filter"); assertThat(filter, instanceOf(ThresholdFilter.class)); @@ -97,13 +97,13 @@ void testRollingFile(final Configuration config) { @Test @LoggerContextSource("log4j2-properties-trailing-space-on-level.properties") void testTrailingSpaceOnLevel(final Configuration config) { - assertEquals(config.getState(), LifeCycle.State.STARTED, "Incorrect State: " + config.getState()); + assertEquals(LifeCycle.State.STARTED, config.getState(), "Incorrect State: " + config.getState()); final Map appenders = config.getAppenders(); assertNotNull(appenders); - assertEquals(appenders.size(), 1, "Incorrect number of Appenders: " + appenders.size()); + assertEquals(1, appenders.size(), "Incorrect number of Appenders: " + appenders.size()); final Map loggers = config.getLoggers(); assertNotNull(loggers); - assertEquals(loggers.size(), 2, "Incorrect number of LoggerConfigs: " + loggers.size()); + assertEquals(2, loggers.size(), "Incorrect number of LoggerConfigs: " + loggers.size()); final Filter filter = config.getFilter(); assertNotNull(filter, "No Filter"); assertThat(filter, instanceOf(ThresholdFilter.class)); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlConfigurationSecurity.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlConfigurationSecurity.java index 07608bb0c1a..64aa3aa4d63 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlConfigurationSecurity.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlConfigurationSecurity.java @@ -18,7 +18,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.io.IOException; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configurator; import org.junit.jupiter.api.Tag; @@ -27,11 +26,11 @@ @Tag("functional") @Tag("security") -public class XmlConfigurationSecurity { +class XmlConfigurationSecurity { @Test @Timeout(5) - public void xmlSecurity() throws IOException { + void xmlSecurity() { final LoggerContext context = Configurator.initialize("XmlConfigurationSecurity", "XmlConfigurationSecurity.xml"); assertNotNull(context.getConfiguration().getAppender("list")); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlLoggerPropsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlLoggerPropsTest.java index 203790718a4..81d36e00d41 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlLoggerPropsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/xml/XmlLoggerPropsTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class XmlLoggerPropsTest { +class XmlLoggerPropsTest { @BeforeAll static void setupClass() { @@ -46,7 +46,7 @@ static void tearDownClass() { @Test @LoggerContextSource("log4j-loggerprops.xml") - public void testWithProps(final LoggerContext context, @Named("List") final ListAppender listAppender) { + void testWithProps(final LoggerContext context, @Named("List") final ListAppender listAppender) { assertThat(context.getConfiguration(), is(instanceOf(XmlConfiguration.class))); context.getLogger(getClass()).debug("Test with props"); context.getLogger("tiny.bubbles").debug("Test on root"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/context/internal/GarbageFreeSortedArrayThreadContextMapTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/context/internal/GarbageFreeSortedArrayThreadContextMapTest.java index 192c72e85ce..54a4a23a15f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/context/internal/GarbageFreeSortedArrayThreadContextMapTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/context/internal/GarbageFreeSortedArrayThreadContextMapTest.java @@ -28,7 +28,7 @@ import org.apache.logging.log4j.util.PropertiesUtil; import org.junit.jupiter.api.Test; -public class GarbageFreeSortedArrayThreadContextMapTest extends ThreadContextMapSuite { +class GarbageFreeSortedArrayThreadContextMapTest extends ThreadContextMapSuite { private GarbageFreeSortedArrayThreadContextMap createThreadContextMap() { return new GarbageFreeSortedArrayThreadContextMap(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterTest.java index 34f0f7e6967..8996b9f2f16 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterTest.java @@ -29,10 +29,10 @@ /** * Tests the AbstractFilter test. */ -public class AbstractFilterTest { +class AbstractFilterTest { @Test - public void testUnrolledBackwardsCompatible() { + void testUnrolledBackwardsCompatible() { final ConcreteFilter filter = new ConcreteFilter(); final Filter.Result expected = Filter.Result.DENY; verifyMethodsWithUnrolledVarargs(filter, Filter.Result.DENY); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterableTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterableTest.java index fec1da628c3..4f117a1ccf5 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterableTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractFilterableTest.java @@ -18,26 +18,26 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.Filter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class AbstractFilterableTest { +class AbstractFilterableTest { MockedAbstractFilterable filterable; @BeforeEach - public void setup() { + void setup() { filterable = new MockedAbstractFilterable(); } @Test - public void testAddSimpleFilter() throws Exception { + void testAddSimpleFilter() { final Filter filter = ThresholdFilter.createFilter(Level.ERROR, null, null); filterable.addFilter(filter); @@ -45,7 +45,7 @@ public void testAddSimpleFilter() throws Exception { } @Test - public void testAddMultipleSimpleFilters() throws Exception { + void testAddMultipleSimpleFilters() { final Filter filter = ThresholdFilter.createFilter(Level.ERROR, null, null); filterable.addFilter(filter); @@ -53,12 +53,12 @@ public void testAddMultipleSimpleFilters() throws Exception { // adding a second filter converts the filter // into a CompositeFilter.class filterable.addFilter(filter); - assertTrue(filterable.getFilter() instanceof CompositeFilter); + assertInstanceOf(CompositeFilter.class, filterable.getFilter()); assertEquals(2, ((CompositeFilter) filterable.getFilter()).getFilters().size()); } @Test - public void testAddMultipleEqualSimpleFilter() throws Exception { + void testAddMultipleEqualSimpleFilter() { final Filter filter = new EqualFilter("test"); filterable.addFilter(filter); @@ -66,12 +66,12 @@ public void testAddMultipleEqualSimpleFilter() throws Exception { // adding a second filter converts the filter // into a CompositeFilter.class filterable.addFilter(filter); - assertTrue(filterable.getFilter() instanceof CompositeFilter); + assertInstanceOf(CompositeFilter.class, filterable.getFilter()); assertEquals(2, ((CompositeFilter) filterable.getFilter()).getFilters().size()); } @Test - public void testAddCompositeFilter() throws Exception { + void testAddCompositeFilter() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter compositeFilter = CompositeFilter.createFilters(filter1, filter2); @@ -81,7 +81,7 @@ public void testAddCompositeFilter() throws Exception { } @Test - public void testAddMultipleCompositeFilters() throws Exception { + void testAddMultipleCompositeFilters() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter3 = ThresholdFilter.createFilter(Level.ERROR, null, null); @@ -92,12 +92,12 @@ public void testAddMultipleCompositeFilters() throws Exception { // adding a second filter converts the filter // into a CompositeFilter.class filterable.addFilter(compositeFilter); - assertTrue(filterable.getFilter() instanceof CompositeFilter); + assertInstanceOf(CompositeFilter.class, filterable.getFilter()); assertEquals(6, ((CompositeFilter) filterable.getFilter()).getFilters().size()); } @Test - public void testAddSimpleFilterAndCompositeFilter() throws Exception { + void testAddSimpleFilterAndCompositeFilter() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter notInCompositeFilterFilter = ThresholdFilter.createFilter(Level.ERROR, null, null); @@ -108,12 +108,12 @@ public void testAddSimpleFilterAndCompositeFilter() throws Exception { // adding a second filter converts the filter // into a CompositeFilter.class filterable.addFilter(compositeFilter); - assertTrue(filterable.getFilter() instanceof CompositeFilter); + assertInstanceOf(CompositeFilter.class, filterable.getFilter()); assertEquals(2, ((CompositeFilter) filterable.getFilter()).getFilters().size()); } @Test - public void testAddCompositeFilterAndSimpleFilter() throws Exception { + void testAddCompositeFilterAndSimpleFilter() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter notInCompositeFilterFilter = ThresholdFilter.createFilter(Level.ERROR, null, null); @@ -124,12 +124,12 @@ public void testAddCompositeFilterAndSimpleFilter() throws Exception { // adding a second filter converts the filter // into a CompositeFilter.class filterable.addFilter(notInCompositeFilterFilter); - assertTrue(filterable.getFilter() instanceof CompositeFilter); + assertInstanceOf(CompositeFilter.class, filterable.getFilter()); assertEquals(3, ((CompositeFilter) filterable.getFilter()).getFilters().size()); } @Test - public void testRemoveSimpleFilterFromSimpleFilter() throws Exception { + void testRemoveSimpleFilterFromSimpleFilter() { final Filter filter = ThresholdFilter.createFilter(Level.ERROR, null, null); filterable.addFilter(filter); @@ -138,7 +138,7 @@ public void testRemoveSimpleFilterFromSimpleFilter() throws Exception { } @Test - public void testRemoveSimpleEqualFilterFromSimpleFilter() throws Exception { + void testRemoveSimpleEqualFilterFromSimpleFilter() { final Filter filterOriginal = new EqualFilter("test"); final Filter filterCopy = new EqualFilter("test"); @@ -148,7 +148,7 @@ public void testRemoveSimpleEqualFilterFromSimpleFilter() throws Exception { } @Test - public void testRemoveSimpleEqualFilterFromTwoSimpleFilters() throws Exception { + void testRemoveSimpleEqualFilterFromTwoSimpleFilters() { final Filter filterOriginal = new EqualFilter("test"); final Filter filterCopy = new EqualFilter("test"); @@ -161,7 +161,7 @@ public void testRemoveSimpleEqualFilterFromTwoSimpleFilters() throws Exception { } @Test - public void testRemoveSimpleEqualFilterFromMultipleSimpleFilters() throws Exception { + void testRemoveSimpleEqualFilterFromMultipleSimpleFilters() { final Filter filterOriginal = new EqualFilter("test"); final Filter filterCopy = new EqualFilter("test"); @@ -169,7 +169,7 @@ public void testRemoveSimpleEqualFilterFromMultipleSimpleFilters() throws Except filterable.addFilter(filterOriginal); filterable.addFilter(filterCopy); filterable.removeFilter(filterCopy); - assertTrue(filterable.getFilter() instanceof CompositeFilter); + assertInstanceOf(CompositeFilter.class, filterable.getFilter()); assertEquals(2, ((CompositeFilter) filterable.getFilter()).getFilters().size()); filterable.removeFilter(filterCopy); assertEquals(filterOriginal, filterable.getFilter()); @@ -178,7 +178,7 @@ public void testRemoveSimpleEqualFilterFromMultipleSimpleFilters() throws Except } @Test - public void testRemoveNullFromSingleSimpleFilter() throws Exception { + void testRemoveNullFromSingleSimpleFilter() { final Filter filter = ThresholdFilter.createFilter(Level.ERROR, null, null); filterable.addFilter(filter); @@ -187,7 +187,7 @@ public void testRemoveNullFromSingleSimpleFilter() throws Exception { } @Test - public void testRemoveNonExistingFilterFromSingleSimpleFilter() throws Exception { + void testRemoveNonExistingFilterFromSingleSimpleFilter() { final Filter filter = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter newFilter = ThresholdFilter.createFilter(Level.WARN, null, null); @@ -197,7 +197,7 @@ public void testRemoveNonExistingFilterFromSingleSimpleFilter() throws Exception } @Test - public void testRemoveSimpleFilterFromCompositeFilter() { + void testRemoveSimpleFilterFromCompositeFilter() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter compositeFilter = CompositeFilter.createFilters(filter1, filter2); @@ -212,7 +212,7 @@ public void testRemoveSimpleFilterFromCompositeFilter() { } @Test - public void testRemoveSimpleFilterFromCompositeAndSimpleFilter() { + void testRemoveSimpleFilterFromCompositeAndSimpleFilter() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter compositeFilter = CompositeFilter.createFilters(filter1, filter2); @@ -223,12 +223,12 @@ public void testRemoveSimpleFilterFromCompositeAndSimpleFilter() { // should not remove internal filter of compositeFilter filterable.removeFilter(anotherFilter); - assertTrue(filterable.getFilter() instanceof CompositeFilter); + assertInstanceOf(CompositeFilter.class, filterable.getFilter()); assertEquals(2, ((CompositeFilter) filterable.getFilter()).getFilters().size()); } @Test - public void testRemoveCompositeFilterFromCompositeFilter() { + void testRemoveCompositeFilterFromCompositeFilter() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter compositeFilter = CompositeFilter.createFilters(filter1, filter2); @@ -239,7 +239,7 @@ public void testRemoveCompositeFilterFromCompositeFilter() { } @Test - public void testRemoveFiltersFromComposite() { + void testRemoveFiltersFromComposite() { final Filter filter1 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter filter2 = ThresholdFilter.createFilter(Level.ERROR, null, null); final Filter compositeFilter = CompositeFilter.createFilters(filter1, filter2); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractScriptFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractScriptFilterTest.java index d883eaec78a..a9fcb1fc0ae 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractScriptFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/AbstractScriptFilterTest.java @@ -34,7 +34,7 @@ public abstract class AbstractScriptFilterTest { @Test - public void testGroovyFilter(final LoggerContext context, @Named("List") final ListAppender app) throws Exception { + public void testGroovyFilter(final LoggerContext context, @Named("List") final ListAppender app) { final Logger logger = context.getLogger("TestGroovyFilter"); logger.traceEntry(); logger.info("This should not be logged"); @@ -44,15 +44,14 @@ public void testGroovyFilter(final LoggerContext context, @Named("List") final L try { final List messages = app.getMessages(); assertNotNull(messages, "No Messages"); - assertEquals(messages.size(), 2, "Incorrect number of messages. Expected 2, Actual " + messages.size()); + assertEquals(2, messages.size(), "Incorrect number of messages. Expected 2, Actual " + messages.size()); } finally { app.clear(); } } @Test - public void testJavascriptFilter(final LoggerContext context, @Named("List") final ListAppender app) - throws Exception { + public void testJavascriptFilter(final LoggerContext context, @Named("List") final ListAppender app) { final Logger logger = context.getLogger("TestJavaScriptFilter"); logger.traceEntry(); logger.info("This should not be logged"); @@ -62,7 +61,7 @@ public void testJavascriptFilter(final LoggerContext context, @Named("List") fin final List messages = app.getMessages(); try { assertNotNull(messages, "No Messages"); - assertEquals(messages.size(), 2, "Incorrect number of messages. Expected 2, Actual " + messages.size()); + assertEquals(2, messages.size(), "Incorrect number of messages. Expected 2, Actual " + messages.size()); } finally { app.clear(); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterLogDelayTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterLogDelayTest.java index 8c78bf29c08..8fd101038eb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterLogDelayTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterLogDelayTest.java @@ -27,10 +27,10 @@ /** * Unit test for BurstFilter. */ -public class BurstFilterLogDelayTest { +class BurstFilterLogDelayTest { @Test - public void testCompareToOverflow() { + void testCompareToOverflow() { // no overflow, but close final Delayed d1 = BurstFilter.createLogDelay(Long.MAX_VALUE - TimeUnit.SECONDS.toNanos(10) - System.nanoTime()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterTest.java index e76bf6c6f05..4d03e838b9e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/BurstFilterTest.java @@ -33,7 +33,7 @@ * Unit test for BurstFilter. */ @LoggerContextSource("log4j-burst.xml") -public class BurstFilterTest { +class BurstFilterTest { private final ListAppender app; private final BurstFilter filter; @@ -52,7 +52,7 @@ public BurstFilterTest(final LoggerContext context, @Named("ListAppender") final * sure the filter allows the appropriate number of messages to be logged. */ @Test - public void test() throws Exception { + void test() throws Exception { System.nanoTime(); for (int i = 0; i < 110; i++) { if (i % 10 == 0) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/CompositeFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/CompositeFilterTest.java index a7782595620..71b2d99c992 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/CompositeFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/CompositeFilterTest.java @@ -23,10 +23,10 @@ import org.apache.logging.log4j.core.Filter.Result; import org.junit.jupiter.api.Test; -public class CompositeFilterTest { +class CompositeFilterTest { @Test - public void testConcatenation() { + void testConcatenation() { final Filter a = DenyAllFilter.newBuilder().setOnMatch(Result.ACCEPT).build(); final Filter b = DenyAllFilter.newBuilder().setOnMatch(Result.NEUTRAL).build(); final Filter c = DenyAllFilter.newBuilder().setOnMatch(Result.DENY).build(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/DynamicThresholdFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/DynamicThresholdFilterTest.java index 469d7167bcb..2bbaa0c5551 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/DynamicThresholdFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/DynamicThresholdFilterTest.java @@ -17,6 +17,7 @@ package org.apache.logging.log4j.core.filter; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -35,10 +36,10 @@ import org.junit.jupiter.api.Test; @UsingThreadContextMap -public class DynamicThresholdFilterTest { +class DynamicThresholdFilterTest { @Test - public void testFilter() { + void testFilter() { ThreadContext.put("userid", "testuser"); ThreadContext.put("organization", "apache"); final KeyValuePair[] pairs = @@ -47,8 +48,8 @@ public void testFilter() { DynamicThresholdFilter.createFilter("userid", pairs, Level.ERROR, null, null); filter.start(); assertTrue(filter.isStarted()); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, null)); ThreadContext.clearMap(); ThreadContext.put("userid", "JohnDoe"); ThreadContext.put("organization", "apache"); @@ -66,7 +67,7 @@ public void testFilter() { } @Test - public void testFilterWorksWhenParamsArePassedAsArguments() { + void testFilterWorksWhenParamsArePassedAsArguments() { ThreadContext.put("userid", "testuser"); ThreadContext.put("organization", "apache"); final KeyValuePair[] pairs = @@ -85,10 +86,10 @@ public void testFilterWorksWhenParamsArePassedAsArguments() { @Test @LoggerContextSource("log4j2-dynamicfilter.xml") - public void testConfig(final Configuration config) { + void testConfig(final Configuration config) { final Filter filter = config.getFilter(); assertNotNull(filter, "No DynamicThresholdFilter"); - assertTrue(filter instanceof DynamicThresholdFilter, "Not a DynamicThresholdFilter"); + assertInstanceOf(DynamicThresholdFilter.class, filter, "Not a DynamicThresholdFilter"); final DynamicThresholdFilter dynamic = (DynamicThresholdFilter) filter; final String key = dynamic.getKey(); assertNotNull(key, "Key is null"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MapFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MapFilterTest.java index 68bf0e63d9e..49a4bf9066f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MapFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MapFilterTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -39,10 +40,10 @@ import org.apache.logging.log4j.util.IndexedReadOnlyStringMap; import org.junit.jupiter.api.Test; -public class MapFilterTest { +class MapFilterTest { @Test - public void testFilter() { + void testFilter() { final KeyValuePair[] pairs = new KeyValuePair[] {new KeyValuePair("FromAccount", "211000"), new KeyValuePair("ToAccount", "123456")}; MapFilter filter = MapFilter.createFilter(pairs, "and", null, null); @@ -71,10 +72,10 @@ public void testFilter() { @Test @LoggerContextSource("log4j2-mapfilter.xml") - public void testConfig(final Configuration config, @Named("LIST") final ListAppender app) { + void testConfig(final Configuration config, @Named("LIST") final ListAppender app) { final Filter filter = config.getFilter(); assertNotNull(filter, "No MapFilter"); - assertTrue(filter instanceof MapFilter, "Not a MapFilter"); + assertInstanceOf(MapFilter.class, filter, "Not a MapFilter"); final MapFilter mapFilter = (MapFilter) filter; assertFalse(mapFilter.isAnd(), "Should not be And filter"); final IndexedReadOnlyStringMap map = mapFilter.getStringMap(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MarkerFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MarkerFilterTest.java index aa4864d668a..82812e4da98 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MarkerFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/MarkerFilterTest.java @@ -28,10 +28,10 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.junit.jupiter.api.Test; -public class MarkerFilterTest { +class MarkerFilterTest { @Test - public void testMarkers() { + void testMarkers() { final Marker parent = MarkerManager.getMarker("Parent"); final Marker child = MarkerManager.getMarker("Child").setParents(parent); final Marker grandChild = MarkerManager.getMarker("GrandChild").setParents(child); @@ -40,9 +40,9 @@ public void testMarkers() { MarkerFilter filter = MarkerFilter.createFilter("Parent", null, null); filter.start(); assertTrue(filter.isStarted()); - assertSame(Filter.Result.DENY, filter.filter(null, null, stranger, (Object) null, (Throwable) null)); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, null, child, (Object) null, (Throwable) null)); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, null, grandChild, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, null, stranger, (Object) null, null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, null, child, (Object) null, null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, null, grandChild, (Object) null, null)); filter.stop(); LogEvent event = Log4jLogEvent.newBuilder() // .setMarker(grandChild) // diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/NoMarkerFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/NoMarkerFilterTest.java index b39dbf1ffa5..cf51067dee4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/NoMarkerFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/NoMarkerFilterTest.java @@ -28,16 +28,16 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.junit.jupiter.api.Test; -public class NoMarkerFilterTest { +class NoMarkerFilterTest { @Test - public void testMarkers() { + void testMarkers() { final Marker sampleMarker = MarkerManager.getMarker("SampleMarker"); final NoMarkerFilter filter = NoMarkerFilter.newBuilder().build(); filter.start(); assertTrue(filter.isStarted()); - assertSame(Filter.Result.DENY, filter.filter(null, null, sampleMarker, (Object) null, (Throwable) null)); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, null, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, null, sampleMarker, (Object) null, null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, null, null, (Object) null, null)); filter.stop(); LogEvent event = Log4jLogEvent.newBuilder() // .setLevel(Level.DEBUG) // diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/RegexFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/RegexFilterTest.java index a3e8bf3d025..a71e3dad18d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/RegexFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/RegexFilterTest.java @@ -33,22 +33,20 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class RegexFilterTest { +class RegexFilterTest { @BeforeAll - public static void before() { + static void before() { StatusLogger.getLogger().setLevel(Level.OFF); } @Test - public void testThresholds() throws Exception { + void testThresholds() throws Exception { RegexFilter filter = RegexFilter.createFilter(".* test .*", null, false, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame( - Filter.Result.NEUTRAL, - filter.filter(null, Level.DEBUG, null, (Object) "This is a test message", (Throwable) null)); - assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, (Object) "This is not a test", (Throwable) - null)); + Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) "This is a test message", null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, (Object) "This is not a test", null)); LogEvent event = Log4jLogEvent.newBuilder() // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("Another test message")) // @@ -64,29 +62,29 @@ public void testThresholds() throws Exception { } @Test - public void testDotAllPattern() throws Exception { + void testDotAllPattern() throws Exception { final String singleLine = "test single line matches"; final String multiLine = "test multi line matches\nsome more lines"; final RegexFilter filter = RegexFilter.createFilter( ".*line.*", new String[] {"DOTALL", "COMMENTS"}, false, Filter.Result.DENY, Filter.Result.ACCEPT); - final Result singleLineResult = filter.filter(null, null, null, (Object) singleLine, (Throwable) null); - final Result multiLineResult = filter.filter(null, null, null, (Object) multiLine, (Throwable) null); + final Result singleLineResult = filter.filter(null, null, null, (Object) singleLine, null); + final Result multiLineResult = filter.filter(null, null, null, (Object) multiLine, null); assertThat(singleLineResult, equalTo(Result.DENY)); assertThat(multiLineResult, equalTo(Result.DENY)); } @Test - public void testNoMsg() throws Exception { + void testNoMsg() throws Exception { final RegexFilter filter = RegexFilter.createFilter(".* test .*", null, false, null, null); filter.start(); assertTrue(filter.isStarted()); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Message) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Message) null, null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Object[]) null)); } @Test - public void testParameterizedMsg() throws Exception { + void testParameterizedMsg() throws Exception { final String msg = "params {} {}"; final Object[] params = {"foo", "bar"}; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StringMatchFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StringMatchFilterTest.java index 3479975ae65..c95f607347f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StringMatchFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StringMatchFilterTest.java @@ -20,25 +20,25 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.test.junit.LoggerContextSource; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Unit test for {@link StringMatchFilter}. */ -public class StringMatchFilterTest { +class StringMatchFilterTest { /** * Test that if no match-string is set on the builder, the '{@link StringMatchFilter.Builder#build()}' returns * {@code null}. */ @Test - public void testFilterBuilderFailsWithNullText() { - Assertions.assertNull(StringMatchFilter.newBuilder().build()); + void testFilterBuilderFailsWithNullText() { + assertNull(StringMatchFilter.newBuilder().build()); } /** @@ -46,7 +46,7 @@ public void testFilterBuilderFailsWithNullText() { */ @Test void testFilterBuilderFailsWithExceptionOnNullText() { - Assertions.assertThrows(IllegalArgumentException.class, () -> StringMatchFilter.newBuilder() + assertThrows(IllegalArgumentException.class, () -> StringMatchFilter.newBuilder() .setText(null)); } @@ -55,7 +55,7 @@ void testFilterBuilderFailsWithExceptionOnNullText() { */ @Test void testFilterBuilderFailsWithExceptionOnEmptyText() { - Assertions.assertThrows(IllegalArgumentException.class, () -> StringMatchFilter.newBuilder() + assertThrows(IllegalArgumentException.class, () -> StringMatchFilter.newBuilder() .setText("")); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StructuredDataFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StructuredDataFilterTest.java index 35388d17e76..5e33aaf8b36 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StructuredDataFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/StructuredDataFilterTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -32,10 +33,10 @@ import org.apache.logging.log4j.util.IndexedReadOnlyStringMap; import org.junit.jupiter.api.Test; -public class StructuredDataFilterTest { +class StructuredDataFilterTest { @Test - public void testFilter() { + void testFilter() { final KeyValuePair[] pairs = new KeyValuePair[] { new KeyValuePair("id.name", "AccountTransfer"), new KeyValuePair("ToAccount", "123456") }; @@ -65,10 +66,10 @@ public void testFilter() { @Test @LoggerContextSource("log4j2-sdfilter.xml") - public void testConfig(final Configuration config) { + void testConfig(final Configuration config) { final Filter filter = config.getFilter(); assertNotNull(filter, "No StructuredDataFilter"); - assertTrue(filter instanceof StructuredDataFilter, "Not a StructuredDataFilter"); + assertInstanceOf(StructuredDataFilter.class, filter, "Not a StructuredDataFilter"); final StructuredDataFilter sdFilter = (StructuredDataFilter) filter; assertFalse(sdFilter.isAnd(), "Should not be And filter"); final IndexedReadOnlyStringMap map = sdFilter.getStringMap(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilterTest.java index 5858c7013f1..fed69b81d47 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThreadContextMapFilterTest.java @@ -26,10 +26,10 @@ import org.apache.logging.log4j.core.util.KeyValuePair; import org.junit.jupiter.api.Test; -public class ThreadContextMapFilterTest { +class ThreadContextMapFilterTest { @Test - public void testFilter() { + void testFilter() { ThreadContext.put("userid", "testuser"); ThreadContext.put("organization", "Apache"); final KeyValuePair[] pairs = @@ -38,13 +38,13 @@ public void testFilter() { assertNotNull(filter); filter.start(); assertTrue(filter.isStarted()); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, null)); ThreadContext.remove("userid"); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, null)); ThreadContext.put("userid", "JohnDoe"); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, null)); ThreadContext.put("organization", "ASF"); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, null)); ThreadContext.clearMap(); filter = ThreadContextMapFilter.createFilter(pairs, "or", null, null); assertNotNull(filter); @@ -52,17 +52,17 @@ public void testFilter() { assertTrue(filter.isStarted()); ThreadContext.put("userid", "testuser"); ThreadContext.put("organization", "Apache"); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, null)); ThreadContext.put("organization", "ASF"); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, null)); ThreadContext.remove("organization"); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, null)); final KeyValuePair[] single = new KeyValuePair[] {new KeyValuePair("userid", "testuser")}; filter = ThreadContextMapFilter.createFilter(single, null, null, null); assertNotNull(filter); filter.start(); assertTrue(filter.isStarted()); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, (Object) null, null)); ThreadContext.clearMap(); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThresholdFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThresholdFilterTest.java index d9e3f6800aa..0b956bc1a59 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThresholdFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/ThresholdFilterTest.java @@ -26,15 +26,15 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.junit.jupiter.api.Test; -public class ThresholdFilterTest { +class ThresholdFilterTest { @Test - public void testThresholds() { + void testThresholds() { final ThresholdFilter filter = ThresholdFilter.createFilter(Level.ERROR, null, null); filter.start(); assertTrue(filter.isStarted()); - assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, (Throwable) null)); - assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null)); + assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Object) null, null)); + assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, null)); LogEvent event = Log4jLogEvent.newBuilder() // .setLevel(Level.DEBUG) // .setMessage(new SimpleMessage("Test")) // diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/TimeFilterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/TimeFilterTest.java index a3b0bec0782..643d69355c9 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/TimeFilterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/filter/TimeFilterTest.java @@ -35,7 +35,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class TimeFilterTest { +class TimeFilterTest { private static long CLOCKTIME = System.currentTimeMillis(); /** Helper class */ @@ -47,17 +47,17 @@ public long currentTimeMillis() { } @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty(ClockFactory.PROPERTY_NAME, FixedTimeClock.class.getName()); } @AfterAll - public static void afterClass() throws IllegalAccessException { + static void afterClass() throws IllegalAccessException { ClockFactoryTest.resetClocks(); } @Test - public void springForward() { + void springForward() { final TimeFilter filter = new TimeFilter( LocalTime.of(2, 0), LocalTime.of(3, 0), @@ -71,27 +71,20 @@ public void springForward() { CLOCKTIME = date.toInstant().toEpochMilli(); LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.plusDays(1).withHour(2); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.withHour(4); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); - assertSame( - Filter.Result.DENY, - filter.filter(event), - "Time " + CLOCKTIME + " is within range: " + filter.toString()); + assertSame(Filter.Result.DENY, filter.filter(event), "Time " + CLOCKTIME + " is within range: " + filter); } @Test - public void fallBack() { + void fallBack() { final TimeFilter filter = new TimeFilter( LocalTime.of(1, 0), LocalTime.of(2, 0), @@ -106,35 +99,25 @@ public void fallBack() { CLOCKTIME = date.toInstant().toEpochMilli(); LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = ZonedDateTime.of(2020, 11, 1, 1, 6, 30, 0, ZoneId.of("America/Los_Angeles")) .withLaterOffsetAtOverlap(); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); - assertSame( - Filter.Result.DENY, - filter.filter(event), - "Time " + CLOCKTIME + " is within range: " + filter.toString()); + assertSame(Filter.Result.DENY, filter.filter(event), "Time " + CLOCKTIME + " is within range: " + filter); date = date.plusDays(1).withHour(1).withMinute(30); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.withHour(4); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); - assertSame( - Filter.Result.DENY, - filter.filter(event), - "Time " + CLOCKTIME + " is within range: " + filter.toString()); + assertSame(Filter.Result.DENY, filter.filter(event), "Time " + CLOCKTIME + " is within range: " + filter); } @Test - public void overnight() { + void overnight() { final TimeFilter filter = new TimeFilter( LocalTime.of(23, 0), LocalTime.of(1, 0), @@ -149,34 +132,25 @@ public void overnight() { CLOCKTIME = date.toInstant().toEpochMilli(); LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.plusHours(1); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.plusHours(1); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); - assertSame( - Filter.Result.DENY, - filter.filter(event), - "Time " + CLOCKTIME + " is within range: " + filter.toString()); + assertSame(Filter.Result.DENY, filter.filter(event), "Time " + CLOCKTIME + " is within range: " + filter); date = date.plusDays(1).withHour(0); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); } @Test - public void overnightForward() { + void overnightForward() { final TimeFilter filter = new TimeFilter( LocalTime.of(23, 0), LocalTime.of(2, 0), @@ -191,34 +165,25 @@ public void overnightForward() { CLOCKTIME = date.toInstant().toEpochMilli(); LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.plusHours(1); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.plusHours(2); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); - assertSame( - Filter.Result.DENY, - filter.filter(event), - "Time " + CLOCKTIME + " is within range: " + filter.toString()); + assertSame(Filter.Result.DENY, filter.filter(event), "Time " + CLOCKTIME + " is within range: " + filter); date = date.plusDays(1).withHour(0); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); } @Test - public void overnightFallback() { + void overnightFallback() { final TimeFilter filter = new TimeFilter( LocalTime.of(23, 0), LocalTime.of(2, 0), @@ -233,34 +198,25 @@ public void overnightFallback() { CLOCKTIME = date.toInstant().toEpochMilli(); LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.plusHours(1); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); date = date.plusHours(2); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); - assertSame( - Filter.Result.DENY, - filter.filter(event), - "Time " + CLOCKTIME + " is within range: " + filter.toString()); + assertSame(Filter.Result.DENY, filter.filter(event), "Time " + CLOCKTIME + " is within range: " + filter); date = date.plusDays(1).withHour(0); CLOCKTIME = date.toInstant().toEpochMilli(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); } @Test - public void testTime() { + void testTime() { // https://garygregory.wordpress.com/2013/06/18/what-are-the-java-timezone-ids/ final TimeFilter filter = TimeFilter.createFilter("02:00:00", "03:00:00", "America/Los_Angeles", null, null); filter.start(); @@ -271,27 +227,20 @@ public void testTime() { LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); // assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null)); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); cal.add(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, 2); CLOCKTIME = cal.getTimeInMillis(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); assertSame( - Filter.Result.NEUTRAL, - filter.filter(event), - "Time " + CLOCKTIME + " is not within range: " + filter.toString()); + Filter.Result.NEUTRAL, filter.filter(event), "Time " + CLOCKTIME + " is not within range: " + filter); // assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null)); cal.set(Calendar.HOUR_OF_DAY, 4); CLOCKTIME = cal.getTimeInMillis(); event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build(); // assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, (Object) null, (Throwable) null)); - assertSame( - Filter.Result.DENY, - filter.filter(event), - "Time " + CLOCKTIME + " is within range: " + filter.toString()); + assertSame(Filter.Result.DENY, filter.filter(event), "Time " + CLOCKTIME + " is within range: " + filter); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetMissingConstructorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetMissingConstructorTest.java index e54cff6997d..5ed076bd85a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetMissingConstructorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetMissingConstructorTest.java @@ -17,7 +17,7 @@ package org.apache.logging.log4j.core.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import java.lang.reflect.Field; import org.apache.logging.log4j.util.SortedArrayStringMap; @@ -26,12 +26,12 @@ /** * Tests the ContextDataFactory class. */ -public class ContextDataFactoryPropertySetMissingConstructorTest { +class ContextDataFactoryPropertySetMissingConstructorTest { @Test - public void intArgReturnsSortedArrayStringMapIfPropertySpecifiedButMissingIntConstructor() throws Exception { + void intArgReturnsSortedArrayStringMapIfPropertySpecifiedButMissingIntConstructor() throws Exception { System.setProperty("log4j2.ContextData", FactoryTestStringMapWithoutIntConstructor.class.getName()); - assertTrue(ContextDataFactory.createContextData(2) instanceof SortedArrayStringMap); + assertInstanceOf(SortedArrayStringMap.class, ContextDataFactory.createContextData(2)); final SortedArrayStringMap actual = (SortedArrayStringMap) ContextDataFactory.createContextData(2); final Field thresholdField = SortedArrayStringMap.class.getDeclaredField("threshold"); thresholdField.setAccessible(true); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetTest.java index b22e54a38c6..03d8f46dae0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryPropertySetTest.java @@ -17,31 +17,31 @@ package org.apache.logging.log4j.core.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import org.junit.jupiter.api.Test; /** * Tests the ContextDataFactory class. */ -public class ContextDataFactoryPropertySetTest { +class ContextDataFactoryPropertySetTest { @Test - public void noArgReturnsSpecifiedImplIfPropertySpecified() throws Exception { + void noArgReturnsSpecifiedImplIfPropertySpecified() { System.setProperty("log4j2.ContextData", FactoryTestStringMap.class.getName()); - assertTrue(ContextDataFactory.createContextData() instanceof FactoryTestStringMap); + assertInstanceOf(FactoryTestStringMap.class, ContextDataFactory.createContextData()); System.clearProperty("log4j2.ContextData"); } @Test - public void intArgReturnsSpecifiedImplIfPropertySpecified() throws Exception { + void intArgReturnsSpecifiedImplIfPropertySpecified() { System.setProperty("log4j2.ContextData", FactoryTestStringMap.class.getName()); - assertTrue(ContextDataFactory.createContextData(2) instanceof FactoryTestStringMap); + assertInstanceOf(FactoryTestStringMap.class, ContextDataFactory.createContextData(2)); System.clearProperty("log4j2.ContextData"); } @Test - public void intArgSetsCapacityIfPropertySpecified() throws Exception { + void intArgSetsCapacityIfPropertySpecified() { System.setProperty("log4j2.ContextData", FactoryTestStringMap.class.getName()); final FactoryTestStringMap actual = (FactoryTestStringMap) ContextDataFactory.createContextData(2); assertEquals(2, actual.initialCapacity); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryTest.java index 828d51b9d17..c14ba5070ec 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ContextDataFactoryTest.java @@ -17,7 +17,7 @@ package org.apache.logging.log4j.core.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import java.lang.reflect.Field; import org.apache.logging.log4j.util.SortedArrayStringMap; @@ -26,19 +26,19 @@ /** * Tests the ContextDataFactory class. */ -public class ContextDataFactoryTest { +class ContextDataFactoryTest { @Test - public void noArgReturnsSortedArrayStringMapIfNoPropertySpecified() throws Exception { - assertTrue(ContextDataFactory.createContextData() instanceof SortedArrayStringMap); + void noArgReturnsSortedArrayStringMapIfNoPropertySpecified() { + assertInstanceOf(SortedArrayStringMap.class, ContextDataFactory.createContextData()); } @Test - public void intArgReturnsSortedArrayStringMapIfNoPropertySpecified() throws Exception { - assertTrue(ContextDataFactory.createContextData(2) instanceof SortedArrayStringMap); + void intArgReturnsSortedArrayStringMapIfNoPropertySpecified() { + assertInstanceOf(SortedArrayStringMap.class, ContextDataFactory.createContextData(2)); } @Test - public void intArgSetsCapacityIfNoPropertySpecified() throws Exception { + void intArgSetsCapacityIfNoPropertySpecified() throws Exception { final SortedArrayStringMap actual = (SortedArrayStringMap) ContextDataFactory.createContextData(2); final Field thresholdField = SortedArrayStringMap.class.getDeclaredField("threshold"); thresholdField.setAccessible(true); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/JdkMapAdapterStringMapTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/JdkMapAdapterStringMapTest.java index 81ff33dd260..7b06a23a32e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/JdkMapAdapterStringMapTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/JdkMapAdapterStringMapTest.java @@ -44,15 +44,15 @@ /** * Tests the JdkMapAdapterStringMap class. */ -public class JdkMapAdapterStringMapTest { +class JdkMapAdapterStringMapTest { @Test - public void testConstructorDisallowsNull() { + void testConstructorDisallowsNull() { assertThrows(NullPointerException.class, () -> new JdkMapAdapterStringMap(null, false)); } @Test - public void testToString() { + void testToString() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("a2", "bvalue"); @@ -63,7 +63,7 @@ public void testToString() { } @Test - public void testSerialization() throws Exception { + void testSerialization() throws Exception { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -89,7 +89,7 @@ private JdkMapAdapterStringMap deserialize(final byte[] binary) throws IOExcepti } @Test - public void testPutAll() throws Exception { + void testPutAll() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -110,7 +110,7 @@ public void testPutAll() throws Exception { } @Test - public void testPutAll_overwritesSameKeys2() throws Exception { + void testPutAll_overwritesSameKeys2() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -136,7 +136,7 @@ public void testPutAll_overwritesSameKeys2() throws Exception { } @Test - public void testPutAll_nullKeyInLargeOriginal() throws Exception { + void testPutAll_nullKeyInLargeOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -161,7 +161,7 @@ public void testPutAll_nullKeyInLargeOriginal() throws Exception { } @Test - public void testPutAll_nullKeyInSmallOriginal() throws Exception { + void testPutAll_nullKeyInSmallOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -184,7 +184,7 @@ public void testPutAll_nullKeyInSmallOriginal() throws Exception { } @Test - public void testPutAll_nullKeyInSmallAdditional() throws Exception { + void testPutAll_nullKeyInSmallAdditional() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -209,7 +209,7 @@ public void testPutAll_nullKeyInSmallAdditional() throws Exception { } @Test - public void testPutAll_nullKeyInLargeAdditional() throws Exception { + void testPutAll_nullKeyInLargeAdditional() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -232,7 +232,7 @@ public void testPutAll_nullKeyInLargeAdditional() throws Exception { } @Test - public void testPutAll_nullKeyInBoth_LargeOriginal() throws Exception { + void testPutAll_nullKeyInBoth_LargeOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -258,7 +258,7 @@ public void testPutAll_nullKeyInBoth_LargeOriginal() throws Exception { } @Test - public void testPutAll_nullKeyInBoth_SmallOriginal() throws Exception { + void testPutAll_nullKeyInBoth_SmallOriginal() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullORIG"); original.putValue("a", "aORIG"); @@ -282,7 +282,7 @@ public void testPutAll_nullKeyInBoth_SmallOriginal() throws Exception { } @Test - public void testPutAll_overwritesSameKeys1() throws Exception { + void testPutAll_overwritesSameKeys1() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aORIG"); original.putValue("b", "bORIG"); @@ -304,7 +304,7 @@ public void testPutAll_overwritesSameKeys1() throws Exception { } @Test - public void testEquals() { + void testEquals() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -332,7 +332,7 @@ public void testEquals() { } @Test - public void testToMap() throws Exception { + void testToMap() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -353,7 +353,7 @@ public void testToMap() throws Exception { } @Test - public void testPutAll_KeepsExistingValues() { + void testPutAll_KeepsExistingValues() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); @@ -383,7 +383,7 @@ public void testPutAll_KeepsExistingValues() { } @Test - public void testPutAll_sizePowerOfTwo() { + void testPutAll_sizePowerOfTwo() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); @@ -418,7 +418,7 @@ public void testPutAll_sizePowerOfTwo() { } @Test - public void testPutAll_largeAddition() { + void testPutAll_largeAddition() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue(null, "nullVal"); original.putValue("a", "aaa"); @@ -446,7 +446,7 @@ public void testPutAll_largeAddition() { } @Test - public void testPutAllSelfDoesNotModify() { + void testPutAllSelfDoesNotModify() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "bbb"); @@ -462,7 +462,7 @@ public void testPutAllSelfDoesNotModify() { } @Test - public void testNoConcurrentModificationBiConsumerPut() { + void testNoConcurrentModificationBiConsumerPut() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -473,7 +473,7 @@ public void testNoConcurrentModificationBiConsumerPut() { } @Test - public void testNoConcurrentModificationBiConsumerPutValue() { + void testNoConcurrentModificationBiConsumerPutValue() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -484,7 +484,7 @@ public void testNoConcurrentModificationBiConsumerPutValue() { } @Test - public void testNoConcurrentModificationBiConsumerRemove() { + void testNoConcurrentModificationBiConsumerRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -493,7 +493,7 @@ public void testNoConcurrentModificationBiConsumerRemove() { } @Test - public void testNoConcurrentModificationBiConsumerClear() { + void testNoConcurrentModificationBiConsumerClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -504,7 +504,7 @@ public void testNoConcurrentModificationBiConsumerClear() { } @Test - public void testNoConcurrentModificationTriConsumerPut() { + void testNoConcurrentModificationTriConsumerPut() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -514,7 +514,7 @@ public void testNoConcurrentModificationTriConsumerPut() { } @Test - public void testNoConcurrentModificationTriConsumerPutValue() { + void testNoConcurrentModificationTriConsumerPutValue() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -525,7 +525,7 @@ public void testNoConcurrentModificationTriConsumerPutValue() { } @Test - public void testNoConcurrentModificationTriConsumerRemove() { + void testNoConcurrentModificationTriConsumerRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -534,7 +534,7 @@ public void testNoConcurrentModificationTriConsumerRemove() { } @Test - public void testNoConcurrentModificationTriConsumerClear() { + void testNoConcurrentModificationTriConsumerClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.putValue("b", "aaa"); @@ -544,12 +544,12 @@ public void testNoConcurrentModificationTriConsumerClear() { } @Test - public void testInitiallyNotFrozen() { + void testInitiallyNotFrozen() { assertFalse(new JdkMapAdapterStringMap().isFrozen()); } @Test - public void testIsFrozenAfterCallingFreeze() { + void testIsFrozenAfterCallingFreeze() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); assertFalse(original.isFrozen(), "before freeze"); original.freeze(); @@ -557,14 +557,14 @@ public void testIsFrozenAfterCallingFreeze() { } @Test - public void testFreezeProhibitsPutValue() { + void testFreezeProhibitsPutValue() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.freeze(); assertThrows(UnsupportedOperationException.class, () -> original.putValue("a", "aaa")); } @Test - public void testFreezeProhibitsRemove() { + void testFreezeProhibitsRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("b", "bbb"); original.freeze(); @@ -574,7 +574,7 @@ public void testFreezeProhibitsRemove() { } @Test - public void testFreezeAllowsRemoveOfNonExistingKey() { + void testFreezeAllowsRemoveOfNonExistingKey() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("b", "bbb"); original.freeze(); @@ -582,14 +582,14 @@ public void testFreezeAllowsRemoveOfNonExistingKey() { } @Test - public void testFreezeAllowsRemoveIfEmpty() { + void testFreezeAllowsRemoveIfEmpty() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.freeze(); original.remove("a"); // no exception } @Test - public void testFreezeProhibitsClear() { + void testFreezeProhibitsClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "aaa"); original.freeze(); @@ -597,14 +597,14 @@ public void testFreezeProhibitsClear() { } @Test - public void testFreezeAllowsClearIfEmpty() { + void testFreezeAllowsClearIfEmpty() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.freeze(); original.clear(); } @Test - public void testNullKeysAllowed() { + void testNullKeysAllowed() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -631,7 +631,7 @@ public void testNullKeysAllowed() { } @Test - public void testNullKeysCopiedToAsMap() { + void testNullKeysCopiedToAsMap() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -670,7 +670,7 @@ public void testNullKeysCopiedToAsMap() { } @Test - public void testRemove() { + void testRemove() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); assertEquals(1, original.size()); @@ -686,7 +686,7 @@ public void testRemove() { } @Test - public void testRemoveWhenFull() throws Exception { + void testRemoveWhenFull() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("b", "bvalue"); @@ -696,7 +696,7 @@ public void testRemoveWhenFull() throws Exception { } @Test - public void testNullValuesArePreserved() { + void testNullValuesArePreserved() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); assertEquals(1, original.size()); @@ -712,7 +712,7 @@ public void testNullValuesArePreserved() { } @Test - public void testGet() throws Exception { + void testGet() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -730,7 +730,7 @@ public void testGet() throws Exception { } @Test - public void testClear() throws Exception { + void testClear() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -742,7 +742,7 @@ public void testClear() throws Exception { } @Test - public void testContainsKey() throws Exception { + void testContainsKey() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); assertFalse(original.containsKey("a"), "a"); assertFalse(original.containsKey("B"), "B"); @@ -775,7 +775,7 @@ public void testContainsKey() throws Exception { } @Test - public void testSizeAndIsEmpty() throws Exception { + void testSizeAndIsEmpty() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); assertEquals(0, original.size()); assertTrue(original.isEmpty(), "initial"); @@ -806,7 +806,7 @@ public void testSizeAndIsEmpty() throws Exception { } @Test - public void testForEachBiConsumer() throws Exception { + void testForEachBiConsumer() throws Exception { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); @@ -838,7 +838,7 @@ static class State { }; @Test - public void testForEachTriConsumer() throws Exception { + void testForEachTriConsumer() { final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap(); original.putValue("a", "avalue"); original.putValue("B", "Bvalue"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventNanoTimeTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventNanoTimeTest.java index 7c7efd7ba8e..82c091336ea 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventNanoTimeTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventNanoTimeTest.java @@ -17,6 +17,7 @@ package org.apache.logging.log4j.core.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -38,32 +39,32 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class Log4jLogEventNanoTimeTest { +class Log4jLogEventNanoTimeTest { @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "NanoTimeToFileTest.xml"); } @AfterAll - public static void afterClass() { + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testLog4jLogEventUsesNanoTimeClock() throws Exception { + void testLog4jLogEventUsesNanoTimeClock() throws Exception { final File file = new File("target", "NanoTimeToFileTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); final Logger log = LogManager.getLogger("com.foo.Bar"); final long before = System.nanoTime(); log.info("Use actual System.nanoTime()"); - assertTrue(Log4jLogEvent.getNanoClock() instanceof SystemNanoClock, "using SystemNanoClock"); + assertInstanceOf(SystemNanoClock.class, Log4jLogEvent.getNanoClock(), "using SystemNanoClock"); final long DUMMYNANOTIME = 123; Log4jLogEvent.setNanoClock(new DummyNanoClock(DUMMYNANOTIME)); log.info("Use dummy nano clock"); - assertTrue(Log4jLogEvent.getNanoClock() instanceof DummyNanoClock, "using SystemNanoClock"); + assertInstanceOf(DummyNanoClock.class, Log4jLogEvent.getNanoClock(), "using SystemNanoClock"); CoreLoggerContexts.stopLoggerContext(file); // stop async thread diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventTest.java index 119e3dd1ccc..bc90e594d28 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/Log4jLogEventTest.java @@ -20,6 +20,7 @@ import static org.apache.logging.log4j.test.junit.SerialUtil.serialize; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -69,23 +70,23 @@ public long currentTimeMillis() { } @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty(ClockFactory.PROPERTY_NAME, FixedTimeClock.class.getName()); } @AfterAll - public static void afterClass() throws IllegalAccessException { + static void afterClass() throws IllegalAccessException { ClockFactoryTest.resetClocks(); } @Test - public void testToImmutableSame() { + void testToImmutableSame() { final LogEvent logEvent = new Log4jLogEvent(); assertSame(logEvent, logEvent.toImmutable()); } @Test - public void testToImmutableNotSame() { + void testToImmutableNotSame() { final LogEvent logEvent = new Log4jLogEvent.Builder() .setMessage(new ReusableObjectMessage()) .build(); @@ -95,7 +96,7 @@ public void testToImmutableNotSame() { } @Test - public void testJavaIoSerializable() throws Exception { + void testJavaIoSerializable() { final Log4jLogEvent evt = Log4jLogEvent.newBuilder() // .setLoggerName("some.test") // .setLoggerFqcn(Strings.EMPTY) // @@ -123,7 +124,7 @@ public void testJavaIoSerializable() throws Exception { } @Test - public void testJavaIoSerializableWithThrown() throws Exception { + void testJavaIoSerializableWithThrown() { final Error thrown = new InternalError("test error"); final Log4jLogEvent evt = Log4jLogEvent.newBuilder() // .setLoggerName("some.test") // @@ -164,7 +165,7 @@ public void testJavaIoSerializableWithThrown() throws Exception { // }; @Test - public void testJavaIoSerializableWithUnknownThrowable() throws Exception { + void testJavaIoSerializableWithUnknownThrowable() { final String loggerName = "some.test"; final Marker marker = null; final String loggerFQN = Strings.EMPTY; @@ -202,7 +203,7 @@ public void testJavaIoSerializableWithUnknownThrowable() throws Exception { } @Test - public void testNullLevelReplacedWithOFF() throws Exception { + void testNullLevelReplacedWithOFF() { final Level NULL_LEVEL = null; final Log4jLogEvent evt = Log4jLogEvent.newBuilder().setLevel(NULL_LEVEL).build(); @@ -210,19 +211,19 @@ public void testNullLevelReplacedWithOFF() throws Exception { } @Test - public void testTimestampGeneratedByClock() { + void testTimestampGeneratedByClock() { final LogEvent evt = Log4jLogEvent.newBuilder().build(); assertEquals(FixedTimeClock.FIXED_TIME, evt.getTimeMillis()); } @Test - public void testInitiallyDummyNanoClock() { - assertTrue(Log4jLogEvent.getNanoClock() instanceof DummyNanoClock); + void testInitiallyDummyNanoClock() { + assertInstanceOf(DummyNanoClock.class, Log4jLogEvent.getNanoClock()); assertEquals(0, Log4jLogEvent.getNanoClock().nanoTime(), "initial dummy nanotime"); } @Test - public void testNanoTimeGeneratedByNanoClock() { + void testNanoTimeGeneratedByNanoClock() { Log4jLogEvent.setNanoClock(new DummyNanoClock(123)); verifyNanoTimeWithAllConstructors(123); Log4jLogEvent.setNanoClock(new DummyNanoClock(87654)); @@ -251,7 +252,7 @@ private void verifyNanoTimeWithAllConstructors(final long expected) { @SuppressWarnings("deprecation") @Test - public void testBuilderCorrectlyCopiesAllEventAttributes() { + void testBuilderCorrectlyCopiesAllEventAttributes() { final StringMap contextData = ContextDataFactory.createContextData(); contextData.putValue("A", "B"); final ContextStack contextStack = ThreadContext.getImmutableStack(); @@ -300,7 +301,7 @@ public void testBuilderCorrectlyCopiesAllEventAttributes() { } @Test - public void testBuilderCorrectlyCopiesAllEventAttributesInclContextData() { + void testBuilderCorrectlyCopiesAllEventAttributesInclContextData() { final StringMap contextData = new SortedArrayStringMap(); contextData.putValue("A", "B"); final ContextStack contextStack = ThreadContext.getImmutableStack(); @@ -349,7 +350,7 @@ public void testBuilderCorrectlyCopiesAllEventAttributesInclContextData() { } @Test - public void testBuilderCorrectlyCopiesMutableLogEvent() throws Exception { + void testBuilderCorrectlyCopiesMutableLogEvent() throws Exception { final StringMap contextData = new SortedArrayStringMap(); contextData.putValue("A", "B"); final ContextStack contextStack = ThreadContext.getImmutableStack(); @@ -417,7 +418,7 @@ public void testBuilderCorrectlyCopiesMutableLogEvent() throws Exception { @SuppressWarnings("deprecation") @Test - public void testEquals() { + void testEquals() { final StringMap contextData = ContextDataFactory.createContextData(); contextData.putValue("A", "B"); ThreadContext.push("first"); @@ -536,7 +537,7 @@ private void different(final String reason, final Log4jLogEvent.Builder builder, } @Test - public void testToString() { + void testToString() { // Throws an NPE in 2.6.2 assertNotNull(new Log4jLogEvent().toString()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/MutableLogEventTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/MutableLogEventTest.java index 0723d6ff735..7f4ebd2d4bb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/MutableLogEventTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/MutableLogEventTest.java @@ -47,7 +47,7 @@ /** * Tests the MutableLogEvent class. */ -public class MutableLogEventTest { +class MutableLogEventTest { private static final StringMap CONTEXT_DATA = createContextData(); private static final ThreadContext.ContextStack STACK = new MutableThreadContextStack(Arrays.asList("abc", "xyz")); @@ -59,13 +59,13 @@ private static StringMap createContextData() { } @Test - public void testToImmutable() { + void testToImmutable() { final LogEvent logEvent = new MutableLogEvent(); assertNotSame(logEvent, logEvent.toImmutable()); } @Test - public void testInitFromCopiesAllFields() { + void testInitFromCopiesAllFields() { // private ThrowableProxy thrownProxy; final Log4jLogEvent source = Log4jLogEvent.newBuilder() // .setContextData(CONTEXT_DATA) // @@ -107,7 +107,7 @@ public void testInitFromCopiesAllFields() { } @Test - public void testInitFromReusableCopiesFormatString() { + void testInitFromReusableCopiesFormatString() { final Message message = ReusableMessageFactory.INSTANCE.newMessage("msg in a {}", "bottle"); final Log4jLogEvent source = Log4jLogEvent.newBuilder() // .setContextData(CONTEXT_DATA) // @@ -150,7 +150,7 @@ public void testInitFromReusableCopiesFormatString() { } @Test - public void testInitFromReusableObjectCopiesParameter() { + void testInitFromReusableObjectCopiesParameter() { final Object param = new Object(); final Message message = ReusableMessageFactory.INSTANCE.newMessage(param); final Log4jLogEvent source = Log4jLogEvent.newBuilder() @@ -183,7 +183,7 @@ public void testInitFromReusableObjectCopiesParameter() { } @Test - public void testClear() { + void testClear() { final MutableLogEvent mutable = new MutableLogEvent(); // initialize the event with an empty message final ReusableSimpleMessage simpleMessage = new ReusableSimpleMessage(); @@ -268,7 +268,7 @@ public void testClear() { } @Test - public void testJavaIoSerializable() throws Exception { + void testJavaIoSerializable() { final MutableLogEvent evt = new MutableLogEvent(); evt.setContextData(CONTEXT_DATA); evt.setContextStack(STACK); @@ -312,7 +312,7 @@ public void testJavaIoSerializable() throws Exception { } @Test - public void testJavaIoSerializableWithThrown() throws Exception { + void testJavaIoSerializableWithThrown() { final MutableLogEvent evt = new MutableLogEvent(); evt.setContextData(CONTEXT_DATA); evt.setContextStack(STACK); @@ -358,7 +358,7 @@ public void testJavaIoSerializableWithThrown() throws Exception { } @Test - public void testPreservesLocation() { + void testPreservesLocation() { final StackTraceElement source = new RuntimeException().getStackTrace()[0]; final MutableLogEvent mutable = new MutableLogEvent(); mutable.setSource(source); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ReusableLogEventFactoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ReusableLogEventFactoryTest.java index f0fed9d133b..a970031732c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ReusableLogEventFactoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ReusableLogEventFactoryTest.java @@ -31,10 +31,10 @@ /** * Tests the ReusableLogEventFactory class. */ -public class ReusableLogEventFactoryTest { +class ReusableLogEventFactoryTest { @Test - public void testCreateEventReturnsDifferentInstanceIfNotReleased() throws Exception { + void testCreateEventReturnsDifferentInstanceIfNotReleased() { final ReusableLogEventFactory factory = new ReusableLogEventFactory(); final LogEvent event1 = callCreateEvent(factory, "a", Level.DEBUG, new SimpleMessage("abc"), null); final LogEvent event2 = callCreateEvent(factory, "b", Level.INFO, new SimpleMessage("xyz"), null); @@ -44,7 +44,7 @@ public void testCreateEventReturnsDifferentInstanceIfNotReleased() throws Except } @Test - public void testCreateEventReturnsSameInstance() throws Exception { + void testCreateEventReturnsSameInstance() { final ReusableLogEventFactory factory = new ReusableLogEventFactory(); final LogEvent event1 = callCreateEvent(factory, "a", Level.DEBUG, new SimpleMessage("abc"), null); ReusableLogEventFactory.release(event1); @@ -58,7 +58,7 @@ public void testCreateEventReturnsSameInstance() throws Exception { } @Test - public void testCreateEventOverwritesFields() throws Exception { + void testCreateEventOverwritesFields() { final ReusableLogEventFactory factory = new ReusableLogEventFactory(); final LogEvent event1 = callCreateEvent(factory, "a", Level.DEBUG, new SimpleMessage("abc"), null); assertEquals("a", event1.getLoggerName(), "logger"); @@ -87,7 +87,7 @@ private LogEvent callCreateEvent( } @Test - public void testCreateEventReturnsThreadLocalInstance() throws Exception { + void testCreateEventReturnsThreadLocalInstance() throws Exception { final ReusableLogEventFactory factory = new ReusableLogEventFactory(); final AtomicReference event1 = new AtomicReference<>(); final AtomicReference event2 = new AtomicReference<>(); @@ -127,7 +127,7 @@ public void run() { @SuppressWarnings("deprecation") @Test - public void testCreateEventInitFieldsProperly() throws Exception { + void testCreateEventInitFieldsProperly() { final ReusableLogEventFactory factory = new ReusableLogEventFactory(); final LogEvent event = callCreateEvent(factory, "logger", Level.INFO, new SimpleMessage("xyz"), null); try { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjectorTest.java index 896d0d2d8b7..b2bdb145548 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/impl/ThreadContextDataInjectorTest.java @@ -66,7 +66,7 @@ private static void resetThreadContextMap() { } @Before - public void before() throws ReflectiveOperationException { + public void before() { System.setProperty("log4j2.threadContextMap", threadContextMapClassName); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java index 767464d2d32..a0114d9717b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java @@ -16,9 +16,11 @@ */ package org.apache.logging.log4j.core.jackson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; @@ -28,14 +30,12 @@ import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.util.ClassUtil; import java.io.IOException; -import org.apache.logging.log4j.core.test.categories.Layouts; import org.apache.logging.log4j.util.Strings; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(Layouts.Json.class) -public class JacksonIssue429MyNamesTest { +@Tag("Layouts.Json") +class JacksonIssue429MyNamesTest { @SuppressWarnings("serial") static class MyStackTraceElementDeserializer extends StdScalarDeserializer { @@ -49,7 +49,7 @@ public MyStackTraceElementDeserializer() { @Override public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) - throws IOException, JsonProcessingException { + throws IOException { JsonToken t = jp.getCurrentToken(); // Must get an Object if (t == JsonToken.START_OBJECT) { @@ -108,15 +108,15 @@ protected ObjectMapper objectMapper() { } @Test - public void testStackTraceElementWithCustom() throws Exception { + void testStackTraceElementWithCustom() throws Exception { // first, via bean that contains StackTraceElement final StackTraceBean bean = MAPPER.readValue( aposToQuotes( "{'Location':{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}}"), StackTraceBean.class); - Assert.assertNotNull(bean); - Assert.assertNotNull(bean.location); - Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); + assertNotNull(bean); + assertNotNull(bean.location); + assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); // and then directly, iff registered final ObjectMapper mapper = new ObjectMapper(); @@ -127,7 +127,7 @@ public void testStackTraceElementWithCustom() throws Exception { final StackTraceElement elem = mapper.readValue( aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}"), StackTraceElement.class); - Assert.assertNotNull(elem); - Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber()); + assertNotNull(elem); + assertEquals(StackTraceBean.NUM, elem.getLineNumber()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java index e9edda0b788..e2ccda0a49d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java @@ -16,22 +16,22 @@ */ package org.apache.logging.log4j.core.jackson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; -import org.apache.logging.log4j.core.test.categories.Layouts; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(Layouts.Json.class) -public class JacksonIssue429Test { +@Tag("Layouts.Json") +class JacksonIssue429Test { @SuppressWarnings("serial") static class Jackson429StackTraceElementDeserializer extends StdDeserializer { @@ -43,7 +43,7 @@ public Jackson429StackTraceElementDeserializer() { @Override public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) - throws IOException, JsonProcessingException { + throws IOException { jp.skipChildren(); return new StackTraceElement("a", "b", "b", StackTraceBean.NUM); } @@ -70,12 +70,12 @@ protected ObjectMapper objectMapper() { } @Test - public void testStackTraceElementWithCustom() throws Exception { + void testStackTraceElementWithCustom() throws Exception { // first, via bean that contains StackTraceElement final StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"), StackTraceBean.class); - Assert.assertNotNull(bean); - Assert.assertNotNull(bean.location); - Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); + assertNotNull(bean); + assertNotNull(bean.location); + assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); // and then directly, iff registered final ObjectMapper mapper = new ObjectMapper(); @@ -86,7 +86,7 @@ public void testStackTraceElementWithCustom() throws Exception { final StackTraceElement elem = mapper.readValue( aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"), StackTraceElement.class); - Assert.assertNotNull(elem); - Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber()); + assertNotNull(elem); + assertEquals(StackTraceBean.NUM, elem.getLineNumber()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java index 34f8ad792c7..acc7d439582 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -public class LevelMixInXmlTest extends LevelMixInTest { +class LevelMixInXmlTest extends LevelMixInTest { @Override protected ObjectMapper newObjectMapper() { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java index 55070004120..2d73af1c432 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java @@ -16,27 +16,27 @@ */ package org.apache.logging.log4j.core.jackson; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; -import org.apache.logging.log4j.core.test.categories.Layouts; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(Layouts.Json.class) -public class StackTraceElementMixInTest { +@Tag("Layouts.Json") +class StackTraceElementMixInTest { @Test - public void testLog4jJsonObjectMapper() throws Exception { + void testLog4jJsonObjectMapper() throws Exception { this.roundtrip(new Log4jJsonObjectMapper()); } @Test - public void testLog4jYamlObjectMapper() throws Exception { + void testLog4jYamlObjectMapper() throws Exception { this.roundtrip(new Log4jYamlObjectMapper()); } @@ -53,11 +53,11 @@ private void roundtrip(final ObjectMapper mapper) new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123); final String s = mapper.writeValueAsString(expected); final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class); - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } @Test - public void testLog4jXmlObjectMapper() throws Exception { + void testLog4jXmlObjectMapper() throws Exception { this.roundtrip(new Log4jXmlObjectMapper()); } @@ -66,7 +66,7 @@ protected String aposToQuotes(final String json) { } @Test - public void testFromJsonWithSimpleModule() throws Exception { + void testFromJsonWithSimpleModule() throws Exception { final ObjectMapper mapper = new ObjectMapper(); final SimpleModule module = new SimpleModule(); module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer()); @@ -76,11 +76,11 @@ public void testFromJsonWithSimpleModule() throws Exception { final String s = this.aposToQuotes( "{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"); final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class); - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } @Test - public void testFromJsonWithLog4jModule() throws Exception { + void testFromJsonWithLog4jModule() throws Exception { final ObjectMapper mapper = new ObjectMapper(); final boolean encodeThreadContextAsList = false; final SimpleModule module = new Log4jJsonModule(encodeThreadContextAsList, true, false, false); @@ -91,6 +91,6 @@ public void testFromJsonWithLog4jModule() throws Exception { final String s = this.aposToQuotes( "{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"); final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class); - Assert.assertEquals(expected, actual); + assertEquals(expected, actual); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jmx/ServerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jmx/ServerTest.java index 958785dee8a..501988fa3f2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jmx/ServerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/jmx/ServerTest.java @@ -24,10 +24,10 @@ /** * Unit tests for the Server class. */ -public class ServerTest { +class ServerTest { @Test - public void testEscapeQuotesButDoesNotEscapeEquals() throws Exception { + void testEscapeQuotesButDoesNotEscapeEquals() throws Exception { final String ctx = "WebAppClassLoader=1320771902@4eb9613e"; // LOG4J2-492 final String ctxName = Server.escape(ctx); assertEquals("\"WebAppClassLoader=1320771902@4eb9613e\"", ctxName); @@ -36,7 +36,7 @@ public void testEscapeQuotesButDoesNotEscapeEquals() throws Exception { } @Test - public void testEscapeQuotesButDoesNotEscapeComma() throws Exception { + void testEscapeQuotesButDoesNotEscapeComma() throws Exception { final String ctx = "a,b,c"; final String ctxName = Server.escape(ctx); assertEquals("\"a,b,c\"", ctxName); @@ -45,7 +45,7 @@ public void testEscapeQuotesButDoesNotEscapeComma() throws Exception { } @Test - public void testEscapeQuotesButDoesNotEscapeColon() throws Exception { + void testEscapeQuotesButDoesNotEscapeColon() throws Exception { final String ctx = "a:b:c"; final String ctxName = Server.escape(ctx); assertEquals("\"a:b:c\"", ctxName); @@ -54,7 +54,7 @@ public void testEscapeQuotesButDoesNotEscapeColon() throws Exception { } @Test - public void testEscapeQuotesAndEscapesQuestion() throws Exception { + void testEscapeQuotesAndEscapesQuestion() throws Exception { final String ctx = "a?c"; final String ctxName = Server.escape(ctx); assertEquals("\"a\\?c\"", ctxName); @@ -63,7 +63,7 @@ public void testEscapeQuotesAndEscapesQuestion() throws Exception { } @Test - public void testEscapeQuotesAndEscapesStar() throws Exception { + void testEscapeQuotesAndEscapesStar() throws Exception { final String ctx = "a*c"; final String ctxName = Server.escape(ctx); assertEquals("\"a\\*c\"", ctxName); @@ -72,7 +72,7 @@ public void testEscapeQuotesAndEscapesStar() throws Exception { } @Test - public void testEscapeQuotesAndEscapesBackslash() throws Exception { + void testEscapeQuotesAndEscapesBackslash() throws Exception { final String ctx = "a\\c"; final String ctxName = Server.escape(ctx); assertEquals("\"a\\\\c\"", ctxName); @@ -81,7 +81,7 @@ public void testEscapeQuotesAndEscapesBackslash() throws Exception { } @Test - public void testEscapeQuotesAndEscapesQuote() throws Exception { + void testEscapeQuotesAndEscapesQuote() throws Exception { final String ctx = "a\"c"; final String ctxName = Server.escape(ctx); assertEquals("\"a\\\"c\"", ctxName); @@ -90,7 +90,7 @@ public void testEscapeQuotesAndEscapesQuote() throws Exception { } @Test - public void testEscapeIgnoresSpaces() throws Exception { + void testEscapeIgnoresSpaces() throws Exception { final String ctx = "a c"; final String ctxName = Server.escape(ctx); assertEquals("a c", ctxName); @@ -99,7 +99,7 @@ public void testEscapeIgnoresSpaces() throws Exception { } @Test - public void testEscapeEscapesLineFeed() throws Exception { + void testEscapeEscapesLineFeed() throws Exception { final String ctx = "a\rc"; final String ctxName = Server.escape(ctx); assertEquals("ac", ctxName); @@ -108,7 +108,7 @@ public void testEscapeEscapesLineFeed() throws Exception { } @Test - public void testEscapeEscapesCarriageReturn() throws Exception { + void testEscapeEscapesCarriageReturn() throws Exception { final String ctx = "a\nc"; final String ctxName = Server.escape(ctx); assertEquals("\"a\\nc\"", ctxName); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/AbstractStringLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/AbstractStringLayoutTest.java index e48c90f6b54..d15961bca51 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/AbstractStringLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/AbstractStringLayoutTest.java @@ -30,7 +30,7 @@ /** * Tests AbstractStringLayout. */ -public class AbstractStringLayoutTest { +class AbstractStringLayoutTest { // Configuration explicitly null private static final Serializer serializer = new SerializerBuilder() @@ -57,7 +57,7 @@ public String toSerializable(final LogEvent event) { } @Test - public void testGetStringBuilderCapacityRestrictedToMax() throws Exception { + void testGetStringBuilderCapacityRestrictedToMax() { final StringBuilder sb = ConcreteStringLayout.getStringBuilder(); final int initialCapacity = sb.capacity(); assertEquals(ConcreteStringLayout.DEFAULT_STRING_BUILDER_SIZE, sb.capacity(), "initial capacity"); @@ -93,7 +93,7 @@ public void testGetStringBuilderCapacityRestrictedToMax() throws Exception { } @Test - public void testNullConfigurationIsAllowed() { + void testNullConfigurationIsAllowed() { try { final ConcreteStringLayout layout = new ConcreteStringLayout(); layout.serializeToString(serializer); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithGelfLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithGelfLayoutTest.java index 06f1b4a13f8..5736383b419 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithGelfLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithGelfLayoutTest.java @@ -44,7 +44,7 @@ * @since 2.8 */ @Tag("concurrency") -public class ConcurrentLoggingWithGelfLayoutTest { +class ConcurrentLoggingWithGelfLayoutTest { private static final Path PATH = Paths.get("target", "test-gelf-layout.log"); @AfterAll @@ -55,7 +55,7 @@ static void after() throws IOException { @Test @LoggerContextSource("log4j2-gelf-layout.xml") - public void testConcurrentLogging(final LoggerContext context) throws Throwable { + void testConcurrentLogging(final LoggerContext context) throws Throwable { final Logger log = context.getLogger(ConcurrentLoggingWithGelfLayoutTest.class); final int threadCount = Runtime.getRuntime().availableProcessors() * 2; final CountDownLatch latch = new CountDownLatch(threadCount); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java index addaf794232..8224b7473f6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java @@ -18,7 +18,7 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.endsWith; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.nio.charset.Charset; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvLogEventLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvLogEventLayoutTest.java index 4f85617f5a7..fadd4a0fecf 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvLogEventLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvLogEventLayoutTest.java @@ -149,27 +149,27 @@ private void testLayout( } @Test - public void testLayoutDefault() throws Exception { + public void testLayoutDefault() { testLayout(CSVFormat.DEFAULT); } @Test - public void testLayoutExcel() throws Exception { + public void testLayoutExcel() { testLayout(CSVFormat.EXCEL); } @Test - public void testLayoutMySQL() throws Exception { + public void testLayoutMySQL() { testLayout(CSVFormat.MYSQL); } @Test - public void testLayoutRFC4180() throws Exception { + public void testLayoutRFC4180() { testLayout(CSVFormat.RFC4180); } @Test - public void testLayoutTab() throws Exception { + public void testLayoutTab() { testLayout(CSVFormat.TDF); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutAllAsyncTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutAllAsyncTest.java index 571795ffadf..1bcb5ffcf22 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutAllAsyncTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutAllAsyncTest.java @@ -21,47 +21,46 @@ import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.async.AsyncLoggerContextSelector; import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.test.categories.Layouts; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Tests {@link AbstractCsvLayout} with all loggers async. * * @since 2.6 */ -@Category(Layouts.Csv.class) -public class CsvParameterLayoutAllAsyncTest { +@Tag("Layouts.Csv") +class CsvParameterLayoutAllAsyncTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerTest.xml"); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, Strings.EMPTY); } @Test - public void testLayoutDefaultNormal() throws Exception { + void testLayoutDefaultNormal() throws Exception { final Logger root = (Logger) LogManager.getRootLogger(); CsvParameterLayoutTest.testLayoutNormalApi(root, CsvParameterLayout.createDefaultLayout(), false); } @Test - public void testLayoutDefaultObjectArrayMessage() throws Exception { + void testLayoutDefaultObjectArrayMessage() throws Exception { final Logger root = (Logger) LogManager.getRootLogger(); CsvParameterLayoutTest.testLayoutNormalApi(root, CsvParameterLayout.createDefaultLayout(), true); } @Test - public void testLayoutTab() throws Exception { + void testLayoutTab() throws Exception { final Logger root = (Logger) LogManager.getRootLogger(); CsvParameterLayoutTest.testLayoutNormalApi(root, CsvParameterLayout.createLayout(CSVFormat.TDF), true); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutTest.java index e7913c992ea..50bff2beac7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/CsvParameterLayoutTest.java @@ -172,7 +172,7 @@ public void testLayoutTab() throws Exception { @Test public void testLogJsonArgument() throws InterruptedException { - final ListAppender appender = (ListAppender) init.getAppender("List"); + final ListAppender appender = init.getAppender("List"); appender.countDownLatch = new CountDownLatch(4); appender.clear(); final Logger logger = (Logger) LogManager.getRootLogger(); @@ -180,7 +180,7 @@ public void testLogJsonArgument() throws InterruptedException { logger.error("log:{}", json); // wait until background thread finished processing final int msgCount = 1; - if (appender.getMessages().size() < msgCount) { + if (appender.getMessages().isEmpty()) { appender.countDownLatch.await(5, TimeUnit.SECONDS); } assertEquals( diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout2Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout2Test.java index eb05ec10287..47bc55eafde 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout2Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout2Test.java @@ -30,10 +30,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("GelfLayout2Test.xml") -public class GelfLayout2Test { +class GelfLayout2Test { @Test - public void gelfLayout(final LoggerContext context, @Named final ListAppender list) throws IOException { + void gelfLayout(final LoggerContext context, @Named final ListAppender list) throws IOException { list.clear(); final Logger logger = context.getLogger(getClass()); logger.info("Message"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout3Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout3Test.java index 7bc09bcbc28..ba67f16a8c2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout3Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayout3Test.java @@ -38,10 +38,10 @@ @LoggerContextSource("GelfLayout3Test.xml") @UsingAnyThreadContext @Tag("json") -public class GelfLayout3Test { +class GelfLayout3Test { @Test - public void gelfLayout(final LoggerContext context, @Named final ListAppender list) throws IOException { + void gelfLayout(final LoggerContext context, @Named final ListAppender list) throws IOException { list.clear(); final Logger logger = context.getLogger(getClass()); ThreadContext.put("loginId", "rgoers"); @@ -66,7 +66,7 @@ public void gelfLayout(final LoggerContext context, @Named final ListAppender li } @Test - public void mapMessage(final LoggerContext context, @Named final ListAppender list) throws IOException { + void mapMessage(final LoggerContext context, @Named final ListAppender list) throws IOException { list.clear(); final Logger logger = context.getLogger(getClass()); ThreadContext.put("loginId", "rgoers"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutPatternSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutPatternSelectorTest.java index a7acf02f450..9eb4493ac3d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutPatternSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutPatternSelectorTest.java @@ -39,10 +39,10 @@ @LoggerContextSource("GelfLayoutPatternSelectorTest.xml") @UsingAnyThreadContext @Tag("json") -public class GelfLayoutPatternSelectorTest { +class GelfLayoutPatternSelectorTest { @Test - public void gelfLayout(final LoggerContext context, @Named final ListAppender list) throws IOException { + void gelfLayout(final LoggerContext context, @Named final ListAppender list) throws IOException { list.clear(); final Logger logger = context.getLogger(getClass()); ThreadContext.put("loginId", "rgoers"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutTest.java index 8d547079645..569a6698511 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/GelfLayoutTest.java @@ -49,7 +49,7 @@ import org.junit.jupiter.api.Test; @UsingAnyThreadContext -public class GelfLayoutTest { +class GelfLayoutTest { static ConfigurationFactory configFactory = new BasicConfigurationFactory(); @@ -66,12 +66,12 @@ public class GelfLayoutTest { private static final String VALUE1 = "Value1"; @AfterAll - public static void cleanupClass() { + static void cleanupClass() { ConfigurationFactory.removeConfigurationFactory(configFactory); } @BeforeAll - public static void setupClass() { + static void setupClass() { ConfigurationFactory.setConfigurationFactory(configFactory); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); @@ -254,47 +254,47 @@ private void testCompressedLayout( } @Test - public void testLayoutGzipCompression() throws Exception { + void testLayoutGzipCompression() throws Exception { testCompressedLayout(CompressionType.GZIP, true, true, HOSTNAME, false, false); } @Test - public void testLayoutNoCompression() throws Exception { + void testLayoutNoCompression() throws Exception { testCompressedLayout(CompressionType.OFF, true, true, HOSTNAME, false, false); } @Test - public void testLayoutZlibCompression() throws Exception { + void testLayoutZlibCompression() throws Exception { testCompressedLayout(CompressionType.ZLIB, true, true, HOSTNAME, false, false); } @Test - public void testLayoutNoStacktrace() throws Exception { + void testLayoutNoStacktrace() throws Exception { testCompressedLayout(CompressionType.OFF, false, true, HOSTNAME, false, false); } @Test - public void testLayoutNoThreadContext() throws Exception { + void testLayoutNoThreadContext() throws Exception { testCompressedLayout(CompressionType.OFF, true, false, HOSTNAME, false, false); } @Test - public void testLayoutNoHost() throws Exception { + void testLayoutNoHost() throws Exception { testCompressedLayout(CompressionType.OFF, true, true, null, false, false); } @Test - public void testLayoutNullDelimiter() throws Exception { + void testLayoutNullDelimiter() throws Exception { testCompressedLayout(CompressionType.OFF, false, true, HOSTNAME, true, false); } @Test - public void testLayoutNewLineDelimiter() throws Exception { + void testLayoutNewLineDelimiter() throws Exception { testCompressedLayout(CompressionType.OFF, true, true, HOSTNAME, false, true); } @Test - public void testFormatTimestamp() { + void testFormatTimestamp() { assertEquals("0", GelfLayout.formatTimestamp(0L).toString()); assertEquals("1.000", GelfLayout.formatTimestamp(1000L).toString()); assertEquals("1.001", GelfLayout.formatTimestamp(1001L).toString()); @@ -316,17 +316,17 @@ private void testRequiresLocation(final String messagePattern, final Boolean req } @Test - public void testRequiresLocationPatternNotSet() { + void testRequiresLocationPatternNotSet() { testRequiresLocation(null, false); } @Test - public void testRequiresLocationPatternNotContainsLocation() { + void testRequiresLocationPatternNotContainsLocation() { testRequiresLocation("%m %n", false); } @Test - public void testRequiresLocationPatternContainsLocation() { + void testRequiresLocationPatternContainsLocation() { testRequiresLocation("%C %m %t", true); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/HtmlLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/HtmlLayoutTest.java index 9a222e5145f..13901d3af08 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/HtmlLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/HtmlLayoutTest.java @@ -51,7 +51,7 @@ import org.junit.jupiter.api.Test; @UsingAnyThreadContext -public class HtmlLayoutTest { +class HtmlLayoutTest { private static class MyLogEvent extends AbstractLogEvent { private static final long serialVersionUID = 0; @@ -87,14 +87,14 @@ public Message getMessage() { static ConfigurationFactory cf = new BasicConfigurationFactory(); @BeforeAll - public static void setupClass() { + static void setupClass() { ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); } @AfterAll - public static void cleanupClass() { + static void cleanupClass() { ConfigurationFactory.removeConfigurationFactory(cf); } @@ -104,13 +104,13 @@ public static void cleanupClass() { private static final String multiLine = "First line
Second line"; @Test - public void testDefaultContentType() { + void testDefaultContentType() { final HtmlLayout layout = HtmlLayout.createDefaultLayout(); assertEquals("text/html; charset=UTF-8", layout.getContentType()); } @Test - public void testContentType() { + void testContentType() { final HtmlLayout layout = HtmlLayout.newBuilder() .withContentType("text/html; charset=UTF-16") .build(); @@ -120,7 +120,7 @@ public void testContentType() { } @Test - public void testDefaultCharset() { + void testDefaultCharset() { final HtmlLayout layout = HtmlLayout.createDefaultLayout(); assertEquals(StandardCharsets.UTF_8, layout.getCharset()); } @@ -129,16 +129,16 @@ public void testDefaultCharset() { * Test case for MDC conversion pattern. */ @Test - public void testLayoutIncludeLocationNo() throws Exception { + void testLayoutIncludeLocationNo() throws Exception { testLayout(false); } @Test - public void testLayoutIncludeLocationYes() throws Exception { + void testLayoutIncludeLocationYes() throws Exception { testLayout(true); } - private void testLayout(final boolean includeLocation) throws Exception { + private void testLayout(final boolean includeLocation) { final Map appenders = root.getAppenders(); for (final Appender appender : appenders.values()) { root.removeAppender(appender); @@ -184,9 +184,9 @@ private void testLayout(final boolean includeLocation) throws Exception { assertEquals("Log4j Log Messages", list.get(4), "Incorrect title"); assertEquals("", list.get(list.size() - 1), "Incorrect footer"); if (includeLocation) { - assertEquals(list.get(50), multiLine, "Incorrect multiline"); + assertEquals(multiLine, list.get(50), "Incorrect multiline"); assertTrue(html.contains("HtmlLayoutTest.java:"), "Missing location"); - assertEquals(list.get(71), body, "Incorrect body"); + assertEquals(body, list.get(71), "Incorrect body"); } else { assertFalse(html.contains("HtmlLayoutTest.java:"), "Location should not be in the output table"); } @@ -196,7 +196,7 @@ private void testLayout(final boolean includeLocation) throws Exception { } @Test - public void testLayoutWithoutDataPattern() { + void testLayoutWithoutDataPattern() { final HtmlLayout layout = HtmlLayout.newBuilder().build(); final MyLogEvent event = new MyLogEvent(); @@ -207,7 +207,7 @@ public void testLayoutWithoutDataPattern() { } @Test - public void testLayoutWithDatePatternJvmElapseTime() { + void testLayoutWithDatePatternJvmElapseTime() { final HtmlLayout layout = HtmlLayout.newBuilder().setDatePattern("JVM_ELAPSE_TIME").build(); @@ -219,7 +219,7 @@ public void testLayoutWithDatePatternJvmElapseTime() { } @Test - public void testLayoutWithDatePatternUnix() { + void testLayoutWithDatePatternUnix() { final HtmlLayout layout = HtmlLayout.newBuilder().setDatePattern("UNIX").build(); final MyLogEvent event = new MyLogEvent(); @@ -229,7 +229,7 @@ public void testLayoutWithDatePatternUnix() { } @Test - public void testLayoutWithDatePatternUnixMillis() { + void testLayoutWithDatePatternUnixMillis() { final HtmlLayout layout = HtmlLayout.newBuilder().setDatePattern("UNIX_MILLIS").build(); @@ -240,7 +240,7 @@ public void testLayoutWithDatePatternUnixMillis() { } @Test - public void testLayoutWithDatePatternFixedFormat() { + void testLayoutWithDatePatternFixedFormat() { for (final String timeZone : new String[] {"GMT+8", "GMT+0530", "UTC", null}) { for (final FixedFormat format : FixedFormat.values()) { testLayoutWithDatePatternFixedFormat(format, timeZone); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutMillisTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutMillisTest.java index 30720ad6f14..614219e6114 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutMillisTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutMillisTest.java @@ -62,7 +62,7 @@ public void before() { public void testTimestamp() { logger.info("This is a test message"); final List message = app.getMessages(); - assertTrue("No messages", message != null && message.size() > 0); + assertTrue("No messages", message != null && !message.isEmpty()); final String json = message.get(0); System.out.println(json); assertNotNull("No JSON message", json); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java index 07f5e00cc07..a0f67ffa0cc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java @@ -16,12 +16,13 @@ */ package org.apache.logging.log4j.core.layout; +import static org.assertj.core.api.Assertions.fail; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -44,7 +45,6 @@ import org.apache.logging.log4j.core.lookup.JavaLookup; import org.apache.logging.log4j.core.test.BasicConfigurationFactory; import org.apache.logging.log4j.core.test.appender.ListAppender; -import org.apache.logging.log4j.core.test.categories.Layouts; import org.apache.logging.log4j.core.util.DummyNanoClock; import org.apache.logging.log4j.core.util.KeyValuePair; import org.apache.logging.log4j.core.util.SystemClock; @@ -56,29 +56,28 @@ import org.apache.logging.log4j.util.SortedArrayStringMap; import org.apache.logging.log4j.util.StringMap; import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; /** * Tests the JsonLayout class. */ -@Category(Layouts.Json.class) -public class JsonLayoutTest { +@Tag("Layouts.Json") +class JsonLayoutTest { static ConfigurationFactory cf = new BasicConfigurationFactory(); private static final String DQUOTE = "\""; - @AfterClass - public static void cleanupClass() { + @AfterAll + static void cleanupClass() { ConfigurationFactory.removeConfigurationFactory(cf); ThreadContext.clearAll(); } - @BeforeClass - public static void setupClass() { + @BeforeAll + static void setupClass() { ThreadContext.clearAll(); ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); @@ -91,8 +90,7 @@ public static void setupClass() { private void checkAt(final String expected, final int lineIndex, final List list) { final String trimedLine = list.get(lineIndex).trim(); - assertTrue( - "Incorrect line index " + lineIndex + ": " + Strings.dquote(trimedLine), trimedLine.equals(expected)); + assertEquals(expected, trimedLine, "Incorrect line index " + lineIndex + ": " + Strings.dquote(trimedLine)); } private void checkContains(final String expected, final List list) { @@ -102,7 +100,7 @@ private void checkContains(final String expected, final List list) { return; } } - Assert.fail("Cannot find " + expected + " in " + list); + fail("Cannot find " + expected + " in " + list); } private void checkMapEntry( @@ -115,11 +113,11 @@ private void checkMapEntry( if (contextMapAslist) { // {"key":"KEY", "value":"VALUE"} final String expected = String.format("{\"key\":\"%s\",\"value\":\"%s\"}", key, value); - assertTrue("Cannot find contextMapAslist " + expected + " in " + str, str.contains(expected)); + assertTrue(str.contains(expected), "Cannot find contextMapAslist " + expected + " in " + str); } else { // "KEY":"VALUE" final String expected = String.format("\"%s\":\"%s\"", key, value); - assertTrue("Cannot find contextMap " + expected + " in " + str, str.contains(expected)); + assertTrue(str.contains(expected), "Cannot find contextMap " + expected + " in " + str); } } @@ -127,17 +125,17 @@ private void checkProperty(final String key, final String value, final boolean c final String propSep = this.toPropertySeparator(compact); // {"key":"MDC.B","value":"B_Value"} final String expected = String.format("\"%s\"%s\"%s\"", key, propSep, value); - assertTrue("Cannot find " + expected + " in " + str, str.contains(expected)); + assertTrue(str.contains(expected), "Cannot find " + expected + " in " + str); } private void checkPropertyName(final String name, final boolean compact, final String str) { final String propSep = this.toPropertySeparator(compact); - assertTrue(str, str.contains(DQUOTE + name + DQUOTE + propSep)); + assertTrue(str.contains(DQUOTE + name + DQUOTE + propSep), str); } private void checkPropertyNameAbsent(final String name, final boolean compact, final String str) { final String propSep = this.toPropertySeparator(compact); - assertFalse(str, str.contains(DQUOTE + name + DQUOTE + propSep)); + assertFalse(str.contains(DQUOTE + name + DQUOTE + propSep), str); } private void testAllFeatures( @@ -167,13 +165,13 @@ private void testAllFeatures( this.toPropertySeparator(compact); if (endOfLine == null) { // Just check for \n since \r might or might not be there. - assertEquals(str, !compact || eventEol, str.contains("\n")); + assertEquals(!compact || eventEol, str.contains("\n"), str); } else { - assertEquals(str, !compact || eventEol, str.contains(endOfLine)); - assertEquals(str, compact && eventEol, str.endsWith(endOfLine)); + assertEquals(!compact || eventEol, str.contains(endOfLine), str); + assertEquals(compact && eventEol, str.endsWith(endOfLine), str); } - assertEquals(str, locationInfo, str.contains("source")); - assertEquals(str, includeContext, str.contains("contextMap")); + assertEquals(locationInfo, str.contains("source"), str); + assertEquals(includeContext, str.contains("contextMap"), str); final Log4jLogEvent actual = new Log4jJsonObjectMapper(contextMapAslist, includeStacktrace, false, false) .readValue(str, Log4jLogEvent.class); @@ -229,19 +227,19 @@ private void testAllFeatures( } @Test - public void testContentType() { + void testContentType() { final AbstractJacksonLayout layout = JsonLayout.createDefaultLayout(); assertEquals("application/json; charset=UTF-8", layout.getContentType()); } @Test - public void testDefaultCharset() { + void testDefaultCharset() { final AbstractJacksonLayout layout = JsonLayout.createDefaultLayout(); assertEquals(StandardCharsets.UTF_8, layout.getCharset()); } @Test - public void testEscapeLayout() throws Exception { + void testEscapeLayout() { final Map appenders = this.rootLogger.getAppenders(); for (final Appender appender : appenders.values()) { this.rootLogger.removeAppender(appender); @@ -289,7 +287,7 @@ public void testEscapeLayout() throws Exception { * Test case for MDC conversion pattern. */ @Test - public void testLayout() throws Exception { + void testLayout() { final Map appenders = this.rootLogger.getAppenders(); for (final Appender appender : appenders.values()) { this.rootLogger.removeAppender(appender); @@ -349,7 +347,7 @@ public void testLayout() throws Exception { } @Test - public void testLayoutLoggerName() throws Exception { + void testLayoutLoggerName() throws Exception { final boolean propertiesAsList = false; // @formatter:off final AbstractJacksonLayout layout = JsonLayout.newBuilder() @@ -374,7 +372,7 @@ public void testLayoutLoggerName() throws Exception { .build(); // @formatter:on final String str = layout.toSerializable(expected); - assertTrue(str, str.contains("\"loggerName\":\"a.B\"")); + assertTrue(str.contains("\"loggerName\":\"a.B\""), str); final Log4jLogEvent actual = new Log4jJsonObjectMapper(propertiesAsList, true, false, false).readValue(str, Log4jLogEvent.class); assertEquals(expected.getLoggerName(), actual.getLoggerName()); @@ -382,7 +380,7 @@ public void testLayoutLoggerName() throws Exception { } @Test - public void testAdditionalFields() throws Exception { + void testAdditionalFields() { final AbstractJacksonLayout layout = JsonLayout.newBuilder() .setLocationInfo(false) .setProperties(false) @@ -397,13 +395,13 @@ public void testAdditionalFields() throws Exception { .setConfiguration(ctx.getConfiguration()) .build(); final String str = layout.toSerializable(LogEventFixtures.createLogEvent()); - assertTrue(str, str.contains("\"KEY1\":\"VALUE1\"")); - assertTrue(str, str.contains("\"KEY2\":\"" + new JavaLookup().getRuntime() + "\"")); + assertTrue(str.contains("\"KEY1\":\"VALUE1\""), str); + assertTrue(str.contains("\"KEY2\":\"" + new JavaLookup().getRuntime() + "\""), str); } // Test for LOG4J2-2345 @Test - public void testReusableLayoutMessageWithCurlyBraces() throws Exception { + void testReusableLayoutMessageWithCurlyBraces() throws Exception { final boolean propertiesAsList = false; final AbstractJacksonLayout layout = JsonLayout.newBuilder() .setLocationInfo(false) @@ -429,7 +427,7 @@ public void testReusableLayoutMessageWithCurlyBraces() throws Exception { mutableLogEvent.initFrom(expected); final String str = layout.toSerializable(mutableLogEvent); final String expectedMessage = "Testing " + TestObj.TO_STRING_VALUE; - assertTrue(str, str.contains("\"message\":\"" + expectedMessage + '"')); + assertTrue(str.contains("\"message\":\"" + expectedMessage + '"'), str); final Log4jLogEvent actual = new Log4jJsonObjectMapper(propertiesAsList, true, false, false).readValue(str, Log4jLogEvent.class); assertEquals(expectedMessage, actual.getMessage().getFormattedMessage()); @@ -440,7 +438,7 @@ public void testReusableLayoutMessageWithCurlyBraces() throws Exception { // Test for LOG4J2-2312 LOG4J2-2341 @Test - public void testLayoutRingBufferEventReusableMessageWithCurlyBraces() throws Exception { + void testLayoutRingBufferEventReusableMessageWithCurlyBraces() throws Exception { final boolean propertiesAsList = false; final AbstractJacksonLayout layout = JsonLayout.newBuilder() .setLocationInfo(false) @@ -492,45 +490,45 @@ public String toString() { } @Test - public void testLocationOffCompactOffMdcOff() throws Exception { + void testLocationOffCompactOffMdcOff() throws Exception { this.testAllFeatures(false, false, false, null, false, false, true); } @Test - public void testLocationOnCompactOnMdcOn() throws Exception { + void testLocationOnCompactOnMdcOn() throws Exception { this.testAllFeatures(true, true, false, null, true, false, true); } @Test - public void testLocationOnCompactOnEventEolOnMdcOn() throws Exception { + void testLocationOnCompactOnEventEolOnMdcOn() throws Exception { this.testAllFeatures(true, true, true, null, true, false, true); } @Test - public void testLocationOnCompactOnEventEolOnMdcOnMdcAsList() throws Exception { + void testLocationOnCompactOnEventEolOnMdcOnMdcAsList() throws Exception { this.testAllFeatures(true, true, true, null, true, true, true); } @Test - public void testExcludeStacktrace() throws Exception { + void testExcludeStacktrace() throws Exception { this.testAllFeatures(false, false, false, null, false, false, false); } @Test - public void testLocationOnCustomEndOfLine() throws Exception { + void testLocationOnCustomEndOfLine() throws Exception { this.testAllFeatures(true, true, true, "CUSTOM_END_OF_LINE", true, false, true); } @Test - public void testStacktraceAsString() throws Exception { + void testStacktraceAsString() { final String str = prepareJSONForStacktraceTests(true); - assertTrue(str, str.contains("\"extendedStackTrace\":\"java.lang.NullPointerException")); + assertTrue(str.contains("\"extendedStackTrace\":\"java.lang.NullPointerException"), str); } @Test - public void testStacktraceAsNonString() throws Exception { + void testStacktraceAsNonString() { final String str = prepareJSONForStacktraceTests(false); - assertTrue(str, str.contains("\"extendedStackTrace\":[")); + assertTrue(str.contains("\"extendedStackTrace\":["), str); } private String prepareJSONForStacktraceTests(final boolean stacktraceAsString) { @@ -546,15 +544,15 @@ private String prepareJSONForStacktraceTests(final boolean stacktraceAsString) { } @Test - public void testObjectMessageAsJsonString() { + void testObjectMessageAsJsonString() { final String str = prepareJSONForObjectMessageAsJsonObjectTests(1234, false); - assertTrue(str, str.contains("\"message\":\"" + this.getClass().getCanonicalName() + "$TestClass@")); + assertTrue(str.contains("\"message\":\"" + this.getClass().getCanonicalName() + "$TestClass@"), str); } @Test - public void testObjectMessageAsJsonObject() { + void testObjectMessageAsJsonObject() { final String str = prepareJSONForObjectMessageAsJsonObjectTests(1234, true); - assertTrue(str, str.contains("\"message\":{\"value\":1234}")); + assertTrue(str.contains("\"message\":{\"value\":1234}"), str); } private String prepareJSONForObjectMessageAsJsonObjectTests( @@ -580,10 +578,10 @@ private String prepareJSONForObjectMessageAsJsonObjectTests( } @Test - public void testInstantSortsBeforeMessage() { + void testInstantSortsBeforeMessage() { final String str = prepareJSONForEventWithTimeAsInstant(); - assertTrue(str, str.startsWith("{\"instant\":{\"epochSecond\":0,\"nanoOfSecond\":1000000},")); - assertTrue(str, str.contains("\"message\":\"message\"")); + assertTrue(str.startsWith("{\"instant\":{\"epochSecond\":0,\"nanoOfSecond\":1000000},"), str); + assertTrue(str.contains("\"message\":\"message\""), str); } private String prepareJSONForEventWithTimeAsInstant() { @@ -605,7 +603,7 @@ private String prepareJSONForEventWithTimeAsInstant() { } @Test - public void testIncludeNullDelimiterTrue() throws Exception { + void testIncludeNullDelimiterTrue() { final AbstractJacksonLayout layout = JsonLayout.newBuilder() .setCompact(true) .setIncludeNullDelimiter(true) @@ -615,7 +613,7 @@ public void testIncludeNullDelimiterTrue() throws Exception { } @Test - public void testIncludeNullDelimiterFalse() throws Exception { + void testIncludeNullDelimiterFalse() { final AbstractJacksonLayout layout = JsonLayout.newBuilder() .setCompact(true) .setIncludeNullDelimiter(false) @@ -628,21 +626,21 @@ public void testIncludeNullDelimiterFalse() throws Exception { * @see LOG4J2-2749 */ @Test - public void testEmptyValuesAreIgnored() { + void testEmptyValuesAreIgnored() { final AbstractJacksonLayout layout = JsonLayout.newBuilder() .setAdditionalFields(new KeyValuePair[] {new KeyValuePair("empty", "${ctx:empty:-}")}) .setConfiguration(ctx.getConfiguration()) .build(); final String str = layout.toSerializable(LogEventFixtures.createLogEvent()); - assertFalse(str, str.contains("\"empty\"")); + assertFalse(str.contains("\"empty\""), str); } /** * @see LOG4J2-3358 */ @Test - public void jsonLayout_should_substitute_lookups() { + void jsonLayout_should_substitute_lookups() { // Create the layout. final KeyValuePair[] additionalFields = { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Log4j2_2195_Test.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Log4j2_2195_Test.java index a97a1d729e9..6dbb93cc898 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Log4j2_2195_Test.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Log4j2_2195_Test.java @@ -32,10 +32,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("LOG4J-2195/log4j2.xml") -public class Log4j2_2195_Test { +class Log4j2_2195_Test { @Test - public void test(final LoggerContext context, @Named("ListAppender") final ListAppender listAppender) { + void test(final LoggerContext context, @Named("ListAppender") final ListAppender listAppender) { listAppender.clear(); context.getLogger(getClass()).info("This is a test.", new Exception("Test exception!")); assertNotNull(listAppender); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java index c408a70e550..06fb6766e0b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java @@ -16,10 +16,10 @@ */ package org.apache.logging.log4j.core.layout; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.util.Collections; @@ -104,8 +104,8 @@ static void assertEqualLogEvents( assertEquals(expected.getTimeMillis(), actual.getTimeMillis()); assertEquals(includeSource ? expected.getSource() : null, actual.getSource()); assertEquals(expected.getThreadName(), actual.getThreadName()); - assertNotNull("original should have an exception", expected.getThrown()); - assertNull("exception should not be serialized", actual.getThrown()); + assertNotNull(expected.getThrown(), "original should have an exception"); + assertNull(actual.getThrown(), "exception should not be serialized"); if (includeStacktrace) { // TODO should compare the rest of the ThrowableProxy assertEquals(expected.getThrownProxy(), actual.getThrownProxy()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutLookupDateTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutLookupDateTest.java index eae2d034f5f..3424fc5d512 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutLookupDateTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutLookupDateTest.java @@ -30,10 +30,10 @@ * This shows the behavior this user wants to disable. */ @LoggerContextSource("log4j-list-lookups.xml") -public class PatternLayoutLookupDateTest { +class PatternLayoutLookupDateTest { @Test - public void testDateLookupInMessage(final LoggerContext context, @Named("List") final ListAppender listAppender) { + void testDateLookupInMessage(final LoggerContext context, @Named("List") final ListAppender listAppender) { listAppender.clear(); final String template = "${date:YYYY-MM-dd}"; context.getLogger(PatternLayoutLookupDateTest.class.getName()).info(template); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutMainMapLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutMainMapLookupTest.java index 2b4de12713a..b519104e8e6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutMainMapLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutMainMapLookupTest.java @@ -34,7 +34,7 @@ * Tests LOG4j2-962. */ @LoggerContextSource(value = "log4j2-962.xml", reconfigure = ReconfigurationPolicy.BEFORE_EACH) -public class PatternLayoutMainMapLookupTest { +class PatternLayoutMainMapLookupTest { static { // Must be set before Log4j writes the header to the appenders. @@ -42,13 +42,13 @@ public class PatternLayoutMainMapLookupTest { } @Test - public void testFileName(@Named("File") final FileAppender fileApp) { + void testFileName(@Named("File") final FileAppender fileApp) { final String name = fileApp.getFileName(); assertEquals("target/value0.log", name); } @Test - public void testHeader(final LoggerContext context, @Named("List") final ListAppender listApp) { + void testHeader(final LoggerContext context, @Named("List") final ListAppender listApp) { final Logger logger = context.getLogger(getClass()); logger.info("Hello World"); final List initialMessages = listApp.getMessages(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutNoLookupDateTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutNoLookupDateTest.java index 47379cbe69d..437e44bc175 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutNoLookupDateTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutNoLookupDateTest.java @@ -16,25 +16,26 @@ */ package org.apache.logging.log4j.core.layout; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.test.appender.ListAppender; import org.apache.logging.log4j.core.test.junit.LoggerContextSource; import org.apache.logging.log4j.core.test.junit.Named; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * See (LOG4J2-905) Ability to disable (date) lookup completely, compatibility issues with other libraries like camel. */ @LoggerContextSource("log4j-list.xml") -public class PatternLayoutNoLookupDateTest { +class PatternLayoutNoLookupDateTest { @Test - public void testDateLookupInMessage(final LoggerContext context, @Named("List") final ListAppender listAppender) { + void testDateLookupInMessage(final LoggerContext context, @Named("List") final ListAppender listAppender) { listAppender.clear(); final String template = "${date:YYYY-MM-dd}"; context.getLogger(PatternLayoutNoLookupDateTest.class).info(template); final String string = listAppender.getMessages().get(0); - Assertions.assertTrue(string.contains(template), string); + assertTrue(string.contains(template), string); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutTest.java index 6e800d0f8ad..ba58e68df40 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutTest.java @@ -42,7 +42,7 @@ import org.junit.jupiter.api.Test; @UsingAnyThreadContext -public class PatternLayoutTest { +class PatternLayoutTest { public static class FauxLogger { public String formatEvent(final LogEvent event, final Layout layout) { return new String(layout.toByteArray(event)); @@ -61,7 +61,7 @@ public static void cleanupClass() { } @BeforeAll - public static void setupClass() { + static void setupClass() { ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); @@ -112,7 +112,7 @@ private void assertEncode(final String expectedStr, final PatternLayout layout, } @Test - public void testEqualsEmptyMarker() throws Exception { + void testEqualsEmptyMarker() { // replace "[]" with the empty string final PatternLayout layout = PatternLayout.newBuilder() .withPattern("[%logger]%equals{[%marker]}{[]}{} %msg") @@ -142,7 +142,7 @@ public void testEqualsEmptyMarker() throws Exception { } @Test - public void testHeaderFooterJavaLookup() throws Exception { + void testHeaderFooterJavaLookup() { // % does not work here. final String pattern = "%d{UNIX} MyApp%n${java:version}%n${java:runtime}%n${java:vm}%n${java:os}%n${java:hw}"; final PatternLayout layout = PatternLayout.newBuilder() @@ -175,7 +175,7 @@ public void testHeaderFooterJavaLookup() throws Exception { * Tests LOG4J2-962. */ @Test - public void testHeaderFooterMainLookup() { + void testHeaderFooterMainLookup() { MainMapLookup.setMainArguments("value0", "value1", "value2"); final PatternLayout layout = PatternLayout.newBuilder() .withConfiguration(ctx.getConfiguration()) @@ -194,7 +194,7 @@ public void testHeaderFooterMainLookup() { } @Test - public void testHeaderFooterThreadContext() throws Exception { + void testHeaderFooterThreadContext() { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%d{UNIX} %m") .withConfiguration(ctx.getConfiguration()) @@ -211,8 +211,7 @@ public void testHeaderFooterThreadContext() throws Exception { "expected \"Hello world Header\", actual " + Strings.dquote(new String(header))); } - private void testMdcPattern(final String patternStr, final String expectedStr, final boolean useThreadContext) - throws Exception { + private void testMdcPattern(final String patternStr, final String expectedStr, final boolean useThreadContext) { final PatternLayout layout = PatternLayout.newBuilder() .withPattern(patternStr) .withConfiguration(ctx.getConfiguration()) @@ -232,37 +231,37 @@ private void testMdcPattern(final String patternStr, final String expectedStr, f } @Test - public void testMdcPattern0() throws Exception { + void testMdcPattern0() throws Exception { testMdcPattern("%m : %X", "Hello : {key1=value1, key2=value2}", true); } @Test - public void testMdcPattern1() throws Exception { + void testMdcPattern1() throws Exception { testMdcPattern("%m : %X", "Hello : {}", false); } @Test - public void testMdcPattern2() throws Exception { + void testMdcPattern2() throws Exception { testMdcPattern("%m : %X{key1}", "Hello : value1", true); } @Test - public void testMdcPattern3() throws Exception { + void testMdcPattern3() throws Exception { testMdcPattern("%m : %X{key2}", "Hello : value2", true); } @Test - public void testMdcPattern4() throws Exception { + void testMdcPattern4() throws Exception { testMdcPattern("%m : %X{key3}", "Hello : ", true); } @Test - public void testMdcPattern5() throws Exception { + void testMdcPattern5() throws Exception { testMdcPattern("%m : %X{key1}, %X{key2}, %X{key3}", "Hello : value1, value2, ", true); } @Test - public void testPatternSelector() throws Exception { + void testPatternSelector() { final PatternMatch[] patterns = new PatternMatch[1]; patterns[0] = new PatternMatch("FLOW", "%d %-5p [%t]: ====== %C{1}.%M:%L %m ======%n"); final PatternSelector selector = MarkerPatternSelector.createSelector( @@ -295,7 +294,7 @@ public void testPatternSelector() throws Exception { } @Test - public void testRegex() throws Exception { + void testRegex() { final PatternLayout layout = PatternLayout.newBuilder() .withPattern(regexPattern) .withConfiguration(ctx.getConfiguration()) @@ -311,7 +310,7 @@ public void testRegex() throws Exception { } @Test - public void testRegexEmptyMarker() throws Exception { + void testRegexEmptyMarker() { // replace "[]" with the empty string final PatternLayout layout = PatternLayout.newBuilder() .withPattern("[%logger]%replace{[%marker]}{\\[\\]}{} %msg") @@ -342,7 +341,7 @@ public void testRegexEmptyMarker() throws Exception { } @Test - public void testEqualsMarkerWithMessageSubstitution() throws Exception { + void testEqualsMarkerWithMessageSubstitution() { // replace "[]" with the empty string final PatternLayout layout = PatternLayout.newBuilder() .withPattern("[%logger]%equals{[%marker]}{[]}{[%msg]}") @@ -370,7 +369,7 @@ public void testEqualsMarkerWithMessageSubstitution() throws Exception { } @Test - public void testSpecialChars() throws Exception { + void testSpecialChars() { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("\\\\%level\\t%msg\\n\\t%logger\\r\\n\\f") .withConfiguration(ctx.getConfiguration()) @@ -392,7 +391,7 @@ public void testSpecialChars() throws Exception { } @Test - public void testUnixTime() throws Exception { + void testUnixTime() { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%d{UNIX} %m") .withConfiguration(ctx.getConfiguration()) @@ -418,7 +417,7 @@ public void testUnixTime() throws Exception { } @SuppressWarnings("unused") - private void testUnixTime(final String pattern) throws Exception { + private void testUnixTime(final String pattern) { final PatternLayout layout = PatternLayout.newBuilder() .withPattern(pattern + " %m") .withConfiguration(ctx.getConfiguration()) @@ -444,7 +443,7 @@ private void testUnixTime(final String pattern) throws Exception { } @Test - public void testUnixTimeMillis() throws Exception { + void testUnixTimeMillis() { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%d{UNIX_MILLIS} %m") .withConfiguration(ctx.getConfiguration()) @@ -470,7 +469,7 @@ public void testUnixTimeMillis() throws Exception { } @Test - public void testUsePlatformDefaultIfNoCharset() throws Exception { + void testUsePlatformDefaultIfNoCharset() { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%m") .withConfiguration(ctx.getConfiguration()) @@ -479,7 +478,7 @@ public void testUsePlatformDefaultIfNoCharset() throws Exception { } @Test - public void testUseSpecifiedCharsetIfExists() throws Exception { + void testUseSpecifiedCharsetIfExists() { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%m") .withConfiguration(ctx.getConfiguration()) @@ -489,7 +488,7 @@ public void testUseSpecifiedCharsetIfExists() throws Exception { } @Test - public void testLoggerNameTruncationByRetainingPartsFromEnd() throws Exception { + void testLoggerNameTruncationByRetainingPartsFromEnd() { { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%c{1} %m") @@ -544,7 +543,7 @@ public void testLoggerNameTruncationByRetainingPartsFromEnd() throws Exception { } @Test - public void testCallersFqcnTruncationByRetainingPartsFromEnd() throws Exception { + void testCallersFqcnTruncationByRetainingPartsFromEnd() { { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%C{1} %m") @@ -637,7 +636,7 @@ public void testCallersFqcnTruncationByRetainingPartsFromEnd() throws Exception } @Test - public void testLoggerNameTruncationByDroppingPartsFromFront() throws Exception { + void testLoggerNameTruncationByDroppingPartsFromFront() { { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%c{-1} %m") @@ -710,7 +709,7 @@ public void testLoggerNameTruncationByDroppingPartsFromFront() throws Exception } @Test - public void testCallersFqcnTruncationByDroppingPartsFromFront() throws Exception { + void testCallersFqcnTruncationByDroppingPartsFromFront() { { final PatternLayout layout = PatternLayout.newBuilder() .withPattern("%C{-1} %m") diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternSelectorTest.java index 9670b70183a..0bfb157f835 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternSelectorTest.java @@ -27,7 +27,7 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.junit.jupiter.api.Test; -public class PatternSelectorTest { +class PatternSelectorTest { public static class FauxLogger { public String formatEvent(final LogEvent event, final Layout layout) { @@ -38,7 +38,7 @@ public String formatEvent(final LogEvent event, final Layout layout) { LoggerContext ctx = LoggerContext.getContext(); @Test - public void testMarkerPatternSelector() throws Exception { + void testMarkerPatternSelector() { final PatternMatch[] patterns = new PatternMatch[1]; patterns[0] = new PatternMatch("FLOW", "%d %-5p [%t]: ====== %C{1}.%M:%L %m ======%n"); final PatternSelector selector = MarkerPatternSelector.createSelector( @@ -71,7 +71,7 @@ public void testMarkerPatternSelector() throws Exception { } @Test - public void testLevelPatternSelector() throws Exception { + void testLevelPatternSelector() { final PatternMatch[] patterns = new PatternMatch[1]; patterns[0] = new PatternMatch("TRACE", "%d %-5p [%t]: ====== %C{1}.%M:%L %m ======%n"); final PatternSelector selector = diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Rfc5424LayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Rfc5424LayoutTest.java index 944ef9f171f..87157ec68bf 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Rfc5424LayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/Rfc5424LayoutTest.java @@ -60,7 +60,7 @@ import org.junit.jupiter.params.provider.ValueSource; @UsingAnyThreadContext -public class Rfc5424LayoutTest { +class Rfc5424LayoutTest { LoggerContext ctx = LoggerContext.getContext(); Logger root = ctx.getRootLogger(); @@ -92,7 +92,7 @@ public class Rfc5424LayoutTest { static ConfigurationFactory cf = new BasicConfigurationFactory(); @BeforeAll - public static void setupClass() { + static void setupClass() { StatusLogger.getLogger().setLevel(Level.OFF); ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); @@ -100,7 +100,7 @@ public static void setupClass() { } @AfterAll - public static void cleanupClass() { + static void cleanupClass() { ConfigurationFactory.removeConfigurationFactory(cf); } @@ -108,7 +108,7 @@ public static void cleanupClass() { * Test case for MDC conversion pattern. */ @Test - public void testLayout() throws Exception { + void testLayout() { for (final Appender appender : root.getAppenders().values()) { root.removeAppender(appender); } @@ -200,7 +200,7 @@ public void testLayout() throws Exception { * Test case for MDC conversion pattern. */ @Test - public void testCollection() throws Exception { + void testCollection() { for (final Appender appender : root.getAppenders().values()) { root.removeAppender(appender); } @@ -290,7 +290,7 @@ public void testCollection() throws Exception { * Test case for escaping newlines and other SD PARAM-NAME special characters. */ @Test - public void testEscape() throws Exception { + void testEscape() { for (final Appender appender : root.getAppenders().values()) { root.removeAppender(appender); } @@ -371,7 +371,7 @@ public void testEscape() throws Exception { * Test case for MDC exception conversion pattern. */ @Test - public void testException() throws Exception { + void testException() { for (final Appender appender : root.getAppenders().values()) { root.removeAppender(appender); } @@ -426,7 +426,7 @@ public void testException() throws Exception { * Test case for MDC logger field inclusion. */ @Test - public void testMDCLoggerFields() throws Exception { + void testMDCLoggerFields() { for (final Appender appender : root.getAppenders().values()) { root.removeAppender(appender); } @@ -471,7 +471,7 @@ public void testMDCLoggerFields() throws Exception { try { final List list = appender.getMessages(); - assertTrue(list.size() > 0, "Not enough list entries"); + assertTrue(!list.isEmpty(), "Not enough list entries"); assertTrue(list.get(0).contains("Rfc5424LayoutTest.testMDCLoggerFields"), "No class/method"); appender.clear(); @@ -482,7 +482,7 @@ public void testMDCLoggerFields() throws Exception { } @Test - public void testLoggerFields() { + void testLoggerFields() { final String[] fields = new String[] { "[BAZ@32473 baz=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]", "[RequestContext@3692 bar=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]", @@ -535,7 +535,7 @@ public void testLoggerFields() { try { final List list = appender.getMessages(); - assertTrue(list.size() > 0, "Not enough list entries"); + assertTrue(!list.isEmpty(), "Not enough list entries"); final String message = list.get(0); assertTrue(message.contains("Rfc5424LayoutTest.testLoggerFields"), "No class/method"); for (final String value : expectedToContain) { @@ -549,7 +549,7 @@ public void testLoggerFields() { } @Test - public void testDiscardEmptyLoggerFields() { + void testDiscardEmptyLoggerFields() { final String mdcId = "RequestContext"; for (final Appender appender : root.getAppenders().values()) { @@ -602,7 +602,7 @@ public void testDiscardEmptyLoggerFields() { try { final List list = appender.getMessages(); - assertTrue(list.size() > 0, "Not enough list entries"); + assertTrue(!list.isEmpty(), "Not enough list entries"); final String message = list.get(0); assertFalse(message.contains("SD-ID"), "SD-ID should have been discarded"); assertTrue(message.contains("BAZ"), "BAZ should have been included"); @@ -615,7 +615,7 @@ public void testDiscardEmptyLoggerFields() { } @Test - public void testSubstituteStructuredData() { + void testSubstituteStructuredData() { final String mdcId = "RequestContext"; final String expectedToContain = String.format("ATM %s MSG-ID - Message", PROCESSID); @@ -653,7 +653,7 @@ public void testSubstituteStructuredData() { try { final List list = appender.getMessages(); - assertTrue(list.size() > 0, "Not enough list entries"); + assertTrue(!list.isEmpty(), "Not enough list entries"); final String message = list.get(0); assertTrue(message.contains(expectedToContain), "Not the expected message received"); appender.clear(); @@ -664,7 +664,7 @@ public void testSubstituteStructuredData() { } @Test - public void testParameterizedMessage() { + void testParameterizedMessage() { for (final Appender appender : root.getAppenders().values()) { root.removeAppender(appender); } @@ -698,7 +698,7 @@ public void testParameterizedMessage() { root.info("Hello {}", "World"); try { final List list = appender.getMessages(); - assertTrue(list.size() > 0, "Not enough list entries"); + assertTrue(!list.isEmpty(), "Not enough list entries"); final String message = list.get(0); assertTrue( message.contains("Hello World"), "Incorrect message. Expected - Hello World, Actual - " + message); @@ -734,7 +734,7 @@ void testLayoutBuilder() { root.info("Hello {}", "World"); try { final List list = appender.getMessages(); - assertTrue(list.size() > 0, "Not enough list entries"); + assertTrue(!list.isEmpty(), "Not enough list entries"); final String message = list.get(0); assertTrue( message.contains("Hello World"), "Incorrect message. Expected - Hello World, Actual - " + message); @@ -745,7 +745,7 @@ void testLayoutBuilder() { } @Test - public void testLayoutBuilderDefaultValues() { + void testLayoutBuilderDefaultValues() { final Rfc5424Layout layout = new Rfc5424Layout.Rfc5424LayoutBuilder().build(); checkDefaultValues(layout); @@ -763,7 +763,7 @@ private void checkDefaultValues(final Rfc5424Layout layout) { assertNotNull(layout); assertEquals(Facility.LOCAL0, layout.getFacility()); assertEquals(String.valueOf(Rfc5424Layout.DEFAULT_ENTERPRISE_NUMBER), layout.getEnterpriseNumber()); - assertEquals(true, layout.isIncludeMdc()); + assertTrue(layout.isIncludeMdc()); assertEquals(Rfc5424Layout.DEFAULT_MDCID, layout.getMdcId()); assertEquals(Rfc5424Layout.DEFAULT_ID, layout.getDefaultId()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SerializedLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SerializedLayoutTest.java index 7f1fb2e849b..de18512f1dd 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SerializedLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SerializedLayoutTest.java @@ -84,7 +84,7 @@ public static void cleanupClass() { * Test case for MDC conversion pattern. */ @Test - public void testLayout() throws Exception { + public void testLayout() { final Map appenders = root.getAppenders(); for (final Appender appender : appenders.values()) { root.removeAppender(appender); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/StringBuilderEncoderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/StringBuilderEncoderTest.java index 45e82cfd468..6045f2a49d6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/StringBuilderEncoderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/StringBuilderEncoderTest.java @@ -26,10 +26,10 @@ /** * Tests the {@code TextEncoderHelper} class. */ -public class StringBuilderEncoderTest { +class StringBuilderEncoderTest { @Test - public void testEncodeText_TextFitCharBuff_BytesFitByteBuff() throws Exception { + void testEncodeText_TextFitCharBuff_BytesFitByteBuff() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 16, 8 * 1024); final StringBuilder text = createText(15); final SpyByteBufferDestination destination = new SpyByteBufferDestination(17, 17); @@ -44,7 +44,7 @@ public void testEncodeText_TextFitCharBuff_BytesFitByteBuff() throws Exception { } @Test - public void testEncodeText_TextFitCharBuff_BytesDontFitByteBuff() throws Exception { + void testEncodeText_TextFitCharBuff_BytesDontFitByteBuff() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 16, 8 * 1024); final StringBuilder text = createText(15); final SpyByteBufferDestination destination = new SpyByteBufferDestination(14, 15); @@ -68,7 +68,7 @@ public void testEncodeText_TextFitCharBuff_BytesDontFitByteBuff() throws Excepti } @Test - public void testEncodeText_TextFitCharBuff_BytesDontFitByteBuff_MultiplePasses() throws Exception { + void testEncodeText_TextFitCharBuff_BytesDontFitByteBuff_MultiplePasses() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 16, 8 * 1024); final StringBuilder text = createText(15); final SpyByteBufferDestination destination = new SpyByteBufferDestination(4, 20); @@ -102,7 +102,7 @@ public void testEncodeText_TextFitCharBuff_BytesDontFitByteBuff_MultiplePasses() } @Test - public void testEncodeText_TextDoesntFitCharBuff_BytesFitByteBuff() throws Exception { + void testEncodeText_TextDoesntFitCharBuff_BytesFitByteBuff() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 4, 8 * 1024); final StringBuilder text = createText(15); final SpyByteBufferDestination destination = new SpyByteBufferDestination(17, 17); @@ -117,7 +117,7 @@ public void testEncodeText_TextDoesntFitCharBuff_BytesFitByteBuff() throws Excep } @Test - public void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_BytesFitByteBuff() throws Exception { + void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_BytesFitByteBuff() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 4, 8 * 1024); final StringBuilder text = new StringBuilder( // 日本語テスト文章 "\u65e5\u672c\u8a9e\u30c6\u30b9\u30c8\u6587\u7ae0"); @@ -134,7 +134,7 @@ public void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_BytesFitByteBuff() } @Test - public void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_BytesFitByteBuff() throws Exception { + void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_BytesFitByteBuff() { final Charset SHIFT_JIS = Charset.forName("Shift_JIS"); final StringBuilderEncoder helper = new StringBuilderEncoder(SHIFT_JIS, 4, 8 * 1024); final StringBuilder text = new StringBuilder( // 日本語テスト文章 @@ -152,7 +152,7 @@ public void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_BytesFitByteBuf } @Test - public void testEncodeText_TextDoesntFitCharBuff_BytesDontFitByteBuff() throws Exception { + void testEncodeText_TextDoesntFitCharBuff_BytesDontFitByteBuff() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 4, 8 * 1024); final StringBuilder text = createText(15); final SpyByteBufferDestination destination = new SpyByteBufferDestination(3, 17); @@ -170,7 +170,7 @@ public void testEncodeText_TextDoesntFitCharBuff_BytesDontFitByteBuff() throws E } @Test - public void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_BytesDontFitByteBuff() throws Exception { + void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_BytesDontFitByteBuff() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 4, 8 * 1024); final StringBuilder text = new StringBuilder( // 日本語テスト文章 "\u65e5\u672c\u8a9e\u30c6\u30b9\u30c8\u6587\u7ae0"); @@ -187,8 +187,7 @@ public void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_BytesDontFitByteBuf } @Test - public void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_DoesntFitTempByteBuff_BytesDontFitDestinationByteBuff() - throws Exception { + void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_DoesntFitTempByteBuff_BytesDontFitDestinationByteBuff() { final StringBuilderEncoder helper = new StringBuilderEncoder(StandardCharsets.UTF_8, 4, 5); final StringBuilder text = new StringBuilder( // 日本語テスト文章日本語テスト文章 "\u65e5\u672c\u8a9e\u30c6\u30b9\u30c8\u6587\u7ae0\u65e5\u672c\u8a9e\u30c6\u30b9\u30c8\u6587\u7ae0"); @@ -205,7 +204,7 @@ public void testEncodeText_JapaneseTextUtf8DoesntFitCharBuff_DoesntFitTempByteBu } @Test - public void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_BytesDontFitByteBuff() throws Exception { + void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_BytesDontFitByteBuff() { final Charset SHIFT_JIS = Charset.forName("Shift_JIS"); final StringBuilderEncoder helper = new StringBuilderEncoder(SHIFT_JIS, 4, 8 * 1024); final StringBuilder text = new StringBuilder( // 日本語テスト文章 @@ -222,9 +221,7 @@ public void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_BytesDontFitByt } @Test - public void - testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_DoesntFitTempByteBuff_BytesDontFitDestinationByteBuff() - throws Exception { + void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_DoesntFitTempByteBuff_BytesDontFitDestinationByteBuff() { final Charset SHIFT_JIS = Charset.forName("Shift_JIS"); final StringBuilderEncoder helper = new StringBuilderEncoder(SHIFT_JIS, 4, 5); final StringBuilder text = new StringBuilder( // 日本語テスト文章日本語テスト文章 @@ -241,7 +238,7 @@ public void testEncodeText_JapaneseTextShiftJisDoesntFitCharBuff_BytesDontFitByt } @Test - public void testCopyCopiesAllDataIfSuffientRemainingSpace() throws Exception { + void testCopyCopiesAllDataIfSuffientRemainingSpace() { final CharBuffer buff = CharBuffer.wrap(new char[16]); final StringBuilder text = createText(15); final int length = TextEncoderHelper.copy(text, 0, buff); @@ -253,7 +250,7 @@ public void testCopyCopiesAllDataIfSuffientRemainingSpace() throws Exception { } @Test - public void testCopyUpToRemainingSpace() throws Exception { + void testCopyUpToRemainingSpace() { final CharBuffer buff = CharBuffer.wrap(new char[3]); final StringBuilder text = createText(15); final int length = TextEncoderHelper.copy(text, 0, buff); @@ -266,7 +263,7 @@ public void testCopyUpToRemainingSpace() throws Exception { } @Test - public void testCopyDoesNotWriteBeyondStringText() throws Exception { + void testCopyDoesNotWriteBeyondStringText() { final CharBuffer buff = CharBuffer.wrap(new char[5]); assertEquals(0, buff.position(), "initial buffer position"); final StringBuilder text = createText(2); @@ -282,7 +279,7 @@ public void testCopyDoesNotWriteBeyondStringText() throws Exception { } @Test - public void testCopyStartsAtBufferPosition() throws Exception { + void testCopyStartsAtBufferPosition() { final CharBuffer buff = CharBuffer.wrap(new char[10]); final int START_POSITION = 5; buff.position(START_POSITION); // set start position @@ -296,7 +293,7 @@ public void testCopyStartsAtBufferPosition() throws Exception { } @Test - public void testEncode_ALotWithoutErrors() throws Exception { + void testEncode_ALotWithoutErrors() { final StringBuilderEncoder helper = new StringBuilderEncoder(Charset.defaultCharset()); final StringBuilder text = new StringBuilder( "2016-04-13 21:07:47,487 DEBUG [org.apache.logging.log4j.perf.jmh.FileAppenderBenchmark.log4j2ParameterizedString-jmh-worker-1] FileAppenderBenchmark - This is a debug [2383178] message\r\n"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SyslogLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SyslogLayoutTest.java index 41705b0a3df..4ae6dd14b98 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SyslogLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/SyslogLayoutTest.java @@ -37,7 +37,7 @@ import org.junit.jupiter.api.Test; @UsingAnyThreadContext -public class SyslogLayoutTest { +class SyslogLayoutTest { LoggerContext ctx = LoggerContext.getContext(); Logger root = ctx.getRootLogger(); @@ -50,14 +50,14 @@ public class SyslogLayoutTest { static ConfigurationFactory cf = new BasicConfigurationFactory(); @BeforeAll - public static void setupClass() { + static void setupClass() { ConfigurationFactory.setConfigurationFactory(cf); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); } @AfterAll - public static void cleanupClass() { + static void cleanupClass() { ConfigurationFactory.removeConfigurationFactory(cf); } @@ -65,7 +65,7 @@ public static void cleanupClass() { * Test case for MDC conversion pattern. */ @Test - public void testLayout() throws Exception { + void testLayout() { for (final Appender appender : root.getAppenders().values()) { root.removeAppender(appender); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/XmlLayoutTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/XmlLayoutTest.java index 7831643f610..db755ae2bf6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/XmlLayoutTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/XmlLayoutTest.java @@ -237,7 +237,7 @@ public void testDefaultCharset() { * Test case for MDC conversion pattern. */ @Test - public void testLayout() throws Exception { + public void testLayout() { final Map appenders = this.rootLogger.getAppenders(); for (final Appender appender : appenders.values()) { this.rootLogger.removeAppender(appender); @@ -281,8 +281,8 @@ public void testLayout() throws Exception { final List list = appender.getMessages(); final String string = list.get(0); - assertTrue("Incorrect header: " + string, string.equals("")); - assertTrue("Incorrect footer", list.get(list.size() - 1).equals("
")); + assertEquals("Incorrect header: " + string, "", string); + assertEquals("Incorrect footer", "", list.get(list.size() - 1)); this.checkContains("loggerFqcn=\"" + AbstractLogger.class.getName() + "\"", list); this.checkContains("level=\"DEBUG\"", list); this.checkContains(">starting mdc pattern test", list); @@ -320,7 +320,7 @@ public void testLayoutLoggerName() { } @Test - public void testAdditionalFields() throws Exception { + public void testAdditionalFields() { final AbstractJacksonLayout layout = XmlLayout.newBuilder() .setLocationInfo(false) .setProperties(false) @@ -352,13 +352,13 @@ public void testExcludeStacktrace() throws Exception { } @Test - public void testStacktraceAsString() throws Exception { + public void testStacktraceAsString() { final String str = prepareXMLForStacktraceTests(true); assertTrue(str, str.contains("java.lang.NullPointerException")); } @Test - public void testStacktraceAsNonString() throws Exception { + public void testStacktraceAsNonString() { final String str = prepareXMLForStacktraceTests(false); assertTrue(str, str.contains(" list) { final String trimedLine = list.get(lineIndex).trim(); - assertTrue( - "Incorrect line index " + lineIndex + ": " + Strings.dquote(trimedLine), trimedLine.equals(expected)); + assertEquals(expected, trimedLine, "Incorrect line index " + lineIndex + ": " + Strings.dquote(trimedLine)); } private void checkContains(final String expected, final List list) { @@ -90,14 +88,14 @@ private void checkContains(final String expected, final List list) { return; } } - Assert.fail("Cannot find " + expected + " in " + list); + fail("Cannot find " + expected + " in " + list); } private void checkMapEntry(final String key, final String value, final boolean compact, final String str) { // "name":"value" // final String expected = String.format("- key: \"%s\"\n value: \"%s\"", key, value); final String expected = String.format("%s: \"%s\"", key, value); - assertTrue("Cannot find " + expected + " in " + str, str.contains(expected)); + assertTrue(str.contains(expected), "Cannot find " + expected + " in " + str); } private void checkProperty( @@ -105,18 +103,18 @@ private void checkProperty( final String propSep = this.toPropertySeparator(compact, isValue); // {"key":"MDC.B","value":"B_Value"} final String expected = String.format("%s%s\"%s\"", key, propSep, value); - assertTrue("Cannot find " + expected + " in " + str, str.contains(expected)); + assertTrue(str.contains(expected), "Cannot find " + expected + " in " + str); } private void checkPropertyName(final String name, final boolean compact, final String str, final boolean isValue) { final String propSep = this.toPropertySeparator(compact, isValue); - assertTrue(str, str.contains(name + propSep)); + assertTrue(str.contains(name + propSep), str); } private void checkPropertyNameAbsent( final String name, final boolean compact, final String str, final boolean isValue) { final String propSep = this.toPropertySeparator(compact, isValue); - assertFalse(str, str.contains(name + propSep)); + assertFalse(str.contains(name + propSep), str); } private void testAllFeatures( @@ -137,9 +135,9 @@ private void testAllFeatures( final String str = layout.toSerializable(expected); // System.out.println(str); // Just check for \n since \r might or might not be there. - assertEquals(str, !compact || eventEol, str.contains("\n")); - assertEquals(str, includeSource, str.contains("source")); - assertEquals(str, includeContext, str.contains("contextMap")); + assertEquals(!compact || eventEol, str.contains("\n"), str); + assertEquals(includeSource, str.contains("source"), str); + assertEquals(includeContext, str.contains("contextMap"), str); final Log4jLogEvent actual = new Log4jYamlObjectMapper(contextMapAslist, includeStacktrace, false) .readValue(str, Log4jLogEvent.class); LogEventFixtures.assertEqualLogEvents(expected, actual, includeSource, includeContext, includeStacktrace); @@ -194,19 +192,19 @@ private void testAllFeatures( } @Test - public void testContentType() { + void testContentType() { final AbstractJacksonLayout layout = YamlLayout.createDefaultLayout(); assertEquals("application/yaml; charset=UTF-8", layout.getContentType()); } @Test - public void testDefaultCharset() { + void testDefaultCharset() { final AbstractJacksonLayout layout = YamlLayout.createDefaultLayout(); assertEquals(StandardCharsets.UTF_8, layout.getCharset()); } @Test - public void testEscapeLayout() throws Exception { + void testEscapeLayout() { final Map appenders = this.rootLogger.getAppenders(); for (final Appender appender : appenders.values()) { this.rootLogger.removeAppender(appender); @@ -247,7 +245,7 @@ public void testEscapeLayout() throws Exception { * Test case for MDC conversion pattern. */ @Test - public void testLayout() throws Exception { + void testLayout() { final Map appenders = this.rootLogger.getAppenders(); for (final Appender appender : appenders.values()) { this.rootLogger.removeAppender(appender); @@ -292,7 +290,7 @@ public void testLayout() throws Exception { } @Test - public void testLayoutLoggerName() throws Exception { + void testLayoutLoggerName() throws Exception { final AbstractJacksonLayout layout = YamlLayout.newBuilder() .setLocationInfo(false) .setProperties(false) @@ -308,14 +306,14 @@ public void testLayoutLoggerName() throws Exception { .setTimeMillis(1) .build(); final String str = layout.toSerializable(expected); - assertTrue(str, str.contains("loggerName: \"a.B\"")); + assertTrue(str.contains("loggerName: \"a.B\""), str); final Log4jLogEvent actual = new Log4jYamlObjectMapper(false, true, false).readValue(str, Log4jLogEvent.class); assertEquals(expected.getLoggerName(), actual.getLoggerName()); assertEquals(expected, actual); } @Test - public void testAdditionalFields() throws Exception { + void testAdditionalFields() throws Exception { final AbstractJacksonLayout layout = YamlLayout.newBuilder() .setLocationInfo(false) .setProperties(false) @@ -343,30 +341,30 @@ private String getJSONChildNodeValueAsText(final JsonNode parentNode, final Stri } @Test - public void testLocationOffCompactOffMdcOff() throws Exception { + void testLocationOffCompactOffMdcOff() throws Exception { this.testAllFeatures(false, false, false, false, false, true); } @Test - public void testLocationOnCompactOffEventEolOffMdcOn() throws Exception { + void testLocationOnCompactOffEventEolOffMdcOn() throws Exception { this.testAllFeatures(true, false, false, true, false, true); } @Test - public void testExcludeStacktrace() throws Exception { + void testExcludeStacktrace() throws Exception { this.testAllFeatures(false, false, false, false, false, false); } @Test - public void testStacktraceAsString() throws Exception { + void testStacktraceAsString() { final String str = prepareYAMLForStacktraceTests(true); - assertTrue(str, str.contains("extendedStackTrace: \"java.lang.NullPointerException")); + assertTrue(str.contains("extendedStackTrace: \"java.lang.NullPointerException"), str); } @Test - public void testStacktraceAsNonString() throws Exception { + void testStacktraceAsNonString() { final String str = prepareYAMLForStacktraceTests(false); - assertTrue(str, str.contains("extendedStackTrace:\n - ")); + assertTrue(str.contains("extendedStackTrace:\n - "), str); } private String prepareYAMLForStacktraceTests(final boolean stacktraceAsString) { @@ -381,7 +379,7 @@ private String prepareYAMLForStacktraceTests(final boolean stacktraceAsString) { } @Test - public void testIncludeNullDelimiterTrue() throws Exception { + void testIncludeNullDelimiterTrue() { final AbstractJacksonLayout layout = YamlLayout.newBuilder().setIncludeNullDelimiter(true).build(); final String str = layout.toSerializable(LogEventFixtures.createLogEvent()); @@ -389,7 +387,7 @@ public void testIncludeNullDelimiterTrue() throws Exception { } @Test - public void testIncludeNullDelimiterFalse() throws Exception { + void testIncludeNullDelimiterFalse() { final AbstractJacksonLayout layout = YamlLayout.newBuilder().setIncludeNullDelimiter(false).build(); final String str = layout.toSerializable(LogEventFixtures.createLogEvent()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/CaseLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/CaseLookupTest.java index aeee3d34c4e..d12ff39a8b0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/CaseLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/CaseLookupTest.java @@ -21,10 +21,10 @@ import org.junit.jupiter.api.Test; -public class CaseLookupTest { +class CaseLookupTest { @Test - public void testLookup() { + void testLookup() { final String testStr = "JabberWocky"; final String lower = "jabberwocky"; final String upper = "JABBERWOCKY"; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ContextMapLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ContextMapLookupTest.java index 3ecb6b05118..d294f2fd27e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ContextMapLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ContextMapLookupTest.java @@ -75,7 +75,7 @@ public void testLookup() { * ContextMapLookup can be used in many other ways in a config file. */ @Test - public void testFileLog() throws Exception { + public void testFileLog() { final Logger logger = LogManager.getLogger(); logger.info("Hello from testFileLog!"); final File logFile = new File("target", this.getClass().getName() + ".testFileLog.log"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/DateLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/DateLookupTest.java index 7237b40140a..b971317b511 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/DateLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/DateLookupTest.java @@ -31,10 +31,10 @@ import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; -public class DateLookupTest { +class DateLookupTest { @Test - public void testCorrectEvent() { + void testCorrectEvent() { final LogEvent mockedEvent = mock(LogEvent.class); final Calendar cal = Calendar.getInstance(); cal.set(2011, Calendar.DECEMBER, 30, 10, 56, 35); @@ -45,7 +45,7 @@ public void testCorrectEvent() { } @Test - public void testValidKeyWithoutEvent() { + void testValidKeyWithoutEvent() { final String dateFormat = "MM/dd/yyyy"; final Calendar cal = Calendar.getInstance(); @@ -63,7 +63,7 @@ public void testValidKeyWithoutEvent() { @ParameterizedTest @NullSource @ValueSource(strings = {"bananas"}) - public void testInvalidKey(final String key) { + void testInvalidKey(final String key) { // For invalid keys without event, the current time in default format should be returned. // Checking this may depend on locale and exact time, and could become flaky. // Therefore we just check that the result isn't null and that (formatting) exceptions are caught. diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EnvironmentLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EnvironmentLookupTest.java index 699425d6c94..4f119566d0f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EnvironmentLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EnvironmentLookupTest.java @@ -21,10 +21,10 @@ import org.junit.jupiter.api.Test; -public class EnvironmentLookupTest { +class EnvironmentLookupTest { @Test - public void testLookup() { + void testLookup() { final StrLookup lookup = new EnvironmentLookup(); String value = lookup.lookup("PATH"); assertNotNull(value); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EventLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EventLookupTest.java index 1541553fa7d..8b85421ce7b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EventLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/EventLookupTest.java @@ -31,14 +31,14 @@ * * @since 2.4 */ -public class EventLookupTest { +class EventLookupTest { private static final String ABSENT_MARKER_NAME = "NONE"; private final String markerName = "EventLookupTest"; private final StrLookup strLookup = new EventLookup(); @Test - public void testLookupEventMarker() { + void testLookupEventMarker() { final Marker marker = MarkerManager.getMarker(markerName); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // @@ -52,7 +52,7 @@ public void testLookupEventMarker() { } @Test - public void testLookupEventMessage() { + void testLookupEventMessage() { final String msg = "Hello, world!"; final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // @@ -65,7 +65,7 @@ public void testLookupEventMessage() { } @Test - public void testLookupEventLevel() { + void testLookupEventLevel() { final String msg = "Hello, world!"; final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // @@ -78,7 +78,7 @@ public void testLookupEventLevel() { } @Test - public void testLookupEventTimestamp() { + void testLookupEventTimestamp() { final String msg = "Hello, world!"; final long now = System.currentTimeMillis(); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -93,7 +93,7 @@ public void testLookupEventTimestamp() { } @Test - public void testLookupEventLogger() { + void testLookupEventLogger() { final String msg = "Hello, world!"; final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // @@ -106,7 +106,7 @@ public void testLookupEventLogger() { } @Test - public void testLookupEventThreadName() { + void testLookupEventThreadName() { final String msg = "Hello, world!"; final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/InterpolatorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/InterpolatorTest.java index 38fcf77ee63..1301ac8a666 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/InterpolatorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/InterpolatorTest.java @@ -63,7 +63,7 @@ public class InterpolatorTest { @ClassRule public static final RuleChain RULES = RuleChain.outerRule(new ExternalResource() { @Override - protected void before() throws Throwable { + protected void before() { System.setProperty(TESTKEY, TESTVAL); System.setProperty(TESTKEY2, TESTVAL); System.setProperty("log4j2.enableJndiLookup", "true"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiDisabledLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiDisabledLookupTest.java index 80b707c736c..6827b0035c6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiDisabledLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiDisabledLookupTest.java @@ -18,17 +18,17 @@ import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * JndiDisabledLookupTest * * Verifies the Lookups are disabled without the log4j2.enableJndiLookup property set to true. */ -public class JndiDisabledLookupTest { +class JndiDisabledLookupTest { @Test - public void testLookup() { + void testLookup() { assertThrows(IllegalStateException.class, JndiLookup::new); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiExploit.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiExploit.java index 85987f7de54..ed34340c86e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiExploit.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiExploit.java @@ -29,8 +29,7 @@ public class JndiExploit implements ObjectFactory { @Override public Object getObjectInstance( - final Object obj, final Name name, final Context nameCtx, final Hashtable environment) - throws Exception { + final Object obj, final Name name, final Context nameCtx, final Hashtable environment) { fail("getObjectInstance must not be allowed"); return null; } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiLookupTest.java index ac5cee87936..b68fb2eb8ae 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiLookupTest.java @@ -71,7 +71,7 @@ public void testLookup() { } @Test - public void testNonStringLookup() throws Exception { + public void testNonStringLookup() { // LOG4J2-1310 final StrLookup lookup = new JndiLookup(); final String integralValue = lookup.lookup(TEST_INTEGRAL_NAME); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiRestrictedLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiRestrictedLookupTest.java index ae69a1dc5d8..9fc683d1aeb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiRestrictedLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiRestrictedLookupTest.java @@ -20,7 +20,6 @@ import java.io.Serializable; import javax.naming.Context; -import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; @@ -109,7 +108,7 @@ public void testBadSerializableLookup() throws Exception { } @Test - public void testDnsLookup() throws Exception { + public void testDnsLookup() { final StrLookup lookup = new JndiLookup(); final String result = lookup.lookup("dns:/" + DOMAIN); if (result != null) { @@ -124,7 +123,7 @@ public Fruit(final String f) { fruit = f; } - public Reference getReference() throws NamingException { + public Reference getReference() { return new Reference( Fruit.class.getName(), diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupTest.java index 5c822b9423c..38ef1f08154 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupTest.java @@ -35,7 +35,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jLookupTest { +class Log4jLookupTest { private static final File EXPECT = new File(System.getProperty("user.home"), "/a/b/c/d/e/log4j2.xml"); @@ -49,19 +49,19 @@ public class Log4jLookupTest { private ConfigurationSource configSrc; @BeforeEach - public void setup() { + void setup() { ContextAnchor.THREAD_CONTEXT.set(mockCtx); given(config.getConfigurationSource()).willReturn(configSrc); given(configSrc.getFile()).willReturn(EXPECT); } @AfterEach - public void cleanup() { + void cleanup() { ContextAnchor.THREAD_CONTEXT.set(null); } @Test - public void lookupConfigLocation() { + void lookupConfigLocation() { final StrLookup log4jLookup = new Log4jLookup(); ((ConfigurationAware) log4jLookup).setConfiguration(config); final String value = log4jLookup.lookup(KEY_CONFIG_LOCATION); @@ -69,7 +69,7 @@ public void lookupConfigLocation() { } @Test - public void lookupConfigParentLocation() { + void lookupConfigParentLocation() { final StrLookup log4jLookup = new Log4jLookup(); ((ConfigurationAware) log4jLookup).setConfiguration(config); final String value = log4jLookup.lookup(KEY_CONFIG_PARENT_LOCATION); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupWithSpacesTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupWithSpacesTest.java index 7f80bc89f8b..6a445ba08e8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupWithSpacesTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/Log4jLookupWithSpacesTest.java @@ -35,7 +35,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jLookupWithSpacesTest { +class Log4jLookupWithSpacesTest { private static final File EXPECT = new File(System.getProperty("user.home"), "/a a/b b/c c/d d/e e/log4j2 file.xml"); @@ -50,19 +50,19 @@ public class Log4jLookupWithSpacesTest { private ConfigurationSource configSrc; @BeforeEach - public void setup() { + void setup() { ContextAnchor.THREAD_CONTEXT.set(mockCtx); given(config.getConfigurationSource()).willReturn(configSrc); given(configSrc.getFile()).willReturn(EXPECT); } @AfterEach - public void cleanup() { + void cleanup() { ContextAnchor.THREAD_CONTEXT.set(null); } @Test - public void lookupConfigLocation_withSpaces() { + void lookupConfigLocation_withSpaces() { final StrLookup log4jLookup = new Log4jLookup(); ((ConfigurationAware) log4jLookup).setConfiguration(config); final String value = log4jLookup.lookup(KEY_CONFIG_LOCATION); @@ -72,7 +72,7 @@ public void lookupConfigLocation_withSpaces() { } @Test - public void lookupConfigParentLocation_withSpaces() { + void lookupConfigParentLocation_withSpaces() { final StrLookup log4jLookup = new Log4jLookup(); ((ConfigurationAware) log4jLookup).setConfiguration(config); final String value = log4jLookup.lookup(KEY_CONFIG_PARENT_LOCATION); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MainLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MainLookupTest.java index 7cc93300b5d..bde633be44d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MainLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MainLookupTest.java @@ -25,10 +25,10 @@ /** * Tests MainLookup. */ -public class MainLookupTest { +class MainLookupTest { @Test - public void testMainArgs() { + void testMainArgs() { MainMapLookup.setMainArguments("--file", "foo.txt", "--verbose", "-x", "bar"); final String str = "${key} ${main:-1} ${main:0} ${main:1} ${main:2} ${main:3} ${main:4} ${main:\\--file} ${main:foo.txt} ${main:\\--verbose} ${main:\\-x} ${main:bar} ${main:\\--quiet:-true}"; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MapLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MapLookupTest.java index d623690a756..2ad36d5aca9 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MapLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MapLookupTest.java @@ -29,17 +29,17 @@ /** * Tests {@link MapLookup}. */ -public class MapLookupTest { +class MapLookupTest { @Test - public void testEmptyMap() { + void testEmptyMap() { final MapLookup lookup = new MapLookup(new HashMap()); assertNull(lookup.lookup(null)); assertNull(lookup.lookup("X")); } @Test - public void testMap() { + void testMap() { final HashMap map = new HashMap<>(); map.put("A", "B"); final MapLookup lookup = new MapLookup(map); @@ -48,14 +48,14 @@ public void testMap() { } @Test - public void testNullMap() { + void testNullMap() { final MapLookup lookup = new MapLookup(); assertNull(lookup.lookup(null)); assertNull(lookup.lookup("X")); } @Test - public void testMainMap() { + void testMainMap() { MainMapLookup.setMainArguments("--file", "foo.txt"); final MapLookup lookup = MainMapLookup.MAIN_SINGLETON; assertNull(lookup.lookup(null)); @@ -67,7 +67,7 @@ public void testMainMap() { } @Test - public void testEventStringMapMessage() { + void testEventStringMapMessage() { final HashMap map = new HashMap<>(); map.put("A", "B"); final HashMap eventMap = new HashMap<>(); @@ -80,7 +80,7 @@ public void testEventStringMapMessage() { } @Test - public void testEventMapMessage() { + void testEventMapMessage() { final HashMap map = new HashMap<>(); map.put("A", "B"); final HashMap eventMap = new HashMap<>(); @@ -93,7 +93,7 @@ public void testEventMapMessage() { } @Test - public void testLookupMapMessageIsCheckedBeforeDefaultMap() { + void testLookupMapMessageIsCheckedBeforeDefaultMap() { final HashMap map = new HashMap<>(); map.put("A", "ADefault"); map.put("B", "BDefault"); @@ -107,7 +107,7 @@ public void testLookupMapMessageIsCheckedBeforeDefaultMap() { } @Test - public void testNullEvent() { + void testNullEvent() { final HashMap map = new HashMap<>(); map.put("A", "B"); final MapLookup lookup = new MapLookup(map); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupConfigTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupConfigTest.java index 2ca4cfb1715..9ceaab37597 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupConfigTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupConfigTest.java @@ -38,7 +38,7 @@ */ @LoggerContextSource("log4j-marker-lookup.yaml") @Tag("yaml") -public class MarkerLookupConfigTest { +class MarkerLookupConfigTest { public static final Marker PAYLOAD = MarkerManager.getMarker("PAYLOAD"); private static final String PAYLOAD_LOG = "Message in payload.log"; @@ -50,7 +50,7 @@ public class MarkerLookupConfigTest { private static final String SQL_LOG = "Message in sql.log"; @Test - public void test() throws IOException { + void test() throws IOException { final Logger logger = LogManager.getLogger(); logger.info(SQL, SQL_LOG); logger.info(PAYLOAD, PAYLOAD_LOG); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupTest.java index 71dd347d998..35d4c4cf34d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/MarkerLookupTest.java @@ -32,14 +32,14 @@ * * @since 2.4 */ -public class MarkerLookupTest { +class MarkerLookupTest { private static final String ABSENT_MARKER_NAME = "NONE"; private final String markerName = "MarkerLookupTest"; private final StrLookup strLookup = new MarkerLookup(); @Test - public void testLookupEventExistant() { + void testLookupEventExistant() { final Marker marker = MarkerManager.getMarker(markerName); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // @@ -53,7 +53,7 @@ public void testLookupEventExistant() { } @Test - public void testLookupEventNonExistant() { + void testLookupEventNonExistant() { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // .setLoggerFqcn("org.apache.logging.log4j.core.Logger") // @@ -65,7 +65,7 @@ public void testLookupEventNonExistant() { } @Test - public void testLookupEventNonExistantKey() { + void testLookupEventNonExistantKey() { final Marker marker = MarkerManager.getMarker(markerName); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(this.getClass().getName()) // @@ -79,20 +79,20 @@ public void testLookupEventNonExistantKey() { } @Test - public void testLookupEventNullNonExistant() { + void testLookupEventNullNonExistant() { final String value = strLookup.lookup(null, ABSENT_MARKER_NAME); assertNull(value); } @Test - public void testLookupExistant() { + void testLookupExistant() { final String value = strLookup.lookup(MarkerManager.getMarker(markerName).getName()); assertEquals(markerName, value); } @Test - public void testLookupNonExistant() { + void testLookupNonExistant() { final String value = strLookup.lookup(ABSENT_MARKER_NAME); assertNull(value); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/PropertiesLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/PropertiesLookupTest.java index 97bb5a60cfc..c12b30284a6 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/PropertiesLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/PropertiesLookupTest.java @@ -30,10 +30,10 @@ /** * Tests {@link PropertiesLookup}. */ -public class PropertiesLookupTest { +class PropertiesLookupTest { @Test - public void testLookupContextProperty() { + void testLookupContextProperty() { final StrLookup propertiesLookup = new PropertiesLookup(Property.EMPTY_ARRAY, Collections.singletonMap("A", "1")); assertEquals("1", propertiesLookup.lookup("A")); @@ -43,7 +43,7 @@ public void testLookupContextProperty() { } @Test - public void testLookupConfigProperty() { + void testLookupConfigProperty() { final StrLookup propertiesLookup = new PropertiesLookup(new Property[] {Property.createProperty("A", "1")}, Collections.emptyMap()); assertEquals("1", propertiesLookup.lookup("A")); @@ -53,7 +53,7 @@ public void testLookupConfigProperty() { } @Test - public void testConfigPropertiesPreferredOverContextProperties() { + void testConfigPropertiesPreferredOverContextProperties() { final StrLookup propertiesLookup = new PropertiesLookup( new Property[] {Property.createProperty("A", "1")}, Collections.singletonMap("A", "2")); assertEquals("1", propertiesLookup.lookup("A")); @@ -63,25 +63,25 @@ public void testConfigPropertiesPreferredOverContextProperties() { } @Test - public void testEvaluateResultsSupportRecursiveEvaluation() { + void testEvaluateResultsSupportRecursiveEvaluation() { final PropertiesLookup lookup = new PropertiesLookup(Collections.singletonMap("key", "value")); assertFalse(lookup.evaluate("key").isLookupEvaluationAllowedInValue()); } @Test - public void testEvaluateReturnsNullWhenKeyIsNotFound() { + void testEvaluateReturnsNullWhenKeyIsNotFound() { final PropertiesLookup lookup = new PropertiesLookup(Collections.emptyMap()); assertNull(lookup.evaluate("key")); } @Test - public void testEvaluateReturnsNullWhenKeyIsNull() { + void testEvaluateReturnsNullWhenKeyIsNull() { final PropertiesLookup lookup = new PropertiesLookup(Collections.emptyMap()); assertNull(lookup.evaluate(null)); } @Test - public void testContextPropertiesAreMutable() { + void testContextPropertiesAreMutable() { final Map contextProperties = new HashMap<>(); final PropertiesLookup lookup = new PropertiesLookup(Property.EMPTY_ARRAY, contextProperties); assertNull(lookup.evaluate("key")); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ResourceBundleLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ResourceBundleLookupTest.java index 65683af4391..b7c959296c8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ResourceBundleLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/ResourceBundleLookupTest.java @@ -21,29 +21,30 @@ import org.junit.jupiter.api.Test; -public class ResourceBundleLookupTest { +class ResourceBundleLookupTest { @Test - public void testLookup() { + void testLookup() { final StrLookup lookup = new ResourceBundleLookup(); lookup.lookup("org.apache.logging.log4j.core.lookup.resource-bundle_en:KeyA"); assertEquals("ValueA", lookup.lookup("org.apache.logging.log4j.core.lookup.resource-bundle:KeyA")); } @Test - public void testLookupWithLocale() { + void testLookupWithLocale() { final StrLookup lookup = new ResourceBundleLookup(); lookup.lookup("org.apache.logging.log4j.core.lookup.resource-bundle:KeyA"); assertEquals("ValueA", lookup.lookup("org.apache.logging.log4j.core.lookup.resource-bundle:KeyA")); } - public void testMissingKey() { + @Test + void testMissingKey() { final StrLookup lookup = new ResourceBundleLookup(); assertNull(lookup.lookup("org.apache.logging.log4j.core.lookup.resource-bundle:KeyUnkown")); } @Test - public void testBadFormatBundleOnly() { + void testBadFormatBundleOnly() { final StrLookup lookup = new ResourceBundleLookup(); assertNull(lookup.lookup("X")); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StrSubstitutorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StrSubstitutorTest.java index f080c7fc4c5..84b3b621e3c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StrSubstitutorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StrSubstitutorTest.java @@ -28,23 +28,23 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class StrSubstitutorTest { +class StrSubstitutorTest { private static final String TESTKEY = "TestKey"; private static final String TESTVAL = "TestValue"; @AfterAll - public static void after() { + static void after() { System.clearProperty(TESTKEY); } @BeforeAll - public static void before() { + static void before() { System.setProperty(TESTKEY, TESTVAL); } @Test - public void testJavaDocExample() { + void testJavaDocExample() { final Map valuesMap = new HashMap<>(); valuesMap.put("animal", "quick brown fox"); valuesMap.put("target", "lazy dog"); @@ -55,7 +55,7 @@ public void testJavaDocExample() { } @Test - public void testDelimiterExampleFromJavaDoc() { + void testDelimiterExampleFromJavaDoc() { final Map valuesMap = new HashMap<>(); valuesMap.put("animal", "quick brown fox"); valuesMap.put("target", "lazy dog"); @@ -66,7 +66,7 @@ public void testDelimiterExampleFromJavaDoc() { } @Test - public void testEscapedRecursionExampleFromJavaDoc() { + void testEscapedRecursionExampleFromJavaDoc() { final Map valuesMap = new HashMap<>(); valuesMap.put("name", "x"); final String templateString = "The variable $${${name}} must be used."; @@ -83,7 +83,7 @@ public void testEscapedRecursionExampleFromJavaDoc() { } @Test - public void testPrePostfixRecursionExampleFromJavaDoc() { + void testPrePostfixRecursionExampleFromJavaDoc() { final Map valuesMap = new HashMap<>(); valuesMap.put("name", "x"); final String templateString = "The variable ${$[name]} must be used."; @@ -93,7 +93,7 @@ public void testPrePostfixRecursionExampleFromJavaDoc() { } @Test - public void testRecursionExampleFromJavaDoc() { + void testRecursionExampleFromJavaDoc() { final Map valuesMap = new HashMap<>(); valuesMap.put("name", "x"); valuesMap.put("x", "3"); @@ -108,7 +108,7 @@ public void testRecursionExampleFromJavaDoc() { } @Test - public void testValueEscapeDelimiter() { + void testValueEscapeDelimiter() { final Map valuesMap = new HashMap<>(); // Example from MainMapLookup. Key contains ":-" valuesMap.put("main:--file", "path/file.txt"); @@ -139,7 +139,7 @@ public void testValueEscapeDelimiter() { } @Test - public void testDefault() { + void testDefault() { final Map map = new HashMap<>(); map.put(TESTKEY, TESTVAL); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -151,7 +151,7 @@ public void testDefault() { } @Test - public void testDefaultReferencesLookupValue() { + void testDefaultReferencesLookupValue() { final Map map = new HashMap<>(); map.put(TESTKEY, "${java:version}"); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -161,7 +161,7 @@ public void testDefaultReferencesLookupValue() { } @Test - public void testInfiniteSubstitutionOnString() { + void testInfiniteSubstitutionOnString() { final StrLookup lookup = new Interpolator(new NonRecursiveLookup(new HashMap<>())); final StrSubstitutor subst = new StrSubstitutor(lookup); final String infiniteSubstitution = "${${::-${::-$${::-j}}}}"; @@ -169,7 +169,7 @@ public void testInfiniteSubstitutionOnString() { } @Test - public void testInfiniteSubstitutionOnStringBuilder() { + void testInfiniteSubstitutionOnStringBuilder() { final StrLookup lookup = new Interpolator(new NonRecursiveLookup(new HashMap<>())); final StrSubstitutor subst = new StrSubstitutor(lookup); final String infiniteSubstitution = "${${::-${::-$${::-j}}}}"; @@ -177,7 +177,7 @@ public void testInfiniteSubstitutionOnStringBuilder() { } @Test - public void testLookup() { + void testLookup() { final Map map = new HashMap<>(); map.put(TESTKEY, TESTVAL); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -197,7 +197,7 @@ public void testLookup() { } @Test - public void testLookupsNestedWithoutRecursiveEvaluation() { + void testLookupsNestedWithoutRecursiveEvaluation() { final Map map = new HashMap<>(); map.put("first", "${java:version}"); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -206,7 +206,7 @@ public void testLookupsNestedWithoutRecursiveEvaluation() { } @Test - public void testLookupThrows() { + void testLookupThrows() { final StrSubstitutor subst = new StrSubstitutor(new Interpolator(new StrLookup() { @Override @@ -226,7 +226,7 @@ public String lookup(final String key) { } @Test - public void testNestedSelfReferenceWithRecursiveEvaluation() { + void testNestedSelfReferenceWithRecursiveEvaluation() { final Map map = new HashMap<>(); map.put("first", "${${ctx:first}}"); final StrLookup lookup = new Interpolator(new RecursiveLookup(map)); @@ -235,7 +235,7 @@ public void testNestedSelfReferenceWithRecursiveEvaluation() { } @Test - public void testNoRecursiveEvaluationWithDefault() { + void testNoRecursiveEvaluationWithDefault() { final Map map = new HashMap<>(); map.put("first", "${java:version}"); map.put("second", "${java:runtime}"); @@ -245,7 +245,7 @@ public void testNoRecursiveEvaluationWithDefault() { } @Test - public void testNoRecursiveEvaluationWithDepthOne() { + void testNoRecursiveEvaluationWithDepthOne() { final Map map = new HashMap<>(); map.put("first", "${java:version}"); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -254,7 +254,7 @@ public void testNoRecursiveEvaluationWithDepthOne() { } @Test - public void testRandomWithRecursiveDefault() { + void testRandomWithRecursiveDefault() { final Map map = new HashMap<>(); map.put("first", "${env:RANDOM:-${ctx:first}}"); final StrLookup lookup = new Interpolator(new RecursiveLookup(map)); @@ -263,7 +263,7 @@ public void testRandomWithRecursiveDefault() { } @Test - public void testRecursiveSubstitution() { + void testRecursiveSubstitution() { final Map map = new HashMap<>(); map.put("first", "${ctx:first}"); map.put("second", "secondValue"); @@ -273,7 +273,7 @@ public void testRecursiveSubstitution() { } @Test - public void testRecursiveWithDefault() { + void testRecursiveWithDefault() { final Map map = new HashMap<>(); map.put("first", "${ctx:first:-default}"); final StrLookup lookup = new Interpolator(new RecursiveLookup(map)); @@ -282,7 +282,7 @@ public void testRecursiveWithDefault() { } @Test - public void testRecursiveWithRecursiveDefault() { + void testRecursiveWithRecursiveDefault() { final Map map = new HashMap<>(); map.put("first", "${ctx:first:-${ctx:first}}"); final StrLookup lookup = new Interpolator(new RecursiveLookup(map)); @@ -291,7 +291,7 @@ public void testRecursiveWithRecursiveDefault() { } @Test - public void testReplaceProperties() { + void testReplaceProperties() { final Properties properties = new Properties(); properties.put("a", "A"); assertNull(StrSubstitutor.replace((String) null, properties)); @@ -301,7 +301,7 @@ public void testReplaceProperties() { } @Test - public void testTopLevelLookupsWithoutRecursiveEvaluation() { + void testTopLevelLookupsWithoutRecursiveEvaluation() { final Map map = new HashMap<>(); map.put("key", "VaLuE"); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -310,7 +310,7 @@ public void testTopLevelLookupsWithoutRecursiveEvaluation() { } @Test - public void testTopLevelLookupsWithoutRecursiveEvaluation_doubleLower() { + void testTopLevelLookupsWithoutRecursiveEvaluation_doubleLower() { final Map map = new HashMap<>(); map.put("key", "VaLuE"); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -319,7 +319,7 @@ public void testTopLevelLookupsWithoutRecursiveEvaluation_doubleLower() { } @Test - public void testTopLevelLookupsWithoutRecursiveEvaluationAndDefaultValueLookup() { + void testTopLevelLookupsWithoutRecursiveEvaluationAndDefaultValueLookup() { final Map map = new HashMap<>(); map.put("key2", "TWO"); final StrLookup lookup = new Interpolator(new NonRecursiveLookup(map)); @@ -328,7 +328,7 @@ public void testTopLevelLookupsWithoutRecursiveEvaluationAndDefaultValueLookup() } @Test - public void testNonRecursiveReferencesRecursive() { + void testNonRecursiveReferencesRecursive() { final StrLookup lookup = new StrLookup() { @Override public String lookup(final String key) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StructuredDataLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StructuredDataLookupTest.java index 987b7c4908a..aea694f6927 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StructuredDataLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/StructuredDataLookupTest.java @@ -30,17 +30,17 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class StructuredDataLookupTest { +class StructuredDataLookupTest { private StructuredDataLookup dataLookup; @BeforeEach - public void setUp() { + void setUp() { dataLookup = new StructuredDataLookup(); } @Test - public void testCorrectEvent() { + void testCorrectEvent() { final Message msg = new StructuredDataMessage("TestId", "This is a test", "Audit"); final LogEvent event = Log4jLogEvent.newBuilder().setLevel(Level.DEBUG).setMessage(msg).build(); @@ -54,7 +54,7 @@ public void testCorrectEvent() { } @Test - public void testNullLookup() { + void testNullLookup() { assertNull(dataLookup.lookup(null, null)); assertNull(dataLookup.lookup(null)); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/SystemPropertiesLookupTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/SystemPropertiesLookupTest.java index 9cacf24299a..4063f3558ae 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/SystemPropertiesLookupTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/SystemPropertiesLookupTest.java @@ -23,23 +23,23 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class SystemPropertiesLookupTest { +class SystemPropertiesLookupTest { private static final String TESTKEY = "TestKey"; private static final String TESTVAL = "TestValue"; @BeforeAll - public static void before() { + static void before() { System.setProperty(TESTKEY, TESTVAL); } @AfterAll - public static void after() { + static void after() { System.clearProperty(TESTKEY); } @Test - public void testLookup() { + void testLookup() { final StrLookup lookup = new SystemPropertiesLookup(); String value = lookup.lookup(TESTKEY); assertEquals(TESTVAL, value); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/message/ExtendedThreadInformationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/message/ExtendedThreadInformationTest.java index ea017446dbf..3dca41c498f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/message/ExtendedThreadInformationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/message/ExtendedThreadInformationTest.java @@ -24,9 +24,9 @@ /** * Tests that ThreadDumpMessage uses ExtendedThreadInformation when available. */ -public class ExtendedThreadInformationTest { +class ExtendedThreadInformationTest { @Test - public void testMessage() { + void testMessage() { final ThreadDumpMessage msg = new ThreadDumpMessage("Testing"); final String message = msg.getFormattedMessage(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/JndiManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/JndiManagerTest.java index 39b6aaa22a3..5a2660610f3 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/JndiManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/JndiManagerTest.java @@ -26,12 +26,12 @@ /** * Tests {@link JndiManager}. */ -public class JndiManagerTest { +class JndiManagerTest { private static final String TRUE = "true"; @Test - public void testIsJndiContextSelectorEnabled() { + void testIsJndiContextSelectorEnabled() { assertFalse(JndiManager.isJndiContextSelectorEnabled()); try { System.setProperty("log4j2.enableJndiContextSelector", TRUE); @@ -42,7 +42,7 @@ public void testIsJndiContextSelectorEnabled() { } @Test - public void testIsJndiEnabled() { + void testIsJndiEnabled() { assertFalse(JndiManager.isJndiEnabled()); try { System.setProperty("log4j2.enableJndiJms", TRUE); @@ -53,7 +53,7 @@ public void testIsJndiEnabled() { } @Test - public void testIsJndiJdbcEnabled() { + void testIsJndiJdbcEnabled() { assertFalse(JndiManager.isJndiJdbcEnabled()); try { System.setProperty("log4j2.enableJndiJdbc", TRUE); @@ -64,7 +64,7 @@ public void testIsJndiJdbcEnabled() { } @Test - public void testIsJndiJmsEnabled() { + void testIsJndiJmsEnabled() { assertFalse(JndiManager.isJndiJmsEnabled()); try { System.setProperty("log4j2.enableJndiJms", TRUE); @@ -75,12 +75,12 @@ public void testIsJndiJmsEnabled() { } @Test - public void testIsJndiLookupEnabled() { + void testIsJndiLookupEnabled() { assertFalse(JndiManager.isJndiLookupEnabled()); } @Test - public void testNoInstanceByDefault() { + void testNoInstanceByDefault() { assertThrows(IllegalStateException.class, () -> JndiManager.getDefaultManager()); assertThrows(IllegalStateException.class, () -> JndiManager.getDefaultManager(null)); assertThrows(IllegalStateException.class, () -> JndiManager.getDefaultManager("A")); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/PriorityTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/PriorityTest.java index dfcfd1e9c5e..d325f13fed7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/PriorityTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/PriorityTest.java @@ -21,10 +21,10 @@ import org.apache.logging.log4j.Level; import org.junit.jupiter.api.Test; -public class PriorityTest { +class PriorityTest { @Test - public void testP1() { + void testP1() { final int p = Priority.getPriority(Facility.AUTH, Level.INFO); assertEquals(38, p, "Expected priority value is 38, got " + p); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/SmtpManagerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/SmtpManagerTest.java index ae7cd9e55dc..c95e3aa8915 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/SmtpManagerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/SmtpManagerTest.java @@ -33,10 +33,10 @@ import org.apache.logging.log4j.message.ReusableSimpleMessage; import org.junit.jupiter.api.Test; -public class SmtpManagerTest { +class SmtpManagerTest { @Test - public void testCreateManagerName() { + void testCreateManagerName() { final String managerName = SmtpManager.createManagerName( "to", "cc", @@ -87,7 +87,7 @@ private void testAdd(final LogEvent event) { // LOG4J2-3172: make sure existing protections are not violated @Test - public void testAdd_WhereLog4jLogEventWithReusableMessage() { + void testAdd_WhereLog4jLogEventWithReusableMessage() { final LogEvent event = new Log4jLogEvent.Builder() .setMessage(getReusableMessage("test message")) .build(); @@ -96,14 +96,14 @@ public void testAdd_WhereLog4jLogEventWithReusableMessage() { // LOG4J2-3172: make sure existing protections are not violated @Test - public void testAdd_WhereMutableLogEvent() { + void testAdd_WhereMutableLogEvent() { final MutableLogEvent event = new MutableLogEvent(new StringBuilder("test message"), null); testAdd(event); } // LOG4J2-3172 @Test - public void testAdd_WhereRingBufferLogEvent() { + void testAdd_WhereRingBufferLogEvent() { final RingBufferLogEvent event = new RingBufferLogEvent(); event.setValues( null, diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/UrlConnectionFactoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/UrlConnectionFactoryTest.java index 265c538da88..6ba0ee9a918 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/UrlConnectionFactoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/UrlConnectionFactoryTest.java @@ -111,7 +111,7 @@ void testBadCredentials(WireMockRuntimeInfo info) throws Exception { @Test @SetTestProperty(key = "log4j2.configurationUsername", value = "testUser") @SetTestProperty(key = "log4j2.configurationPassword", value = "password") - public void withAuthentication(WireMockRuntimeInfo info) throws Exception { + void withAuthentication(WireMockRuntimeInfo info) throws Exception { WireMock wireMock = info.getWireMock(); // RFC 1123 format rounds to full seconds ZonedDateTime now = ZonedDateTime.now().truncatedTo(ChronoUnit.SECONDS); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/EnvironmentPasswordProviderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/EnvironmentPasswordProviderTest.java index c741549b417..1f7500345d2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/EnvironmentPasswordProviderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/EnvironmentPasswordProviderTest.java @@ -21,15 +21,15 @@ import org.junit.jupiter.api.Test; -public class EnvironmentPasswordProviderTest { +class EnvironmentPasswordProviderTest { @Test - public void testConstructorDisallowsNull() { + void testConstructorDisallowsNull() { assertThrows(NullPointerException.class, () -> new EnvironmentPasswordProvider(null)); } @Test - public void testGetPasswordReturnsEnvironmentVariableValue() { + void testGetPasswordReturnsEnvironmentVariableValue() { final String value = System.getenv("PATH"); if (value == null) { return; // we cannot test in this environment diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/FilePasswordProviderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/FilePasswordProviderTest.java index eca30bd4d80..c7d2571f667 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/FilePasswordProviderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/FilePasswordProviderTest.java @@ -25,10 +25,10 @@ import java.nio.file.Path; import org.junit.jupiter.api.Test; -public class FilePasswordProviderTest { +class FilePasswordProviderTest { @Test - public void testGetPassword() throws Exception { + void testGetPassword() throws Exception { final String PASSWORD = "myPass123"; final Path path = Files.createTempFile("testPass", ".txt"); Files.write(path, PASSWORD.getBytes(Charset.defaultCharset())); @@ -39,12 +39,12 @@ public void testGetPassword() throws Exception { } @Test - public void testConstructorDisallowsNull() throws Exception { + void testConstructorDisallowsNull() { assertThrows(NullPointerException.class, () -> new FilePasswordProvider(null)); } @Test - public void testConstructorFailsIfFileDoesNotExist() throws Exception { + void testConstructorFailsIfFileDoesNotExist() { assertThrows(NoSuchFileException.class, () -> new FilePasswordProvider("nosuchfile")); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/KeyStoreConfigurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/KeyStoreConfigurationTest.java index f7a22ac0ccc..1889d5b2aa0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/KeyStoreConfigurationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/KeyStoreConfigurationTest.java @@ -35,18 +35,18 @@ @UsingStatusListener // Suppresses `StatusLogger` output, unless there is a failure @SetSystemProperty(key = "sun.security.mscapi.keyStoreCompatibilityMode", value = "false") -public class KeyStoreConfigurationTest { +class KeyStoreConfigurationTest { @SuppressWarnings("deprecation") @Test - public void loadEmptyConfigurationDeprecated() { + void loadEmptyConfigurationDeprecated() { assertThrows( StoreConfigurationException.class, () -> new KeyStoreConfiguration(null, SslKeyStoreConstants.NULL_PWD, null, null)); } @Test - public void loadEmptyConfiguration() { + void loadEmptyConfiguration() { assertThrows( StoreConfigurationException.class, () -> new KeyStoreConfiguration( @@ -54,7 +54,7 @@ public void loadEmptyConfiguration() { } @Test - public void loadNotEmptyConfigurationDeprecated() throws StoreConfigurationException { + void loadNotEmptyConfigurationDeprecated() throws StoreConfigurationException { @SuppressWarnings("deprecation") final KeyStoreConfiguration ksc = new KeyStoreConfiguration( SslKeyStoreConstants.KEYSTORE_LOCATION, @@ -90,7 +90,7 @@ static Stream configurations() { @ParameterizedTest @MethodSource("configurations") - public void loadNotEmptyConfiguration( + void loadNotEmptyConfiguration( final String keystoreFile, final Supplier password, final String keystoreType) throws StoreConfigurationException { final KeyStoreConfiguration ksc = @@ -101,7 +101,7 @@ public void loadNotEmptyConfiguration( } @Test - public void returnTheSameKeyStoreAfterMultipleLoadsDeprecated() throws StoreConfigurationException { + void returnTheSameKeyStoreAfterMultipleLoadsDeprecated() throws StoreConfigurationException { @SuppressWarnings("deprecation") final KeyStoreConfiguration ksc = new KeyStoreConfiguration( SslKeyStoreConstants.KEYSTORE_LOCATION, @@ -114,7 +114,7 @@ public void returnTheSameKeyStoreAfterMultipleLoadsDeprecated() throws StoreConf } @Test - public void returnTheSameKeyStoreAfterMultipleLoads() throws StoreConfigurationException { + void returnTheSameKeyStoreAfterMultipleLoads() throws StoreConfigurationException { final KeyStoreConfiguration ksc = new KeyStoreConfiguration( SslKeyStoreConstants.KEYSTORE_LOCATION, new MemoryPasswordProvider(SslKeyStoreConstants.KEYSTORE_PWD()), @@ -127,7 +127,7 @@ public void returnTheSameKeyStoreAfterMultipleLoads() throws StoreConfigurationE @SuppressWarnings("deprecation") @Test - public void wrongPasswordDeprecated() { + void wrongPasswordDeprecated() { assertThrows( StoreConfigurationException.class, () -> new KeyStoreConfiguration(SslKeyStoreConstants.KEYSTORE_LOCATION, "wrongPassword!", null, null)); @@ -162,7 +162,7 @@ static Stream wrongConfigurations() { @ParameterizedTest @MethodSource("wrongConfigurations") - public void wrongPassword(final String keystoreFile, final Supplier password, final String keystoreType) { + void wrongPassword(final String keystoreFile, final Supplier password, final String keystoreType) { assertThrows( StoreConfigurationException.class, () -> new KeyStoreConfiguration( diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/MemoryPasswordProviderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/MemoryPasswordProviderTest.java index 948732d5405..068ddb275db 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/MemoryPasswordProviderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/MemoryPasswordProviderTest.java @@ -23,21 +23,21 @@ import java.util.Arrays; import org.junit.jupiter.api.Test; -public class MemoryPasswordProviderTest { +class MemoryPasswordProviderTest { @Test - public void testConstructorAllowsNull() { + void testConstructorAllowsNull() { assertNull(new MemoryPasswordProvider(null).getPassword()); } @Test - public void testConstructorDoesNotModifyOriginalParameterArray() { + void testConstructorDoesNotModifyOriginalParameterArray() { final char[] initial = "123".toCharArray(); new MemoryPasswordProvider(initial); assertArrayEquals("123".toCharArray(), initial); } @Test - public void testGetPasswordReturnsCopyOfConstructorArray() { + void testGetPasswordReturnsCopyOfConstructorArray() { final char[] initial = "123".toCharArray(); final MemoryPasswordProvider provider = new MemoryPasswordProvider(initial); final char[] actual = provider.getPassword(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/SslConfigurationFactoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/SslConfigurationFactoryTest.java index c413fd0ff58..308f7546ef0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/SslConfigurationFactoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/SslConfigurationFactoryTest.java @@ -30,8 +30,9 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -@UsingStatusListener // Suppresses `StatusLogger` output, unless there is a failure -public class SslConfigurationFactoryTest { +// Suppresses `StatusLogger` output, unless there is a failure +@UsingStatusListener +class SslConfigurationFactoryTest { private static final String TRUSTSTORE_LOCATION_PROP_NAME = "log4j2.trustStoreLocation"; @@ -56,7 +57,7 @@ private static void addTruststoreConfiguration(final Properties props) { } @Test - public void testStaticConfiguration() { + void testStaticConfiguration() { // Case 1: Empty configuration final Properties props = new Properties(); @@ -104,7 +105,7 @@ static Stream windowsKeystoreConfigs() { @EnabledOnOs(OS.WINDOWS) @ParameterizedTest @MethodSource("windowsKeystoreConfigs") - public void testPasswordLessStores(final String location, final String password) { + void testPasswordLessStores(final String location, final String password) { // Create the configuration final Properties props = new Properties(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java index 77f41f916b8..39aee7bf08d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationTest.java @@ -23,10 +23,10 @@ import org.junit.jupiter.api.Test; @Disabled -public class StoreConfigurationTest> { +class StoreConfigurationTest> { @Test - public void equalsWithNotNullValues() { + void equalsWithNotNullValues() { final String location = "/to/the/file.jks"; final PasswordProvider password = new MemoryPasswordProvider("changeit".toCharArray()); final StoreConfiguration a = new StoreConfiguration<>(location, password); @@ -37,7 +37,7 @@ public void equalsWithNotNullValues() { } @Test - public void notEqualsWithNullAndNotNullValues() { + void notEqualsWithNullAndNotNullValues() { final String location = "/to/the/file.jks"; final PasswordProvider password = new MemoryPasswordProvider("changeit".toCharArray()); final StoreConfiguration a = new StoreConfiguration<>(location, password); @@ -48,7 +48,7 @@ public void notEqualsWithNullAndNotNullValues() { } @Test - public void equalsWithNullValues() { + void equalsWithNullValues() { final StoreConfiguration a = new StoreConfiguration<>(null, new MemoryPasswordProvider(null)); final StoreConfiguration b = new StoreConfiguration<>(null, new MemoryPasswordProvider(null)); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/TrustStoreConfigurationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/TrustStoreConfigurationTest.java index e23be4d1f0c..72b605e22b4 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/TrustStoreConfigurationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/ssl/TrustStoreConfigurationTest.java @@ -24,18 +24,19 @@ import org.apache.logging.log4j.test.junit.UsingStatusListener; import org.junit.jupiter.api.Test; -@UsingStatusListener // Suppresses `StatusLogger` output, unless there is a failure -public class TrustStoreConfigurationTest { +// Suppresses `StatusLogger` output, unless there is a failure +@UsingStatusListener +class TrustStoreConfigurationTest { @SuppressWarnings("deprecation") @Test - public void loadEmptyConfigurationDeprecated() { + void loadEmptyConfigurationDeprecated() { assertThrows( StoreConfigurationException.class, () -> new TrustStoreConfiguration(null, SslKeyStoreConstants.NULL_PWD, null, null)); } @Test - public void loadEmptyConfiguration() { + void loadEmptyConfiguration() { assertThrows( StoreConfigurationException.class, () -> new TrustStoreConfiguration( @@ -43,7 +44,7 @@ public void loadEmptyConfiguration() { } @Test - public void loadConfigurationDeprecated() throws StoreConfigurationException { + void loadConfigurationDeprecated() throws StoreConfigurationException { @SuppressWarnings("deprecation") final TrustStoreConfiguration ksc = new TrustStoreConfiguration( SslKeyStoreConstants.TRUSTSTORE_LOCATION, SslKeyStoreConstants.TRUSTSTORE_PWD(), null, null); @@ -52,7 +53,7 @@ public void loadConfigurationDeprecated() throws StoreConfigurationException { } @Test - public void loadConfiguration() throws StoreConfigurationException { + void loadConfiguration() throws StoreConfigurationException { final TrustStoreConfiguration ksc = new TrustStoreConfiguration( SslKeyStoreConstants.TRUSTSTORE_LOCATION, new MemoryPasswordProvider(SslKeyStoreConstants.TRUSTSTORE_PWD()), @@ -63,7 +64,7 @@ public void loadConfiguration() throws StoreConfigurationException { } @Test - public void returnTheSameKeyStoreAfterMultipleLoadsDeprecated() throws StoreConfigurationException { + void returnTheSameKeyStoreAfterMultipleLoadsDeprecated() throws StoreConfigurationException { @SuppressWarnings("deprecation") final TrustStoreConfiguration ksc = new TrustStoreConfiguration( SslKeyStoreConstants.TRUSTSTORE_LOCATION, SslKeyStoreConstants.TRUSTSTORE_PWD(), null, null); @@ -73,7 +74,7 @@ public void returnTheSameKeyStoreAfterMultipleLoadsDeprecated() throws StoreConf } @Test - public void returnTheSameKeyStoreAfterMultipleLoads() throws StoreConfigurationException { + void returnTheSameKeyStoreAfterMultipleLoads() throws StoreConfigurationException { final TrustStoreConfiguration ksc = new TrustStoreConfiguration( SslKeyStoreConstants.TRUSTSTORE_LOCATION, new MemoryPasswordProvider(SslKeyStoreConstants.TRUSTSTORE_PWD()), @@ -86,7 +87,7 @@ public void returnTheSameKeyStoreAfterMultipleLoads() throws StoreConfigurationE @SuppressWarnings("deprecation") @Test - public void wrongPasswordDeprecated() { + void wrongPasswordDeprecated() { assertThrows( StoreConfigurationException.class, () -> new TrustStoreConfiguration( @@ -94,7 +95,7 @@ public void wrongPasswordDeprecated() { } @Test - public void wrongPassword() { + void wrongPassword() { assertThrows( StoreConfigurationException.class, () -> new TrustStoreConfiguration( diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/JsonLogEventParserTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/JsonLogEventParserTest.java index 405c15d4be5..8cc81481f4e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/JsonLogEventParserTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/JsonLogEventParserTest.java @@ -16,12 +16,14 @@ */ package org.apache.logging.log4j.core.parser; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.core.LogEvent; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class JsonLogEventParserTest extends LogEventParserTest { +class JsonLogEventParserTest extends LogEventParserTest { private JsonLogEventParser parser; @@ -71,55 +73,55 @@ public class JsonLogEventParserTest extends LogEventParserTest { + " }\n" + "}"; - @Before - public void setup() { + @BeforeEach + void setup() { parser = new JsonLogEventParser(); } @Test - public void testString() throws ParseException { + void testString() throws ParseException { final LogEvent logEvent = parser.parseFrom(JSON); assertLogEvent(logEvent); } - @Test(expected = ParseException.class) - public void testStringEmpty() throws ParseException { - parser.parseFrom(""); + @Test + void testStringEmpty() { + assertThrows(ParseException.class, () -> parser.parseFrom("")); } - @Test(expected = ParseException.class) - public void testStringInvalidJson() throws ParseException { - parser.parseFrom("foobar"); + @Test + void testStringInvalidJson() { + assertThrows(ParseException.class, () -> parser.parseFrom("foobar")); } - @Test(expected = ParseException.class) - public void testStringJsonArray() throws ParseException { - parser.parseFrom("[]"); + @Test + void testStringJsonArray() { + assertThrows(ParseException.class, () -> parser.parseFrom("[]")); } @Test - public void testEmptyObject() throws ParseException { + void testEmptyObject() throws ParseException { parser.parseFrom("{}"); } - @Test(expected = ParseException.class) - public void testStringWrongPropertyType() throws ParseException { - parser.parseFrom("{\"threadId\":\"foobar\"}"); + @Test + void testStringWrongPropertyType() { + assertThrows(ParseException.class, () -> parser.parseFrom("{\"threadId\":\"foobar\"}")); } @Test - public void testStringIgnoreInvalidProperty() throws ParseException { + void testStringIgnoreInvalidProperty() throws ParseException { parser.parseFrom("{\"foo\":\"bar\"}"); } @Test - public void testByteArray() throws ParseException { + void testByteArray() throws ParseException { final LogEvent logEvent = parser.parseFrom(JSON.getBytes(StandardCharsets.UTF_8)); assertLogEvent(logEvent); } @Test - public void testByteArrayOffsetLength() throws ParseException { + void testByteArrayOffsetLength() throws ParseException { final byte[] bytes = ("abc" + JSON + "def").getBytes(StandardCharsets.UTF_8); final LogEvent logEvent = parser.parseFrom(bytes, 3, bytes.length - 6); assertLogEvent(logEvent); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/LogEventParserTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/LogEventParserTest.java index cf3f17f51ce..f8f254f1d61 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/LogEventParserTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/LogEventParserTest.java @@ -19,8 +19,8 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; import java.util.Arrays; import org.apache.logging.log4j.Level; @@ -45,8 +45,8 @@ protected void assertLogEvent(final LogEvent logEvent) { assertThat(logEvent.getThrownProxy().getExtendedStackTrace()[0].getClassName(), equalTo("logtest.Main")); assertThat(logEvent.getLoggerFqcn(), equalTo("org.apache.logging.log4j.spi.AbstractLogger")); assertThat(logEvent.getContextStack().asList(), equalTo(Arrays.asList("one", "two"))); - assertThat((String) logEvent.getContextData().getValue("foo"), equalTo("FOO")); - assertThat((String) logEvent.getContextData().getValue("bar"), equalTo("BAR")); + assertThat(logEvent.getContextData().getValue("foo"), equalTo("FOO")); + assertThat(logEvent.getContextData().getValue("bar"), equalTo("BAR")); assertThat(logEvent.getSource().getClassName(), equalTo("logtest.Main")); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/XmlLogEventParserTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/XmlLogEventParserTest.java index 18525e2c9eb..0805ffa7684 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/XmlLogEventParserTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/XmlLogEventParserTest.java @@ -16,12 +16,14 @@ */ package org.apache.logging.log4j.core.parser; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.core.LogEvent; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class XmlLogEventParserTest extends LogEventParserTest { +class XmlLogEventParserTest extends LogEventParserTest { private XmlLogEventParser parser; @@ -72,55 +74,57 @@ public class XmlLogEventParserTest extends LogEventParserTest { + " \n" + ""; - @Before - public void setup() { + @BeforeEach + void setup() { parser = new XmlLogEventParser(); } @Test - public void testString() throws ParseException { + void testString() throws ParseException { final LogEvent logEvent = parser.parseFrom(XML); assertLogEvent(logEvent); } - @Test(expected = ParseException.class) - public void testStringEmpty() throws ParseException { - parser.parseFrom(""); + @Test + void testStringEmpty() { + assertThrows(ParseException.class, () -> parser.parseFrom("")); } - @Test(expected = ParseException.class) - public void testStringInvalidXml() throws ParseException { - parser.parseFrom("foobar"); + @Test + void testStringInvalidXml() { + assertThrows(ParseException.class, () -> parser.parseFrom("foobar")); } @Test - public void testEmptyObject() throws ParseException { + void testEmptyObject() throws ParseException { parser.parseFrom(""); } - @Test(expected = ParseException.class) - public void testStringWrongPropertyType() throws ParseException { - parser.parseFrom("foobar"); + @Test + void testStringWrongPropertyType() { + assertThrows( + ParseException.class, + () -> parser.parseFrom("foobar")); } @Test - public void testTimeMillisIgnored() throws ParseException { + void testTimeMillisIgnored() throws ParseException { parser.parseFrom("foobar"); } @Test - public void testStringIgnoreInvalidProperty() throws ParseException { + void testStringIgnoreInvalidProperty() throws ParseException { parser.parseFrom("bar"); } @Test - public void testByteArray() throws ParseException { + void testByteArray() throws ParseException { final LogEvent logEvent = parser.parseFrom(XML.getBytes(StandardCharsets.UTF_8)); assertLogEvent(logEvent); } @Test - public void testByteArrayOffsetLength() throws ParseException { + void testByteArrayOffsetLength() throws ParseException { final byte[] bytes = ("abc" + XML + "def").getBytes(StandardCharsets.UTF_8); final LogEvent logEvent = parser.parseFrom(bytes, 3, bytes.length - 6); assertLogEvent(logEvent); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/YamlLogEventParserTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/YamlLogEventParserTest.java index 3fef4d99c3d..9e719d1ce7c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/YamlLogEventParserTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/parser/YamlLogEventParserTest.java @@ -16,12 +16,14 @@ */ package org.apache.logging.log4j.core.parser; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.core.LogEvent; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class YamlLogEventParserTest extends LogEventParserTest { +class YamlLogEventParserTest extends LogEventParserTest { private YamlLogEventParser parser; @@ -67,55 +69,55 @@ public class YamlLogEventParserTest extends LogEventParserTest { + " file: \"Main.java\"\n" + " line: 29"; - @Before - public void setup() { + @BeforeEach + void setup() { parser = new YamlLogEventParser(); } @Test - public void testString() throws ParseException { + void testString() throws ParseException { final LogEvent logEvent = parser.parseFrom(YAML); assertLogEvent(logEvent); } - @Test(expected = ParseException.class) - public void testStringEmpty() throws ParseException { - parser.parseFrom(""); + @Test + void testStringEmpty() { + assertThrows(ParseException.class, () -> parser.parseFrom("")); } - @Test(expected = ParseException.class) - public void testStringInvalidYaml() throws ParseException { - parser.parseFrom("foobar"); + @Test + void testStringInvalidYaml() { + assertThrows(ParseException.class, () -> parser.parseFrom("foobar")); } @Test - public void testEmptyObject() throws ParseException { + void testEmptyObject() throws ParseException { parser.parseFrom("---\n"); } @Test - public void testTimeMillisIgnored() throws ParseException { + void testTimeMillisIgnored() throws ParseException { parser.parseFrom("---\ntimeMillis: \"foobar\"\n"); } - @Test(expected = ParseException.class) - public void testStringWrongPropertyType() throws ParseException { - parser.parseFrom("---\nthreadId: \"foobar\"\n"); + @Test + void testStringWrongPropertyType() { + assertThrows(ParseException.class, () -> parser.parseFrom("---\nthreadId: \"foobar\"\n")); } @Test - public void testStringIgnoreInvalidProperty() throws ParseException { + void testStringIgnoreInvalidProperty() throws ParseException { parser.parseFrom("---\nfoo: \"bar\"\n"); } @Test - public void testByteArray() throws ParseException { + void testByteArray() throws ParseException { final LogEvent logEvent = parser.parseFrom(YAML.getBytes(StandardCharsets.UTF_8)); assertLogEvent(logEvent); } @Test - public void testByteArrayOffsetLength() throws ParseException { + void testByteArrayOffsetLength() throws ParseException { final byte[] bytes = ("abc" + YAML + "def").getBytes(StandardCharsets.UTF_8); final LogEvent logEvent = parser.parseFrom(bytes, 3, bytes.length - 6); assertLogEvent(logEvent); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/CallerInformationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/CallerInformationTest.java index b43f364b806..635e4de01c1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/CallerInformationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/CallerInformationTest.java @@ -27,10 +27,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j2-calling-class.xml") -public class CallerInformationTest { +class CallerInformationTest { @Test - public void testClassLogger(final LoggerContext context, @Named("Class") final ListAppender app) { + void testClassLogger(final LoggerContext context, @Named("Class") final ListAppender app) { app.clear(); final Logger logger = context.getLogger("ClassLogger"); logger.info("Ignored message contents."); @@ -44,7 +44,7 @@ public void testClassLogger(final LoggerContext context, @Named("Class") final L } @Test - public void testMethodLogger(final LoggerContext context, @Named("Method") final ListAppender app) { + void testMethodLogger(final LoggerContext context, @Named("Method") final ListAppender app) { app.clear(); final Logger logger = context.getLogger("MethodLogger"); logger.info("More messages."); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DatePatternConverterTestBase.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DatePatternConverterTestBase.java index cdd279c6910..99bd9c706de 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DatePatternConverterTestBase.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DatePatternConverterTestBase.java @@ -80,17 +80,17 @@ private static Date date(final int year, final int month, final int date) { @Test void testThreadLocalsConstant() { - assertEquals(threadLocalsEnabled, Constants.ENABLE_THREADLOCALS); + assertEquals(Constants.ENABLE_THREADLOCALS, threadLocalsEnabled); } @Test - public void testFormatDateStringBuilderDefaultPattern() { + void testFormatDateStringBuilderDefaultPattern() { assertDatePattern(null, date(2001, 1, 1), "2001-02-01 14:15:16,123"); } @SuppressWarnings("deprecation") @Test - public void testFormatDateStringBuilderIso8601() { + void testFormatDateStringBuilderIso8601() { final DatePatternConverter converter = DatePatternConverter.newInstance(ISO8601_FORMAT_OPTIONS); final StringBuilder sb = new StringBuilder(); converter.format(date(2001, 1, 1), sb); @@ -100,18 +100,18 @@ public void testFormatDateStringBuilderIso8601() { } @Test - public void testFormatDateStringBuilderIso8601BasicWithPeriod() { + void testFormatDateStringBuilderIso8601BasicWithPeriod() { assertDatePattern("ISO8601_BASIC_PERIOD", date(2001, 1, 1), "20010201T141516.123"); } @Test - public void testFormatDateStringBuilderIso8601WithPeriod() { + void testFormatDateStringBuilderIso8601WithPeriod() { assertDatePattern("ISO8601_PERIOD", date(2001, 1, 1), "2001-02-01T14:15:16.123"); } @SuppressWarnings("deprecation") @Test - public void testFormatDateStringBuilderIso8601WithPeriodMicroseconds() { + void testFormatDateStringBuilderIso8601WithPeriodMicroseconds() { final String[] pattern = {"ISO8601_PERIOD_MICROS", "Z"}; final DatePatternConverter converter = DatePatternConverter.newInstance(pattern); final StringBuilder sb = new StringBuilder(); @@ -127,12 +127,12 @@ public void testFormatDateStringBuilderIso8601WithPeriodMicroseconds() { } @Test - public void testFormatDateStringBuilderOriginalPattern() { + void testFormatDateStringBuilderOriginalPattern() { assertDatePattern("yyyy/MM/dd HH-mm-ss.SSS", date(2001, 1, 1), "2001/02/01 14-15-16.123"); } @Test - public void testFormatLogEventStringBuilderDefaultPattern() { + void testFormatLogEventStringBuilderDefaultPattern() { final LogEvent event = new MyLogEvent(); final DatePatternConverter converter = DatePatternConverter.newInstance(null); final StringBuilder sb = new StringBuilder(); @@ -143,7 +143,7 @@ public void testFormatLogEventStringBuilderDefaultPattern() { } @Test - public void testFormatLogEventStringBuilderIso8601() { + void testFormatLogEventStringBuilderIso8601() { final LogEvent event = new MyLogEvent(); final DatePatternConverter converter = DatePatternConverter.newInstance(ISO8601_FORMAT_OPTIONS); final StringBuilder sb = new StringBuilder(); @@ -154,7 +154,7 @@ public void testFormatLogEventStringBuilderIso8601() { } @Test - public void testFormatAmericanPatterns() { + void testFormatAmericanPatterns() { final Date date = date(2011, 2, 11); assertDatePattern("US_MONTH_DAY_YEAR4_TIME", date, "11/03/2011 14:15:16.123"); assertDatePattern("US_MONTH_DAY_YEAR2_TIME", date, "11/03/11 14:15:16.123"); @@ -174,7 +174,7 @@ private static void assertDatePattern(final String format, final Date date, fina } @Test - public void testFormatLogEventStringBuilderIso8601TimezoneJST() { + void testFormatLogEventStringBuilderIso8601TimezoneJST() { final LogEvent event = new MyLogEvent(); final String[] optionsWithTimezone = {ISO8601, "JST"}; final DatePatternConverter converter = DatePatternConverter.newInstance(optionsWithTimezone); @@ -192,7 +192,7 @@ public void testFormatLogEventStringBuilderIso8601TimezoneJST() { } @Test - public void testFormatLogEventStringBuilderIso8601TimezoneOffsetHHCMM() { + void testFormatLogEventStringBuilderIso8601TimezoneOffsetHHCMM() { final LogEvent event = new MyLogEvent(); final String[] optionsWithTimezone = {ISO8601_OFFSET_DATE_TIME_HHCMM}; final DatePatternConverter converter = DatePatternConverter.newInstance(optionsWithTimezone); @@ -206,7 +206,7 @@ public void testFormatLogEventStringBuilderIso8601TimezoneOffsetHHCMM() { } @Test - public void testFormatLogEventStringBuilderIso8601TimezoneOffsetHHMM() { + void testFormatLogEventStringBuilderIso8601TimezoneOffsetHHMM() { final LogEvent event = new MyLogEvent(); final String[] optionsWithTimezone = {ISO8601_OFFSET_DATE_TIME_HHMM}; final DatePatternConverter converter = DatePatternConverter.newInstance(optionsWithTimezone); @@ -220,7 +220,7 @@ public void testFormatLogEventStringBuilderIso8601TimezoneOffsetHHMM() { } @Test - public void testFormatLogEventStringBuilderIso8601TimezoneUTC() { + void testFormatLogEventStringBuilderIso8601TimezoneUTC() { final LogEvent event = new MyLogEvent(); final DatePatternConverter converter = DatePatternConverter.newInstance(new String[] {"ISO8601", "UTC"}); final StringBuilder sb = new StringBuilder(); @@ -236,7 +236,7 @@ public void testFormatLogEventStringBuilderIso8601TimezoneUTC() { } @Test - public void testFormatLogEventStringBuilderIso8601TimezoneZ() { + void testFormatLogEventStringBuilderIso8601TimezoneZ() { final LogEvent event = new MyLogEvent(); final String[] optionsWithTimezone = {ISO8601, "Z"}; final DatePatternConverter converter = DatePatternConverter.newInstance(optionsWithTimezone); @@ -253,7 +253,7 @@ public void testFormatLogEventStringBuilderIso8601TimezoneZ() { } @Test - public void testFormatObjectStringBuilderDefaultPattern() { + void testFormatObjectStringBuilderDefaultPattern() { final DatePatternConverter converter = DatePatternConverter.newInstance(null); final StringBuilder sb = new StringBuilder(); converter.format("nondate", sb); @@ -263,7 +263,7 @@ public void testFormatObjectStringBuilderDefaultPattern() { } @Test - public void testFormatStringBuilderObjectArrayDefaultPattern() { + void testFormatStringBuilderObjectArrayDefaultPattern() { final DatePatternConverter converter = DatePatternConverter.newInstance(null); final StringBuilder sb = new StringBuilder(); converter.format(sb, date(2001, 1, 1), date(2002, 2, 2), date(2003, 3, 3)); @@ -273,7 +273,7 @@ public void testFormatStringBuilderObjectArrayDefaultPattern() { } @Test - public void testFormatStringBuilderObjectArrayIso8601() { + void testFormatStringBuilderObjectArrayIso8601() { final DatePatternConverter converter = DatePatternConverter.newInstance(ISO8601_FORMAT_OPTIONS); final StringBuilder sb = new StringBuilder(); converter.format(sb, date(2001, 1, 1), date(2002, 2, 2), date(2003, 3, 3)); @@ -283,49 +283,49 @@ public void testFormatStringBuilderObjectArrayIso8601() { } @Test - public void testGetPatternReturnsDefaultForEmptyOptionsArray() { + void testGetPatternReturnsDefaultForEmptyOptionsArray() { assertEquals( DEFAULT_PATTERN, DatePatternConverter.newInstance(Strings.EMPTY_ARRAY).getPattern()); } @Test - public void testGetPatternReturnsDefaultForInvalidPattern() { + void testGetPatternReturnsDefaultForInvalidPattern() { final String[] invalid = {"A single `V` is not allow by `DateTimeFormatter` and should cause an exception"}; assertEquals(DEFAULT_PATTERN, DatePatternConverter.newInstance(invalid).getPattern()); } @Test - public void testGetPatternReturnsDefaultForNullOptions() { + void testGetPatternReturnsDefaultForNullOptions() { assertEquals(DEFAULT_PATTERN, DatePatternConverter.newInstance(null).getPattern()); } @Test - public void testGetPatternReturnsDefaultForSingleNullElementOptionsArray() { + void testGetPatternReturnsDefaultForSingleNullElementOptionsArray() { assertEquals( DEFAULT_PATTERN, DatePatternConverter.newInstance(new String[1]).getPattern()); } @Test - public void testGetPatternReturnsDefaultForTwoNullElementsOptionsArray() { + void testGetPatternReturnsDefaultForTwoNullElementsOptionsArray() { assertEquals( DEFAULT_PATTERN, DatePatternConverter.newInstance(new String[2]).getPattern()); } @Test - public void testGetPatternReturnsNullForUnix() { + void testGetPatternReturnsNullForUnix() { final String[] options = {"UNIX"}; assertNull(DatePatternConverter.newInstance(options).getPattern()); } @Test - public void testGetPatternReturnsNullForUnixMillis() { + void testGetPatternReturnsNullForUnixMillis() { final String[] options = {"UNIX_MILLIS"}; assertNull(DatePatternConverter.newInstance(options).getPattern()); } @Test - public void testNewInstanceAllowsNullParameter() { + void testNewInstanceAllowsNullParameter() { DatePatternConverter.newInstance(null); // no errors } @@ -354,7 +354,7 @@ public void testNewInstanceAllowsNullParameter() { }; @Test - public void testPredefinedFormatWithoutTimezone() { + void testPredefinedFormatWithoutTimezone() { for (final String patternName : PATTERN_NAMES) { final String[] options = {patternName}; final DatePatternConverter converter = DatePatternConverter.newInstance(options); @@ -364,7 +364,7 @@ public void testPredefinedFormatWithoutTimezone() { } @Test - public void testPredefinedFormatWithTimezone() { + void testPredefinedFormatWithTimezone() { for (final String patternName : PATTERN_NAMES) { final String[] options = {patternName, "PST"}; // Pacific Standard Time=UTC-8:00 final DatePatternConverter converter = DatePatternConverter.newInstance(options); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DisableAnsiTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DisableAnsiTest.java index bec40c1206b..8cd93ccfb4b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DisableAnsiTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DisableAnsiTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j2-console-disableAnsi.xml") -public class DisableAnsiTest { +class DisableAnsiTest { private static final String EXPECTED = "ERROR LoggerTest o.a.l.l.c.p.DisableAnsiTest org.apache.logging.log4j.core.pattern.DisableAnsiTest" @@ -41,13 +41,13 @@ public class DisableAnsiTest { private ListAppender app; @BeforeEach - public void setUp(final LoggerContext context, @Named("List") final ListAppender app) { + void setUp(final LoggerContext context, @Named("List") final ListAppender app) { this.logger = context.getLogger("LoggerTest"); this.app = app.clear(); } @Test - public void testReplacement() { + void testReplacement() { logger.error(this.getClass().getName()); final List msgs = app.getMessages(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DynamicWordAbbreviatorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DynamicWordAbbreviatorTest.java index b38619ba992..75e7215deda 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DynamicWordAbbreviatorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/DynamicWordAbbreviatorTest.java @@ -16,7 +16,10 @@ */ package org.apache.logging.log4j.core.pattern; -import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -25,7 +28,7 @@ /** * Unit tests for the {@link DynamicWordAbbreviator} class. */ -class DynamicWordAbbreviatorTest extends Assertions { +class DynamicWordAbbreviatorTest { @Test void testNullAndEmptyInputs() { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EncodingPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EncodingPatternConverterTest.java index 873e36b0a0e..f8cd60d4d66 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EncodingPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EncodingPatternConverterTest.java @@ -30,10 +30,10 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.junit.jupiter.api.Test; -public class EncodingPatternConverterTest { +class EncodingPatternConverterTest { @Test - public void testReplacement() { + void testReplacement() { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(EncodingPatternConverterTest.class.getName()) // .setLevel(Level.DEBUG) // @@ -52,7 +52,7 @@ public void testReplacement() { } @Test - public void testJsonEscaping() { + void testJsonEscaping() { final LogEvent event = Log4jLogEvent.newBuilder() .setLoggerName(getClass().getName()) .setLevel(Level.DEBUG) @@ -74,7 +74,7 @@ public void testJsonEscaping() { } @Test - public void testCrlfEscaping() { + void testCrlfEscaping() { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(EncodingPatternConverterTest.class.getName()) // .setLevel(Level.DEBUG) // @@ -92,7 +92,7 @@ public void testCrlfEscaping() { } @Test - public void testXmlEscaping() { + void testXmlEscaping() { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(EncodingPatternConverterTest.class.getName()) // .setLevel(Level.DEBUG) // @@ -111,7 +111,7 @@ public void testXmlEscaping() { } @Test - public void testHandlesThrowable() { + void testHandlesThrowable() { final Configuration configuration = new DefaultConfiguration(); assertFalse(EncodingPatternConverter.newInstance(configuration, new String[] {"%msg", "XML"}) .handlesThrowable()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EndOfBatchPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EndOfBatchPatternConverterTest.java index d1670c5e533..835defe8eb8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EndOfBatchPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EndOfBatchPatternConverterTest.java @@ -22,10 +22,10 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.junit.jupiter.api.Test; -public class EndOfBatchPatternConverterTest { +class EndOfBatchPatternConverterTest { @Test - public void testConverterTrue() { + void testConverterTrue() { final LogEvent event = Log4jLogEvent.newBuilder().setEndOfBatch(true).build(); final StringBuilder sb = new StringBuilder(); final LogEventPatternConverter converter = EndOfBatchPatternConverter.newInstance(null); @@ -34,7 +34,7 @@ public void testConverterTrue() { } @Test - public void testConverterFalse() { + void testConverterFalse() { final LogEvent event = Log4jLogEvent.newBuilder().build(); final StringBuilder sb = new StringBuilder(); final LogEventPatternConverter converter = EndOfBatchPatternConverter.newInstance(null); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsIgnoreCaseReplacementConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsIgnoreCaseReplacementConverterTest.java index 7940c3db12d..969bda3b272 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsIgnoreCaseReplacementConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsIgnoreCaseReplacementConverterTest.java @@ -27,20 +27,20 @@ import org.apache.logging.log4j.util.Strings; import org.junit.jupiter.api.Test; -public class EqualsIgnoreCaseReplacementConverterTest { +class EqualsIgnoreCaseReplacementConverterTest { @Test - public void testMarkerReplacement() { + void testMarkerReplacement() { testReplacement("%marker", Strings.EMPTY); } @Test - public void testMarkerSimpleNameReplacement() { + void testMarkerSimpleNameReplacement() { testReplacement("%markerSimpleName", Strings.EMPTY); } @Test - public void testLoggerNameReplacement() { + void testLoggerNameReplacement() { testReplacement("%logger", "aaa[" + EqualsIgnoreCaseReplacementConverterTest.class.getName() + "]zzz"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsReplacementConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsReplacementConverterTest.java index ad41cfdcb80..09e4d777484 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsReplacementConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/EqualsReplacementConverterTest.java @@ -27,27 +27,27 @@ import org.apache.logging.log4j.util.Strings; import org.junit.jupiter.api.Test; -public class EqualsReplacementConverterTest { +class EqualsReplacementConverterTest { private static final String TEST_MESSAGE = "This is a test"; @Test - public void testMarkerReplacement() { + void testMarkerReplacement() { testReplacement("%marker", Strings.EMPTY); } @Test - public void testMarkerSimpleNameReplacement() { + void testMarkerSimpleNameReplacement() { testReplacement("%markerSimpleName", Strings.EMPTY); } @Test - public void testLoggerNameReplacement() { + void testLoggerNameReplacement() { testReplacement("%logger", "[" + EqualsReplacementConverterTest.class.getName() + "]"); } @Test - public void testMarkerReplacementWithMessage() { + void testMarkerReplacementWithMessage() { testReplacement(TEST_MESSAGE, new String[] {"[%marker]", "[]", "%msg"}); } @@ -72,23 +72,23 @@ private void testReplacement(final String expectedValue, final String[] options) } @Test - public void testParseSubstitutionWithPattern() { + void testParseSubstitutionWithPattern() { testParseSubstitution("%msg", TEST_MESSAGE); } @Test - public void testParseSubstitutionWithoutPattern() { + void testParseSubstitutionWithoutPattern() { final String substitution = "test"; testParseSubstitution(substitution, substitution); } @Test - public void testParseSubstitutionEmpty() { + void testParseSubstitutionEmpty() { testParseSubstitution("", ""); } @Test - public void testParseSubstitutionWithWhiteSpaces() { + void testParseSubstitutionWithWhiteSpaces() { testParseSubstitution(" ", " "); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/FormattingInfoTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/FormattingInfoTest.java index e9364f15a75..0fa6a99a7ae 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/FormattingInfoTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/FormattingInfoTest.java @@ -23,10 +23,10 @@ /** * Testing FormattingInfo. */ -public class FormattingInfoTest { +class FormattingInfoTest { @Test - public void testFormatTruncateFromBeginning() { + void testFormatTruncateFromBeginning() { final StringBuilder message = new StringBuilder("Hello, world"); final FormattingInfo formattingInfo = new FormattingInfo(false, 0, 5, true); @@ -36,7 +36,7 @@ public void testFormatTruncateFromBeginning() { } @Test - public void testFormatTruncateFromEnd() { + void testFormatTruncateFromEnd() { final StringBuilder message = new StringBuilder("Hello, world"); final FormattingInfo formattingInfo = new FormattingInfo(false, 0, 5, false); @@ -46,7 +46,7 @@ public void testFormatTruncateFromEnd() { } @Test - public void testFormatTruncateFromEndGivenFieldStart() { + void testFormatTruncateFromEndGivenFieldStart() { final StringBuilder message = new StringBuilder("2015-03-09 11:49:28,295; INFO org.apache.logging.log4j.PatternParserTest"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/HighlightConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/HighlightConverterTest.java index 7439bf5ff58..ca568695cf8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/HighlightConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/HighlightConverterTest.java @@ -37,10 +37,10 @@ /** * Tests the HighlightConverter. */ -public class HighlightConverterTest { +class HighlightConverterTest { @Test - public void testAnsiEmpty() { + void testAnsiEmpty() { final String[] options = { "", PatternParser.NO_CONSOLE_NO_ANSI + "=false, " + PatternParser.DISABLE_ANSI + "=false" }; @@ -58,7 +58,7 @@ public void testAnsiEmpty() { } @Test - public void testAnsiNonEmpty() { + void testAnsiNonEmpty() { final String[] options = { "%-5level: %msg", PatternParser.NO_CONSOLE_NO_ANSI + "=false, " + PatternParser.DISABLE_ANSI + "=false" }; @@ -76,7 +76,7 @@ public void testAnsiNonEmpty() { } @Test - public void testLevelNamesBad() { + void testLevelNamesBad() { final String colorName = "red"; final String[] options = { "%-5level: %msg", @@ -90,7 +90,7 @@ public void testLevelNamesBad() { } @Test - public void testLevelNamesGood() { + void testLevelNamesGood() { final String colorName = "red"; final String[] options = { "%-5level: %msg", @@ -115,7 +115,7 @@ static Stream colors() { @ParameterizedTest @MethodSource("colors") - public void testColors(final String colorName, final String escape) { + void testColors(final String colorName, final String escape) { final String[] options = { "%-5level: %msg", PatternParser.NO_CONSOLE_NO_ANSI + "=false, " + PatternParser.DISABLE_ANSI + "=false, " + "INFO=" @@ -131,7 +131,7 @@ public void testColors(final String colorName, final String escape) { } @Test - public void testLevelNamesUnknown() { + void testLevelNamesUnknown() { final String colorName = "blue"; final String[] options = { "%level", @@ -164,7 +164,7 @@ public void testLevelNamesUnknown() { } @Test - public void testLevelNamesNone() { + void testLevelNamesNone() { final String[] options = { "%-5level: %msg", PatternParser.NO_CONSOLE_NO_ANSI + "=false, " + PatternParser.DISABLE_ANSI + "=false" }; @@ -176,7 +176,7 @@ public void testLevelNamesNone() { @Test @UsingStatusListener - public void testNoAnsiEmpty(final ListStatusListener listener) { + void testNoAnsiEmpty(final ListStatusListener listener) { final String[] options = {"", PatternParser.DISABLE_ANSI + "=true"}; final HighlightConverter converter = HighlightConverter.newInstance(null, options); assertNotNull(converter); @@ -194,7 +194,7 @@ public void testNoAnsiEmpty(final ListStatusListener listener) { @Test @UsingStatusListener - public void testNoAnsiNonEmpty(final ListStatusListener listener) { + void testNoAnsiNonEmpty(final ListStatusListener listener) { final String[] options = {"%-5level: %msg", PatternParser.DISABLE_ANSI + "=true"}; final HighlightConverter converter = HighlightConverter.newInstance(null, options); assertNotNull(converter); @@ -215,7 +215,7 @@ public void testNoAnsiNonEmpty(final ListStatusListener listener) { */ @Test @UsingStatusListener - public void testBadStyleOption(final ListStatusListener listener) { + void testBadStyleOption(final ListStatusListener listener) { String defaultWarnColor = "yellow"; String defaultInfoColor = "green"; final String[] options = { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LevelPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LevelPatternConverterTest.java index 3b27484a952..70ba0683bf1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LevelPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LevelPatternConverterTest.java @@ -25,7 +25,7 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.junit.jupiter.api.Test; -public class LevelPatternConverterTest { +class LevelPatternConverterTest { private void testLevelLength(final int length, final String debug, final String warn) { final Message msg = new SimpleMessage("Hello"); @@ -54,27 +54,27 @@ private void testLevelLength(final int length, final String debug, final String } @Test - public void testLevelLength1() { + void testLevelLength1() { testLevelLength(1, "D", "W"); } @Test - public void testLevelLength10() { + void testLevelLength10() { testLevelLength(10, "DEBUG", "WARN"); } @Test - public void testLevelLength2() { + void testLevelLength2() { testLevelLength(2, "DE", "WA"); } @Test - public void testLevelLength5() { + void testLevelLength5() { testLevelLength(5, "DEBUG", "WARN"); } @Test - public void testLevelLowerCase() { + void testLevelLowerCase() { final Message msg = new SimpleMessage("Hello"); LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("MyLogger") // @@ -101,7 +101,7 @@ public void testLevelLowerCase() { } @Test - public void testLevelMap() { + void testLevelMap() { final Message msg = new SimpleMessage("Hello"); LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("MyLogger") // @@ -128,7 +128,7 @@ public void testLevelMap() { } @Test - public void testLevelMapWithLength() { + void testLevelMapWithLength() { final Message msg = new SimpleMessage("Hello"); LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("MyLogger") // @@ -155,7 +155,7 @@ public void testLevelMapWithLength() { } @Test - public void testLevelMapWithLengthAndLowerCase() { + void testLevelMapWithLengthAndLowerCase() { final Message msg = new SimpleMessage("Hello"); LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("MyLogger") // diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LiteralPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LiteralPatternConverterTest.java index 355db7c53a7..d3fd0e05678 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LiteralPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LiteralPatternConverterTest.java @@ -23,17 +23,17 @@ /** * Tests the LiteralPatternConverter. */ -public class LiteralPatternConverterTest { +class LiteralPatternConverterTest { @Test - public void testConvertBackslashes() { + void testConvertBackslashes() { final String literal = "ABC\\tDEF\\nGHI\\rJKL\\'MNO\\f \\b \\\\DROPPED:\\x"; final LiteralPatternConverter converter = new LiteralPatternConverter(null, literal, true); assertEquals("ABC\tDEF\nGHI\rJKL\'MNO\f \b \\DROPPED:x", converter.getLiteral()); } @Test - public void testDontConvertBackslashes() { + void testDontConvertBackslashes() { final String literal = "ABC\\tDEF\\nGHI\\rJKL\\'MNO\\f \\b \\\\DROPPED:\\x"; final LiteralPatternConverter converter = new LiteralPatternConverter(null, literal, false); assertEquals(literal, converter.getLiteral()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LocationPatternConvertersRequireLocationTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LocationPatternConvertersRequireLocationTest.java index 64d8019661e..8ca52574d59 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LocationPatternConvertersRequireLocationTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LocationPatternConvertersRequireLocationTest.java @@ -32,8 +32,7 @@ class LocationPatternConvertersRequireLocationTest { */ @ParameterizedTest @CsvSource({"%L", "%l", "%F", "%C", "%M"}) - void testThatLocationDependentPatternConvertersIndicateLocationRequirement(final String converterKey) - throws Exception { + void testThatLocationDependentPatternConvertersIndicateLocationRequirement(final String converterKey) { final PatternFormatter formatter = createSinglePatternFormatterFromConverterKey(converterKey); final LocationAware locationAwareFormatter = assertInstanceOf(LocationAware.class, formatter.getConverter()); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LoggerFqcnPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LoggerFqcnPatternConverterTest.java index 4099a8efc8c..37eb4a68230 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LoggerFqcnPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/LoggerFqcnPatternConverterTest.java @@ -22,12 +22,12 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.junit.jupiter.api.Test; -public class LoggerFqcnPatternConverterTest { +class LoggerFqcnPatternConverterTest { private static final String FQCN = "com.acme.TheClass"; @Test - public void testConverter() { + void testConverter() { final LogEvent event = Log4jLogEvent.newBuilder().setLoggerFqcn(FQCN).build(); final StringBuilder sb = new StringBuilder(); final LogEventPatternConverter converter = LoggerFqcnPatternConverter.newInstance(null); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MapPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MapPatternConverterTest.java index 334cf89f6ff..592e6d2daed 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MapPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MapPatternConverterTest.java @@ -26,10 +26,10 @@ import org.apache.logging.log4j.message.StringMapMessage; import org.junit.jupiter.api.Test; -public class MapPatternConverterTest { +class MapPatternConverterTest { @Test - public void testConverter() { + void testConverter() { final StringMapMessage msg = new StringMapMessage(); msg.put("subject", "I"); @@ -55,7 +55,7 @@ public void testConverter() { } @Test - public void testConverterWithKey() { + void testConverterWithKey() { final StringMapMessage msg = new StringMapMessage(); msg.put("subject", "I"); @@ -75,7 +75,7 @@ public void testConverterWithKey() { } @Test - public void testConverterWithJavaFormat() { + void testConverterWithJavaFormat() { final StringMapMessage msg = new StringMapMessage(); msg.put("subject", "I"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerPatternConverterTest.java index 8c308a523c8..d7431432af1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerPatternConverterTest.java @@ -30,10 +30,10 @@ /** * Tests {@link MarkerPatternConverter}. */ -public class MarkerPatternConverterTest { +class MarkerPatternConverterTest { @Test - public void testLookup() { + void testLookup() { final Message msg = new StructuredDataMessage("Test", "This is a test", "Audit"); final Marker eventMarker = MarkerManager.getMarker("EVENT"); final Marker auditMarker = MarkerManager.getMarker("AUDIT").setParents(eventMarker); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerSimpleNamePatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerSimpleNamePatternConverterTest.java index 78ee08f7da9..b5a49a7cb50 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerSimpleNamePatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MarkerSimpleNamePatternConverterTest.java @@ -30,10 +30,10 @@ /** * Tests {@link MarkerSimpleNamePatternConverter}. */ -public class MarkerSimpleNamePatternConverterTest { +class MarkerSimpleNamePatternConverterTest { @Test - public void testLookup() { + void testLookup() { final Message msg = new StructuredDataMessage("Test", "This is a test", "Audit"); final Marker eventMarker = MarkerManager.getMarker("EVENT"); final Marker auditMarker = MarkerManager.getMarker("AUDIT").setParents(eventMarker); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MaxLengthConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MaxLengthConverterTest.java index 5c888afda65..ae958d187c2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MaxLengthConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MaxLengthConverterTest.java @@ -25,12 +25,12 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.junit.jupiter.api.Test; -public class MaxLengthConverterTest { +class MaxLengthConverterTest { private static final MaxLengthConverter converter = MaxLengthConverter.newInstance(null, new String[] {"%m", "10"}); @Test - public void testUnderMaxLength() { + void testUnderMaxLength() { final Message message = new SimpleMessage("0123456789"); final LogEvent event = Log4jLogEvent.newBuilder() .setLoggerName("MyLogger") @@ -43,7 +43,7 @@ public void testUnderMaxLength() { } @Test - public void testOverMaxLength() { + void testOverMaxLength() { final Message message = new SimpleMessage("01234567890123456789"); final LogEvent event = Log4jLogEvent.newBuilder() .setLoggerName("MyLogger") @@ -56,7 +56,7 @@ public void testOverMaxLength() { } @Test - public void testOverMaxLength21WithEllipsis() { + void testOverMaxLength21WithEllipsis() { final Message message = new SimpleMessage("012345678901234567890123456789"); final LogEvent event = Log4jLogEvent.newBuilder() .setLoggerName("MyLogger") diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MdcPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MdcPatternConverterTest.java index c5beaa5fd4f..e06eea4bbfa 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MdcPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MdcPatternConverterTest.java @@ -29,17 +29,17 @@ import org.junit.jupiter.api.Test; @UsingThreadContextMap -public class MdcPatternConverterTest { +class MdcPatternConverterTest { @BeforeEach - public void setup() { + void setup() { ThreadContext.put("subject", "I"); ThreadContext.put("verb", "love"); ThreadContext.put("object", "Log4j"); } @Test - public void testConverter() { + void testConverter() { final Message msg = new SimpleMessage("Hello"); final MdcPatternConverter converter = MdcPatternConverter.newInstance(null); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -55,7 +55,7 @@ public void testConverter() { } @Test - public void testConverterWithExistingData() { + void testConverterWithExistingData() { final Message msg = new SimpleMessage("Hello"); final MdcPatternConverter converter = MdcPatternConverter.newInstance(null); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -72,7 +72,7 @@ public void testConverterWithExistingData() { } @Test - public void testConverterFullEmpty() { + void testConverterFullEmpty() { ThreadContext.clearMap(); final Message msg = new SimpleMessage("Hello"); final MdcPatternConverter converter = MdcPatternConverter.newInstance(null); @@ -89,7 +89,7 @@ public void testConverterFullEmpty() { } @Test - public void testConverterFullSingle() { + void testConverterFullSingle() { ThreadContext.clearMap(); ThreadContext.put("foo", "bar"); final Message msg = new SimpleMessage("Hello"); @@ -107,7 +107,7 @@ public void testConverterFullSingle() { } @Test - public void testConverterWithKey() { + void testConverterWithKey() { final Message msg = new SimpleMessage("Hello"); final String[] options = new String[] {"object"}; final MdcPatternConverter converter = MdcPatternConverter.newInstance(options); @@ -124,7 +124,7 @@ public void testConverterWithKey() { } @Test - public void testConverterWithKeys() { + void testConverterWithKeys() { final Message msg = new SimpleMessage("Hello"); final String[] options = new String[] {"object, subject"}; final MdcPatternConverter converter = MdcPatternConverter.newInstance(options); @@ -141,7 +141,7 @@ public void testConverterWithKeys() { } @Test - public void testConverterWithKeysAndPrefix() { + void testConverterWithKeysAndPrefix() { final Message msg = new SimpleMessage("Hello"); final String[] options = new String[] {"object, subject"}; final MdcPatternConverter converter = MdcPatternConverter.newInstance(options); @@ -159,7 +159,7 @@ public void testConverterWithKeysAndPrefix() { } @Test - public void testConverterWithKeysSinglePresent() { + void testConverterWithKeysSinglePresent() { final Message msg = new SimpleMessage("Hello"); final String[] options = new String[] {"object, notpresent"}; final MdcPatternConverter converter = MdcPatternConverter.newInstance(options); @@ -176,7 +176,7 @@ public void testConverterWithKeysSinglePresent() { } @Test - public void testConverterWithKeysNonePresent() { + void testConverterWithKeysNonePresent() { ThreadContext.clearMap(); final Message msg = new SimpleMessage("Hello"); final String[] options = new String[] {"object, subject"}; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageAnsiConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageAnsiConverterTest.java index 51278a04d6e..09e3a1bd0ac 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageAnsiConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageAnsiConverterTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-message-ansi.xml") -public class MessageAnsiConverterTest { +class MessageAnsiConverterTest { private static final String EXPECTED = "\u001B[31;1mWarning!\u001B[m Pants on \u001B[31mfire!\u001B[m" + Strings.LINE_SEPARATOR; @@ -40,13 +40,13 @@ public class MessageAnsiConverterTest { private ListAppender app; @BeforeEach - public void setUp(final LoggerContext context, @Named("List") final ListAppender app) { + void setUp(final LoggerContext context, @Named("List") final ListAppender app) { this.logger = context.getLogger("LoggerTest"); this.app = app.clear(); } @Test - public void testReplacement() { + void testReplacement() { // See https://www.javadoc.io/doc/org.jline/jline/latest/org/jline/jansi/AnsiRenderer.html logger.error("@|red,bold Warning!|@ Pants on @|red fire!|@"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessagePatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessagePatternConverterTest.java index 954b80e8843..ba58e2ad3d2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessagePatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessagePatternConverterTest.java @@ -31,10 +31,10 @@ import org.apache.logging.log4j.message.StructuredDataMessage; import org.junit.jupiter.api.Test; -public class MessagePatternConverterTest { +class MessagePatternConverterTest { @Test - public void testPattern() { + void testPattern() { final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, null); Message msg = new SimpleMessage("Hello!"); LogEvent event = Log4jLogEvent.newBuilder() // @@ -65,7 +65,7 @@ public void testPattern() { } @Test - public void testPatternAndParameterizedMessageDateLookup() { + void testPatternAndParameterizedMessageDateLookup() { final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, null); final Message msg = new ParameterizedMessage("${date:now:buhu}"); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -79,7 +79,7 @@ public void testPatternAndParameterizedMessageDateLookup() { } @Test - public void testDefaultDisabledLookup() { + void testDefaultDisabledLookup() { final Configuration config = new DefaultConfigurationBuilder().addProperty("foo", "bar").build(true); final MessagePatternConverter converter = MessagePatternConverter.newInstance(config, null); @@ -95,7 +95,7 @@ public void testDefaultDisabledLookup() { } @Test - public void testDisabledLookup() { + void testDisabledLookup() { final Configuration config = new DefaultConfigurationBuilder().addProperty("foo", "bar").build(true); final MessagePatternConverter converter = @@ -112,7 +112,7 @@ public void testDisabledLookup() { } @Test - public void testLookup() { + void testLookup() { final Configuration config = new DefaultConfigurationBuilder().addProperty("foo", "bar").build(true); final MessagePatternConverter converter = MessagePatternConverter.newInstance(config, new String[] {"lookups"}); @@ -128,7 +128,7 @@ public void testLookup() { } @Test - public void testPatternWithConfiguration() { + void testPatternWithConfiguration() { final Configuration config = new DefaultConfiguration(); final MessagePatternConverter converter = MessagePatternConverter.newInstance(config, null); Message msg = new SimpleMessage("Hello!"); @@ -160,7 +160,7 @@ public void testPatternWithConfiguration() { } @Test - public void testMapMessageFormatJson() { + void testMapMessageFormatJson() { final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, new String[] {"json"}); final Message msg = new StringMapMessage().with("key", "val"); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -174,7 +174,7 @@ public void testMapMessageFormatJson() { } @Test - public void testMapMessageFormatXml() { + void testMapMessageFormatXml() { final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, new String[] {"xml"}); final Message msg = new StringMapMessage().with("key", "val"); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -188,7 +188,7 @@ public void testMapMessageFormatXml() { } @Test - public void testMapMessageFormatDefault() { + void testMapMessageFormatDefault() { final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, null); final Message msg = new StringMapMessage().with("key", "val"); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -202,7 +202,7 @@ public void testMapMessageFormatDefault() { } @Test - public void testStructuredDataFormatFull() { + void testStructuredDataFormatFull() { final MessagePatternConverter converter = MessagePatternConverter.newInstance(null, new String[] {"FULL"}); final Message msg = new StructuredDataMessage("id", "message", "type").with("key", "val"); final LogEvent event = Log4jLogEvent.newBuilder() // diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageStyledConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageStyledConverterTest.java index 06ab681fedd..317c11b78fb 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageStyledConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/MessageStyledConverterTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j-message-styled.xml") -public class MessageStyledConverterTest { +class MessageStyledConverterTest { private static final String EXPECTED = "\u001B[31;1mWarning!\u001B[m Pants on \u001B[31;1mfire!\u001B[m" + Strings.LINE_SEPARATOR; @@ -40,13 +40,13 @@ public class MessageStyledConverterTest { private ListAppender app; @BeforeEach - public void setUp(final LoggerContext context, @Named("List") final ListAppender app) { + void setUp(final LoggerContext context, @Named("List") final ListAppender app) { this.logger = context.getLogger("LoggerTest"); this.app = app.clear(); } @Test - public void testReplacement() { + void testReplacement() { // See https://www.javadoc.io/doc/org.jline/jline/latest/org/jline/jansi/AnsiRenderer.html logger.error("@|WarningStyle Warning!|@ Pants on @|WarningStyle fire!|@"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NameAbbreviatorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NameAbbreviatorTest.java index 92b365a2588..0f4bb16072c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NameAbbreviatorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NameAbbreviatorTest.java @@ -16,29 +16,18 @@ */ package org.apache.logging.log4j.core.pattern; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collection; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Unit tests for {@link NameAbbreviator} which abbreviates dot-delimited strings such as logger and class names. */ -@RunWith(Parameterized.class) -public class NameAbbreviatorTest { +class NameAbbreviatorTest { - private final String pattern; - private final String expected; - - public NameAbbreviatorTest(final String pattern, final String expected) { - this.pattern = pattern; - this.expected = expected; - } - - @Parameterized.Parameters(name = "pattern=\"{0}\", expected={1}") public static Collection data() { return Arrays.asList(new Object[][] { // { pattern, expected } @@ -56,18 +45,20 @@ public static Collection data() { }); } - @Test - public void testAbbreviatorPatterns() throws Exception { - final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(this.pattern); + @MethodSource("data") + @ParameterizedTest(name = "pattern=\"{0}\", expected={1}") + void testAbbreviatorPatterns(final String pattern, final String expected) { + final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(pattern); final StringBuilder destination = new StringBuilder(); abbreviator.abbreviate(this.getClass().getName(), destination); final String actual = destination.toString(); assertEquals(expected, actual); } - @Test - public void testAbbreviatorPatternsAppendLongPrefix() throws Exception { - final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(this.pattern); + @MethodSource("data") + @ParameterizedTest(name = "pattern=\"{0}\", expected={1}") + void testAbbreviatorPatternsAppendLongPrefix(final String pattern, final String expected) { + final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(pattern); final String PREFIX = "some random text big enough to be larger than abbreviated string "; final StringBuilder destination = new StringBuilder(PREFIX); abbreviator.abbreviate(this.getClass().getName(), destination); @@ -75,9 +66,10 @@ public void testAbbreviatorPatternsAppendLongPrefix() throws Exception { assertEquals(PREFIX + expected, actual); } - @Test - public void testAbbreviatorPatternsAppend() throws Exception { - final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(this.pattern); + @MethodSource("data") + @ParameterizedTest(name = "pattern=\"{0}\", expected={1}") + void testAbbreviatorPatternsAppend(final String pattern, final String expected) { + final NameAbbreviator abbreviator = NameAbbreviator.getAbbreviator(pattern); final String PREFIX = "some random text"; final StringBuilder destination = new StringBuilder(PREFIX); abbreviator.abbreviate(this.getClass().getName(), destination); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NanoTimePatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NanoTimePatternConverterTest.java index 75b6e31c7a2..61ea54b481f 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NanoTimePatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NanoTimePatternConverterTest.java @@ -22,10 +22,10 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.junit.jupiter.api.Test; -public class NanoTimePatternConverterTest { +class NanoTimePatternConverterTest { @Test - public void testConverterAppendsLogEventNanoTimeToStringBuilder() { + void testConverterAppendsLogEventNanoTimeToStringBuilder() { final LogEvent event = Log4jLogEvent.newBuilder() // .setNanoTime(1234567) .build(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NdcPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NdcPatternConverterTest.java index 99716d29027..ea35af47820 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NdcPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NdcPatternConverterTest.java @@ -28,28 +28,28 @@ import org.junit.jupiter.api.Test; @UsingThreadContextStack -public class NdcPatternConverterTest { +class NdcPatternConverterTest { @Test - public void testEmpty() { + void testEmpty() { testConverter("[]"); } @Test - public void test1() { + void test1() { ThreadContext.push("foo"); testConverter("[foo]"); } @Test - public void test2() { + void test2() { ThreadContext.push("foo"); ThreadContext.push("bar"); testConverter("[foo, bar]"); } @Test - public void test3() { + void test3() { ThreadContext.push("foo"); ThreadContext.push("bar"); ThreadContext.push("baz"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NoConsoleNoAnsiTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NoConsoleNoAnsiTest.java index abea1d59564..519aa9c5fd1 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NoConsoleNoAnsiTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NoConsoleNoAnsiTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("log4j2-console-noConsoleNoAnsi.xml") -public class NoConsoleNoAnsiTest { +class NoConsoleNoAnsiTest { private static final String EXPECTED = "ERROR LoggerTest o.a.l.l.c.p.NoConsoleNoAnsiTest org.apache.logging.log4j.core.pattern.NoConsoleNoAnsiTest" @@ -41,13 +41,13 @@ public class NoConsoleNoAnsiTest { private ListAppender app; @BeforeEach - public void setUp(final LoggerContext context, @Named("List") final ListAppender app) { + void setUp(final LoggerContext context, @Named("List") final ListAppender app) { this.logger = context.getLogger("LoggerTest"); this.app = app.clear(); } @Test - public void testReplacement() { + void testReplacement() { logger.error(this.getClass().getName()); final List msgs = app.getMessages(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/PatternParserTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/PatternParserTest.java index d5c81c3d787..f493e25bb6a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/PatternParserTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/PatternParserTest.java @@ -17,6 +17,7 @@ package org.apache.logging.log4j.core.pattern; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -40,7 +41,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class PatternParserTest { +class PatternParserTest { static String OUTPUT_FILE = "output/PatternParser"; static String WITNESS_FILE = "witness/PatternParser"; @@ -66,7 +67,7 @@ public class PatternParserTest { private PatternParser parser; @BeforeEach - public void setup() { + void setup() { parser = new PatternParser(KEY); } @@ -80,10 +81,10 @@ private void validateConverter(final List formatter, final int * Test the default pattern */ @Test - public void defaultPattern() { + void defaultPattern() { final List formatters = parser.parse(msgPattern); assertNotNull(formatters); - assertEquals(formatters.size(), 2); + assertEquals(2, formatters.size()); validateConverter(formatters, 0, "Message"); validateConverter(formatters, 1, "Line Sep"); } @@ -92,7 +93,7 @@ public void defaultPattern() { * Test the custom pattern */ @Test - public void testCustomPattern() { + void testCustomPattern() { final List formatters = parser.parse(customPattern); assertNotNull(formatters); final StringMap mdc = ContextDataFactory.createContextData(); @@ -115,12 +116,12 @@ public void testCustomPattern() { formatter.format(event, buf); } final String str = buf.toString(); - final String expected = "INFO [PatternParserTest :100 ] - Hello, world" + Strings.LINE_SEPARATOR; + final String expected = "INFO [PatternParserTest :101 ] - Hello, world" + Strings.LINE_SEPARATOR; assertTrue(str.endsWith(expected), "Expected to end with: " + expected + ". Actual: " + str); } @Test - public void testPatternTruncateFromBeginning() { + void testPatternTruncateFromBeginning() { final List formatters = parser.parse(patternTruncateFromBeginning); assertNotNull(formatters); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -141,7 +142,7 @@ public void testPatternTruncateFromBeginning() { } @Test - public void testPatternTruncateFromEnd() { + void testPatternTruncateFromEnd() { final List formatters = parser.parse(patternTruncateFromEnd); assertNotNull(formatters); final LogEvent event = Log4jLogEvent.newBuilder() // @@ -162,7 +163,7 @@ public void testPatternTruncateFromEnd() { } @Test - public void testBadPattern() { + void testBadPattern() { final Calendar cal = Calendar.getInstance(); cal.set(2001, Calendar.FEBRUARY, 3, 4, 5, 6); cal.set(Calendar.MILLISECOND, 789); @@ -193,7 +194,7 @@ public void testBadPattern() { } @Test - public void testNestedPatternHighlight() { + void testNestedPatternHighlight() { testNestedPatternHighlight(Level.TRACE, "\u001B[30m"); testNestedPatternHighlight(Level.DEBUG, "\u001B[36m"); testNestedPatternHighlight(Level.INFO, "\u001B[32m"); @@ -227,57 +228,57 @@ private void testNestedPatternHighlight(final Level level, final String expected } @Test - public void testNanoPatternShort() { + void testNanoPatternShort() { testFirstConverter("%N", NanoTimePatternConverter.class); } @Test - public void testNanoPatternLong() { + void testNanoPatternLong() { testFirstConverter("%nano", NanoTimePatternConverter.class); } @Test - public void testThreadNamePattern() { + void testThreadNamePattern() { testThreadNamePattern("%thread"); } @Test - public void testThreadNameFullPattern() { + void testThreadNameFullPattern() { testThreadNamePattern("%threadName"); } @Test - public void testThreadIdFullPattern() { + void testThreadIdFullPattern() { testThreadIdPattern("%threadId"); } @Test - public void testThreadIdShortPattern1() { + void testThreadIdShortPattern1() { testThreadIdPattern("%tid"); } @Test - public void testThreadIdShortPattern2() { + void testThreadIdShortPattern2() { testThreadIdPattern("%T"); } @Test - public void testThreadPriorityShortPattern() { + void testThreadPriorityShortPattern() { testThreadPriorityPattern("%tp"); } @Test - public void testThreadPriorityFullPattern() { + void testThreadPriorityFullPattern() { testThreadPriorityPattern("%threadPriority"); } @Test - public void testLoggerFqcnPattern() { + void testLoggerFqcnPattern() { testFirstConverter("%fqcn", LoggerFqcnPatternConverter.class); } @Test - public void testEndOfBatchPattern() { + void testEndOfBatchPattern() { testFirstConverter("%endOfBatch", EndOfBatchPatternConverter.class); } @@ -302,42 +303,42 @@ private void testFirstConverter(final String pattern, final Class checkClass) } @Test - public void testThreadNameShortPattern() { + void testThreadNameShortPattern() { testThreadNamePattern("%t"); } @Test - public void testNanoPatternShortChangesConfigurationNanoClock() { + void testNanoPatternShortChangesConfigurationNanoClock() { final Configuration config = new NullConfiguration(); - assertTrue(config.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, config.getNanoClock()); final PatternParser pp = new PatternParser(config, KEY, null); - assertTrue(config.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, config.getNanoClock()); pp.parse("%m"); - assertTrue(config.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, config.getNanoClock()); pp.parse("%nano"); // this changes the config clock - assertTrue(config.getNanoClock() instanceof SystemNanoClock); + assertInstanceOf(SystemNanoClock.class, config.getNanoClock()); } @Test - public void testNanoPatternLongChangesNanoClockFactoryMode() { + void testNanoPatternLongChangesNanoClockFactoryMode() { final Configuration config = new NullConfiguration(); - assertTrue(config.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, config.getNanoClock()); final PatternParser pp = new PatternParser(config, KEY, null); - assertTrue(config.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, config.getNanoClock()); pp.parse("%m"); - assertTrue(config.getNanoClock() instanceof DummyNanoClock); + assertInstanceOf(DummyNanoClock.class, config.getNanoClock()); pp.parse("%N"); - assertTrue(config.getNanoClock() instanceof SystemNanoClock); + assertInstanceOf(SystemNanoClock.class, config.getNanoClock()); } @Test - public void testDeeplyNestedPattern() { + void testDeeplyNestedPattern() { final List formatters = parser.parse(deeplyNestedPattern); assertNotNull(formatters); assertEquals(1, formatters.size()); @@ -354,12 +355,12 @@ public void testDeeplyNestedPattern() { } @Test - public void testMissingClosingBracket() { + void testMissingClosingBracket() { testFirstConverter("%d{", DatePatternConverter.class); } @Test - public void testClosingBracketButWrongPlace() { + void testClosingBracketButWrongPlace() { final List formatters = parser.parse("}%d{"); assertNotNull(formatters); assertEquals(2, formatters.size()); @@ -369,7 +370,7 @@ public void testClosingBracketButWrongPlace() { } @Test - public void testExceptionWithFilters() { + void testExceptionWithFilters() { final List formatters = parser.parse("%d{DEFAULT} - %msg - %xEx{full}{filters(org.junit,org.eclipse)}%n"); assertNotNull(formatters); @@ -385,7 +386,7 @@ public void testExceptionWithFilters() { } @Test - public void testExceptionWithFiltersAndSeparator() { + void testExceptionWithFiltersAndSeparator() { final List formatters = parser.parse("%d{DEFAULT} - %msg - %xEx{full}{filters(org.junit,org.eclipse)}{separator(|)}%n"); assertNotNull(formatters); @@ -405,11 +406,11 @@ public void testExceptionWithFiltersAndSeparator() { // LOG4J2-2564: Multiple newInstance methods. @Test - public void testMapPatternConverter() { + void testMapPatternConverter() { final List formatters = parser.parse("%K"); assertNotNull(formatters); - assertEquals(formatters.size(), 1); + assertEquals(1, formatters.size()); final PatternFormatter formatter = formatters.get(0); - assertTrue(formatter.getConverter() instanceof MapPatternConverter, "Expected a MapPatternConverter"); + assertInstanceOf(MapPatternConverter.class, formatter.getConverter(), "Expected a MapPatternConverter"); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ProcessIdPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ProcessIdPatternConverterTest.java index 524440f618d..39a9311f8e8 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ProcessIdPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ProcessIdPatternConverterTest.java @@ -23,9 +23,9 @@ /** * Tests that process ID succeeds. */ -public class ProcessIdPatternConverterTest { +class ProcessIdPatternConverterTest { @Test - public void getProcessId() { + void getProcessId() { final String[] defaultValue = {"???"}; final String actual = ProcessIdPatternConverter.newInstance(defaultValue).getProcessId(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementConverterTest.java index 3cfb2155177..a98fd1964ee 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementConverterTest.java @@ -28,10 +28,10 @@ import org.apache.logging.log4j.util.Strings; import org.junit.jupiter.api.Test; -public class RegexReplacementConverterTest { +class RegexReplacementConverterTest { @Test - public void testReplacement() { + void testReplacement() { ThreadContext.put("MyKey", "Apache"); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName(RegexReplacementConverterTest.class.getName()) // diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementTest.java index 521b14f526f..2647869530b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RegexReplacementTest.java @@ -32,7 +32,7 @@ @LoggerContextSource("log4j-replace.xml") @UsingThreadContextMap -public class RegexReplacementTest { +class RegexReplacementTest { private final ListAppender app; private final ListAppender app2; private final org.apache.logging.log4j.Logger logger; @@ -51,7 +51,7 @@ public RegexReplacementTest( } @Test - public void testReplacement() { + void testReplacement() { logger.error(this.getClass().getName()); final List msgs = app.getMessages(); assertNotNull(msgs); @@ -62,7 +62,7 @@ public void testReplacement() { } @Test - public void testMessageReplacement() { + void testMessageReplacement() { ThreadContext.put("MyKey", "Apache"); logger.error("This is a test for ${ctx:MyKey}"); final List msgs = app.getMessages(); @@ -72,7 +72,7 @@ public void testMessageReplacement() { } @Test - public void testConverter() { + void testConverter() { logger2.error(this.getClass().getName()); final List msgs = app2.getMessages(); assertNotNull(msgs); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RepeatPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RepeatPatternConverterTest.java index 170acef48ea..8a6429628ab 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RepeatPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/RepeatPatternConverterTest.java @@ -28,9 +28,9 @@ /** * Tests that process ID succeeds. */ -public class RepeatPatternConverterTest { +class RepeatPatternConverterTest { @Test - public void repeat() { + void repeat() { final String[] args = {"*", "10"}; final String expected = "**********"; final PatternConverter converter = RepeatPatternConverter.newInstance(null, args); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterTest.java index 60ff42bc98e..05e2c53c3de 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterTest.java @@ -28,10 +28,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("SequenceNumberPatternConverterTest.yaml") -public class SequenceNumberPatternConverterTest { +class SequenceNumberPatternConverterTest { @Test - public void testSequenceIncreases(final LoggerContext context, @Named("List") final ListAppender app) { + void testSequenceIncreases(final LoggerContext context, @Named("List") final ListAppender app) { app.clear(); final Logger logger = context.getLogger(getClass().getName()); logger.info("Message 1"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterZeroPaddedTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterZeroPaddedTest.java index 049fe51c720..ccc342dfb17 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterZeroPaddedTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SequenceNumberPatternConverterZeroPaddedTest.java @@ -28,10 +28,10 @@ import org.junit.jupiter.api.Test; @LoggerContextSource("SequenceNumberPatternConverterZeroPaddedTest.yaml") -public class SequenceNumberPatternConverterZeroPaddedTest { +class SequenceNumberPatternConverterZeroPaddedTest { @Test - public void testPaddedSequence(final LoggerContext context, @Named("Padded") final ListAppender app) { + void testPaddedSequence(final LoggerContext context, @Named("Padded") final ListAppender app) { app.clear(); final Logger logger = context.getLogger(getClass().getName()); logger.info("Message 1"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SimpleLiteralPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SimpleLiteralPatternConverterTest.java index 9b07800dfcb..c64c0638f94 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SimpleLiteralPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/SimpleLiteralPatternConverterTest.java @@ -20,10 +20,10 @@ import org.junit.jupiter.api.Test; -public class SimpleLiteralPatternConverterTest { +class SimpleLiteralPatternConverterTest { @Test - public void testConvertBackslashes() { + void testConvertBackslashes() { final String literal = "ABC\\tDEF\\nGHI\\rJKL\\'MNO\\f \\b \\\\DROPPED:\\x"; final LogEventPatternConverter converter = SimpleLiteralPatternConverter.of(literal, true); final String actual = literal(converter); @@ -31,7 +31,7 @@ public void testConvertBackslashes() { } @Test - public void testDontConvertBackslashes() { + void testDontConvertBackslashes() { final String literal = "ABC\\tDEF\\nGHI\\rJKL\\'MNO\\f \\b \\\\DROPPED:\\x"; final LogEventPatternConverter converter = SimpleLiteralPatternConverter.of(literal, false); final String actual = literal(converter); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/StyleConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/StyleConverterTest.java index b9a38631233..6b03c699054 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/StyleConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/StyleConverterTest.java @@ -39,20 +39,20 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class StyleConverterTest { +class StyleConverterTest { private static final String EXPECTED = "\u001B[1;31mERROR\u001B[m \u001B[1;36mLoggerTest\u001B[m o.a.l.l.c.p.StyleConverterTest org.apache.logging.log4j.core.pattern.StyleConverterTest" + Strings.LINE_SEPARATOR; @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable } @Test @LoggerContextSource("log4j-style.xml") - public void testReplacement(final LoggerContext context, @Named("List") final ListAppender app) { + void testReplacement(final LoggerContext context, @Named("List") final ListAppender app) { final Logger logger = context.getLogger("LoggerTest"); logger.error(this.getClass().getName()); @@ -65,13 +65,13 @@ public void testReplacement(final LoggerContext context, @Named("List") final Li } @Test - public void testNull() { + void testNull() { assertNull(StyleConverter.newInstance(null, null)); } @ParameterizedTest @MethodSource("org.apache.logging.log4j.core.pattern.HighlightConverterTest#colors") - public void testHighlightConverterCompatibility(final String color, final String escape) { + void testHighlightConverterCompatibility(final String color, final String escape) { final StyleConverter converter = StyleConverter.newInstance(null, new String[] {"Hello!", color}); final StringBuilder sb = new StringBuilder(); final LogEvent event = Log4jLogEvent.newBuilder().setLevel(Level.INFO).build(); @@ -81,7 +81,7 @@ public void testHighlightConverterCompatibility(final String color, final String @ParameterizedTest @MethodSource("org.apache.logging.log4j.core.pattern.HighlightConverterTest#colors") - public void testLegacyCommaSeparator(final String color, final String escape) { + void testLegacyCommaSeparator(final String color, final String escape) { final StyleConverter converter = StyleConverter.newInstance(null, new String[] {"Hello!", color.replaceAll("\\s+", ",")}); final StringBuilder sb = new StringBuilder(); @@ -92,7 +92,7 @@ public void testLegacyCommaSeparator(final String color, final String escape) { @Test @UsingStatusListener - public void testNoAnsiNoWarnings(final ListStatusListener listener) { + void testNoAnsiNoWarnings(final ListStatusListener listener) { StyleConverter converter = StyleConverter.newInstance(null, new String[] {"", "disableAnsi=true"}); assertThat(converter).isNotNull(); converter = StyleConverter.newInstance(null, new String[] {"", "noConsoleNoAnsi=true"}); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadIdPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadIdPatternConverterTest.java index 9d1326f8901..69a7d9d2a2a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadIdPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadIdPatternConverterTest.java @@ -22,10 +22,10 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.junit.jupiter.api.Test; -public class ThreadIdPatternConverterTest { +class ThreadIdPatternConverterTest { @Test - public void testConverterAppendsLogEventNanoTimeToStringBuilder() { + void testConverterAppendsLogEventNanoTimeToStringBuilder() { final LogEvent event = Log4jLogEvent.newBuilder() // .setThreadId(1) .build(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadNamePatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadNamePatternConverterTest.java index ceff44b5621..545766db5b9 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadNamePatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadNamePatternConverterTest.java @@ -22,10 +22,10 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.junit.jupiter.api.Test; -public class ThreadNamePatternConverterTest { +class ThreadNamePatternConverterTest { @Test - public void testConverterAppendsLogEventNanoTimeToStringBuilder() { + void testConverterAppendsLogEventNanoTimeToStringBuilder() { final LogEvent event = Log4jLogEvent.newBuilder() // .setThreadName("Hello-1") .build(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadPriorityPatternConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadPriorityPatternConverterTest.java index 1338763577b..fd27bbb2ef7 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadPriorityPatternConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/ThreadPriorityPatternConverterTest.java @@ -22,10 +22,10 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent; import org.junit.jupiter.api.Test; -public class ThreadPriorityPatternConverterTest { +class ThreadPriorityPatternConverterTest { @Test - public void testConverterAppendsLogEventNanoTimeToStringBuilder() { + void testConverterAppendsLogEventNanoTimeToStringBuilder() { final LogEvent event = Log4jLogEvent.newBuilder() // .setThreadPriority(1) .build(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/VariablesNotEmptyReplacementConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/VariablesNotEmptyReplacementConverterTest.java index 824c6943d15..261924cbf4c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/VariablesNotEmptyReplacementConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/VariablesNotEmptyReplacementConverterTest.java @@ -27,35 +27,35 @@ import org.apache.logging.log4j.util.Strings; import org.junit.jupiter.api.Test; -public class VariablesNotEmptyReplacementConverterTest { +class VariablesNotEmptyReplacementConverterTest { @Test - public void testMarkerReplacement() { + void testMarkerReplacement() { testReplacement("%marker", Strings.EMPTY); } @Test - public void testMultipleMarkerReplacementEmpty() { + void testMultipleMarkerReplacementEmpty() { testReplacement("<%marker>Foo", Strings.EMPTY); } @Test - public void testMultipleMarkerReplacementSomeEmpty() { + void testMultipleMarkerReplacementSomeEmpty() { testReplacement("<%marker>%msg", "[<>This is a test]"); } @Test - public void testMultipleMarkerReplacement() { + void testMultipleMarkerReplacement() { testReplacement("<%level>%msg", "[This is a test]"); } @Test - public void testMarkerSimpleNameReplacement() { + void testMarkerSimpleNameReplacement() { testReplacement("%markerSimpleName", Strings.EMPTY); } @Test - public void testLoggerNameReplacement() { + void testLoggerNameReplacement() { testReplacement("%logger", "[" + VariablesNotEmptyReplacementConverterTest.class.getName() + "]"); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/BasicContextSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/BasicContextSelectorTest.java index f75cbb8a12c..5c3b50bbf44 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/BasicContextSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/BasicContextSelectorTest.java @@ -16,31 +16,31 @@ */ package org.apache.logging.log4j.core.selector; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LifeCycle; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.util.Constants; -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.Test; -public final class BasicContextSelectorTest { +class BasicContextSelectorTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BasicContextSelector.class.getName()); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR); } @Test - public void testLogManagerShutdown() { + void testLogManagerShutdown() { final LoggerContext context = (LoggerContext) LogManager.getContext(); assertEquals(LifeCycle.State.STARTED, context.getState()); LogManager.shutdown(); @@ -48,7 +48,7 @@ public void testLogManagerShutdown() { } @Test - public void testNotDependentOnClassLoader() { + void testNotDependentOnClassLoader() { assertFalse(LogManager.getFactory().isClassLoaderDependent()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java index 03f7e88b485..fd6220f7e14 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/selector/ClassLoaderContextSelectorTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class ClassLoaderContextSelectorTest { +class ClassLoaderContextSelectorTest { private static final String PKG = ClassLoaderContextSelectorTest.class.getPackage().getName(); @@ -33,7 +33,7 @@ public class ClassLoaderContextSelectorTest { private ClassLoader loader1, loader2, loader3; @BeforeEach - public void setUp() throws Exception { + void setUp() { loader1 = new TestClassLoader(); loader2 = new TestClassLoader(); loader3 = new TestClassLoader(); @@ -43,7 +43,7 @@ public void setUp() throws Exception { } @Test - public void testMultipleClassLoaders() throws Exception { + void testMultipleClassLoaders() throws Exception { final Class logging1 = loader1.loadClass(PKG + ".a.Logging1"); final Field field1 = logging1.getDeclaredField("logger"); final Logger logger1 = (Logger) ReflectionUtil.getStaticFieldValue(field1); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/test/LogBuilderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/test/LogBuilderTest.java index c596c2ea163..c69b9c3994d 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/test/LogBuilderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/test/LogBuilderTest.java @@ -35,7 +35,7 @@ import org.junit.jupiter.params.provider.MethodSource; @LoggerContextSource("org/apache/logging/log4j/core/test/LogBuilderTest.xml") -public class LogBuilderTest { +class LogBuilderTest { private static final Marker MARKER = MarkerManager.getMarker("TestMarker"); private static final CharSequence CHAR_SEQUENCE = "CharSequence"; @@ -49,7 +49,7 @@ public class LogBuilderTest { private ListAppender appender; @BeforeEach - public void setupAppender(final LoggerContext context, @Named("LIST") final ListAppender appender) { + void setupAppender(final LoggerContext context, @Named("LIST") final ListAppender appender) { this.logger = context.getLogger(getClass()); this.appender = appender; } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java index ce487e1bd38..dfa631bc933 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateCustomLoggerTest.java @@ -48,16 +48,16 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class GenerateCustomLoggerTest { +class GenerateCustomLoggerTest { @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty("log4j2.loggerContextFactory", "org.apache.logging.log4j.test.TestLoggerContextFactory"); } @Test @SuppressWarnings("ReturnValueIgnored") - public void testGenerateSource() throws Exception { + void testGenerateSource() throws Exception { final String CLASSNAME = "org.myorg.MyCustomLogger"; // generate custom logger source diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java index ecad9676048..93349f2c0d9 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/tools/GenerateExtendedLoggerTest.java @@ -49,16 +49,16 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class GenerateExtendedLoggerTest { +class GenerateExtendedLoggerTest { @BeforeAll - public static void beforeClass() { + static void beforeClass() { System.setProperty("log4j2.loggerContextFactory", "org.apache.logging.log4j.test.TestLoggerContextFactory"); } @Test @SuppressWarnings("ReturnValueIgnored") - public void testGenerateSource() throws Exception { + void testGenerateSource() throws Exception { final String CLASSNAME = "org.myorg.MyExtendedLogger"; // generate custom logger source diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ClockFactoryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ClockFactoryTest.java index 71d78a4261f..de71272c072 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ClockFactoryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ClockFactoryTest.java @@ -39,48 +39,48 @@ public static void resetClock(final Class clazz) throws IllegalAccessExceptio } @BeforeEach - public void setUp() throws Exception { + void setUp() throws Exception { resetClocks(); } @Test - public void testDefaultIsSystemClock() { + void testDefaultIsSystemClock() { System.clearProperty(ClockFactory.PROPERTY_NAME); assertSame(SystemClock.class, ClockFactory.getClock().getClass()); } @Test - public void testSpecifySystemClockShort() { + void testSpecifySystemClockShort() { System.setProperty(ClockFactory.PROPERTY_NAME, "SystemClock"); assertSame(SystemClock.class, ClockFactory.getClock().getClass()); } @Test - public void testSpecifySystemClockLong() { + void testSpecifySystemClockLong() { System.setProperty(ClockFactory.PROPERTY_NAME, SystemClock.class.getName()); assertSame(SystemClock.class, ClockFactory.getClock().getClass()); } @Test - public void testSpecifyCachedClockShort() { + void testSpecifyCachedClockShort() { System.setProperty(ClockFactory.PROPERTY_NAME, "CachedClock"); assertSame(CachedClock.class, ClockFactory.getClock().getClass()); } @Test - public void testSpecifyCachedClockLong() { + void testSpecifyCachedClockLong() { System.setProperty(ClockFactory.PROPERTY_NAME, CachedClock.class.getName()); assertSame(CachedClock.class, ClockFactory.getClock().getClass()); } @Test - public void testSpecifyCoarseCachedClockShort() { + void testSpecifyCoarseCachedClockShort() { System.setProperty(ClockFactory.PROPERTY_NAME, "CoarseCachedClock"); assertSame(CoarseCachedClock.class, ClockFactory.getClock().getClass()); } @Test - public void testSpecifyCoarseCachedClockLong() { + void testSpecifyCoarseCachedClockLong() { System.setProperty(ClockFactory.PROPERTY_NAME, CoarseCachedClock.class.getName()); assertSame(CoarseCachedClock.class, ClockFactory.getClock().getClass()); } @@ -93,7 +93,7 @@ public long currentTimeMillis() { } @Test - public void testCustomClock() { + void testCustomClock() { System.setProperty(ClockFactory.PROPERTY_NAME, MyClock.class.getName()); assertSame(MyClock.class, ClockFactory.getClock().getClass()); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java index 1cfd4d8ecd2..3e00b8c5532 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ContextDataProviderTest.java @@ -35,13 +35,13 @@ import org.junit.jupiter.api.Test; @Tag("functional") -public class ContextDataProviderTest { +class ContextDataProviderTest { private static Logger logger; private static ListAppender appender; @BeforeAll - public static void beforeClass() { + static void beforeClass() { ThreadContextDataInjector.contextDataProviders.add(new TestContextDataProvider()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j-contextData.xml"); final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); @@ -51,7 +51,7 @@ public static void beforeClass() { } @Test - public void testContextProvider() { + void testContextProvider() { ThreadContext.put("loginId", "jdoe"); logger.debug("This is a test"); final List messages = appender.getMessages(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java index 5683f9d5b72..8a93e2b58c0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CronExpressionTest.java @@ -28,10 +28,10 @@ * Class Description goes here. * Created by rgoers on 11/15/15 */ -public class CronExpressionTest { +class CronExpressionTest { @Test - public void testDayOfMonth() throws Exception { + void testDayOfMonth() throws Exception { final CronExpression parser = new CronExpression("0 */15,12 7-11,13-17 * * ?"); final Date date = new GregorianCalendar(2015, 11, 2).getTime(); final Date fireDate = parser.getNextValidTimeAfter(date); @@ -40,7 +40,7 @@ public void testDayOfMonth() throws Exception { } @Test - public void testDayOfWeek() throws Exception { + void testDayOfWeek() throws Exception { final CronExpression parser = new CronExpression("0 */15,12 7-11,13-17 ? * Fri"); final Date date = new GregorianCalendar(2015, 11, 2).getTime(); final Date fireDate = parser.getNextValidTimeAfter(date); @@ -49,7 +49,7 @@ public void testDayOfWeek() throws Exception { } @Test - public void testNextMonth() throws Exception { + void testNextMonth() throws Exception { final CronExpression parser = new CronExpression("0 */15,12 7-11,13-17 1 * ?"); final Date date = new GregorianCalendar(2015, 11, 2).getTime(); final Date fireDate = parser.getNextValidTimeAfter(date); @@ -58,7 +58,7 @@ public void testNextMonth() throws Exception { } @Test - public void testLastDayOfMonth() throws Exception { + void testLastDayOfMonth() throws Exception { final CronExpression parser = new CronExpression("0 */15,12 7-11,13-17 L * ?"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getNextValidTimeAfter(date); @@ -67,7 +67,7 @@ public void testLastDayOfMonth() throws Exception { } @Test - public void testNextDay() throws Exception { + void testNextDay() throws Exception { final CronExpression parser = new CronExpression("0 0 0 * * ?"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getNextValidTimeAfter(date); @@ -76,7 +76,7 @@ public void testNextDay() throws Exception { } @Test - public void testPrevFireTime1() throws Exception { + void testPrevFireTime1() throws Exception { final CronExpression parser = new CronExpression("0 */15,12 7-11,13-17 L * ?"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getPrevFireTime(date); @@ -85,7 +85,7 @@ public void testPrevFireTime1() throws Exception { } @Test - public void testPrevFireTime2() throws Exception { + void testPrevFireTime2() throws Exception { final CronExpression parser = new CronExpression("0 0/5 14,18 * * ?"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getPrevFireTime(date); @@ -97,7 +97,7 @@ public void testPrevFireTime2() throws Exception { * 35,45, and 55 minutes past the hour every hour. */ @Test - public void testPrevFireTime3() throws Exception { + void testPrevFireTime3() throws Exception { final CronExpression parser = new CronExpression("0 35/10 * * * ?"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getPrevFireTime(date); @@ -110,7 +110,7 @@ public void testPrevFireTime3() throws Exception { * 10:15 every day. */ @Test - public void testPrevFireTimeTenFifteen() throws Exception { + void testPrevFireTimeTenFifteen() throws Exception { final CronExpression parser = new CronExpression("0 15 10 * * ? *"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getPrevFireTime(date); @@ -122,7 +122,7 @@ public void testPrevFireTimeTenFifteen() throws Exception { * Every day from 2 pm to 2:59 pm */ @Test - public void testPrevFireTimeTwoPM() throws Exception { + void testPrevFireTimeTwoPM() throws Exception { final CronExpression parser = new CronExpression("0 * 14 * * ?"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getPrevFireTime(date); @@ -134,7 +134,7 @@ public void testPrevFireTimeTwoPM() throws Exception { * 2:10pm and at 2:44pm every Wednesday in the month of March. */ @Test - public void testPrevFireTimeMarch() throws Exception { + void testPrevFireTimeMarch() throws Exception { final CronExpression parser = new CronExpression("0 10,44 14 ? 3 WED"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getPrevFireTime(date); @@ -146,7 +146,7 @@ public void testPrevFireTimeMarch() throws Exception { * Fire at 10:15am on the third Friday of every month. */ @Test - public void testPrevFireTimeThirdFriday() throws Exception { + void testPrevFireTimeThirdFriday() throws Exception { final CronExpression parser = new CronExpression("0 15 10 ? * 6#3"); final Date date = new GregorianCalendar(2015, 10, 2).getTime(); final Date fireDate = parser.getPrevFireTime(date); @@ -159,7 +159,7 @@ public void testPrevFireTimeThirdFriday() throws Exception { * scheduled time. */ @Test - public void testTimeBeforeMilliseconds() throws Exception { + void testTimeBeforeMilliseconds() throws Exception { final CronExpression parser = new CronExpression("0 0 0 * * ?"); final GregorianCalendar cal = new GregorianCalendar(2015, 10, 2, 0, 0, 0); cal.set(Calendar.MILLISECOND, 100); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java index d9fe8c79eff..e1428b33ce2 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/CyclicBufferTest.java @@ -24,10 +24,10 @@ import org.junit.jupiter.api.Test; -public class CyclicBufferTest { +class CyclicBufferTest { @Test - public void testSize0() { + void testSize0() { final CyclicBuffer buffer = new CyclicBuffer<>(Integer.class, 0); assertTrue(buffer.isEmpty()); @@ -47,7 +47,7 @@ public void testSize0() { } @Test - public void testSize1() { + void testSize1() { final CyclicBuffer buffer = new CyclicBuffer<>(Integer.class, 1); assertTrue(buffer.isEmpty()); @@ -68,7 +68,7 @@ public void testSize1() { } @Test - public void testSize3() { + void testSize3() { final CyclicBuffer buffer = new CyclicBuffer<>(Integer.class, 3); assertTrue(buffer.isEmpty()); @@ -89,7 +89,7 @@ public void testSize3() { } @Test - public void testSizeNegative() { + void testSizeNegative() { assertThrows(IllegalArgumentException.class, () -> new CyclicBuffer<>(Integer.class, -1)); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/DummyNanoClockTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/DummyNanoClockTest.java index 48f2147271e..4e4559a52c0 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/DummyNanoClockTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/DummyNanoClockTest.java @@ -23,15 +23,15 @@ /** * Tests the DummyNanoClock. */ -public class DummyNanoClockTest { +class DummyNanoClockTest { @Test - public void testReturnsZeroByDefault() { + void testReturnsZeroByDefault() { assertEquals(0, new DummyNanoClock().nanoTime()); } @Test - public void testReturnsConstructorValue() { + void testReturnsConstructorValue() { assertEquals(123, new DummyNanoClock(123).nanoTime()); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java index 697a8b63992..35ec485703c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/FileUtilsTest.java @@ -36,12 +36,12 @@ /** * Tests the FileUtils class. */ -public class FileUtilsTest { +class FileUtilsTest { private static final String LOG4J_CONFIG_WITH_PLUS = "log4j+config+with+plus+characters.xml"; @Test - public void testFileFromUriWithPlusCharactersInName() throws Exception { + void testFileFromUriWithPlusCharactersInName() throws Exception { final String config = "target/test-classes/log4j+config+with+plus+characters.xml"; final URI uri = new URI(config); final File file = FileUtils.fileFromUri(uri); @@ -50,7 +50,7 @@ public void testFileFromUriWithPlusCharactersInName() throws Exception { } @Test - public void testAbsoluteFileFromUriWithPlusCharactersInName() throws Exception { + void testAbsoluteFileFromUriWithPlusCharactersInName() { final String config = "target/test-classes/log4j+config+with+plus+characters.xml"; final URI uri = new File(config).toURI(); final File file = FileUtils.fileFromUri(uri); @@ -59,7 +59,7 @@ public void testAbsoluteFileFromUriWithPlusCharactersInName() throws Exception { } @Test - public void testAbsoluteFileFromUriWithSpacesInName() throws Exception { + void testAbsoluteFileFromUriWithSpacesInName() { final String config = "target/test-classes/s p a c e s/log4j+config+with+plus+characters.xml"; final URI uri = new File(config).toURI(); final File file = FileUtils.fileFromUri(uri); @@ -68,7 +68,7 @@ public void testAbsoluteFileFromUriWithSpacesInName() throws Exception { } @Test - public void testAbsoluteFileFromJBossVFSUri() throws Exception { + void testAbsoluteFileFromJBossVFSUri() { final String config = "target/test-classes/log4j+config+with+plus+characters.xml"; final String uriStr = new File(config).toURI().toString().replaceAll("^file:", "vfsfile:"); assertTrue(uriStr.startsWith("vfsfile:")); @@ -79,7 +79,7 @@ public void testAbsoluteFileFromJBossVFSUri() throws Exception { } @Test - public void testFileFromUriWithSpacesAndPlusCharactersInName() throws Exception { + void testFileFromUriWithSpacesAndPlusCharactersInName() throws Exception { final String config = "target/test-classes/s%20p%20a%20c%20e%20s/log4j%2Bconfig%2Bwith%2Bplus%2Bcharacters.xml"; final URI uri = new URI(config); final File file = FileUtils.fileFromUri(uri); @@ -93,24 +93,24 @@ class TestMkdir { File testDir; @BeforeEach - public void deleteTestDir() throws IOException { + void deleteTestDir() throws IOException { org.apache.commons.io.FileUtils.deleteDirectory(testDir); } @Test - public void testMkdirDoesntExistDontCreate() { + void testMkdirDoesntExistDontCreate() { assertThrows(IOException.class, () -> FileUtils.mkdir(testDir, false)); } @Test - public void testMkdirFileAlreadyExistsNotDir() throws IOException { + void testMkdirFileAlreadyExistsNotDir() throws IOException { Files.createFile(testDir.toPath()); assertThrows(IOException.class, () -> FileUtils.mkdir(testDir, true)); Files.delete(testDir.toPath()); } @Test - public void testMkdirConcurrent() throws InterruptedException { + void testMkdirConcurrent() throws InterruptedException { final List threads = new ArrayList<>(); final AtomicBoolean anyThreadThrows = new AtomicBoolean(false); for (int i = 0; i < 10000; i++) { diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/InitTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/InitTest.java index ed9321392e7..f239e7a2eed 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/InitTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/InitTest.java @@ -28,16 +28,16 @@ * Test initialization. */ @Disabled -public class InitTest { +class InitTest { @Test - public void initTest() { + void initTest() { final Timer timer = new Timer("Log4j Initialization"); timer.start(); final Logger logger = LogManager.getLogger(); timer.stop(); final long elapsed = timer.getElapsedNanoTime(); - System.out.println(timer.toString()); + System.out.println(timer); assertTrue(elapsed < 1000000000, "Initialization time exceeded threshold; elapsed " + elapsed); } } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java index d189dac9563..ae736d79cbc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/IntegersTest.java @@ -23,16 +23,16 @@ /** * Tests the Integers class. */ -public class IntegersTest { +class IntegersTest { @Test - public void testCeilingNextPowerOfTwoReturnsNextPowerOfTwo() { + void testCeilingNextPowerOfTwoReturnsNextPowerOfTwo() { final int powerOfTwo = Integers.ceilingNextPowerOfTwo(1000); assertEquals(1024, powerOfTwo); } @Test - public void testCeilingNextPowerOfTwoReturnsExactPowerOfTwo() { + void testCeilingNextPowerOfTwoReturnsExactPowerOfTwo() { final int powerOfTwo = Integers.ceilingNextPowerOfTwo(1024); assertEquals(1024, powerOfTwo); } diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java index 5f035e62397..4d64bdac9aa 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java @@ -23,10 +23,10 @@ /** * This class is borrowed from Jackson. */ -public class JsonUtilsTest { +class JsonUtilsTest { @Test - public void testQuoteCharSequenceAsString() throws Exception { + void testQuoteCharSequenceAsString() { final StringBuilder output = new StringBuilder(); final StringBuilder builder = new StringBuilder(); builder.append("foobar"); @@ -41,7 +41,7 @@ public void testQuoteCharSequenceAsString() throws Exception { // For [JACKSON-853] @Test - public void testQuoteLongCharSequenceAsString() throws Exception { + void testQuoteLongCharSequenceAsString() { final StringBuilder output = new StringBuilder(); final StringBuilder input = new StringBuilder(); final StringBuilder sb2 = new StringBuilder(); @@ -57,7 +57,7 @@ public void testQuoteLongCharSequenceAsString() throws Exception { // [JACKSON-884] @Test - public void testCharSequenceWithCtrlChars() throws Exception { + void testCharSequenceWithCtrlChars() { final char[] input = new char[] {0, 1, 2, 3, 4}; final StringBuilder builder = new StringBuilder(); builder.append(input); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java index cf5c677bfc2..06b85795516 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/LoaderTest.java @@ -24,17 +24,17 @@ /** * Tests the Loader class. */ -public class LoaderTest { +class LoaderTest { @Test - public void testLoadClassWithNullClassloaderReturnNull() throws Exception { + void testLoadClassWithNullClassloaderReturnNull() throws Exception { assertNull( Loader.loadClass(Loader.class.getCanonicalName(), null), "Expect null return value for null ClassLoader."); } @Test - public void testLoadClassReturnClassForExistingClass() throws Exception { + void testLoadClassReturnClassForExistingClass() throws Exception { assertEquals( Loader.class, Loader.loadClass(Loader.class.getCanonicalName(), Loader.getClassLoader()), diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java index 23982560fce..9afa5f2069a 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/NetUtilsTest.java @@ -29,10 +29,10 @@ import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; -public class NetUtilsTest { +class NetUtilsTest { @Test - public void testToUriWithoutBackslashes() { + void testToUriWithoutBackslashes() { final String config = "file:///path/to/something/on/unix"; URI uri = NetUtils.toURI(config); @@ -47,7 +47,7 @@ public void testToUriWithoutBackslashes() { } @Test - public void testToUriUnixWithSpaces() { + void testToUriUnixWithSpaces() { final String pathWithSpaces = "/ path / with / spaces"; final URI uri = NetUtils.toURI(pathWithSpaces); @@ -57,7 +57,7 @@ public void testToUriUnixWithSpaces() { @Test @EnabledOnOs(OS.WINDOWS) - public void testToUriWindowsWithBackslashes() { + void testToUriWindowsWithBackslashes() { final String config = "file:///D:\\path\\to\\something/on/windows"; final URI uri = NetUtils.toURI(config); @@ -67,7 +67,7 @@ public void testToUriWindowsWithBackslashes() { @Test @EnabledOnOs(OS.WINDOWS) - public void testToUriWindowsAbsolutePath() { + void testToUriWindowsAbsolutePath() { final String config = "D:\\path\\to\\something\\on\\windows"; final URI uri = NetUtils.toURI(config); @@ -76,7 +76,7 @@ public void testToUriWindowsAbsolutePath() { } @Test - public void testCanonicalHostName() throws UnknownHostException { + void testCanonicalHostName() throws UnknownHostException { assumeThat(InetAddress.getLocalHost().getCanonicalHostName()).contains("."); // If this fails the host might be misconfigured assertThat(NetUtils.getCanonicalLocalHostname()).contains("."); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/OptionConverterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/OptionConverterTest.java index a0926f995b1..f4234e43adc 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/OptionConverterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/OptionConverterTest.java @@ -24,10 +24,10 @@ /** * Tests {@link OptionConverter}. */ -public class OptionConverterTest { +class OptionConverterTest { @Test - public void testSubstVars() { + void testSubstVars() { final Properties props = new Properties(); props.setProperty("key", "${key}"); props.setProperty("testKey", "Log4j"); @@ -43,7 +43,7 @@ public void testSubstVars() { * Verify that substVars doesn't construct dynamic keys. */ @Test - public void testAppend() { + void testAppend() { final Properties props = new Properties(); props.setProperty("key", "Key"); props.setProperty("testKey", "Hello"); @@ -55,7 +55,7 @@ public void testAppend() { * Verify that substVars will treat the second expression up to the first '}' as part of the key. */ @Test - public void testAppend2() { + void testAppend2() { final Properties props = new Properties(); props.setProperty("test${key", "Hello"); assertEquals( @@ -63,7 +63,7 @@ public void testAppend2() { } @Test - public void testRecursion() { + void testRecursion() { final Properties props = new RecursiveProperties(); props.setProperty("name", "Neo"); props.setProperty("greeting", "Hello ${name}"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java index ccdcf12d17d..55f52d79bca 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistryTest.java @@ -35,23 +35,23 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class ShutdownCallbackRegistryTest { +class ShutdownCallbackRegistryTest { @BeforeAll - public static void setUpClass() { + static void setUpClass() { System.setProperty("log4j2.shutdownHookEnabled", "true"); System.setProperty(ShutdownCallbackRegistry.SHUTDOWN_CALLBACK_REGISTRY, Registry.class.getName()); } @AfterAll - public static void afterClass() { + static void afterClass() { System.clearProperty(ShutdownCallbackRegistry.SHUTDOWN_CALLBACK_REGISTRY); System.clearProperty("log4j2.shutdownHookEnabled"); } @Test @LoggerContextSource("ShutdownCallbackRegistryTest.xml") - public void testShutdownCallbackRegistry(final LoggerContext context) { + void testShutdownCallbackRegistry(final LoggerContext context) { assertTrue(context.isStarted(), "LoggerContext should be started"); assertThat(Registry.CALLBACKS, hasSize(1)); Registry.shutdown(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SourceTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SourceTest.java index 1a6c512e3d6..4d2db85972c 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SourceTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SourceTest.java @@ -16,7 +16,8 @@ */ package org.apache.logging.log4j.core.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.File; import java.net.MalformedURLException; @@ -30,17 +31,17 @@ /** * Tests {@link Source}. */ -public class SourceTest { +class SourceTest { @Test - public void testEqualityFile() { + void testEqualityFile() { assertEquals(new Source(new File("foo")), new Source(new File("foo"))); assertEquals(new Source(new File("foo")), new Source(new File("./foo"))); assertEquals(new Source(new File("foo.txt")), new Source(new File("./foo.txt"))); } @Test - public void testEqualityPath() { + void testEqualityPath() { assertEquals(new Source(Paths.get("foo")), new Source(Paths.get("foo"))); assertEquals(new Source(Paths.get("foo")), new Source(Paths.get("./foo"))); assertEquals(new Source(Paths.get("foo.txt")), new Source(Paths.get("./foo.txt"))); @@ -48,14 +49,14 @@ public void testEqualityPath() { @Test @Disabled("File URI is broken.") - public void testEqualityURIFile() { + void testEqualityURIFile() { assertEquals( new Source(Paths.get("foo").toUri()), new Source(Paths.get("./foo").toUri())); } @Test - public void testEqualityURIHttp() { + void testEqualityURIHttp() { assertEquals( new Source(URI.create("http://www.apache.org/index.html")), new Source(URI.create("http://www.apache.org/index.html"))); @@ -66,13 +67,17 @@ public void testEqualityURIHttp() { new Source(URI.create("http://www.apache.org/./././."))); } - public void testEqualityURLFile() throws MalformedURLException { + @Test + @Disabled + void testEqualityURLFile() throws MalformedURLException { assertEquals( new Source(Paths.get("foo").toUri().toURL()), new Source(Paths.get("./foo").toUri().toURL())); } - public void testEqualityURLHttp() throws MalformedURLException { + @Test + @Disabled + void testEqualityURLHttp() throws MalformedURLException { assertEquals( new Source(URI.create("http://www.apache.org/index.html").toURL()), new Source(URI.create("http://www.apache.org/index.html").toURL())); @@ -84,7 +89,9 @@ public void testEqualityURLHttp() throws MalformedURLException { new Source(URI.create("http://www.apache.org/./././.").toURL())); } - public void testEqualityURLHttps() throws MalformedURLException { + @Test + @Disabled + void testEqualityURLHttps() throws MalformedURLException { assertEquals( new Source(URI.create("https://www.apache.org/index.html").toURL()), new Source(URI.create("https://www.apache.org/index.html").toURL())); @@ -97,7 +104,7 @@ public void testEqualityURLHttps() throws MalformedURLException { } @Test - public void testFileConstructor() { + void testFileConstructor() { final Path path = Paths.get("foo"); final URI uri = path.toUri(); final File file = path.toFile(); @@ -109,7 +116,7 @@ public void testFileConstructor() { } @Test - public void testPathStringConstructor() { + void testPathStringConstructor() { final Path path = Paths.get("foo"); final URI uri = path.toUri(); final File file = path.toFile(); @@ -120,7 +127,8 @@ public void testPathStringConstructor() { assertEquals(uri, source.getURI()); } - public void testPathURIFileConstructor() { + @Test + void testPathURIFileConstructor() { final Path path = Paths.get(URI.create("file:///C:/foo")); final URI uri = path.toUri(); final File file = path.toFile(); @@ -132,7 +140,7 @@ public void testPathURIFileConstructor() { } @Test - public void testURIConstructor() throws MalformedURLException { + void testURIConstructor() { final Path path = Paths.get("foo"); final URI uri = path.toUri(); final File file = path.toFile(); @@ -143,7 +151,7 @@ public void testURIConstructor() throws MalformedURLException { } @Test - public void testURIFileConstructor() throws MalformedURLException { + void testURIFileConstructor() { final URI uri = URI.create("file:///C:/foo"); final Path path = Paths.get(uri); final File file = path.toFile(); @@ -153,23 +161,23 @@ public void testURIFileConstructor() throws MalformedURLException { } @Test - public void testURIHttpConstructor() throws MalformedURLException { + void testURIHttpConstructor() { final URI uri = URI.create("http://www.apache.org"); final Source source = new Source(uri); - assertEquals(null, source.getFile()); + assertNull(source.getFile()); assertEquals(uri.toString(), source.getLocation()); } @Test - public void testURIHttpsConstructor() throws MalformedURLException { + void testURIHttpsConstructor() { final URI uri = URI.create("https://www.apache.org"); final Source source = new Source(uri); - assertEquals(null, source.getFile()); + assertNull(source.getFile()); assertEquals(uri.toString(), source.getLocation()); } @Test - public void testURLConstructor() throws MalformedURLException { + void testURLConstructor() throws MalformedURLException { final Path path = Paths.get("foo"); final File file = path.toFile(); final URI uri = path.toUri(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemClockTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemClockTest.java index 06fe0ea2ebf..c1441f9e473 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemClockTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemClockTest.java @@ -20,10 +20,10 @@ import org.junit.jupiter.api.Test; -public class SystemClockTest { +class SystemClockTest { @Test - public void testLessThan2Millis() { + void testLessThan2Millis() { final long millis1 = new SystemClock().currentTimeMillis(); final long sysMillis = System.currentTimeMillis(); @@ -33,7 +33,7 @@ public void testLessThan2Millis() { } @Test - public void testAfterWaitStillLessThan2Millis() throws Exception { + void testAfterWaitStillLessThan2Millis() throws Exception { Thread.sleep(100); final long millis1 = new SystemClock().currentTimeMillis(); final long sysMillis = System.currentTimeMillis(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemNanoClockTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemNanoClockTest.java index 854e169b2a5..3e4d4427540 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemNanoClockTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/SystemNanoClockTest.java @@ -24,10 +24,10 @@ /** * Tests the SystemNanoClock. */ -public class SystemNanoClockTest { +class SystemNanoClockTest { @Test - public void testReturnsSystemNanoTime() { + void testReturnsSystemNanoTime() { final NanoClock clock = new SystemNanoClock(); final long expected = System.nanoTime(); final long actual = clock.nanoTime(); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java index 24b384fff52..be7c214779b 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/UuidTest.java @@ -22,7 +22,7 @@ import java.util.UUID; import org.junit.jupiter.api.Test; -public class UuidTest { +class UuidTest { private static final int COUNT = 200; private static final int THREADS = 10; @@ -30,7 +30,7 @@ public class UuidTest { private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; @Test - public void testTimeBaseUuid() { + void testTimeBaseUuid() { final UUID uuid = UuidUtil.getTimeBasedUuid(); // final UUID uuid2 = UuidUtil.getTimeBasedUUID(); // unused final long current = (System.currentTimeMillis() * 10000) + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH; @@ -62,7 +62,7 @@ public void testTimeBaseUuid() { } @Test - public void testInitialize() { + void testInitialize() { // Test if no ArrayIndexOutOfBoundsException is thrown when Mac address array is null UuidUtil.initialize(null); @@ -78,7 +78,7 @@ public void testInitialize() { } @Test - public void testThreads() throws Exception { + void testThreads() throws Exception { final Thread[] threads = new Thread[THREADS]; final UUID[] uuids = new UUID[COUNT * THREADS]; final long[] elapsed = new long[THREADS]; diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java index 50f61c6c968..5a30ab65420 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormatTest.java @@ -48,7 +48,7 @@ * Tests {@link FixedDateFormat}. */ @ResourceLock(value = Resources.LOCALE, mode = ResourceAccessMode.READ) -public class FixedDateFormatTest { +class FixedDateFormatTest { private boolean containsNanos(final FixedFormat fixedFormat) { final String pattern = fixedFormat.getPattern(); @@ -56,50 +56,50 @@ private boolean containsNanos(final FixedFormat fixedFormat) { } @Test - public void testConstructorDisallowsNullFormat() { + void testConstructorDisallowsNullFormat() { assertThrows(NullPointerException.class, () -> new FixedDateFormat(null, TimeZone.getDefault())); } @Test - public void testConstructorDisallowsNullTimeZone() { + void testConstructorDisallowsNullTimeZone() { assertThrows(NullPointerException.class, () -> new FixedDateFormat(FixedFormat.ABSOLUTE, null)); } @Test - public void testCreateIfSupported_customTimeZoneIfOptionsArrayWithTimeZoneElement() { + void testCreateIfSupported_customTimeZoneIfOptionsArrayWithTimeZoneElement() { final FixedDateFormat fmt = FixedDateFormat.createIfSupported(DEFAULT.getPattern(), "GMT+08:00", ""); assertEquals(DEFAULT.getPattern(), fmt.getFormat()); assertEquals(TimeZone.getTimeZone("GMT+08:00"), fmt.getTimeZone()); } @Test - public void testCreateIfSupported_defaultIfOptionsArrayEmpty() { + void testCreateIfSupported_defaultIfOptionsArrayEmpty() { final FixedDateFormat fmt = FixedDateFormat.createIfSupported(Strings.EMPTY_ARRAY); assertEquals(DEFAULT.getPattern(), fmt.getFormat()); } @Test - public void testCreateIfSupported_defaultIfOptionsArrayNull() { + void testCreateIfSupported_defaultIfOptionsArrayNull() { final FixedDateFormat fmt = FixedDateFormat.createIfSupported((String[]) null); assertEquals(DEFAULT.getPattern(), fmt.getFormat()); } @Test - public void testCreateIfSupported_defaultIfOptionsArrayWithSingleNullElement() { + void testCreateIfSupported_defaultIfOptionsArrayWithSingleNullElement() { final FixedDateFormat fmt = FixedDateFormat.createIfSupported(new String[1]); assertEquals(DEFAULT.getPattern(), fmt.getFormat()); assertEquals(TimeZone.getDefault(), fmt.getTimeZone()); } @Test - public void testCreateIfSupported_defaultTimeZoneIfOptionsArrayWithSecondNullElement() { + void testCreateIfSupported_defaultTimeZoneIfOptionsArrayWithSecondNullElement() { final FixedDateFormat fmt = FixedDateFormat.createIfSupported(DEFAULT.getPattern(), null, ""); assertEquals(DEFAULT.getPattern(), fmt.getFormat()); assertEquals(TimeZone.getDefault(), fmt.getTimeZone()); } @Test - public void testCreateIfSupported_nonNullIfNameMatches() { + void testCreateIfSupported_nonNullIfNameMatches() { for (final FixedDateFormat.FixedFormat format : FixedDateFormat.FixedFormat.values()) { final String[] options = {format.name()}; assertNotNull(FixedDateFormat.createIfSupported(options), format.name()); @@ -107,7 +107,7 @@ public void testCreateIfSupported_nonNullIfNameMatches() { } @Test - public void testCreateIfSupported_nonNullIfPatternMatches() { + void testCreateIfSupported_nonNullIfPatternMatches() { for (final FixedDateFormat.FixedFormat format : FixedDateFormat.FixedFormat.values()) { final String[] options = {format.getPattern()}; assertNotNull(FixedDateFormat.createIfSupported(options), format.name()); @@ -115,19 +115,19 @@ public void testCreateIfSupported_nonNullIfPatternMatches() { } @Test - public void testCreateIfSupported_nullIfNameDoesNotMatch() { + void testCreateIfSupported_nullIfNameDoesNotMatch() { final String[] options = {"DEFAULT3"}; assertNull(FixedDateFormat.createIfSupported(options), "DEFAULT3"); } @Test - public void testCreateIfSupported_nullIfPatternDoesNotMatch() { + void testCreateIfSupported_nullIfPatternDoesNotMatch() { final String[] options = {"y M d H m s"}; assertNull(FixedDateFormat.createIfSupported(options), "y M d H m s"); } @Test - public void testDaylightSavingToSummerTime() throws Exception { + void testDaylightSavingToSummerTime() throws Exception { final Calendar calendar = Calendar.getInstance(); calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse("2017-03-12 00:00:00 UTC")); @@ -192,7 +192,7 @@ public void testDaylightSavingToSummerTime() throws Exception { } @Test - public void testDaylightSavingToWinterTime() throws Exception { + void testDaylightSavingToWinterTime() throws Exception { final Calendar calendar = Calendar.getInstance(); calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse("2017-11-05 00:00:00 UTC")); @@ -259,31 +259,31 @@ public void testDaylightSavingToWinterTime() throws Exception { } @Test - public void testFixedFormat_getDatePatternLengthReturnsDatePatternLength() { + void testFixedFormat_getDatePatternLengthReturnsDatePatternLength() { assertEquals("yyyyMMdd".length(), FixedFormat.COMPACT.getDatePatternLength()); assertEquals("yyyy-MM-dd ".length(), DEFAULT.getDatePatternLength()); } @Test - public void testFixedFormat_getDatePatternLengthZeroIfNoDateInPattern() { + void testFixedFormat_getDatePatternLengthZeroIfNoDateInPattern() { assertEquals(0, FixedFormat.ABSOLUTE.getDatePatternLength()); assertEquals(0, FixedFormat.ABSOLUTE_PERIOD.getDatePatternLength()); } @Test - public void testFixedFormat_getDatePatternNullIfNoDateInPattern() { + void testFixedFormat_getDatePatternNullIfNoDateInPattern() { assertNull(FixedFormat.ABSOLUTE.getDatePattern()); assertNull(FixedFormat.ABSOLUTE_PERIOD.getDatePattern()); } @Test - public void testFixedFormat_getDatePatternReturnsDatePatternIfExists() { + void testFixedFormat_getDatePatternReturnsDatePatternIfExists() { assertEquals("yyyyMMdd", FixedFormat.COMPACT.getDatePattern()); assertEquals("yyyy-MM-dd ", DEFAULT.getDatePattern()); } @Test - public void testFixedFormat_getFastDateFormatNonNullIfDateInPattern() { + void testFixedFormat_getFastDateFormatNonNullIfDateInPattern() { assertNotNull(FixedFormat.COMPACT.getFastDateFormat()); assertNotNull(DEFAULT.getFastDateFormat()); assertEquals("yyyyMMdd", FixedFormat.COMPACT.getFastDateFormat().getPattern()); @@ -291,13 +291,13 @@ public void testFixedFormat_getFastDateFormatNonNullIfDateInPattern() { } @Test - public void testFixedFormat_getFastDateFormatNullIfNoDateInPattern() { + void testFixedFormat_getFastDateFormatNullIfNoDateInPattern() { assertNull(FixedFormat.ABSOLUTE.getFastDateFormat()); assertNull(FixedFormat.ABSOLUTE_PERIOD.getFastDateFormat()); } @Test - public void testFormatLong() { + void testFormatLong() { final long now = System.currentTimeMillis(); final long start = now - TimeUnit.HOURS.toMillis(25); final long end = now + TimeUnit.HOURS.toMillis(25); @@ -317,7 +317,7 @@ public void testFormatLong() { } @Test - public void testFormatLong_goingBackInTime() { + void testFormatLong_goingBackInTime() { final long now = System.currentTimeMillis(); final long start = now - TimeUnit.HOURS.toMillis(25); final long end = now + TimeUnit.HOURS.toMillis(25); @@ -342,7 +342,7 @@ public void testFormatLong_goingBackInTime() { * Daylight Savings started on : 02:00 AM */ @Test - public void testFormatLong_goingBackInTime_DST() { + void testFormatLong_goingBackInTime_DST() { final Calendar instance = Calendar.getInstance(TimeZone.getTimeZone("EST")); instance.set(2017, 2, 12, 2, 0); final long now = instance.getTimeInMillis(); @@ -365,7 +365,7 @@ public void testFormatLong_goingBackInTime_DST() { } @Test - public void testFormatLongCharArrayInt() { + void testFormatLongCharArrayInt() { final long now = System.currentTimeMillis(); final long start = now - TimeUnit.HOURS.toMillis(25); final long end = now + TimeUnit.HOURS.toMillis(25); @@ -389,7 +389,7 @@ public void testFormatLongCharArrayInt() { } @Test - public void testFormatLongCharArrayInt_goingBackInTime() { + void testFormatLongCharArrayInt_goingBackInTime() { final long now = System.currentTimeMillis(); final long start = now - TimeUnit.HOURS.toMillis(25); final long end = now + TimeUnit.HOURS.toMillis(25); @@ -414,7 +414,7 @@ public void testFormatLongCharArrayInt_goingBackInTime() { } @Test - public void testGetFormatReturnsConstructorFixedFormatPattern() { + void testGetFormatReturnsConstructorFixedFormatPattern() { final FixedDateFormat format = new FixedDateFormat(FixedDateFormat.FixedFormat.ABSOLUTE, TimeZone.getDefault()); assertSame(FixedDateFormat.FixedFormat.ABSOLUTE.getPattern(), format.getFormat()); } @@ -422,7 +422,7 @@ public void testGetFormatReturnsConstructorFixedFormatPattern() { @ParameterizedTest @MethodSource("org.apache.logging.log4j.core.util.datetime.FixedDateFormat$FixedFormat#values") @DefaultLocale(language = "en") - public void testFixedFormatLength(FixedFormat format) { + void testFixedFormatLength(FixedFormat format) { LocalDate date = LocalDate.of(2023, 4, 8); LocalTime time = LocalTime.of(19, 5, 14); ZoneId zone = ZoneId.of("Europe/Warsaw"); diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/internal/instant/InstantPatternDynamicFormatterTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/internal/instant/InstantPatternDynamicFormatterTest.java index ddb8c311039..210689fe356 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/internal/instant/InstantPatternDynamicFormatterTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/internal/instant/InstantPatternDynamicFormatterTest.java @@ -42,7 +42,7 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; -public class InstantPatternDynamicFormatterTest { +class InstantPatternDynamicFormatterTest { @ParameterizedTest @MethodSource("sequencingTestCases") diff --git a/log4j-core-test/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java b/log4j-core-test/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java index ad594cbddd5..b0ad37ffb3e 100644 --- a/log4j-core-test/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java +++ b/log4j-core-test/src/test/java/org/apache/logging/log4j/message/MutableLogEventWithReusableParamMsgTest.java @@ -26,9 +26,9 @@ * LOG4J2-1409 */ // test must be in log4j-core but in org.apache.logging.log4j.message package because it calls package-private methods -public class MutableLogEventWithReusableParamMsgTest { +class MutableLogEventWithReusableParamMsgTest { @Test - public void testInteractionWithReusableParameterizedMessage() { + void testInteractionWithReusableParameterizedMessage() { final MutableLogEvent evt = new MutableLogEvent(); final ReusableParameterizedMessage msg = new ReusableParameterizedMessage(); msg.set("Hello {} {} {}", 1, 2, 3); diff --git a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/AbstractStreamTest.java b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/AbstractStreamTest.java index 8554e51d320..53c8bc39388 100644 --- a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/AbstractStreamTest.java +++ b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/AbstractStreamTest.java @@ -16,9 +16,9 @@ */ package org.apache.logging.log4j.io; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import java.util.List; import org.apache.logging.log4j.Level; diff --git a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/IoBuilderTest.java b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/IoBuilderTest.java index eae8b096aa0..d8cebb24b0b 100644 --- a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/IoBuilderTest.java +++ b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/IoBuilderTest.java @@ -16,11 +16,11 @@ */ package org.apache.logging.log4j.io; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; import java.io.PrintStream; import java.util.List; @@ -35,7 +35,7 @@ public class IoBuilderTest { public static LoggerContextRule context = new LoggerContextRule("log4j2-streams-calling-info.xml"); @Test - public void testNoArgBuilderCallerClassInfo() throws Exception { + public void testNoArgBuilderCallerClassInfo() { try (final PrintStream ps = IoBuilder.forLogger().buildPrintStream()) { ps.println("discarded"); final ListAppender app = context.getListAppender("IoBuilderTest"); diff --git a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamCallerInfoTest.java b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamCallerInfoTest.java index 4e69e64f4e9..60f7770b5f6 100644 --- a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamCallerInfoTest.java +++ b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamCallerInfoTest.java @@ -27,7 +27,7 @@ public class LoggerPrintStreamCallerInfoTest extends IoBuilderCallerInfoTesting private PrintStream logOut; @Test - public void close() throws Exception { + public void close() { this.logOut.print("a\nb"); assertMessages("before close size", 1, "close"); this.logOut.close(); @@ -35,7 +35,7 @@ public void close() throws Exception { } @Test - public void print_boolean() throws Exception { + public void print_boolean() { this.logOut.print(true); assertMessages("print", 0, "print_boolean"); this.logOut.println(true); @@ -43,7 +43,7 @@ public void print_boolean() throws Exception { } @Test - public void print_char() throws Exception { + public void print_char() { this.logOut.print('a'); assertMessages("print", 0, "print_char"); this.logOut.println('b'); @@ -51,7 +51,7 @@ public void print_char() throws Exception { } @Test - public void print_chararray() throws Exception { + public void print_chararray() { this.logOut.print("a".toCharArray()); assertMessages("print", 0, "print_chararray"); this.logOut.println("b".toCharArray()); @@ -59,7 +59,7 @@ public void print_chararray() throws Exception { } @Test - public void print_double() throws Exception { + public void print_double() { this.logOut.print(1D); assertMessages("print", 0, "print_double"); this.logOut.println(2D); @@ -67,7 +67,7 @@ public void print_double() throws Exception { } @Test - public void print_float() throws Exception { + public void print_float() { this.logOut.print(1f); assertMessages("print", 0, "print_float"); this.logOut.println(2f); @@ -75,7 +75,7 @@ public void print_float() throws Exception { } @Test - public void print_int() throws Exception { + public void print_int() { this.logOut.print(1); assertMessages("print", 0, "print_int"); this.logOut.println(2); @@ -83,7 +83,7 @@ public void print_int() throws Exception { } @Test - public void print_long() throws Exception { + public void print_long() { this.logOut.print(1L); assertMessages("print", 0, "print_long"); this.logOut.println(2L); @@ -91,7 +91,7 @@ public void print_long() throws Exception { } @Test - public void print_object() throws Exception { + public void print_object() { this.logOut.print((Object) 'a'); assertMessages("print", 0, "print_object"); this.logOut.println((Object) 'b'); @@ -99,19 +99,19 @@ public void print_object() throws Exception { } @Test - public void print_printf() throws Exception { + public void print_printf() { this.logOut.printf("a\n"); assertMessages("println", 1, "print_printf"); } @Test - public void print_printf_locale() throws Exception { + public void print_printf_locale() { this.logOut.printf(Locale.getDefault(), "a\n"); assertMessages("println", 1, "print_printf_locale"); } @Test - public void print_string() throws Exception { + public void print_string() { this.logOut.print("a"); assertMessages("print", 0, "print_string"); this.logOut.println("b"); @@ -130,13 +130,13 @@ public void write_bytes() throws Exception { } @Test - public void write_bytes_offset() throws Exception { + public void write_bytes_offset() { this.logOut.write("c\n".getBytes(), 0, 2); assertMessages("write", 1, "write_bytes_offset"); } @Test - public void write_int() throws Exception { + public void write_int() { this.logOut.write('a'); assertMessages("write int", 0, "write_int"); this.logOut.write('\n'); diff --git a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamTest.java b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamTest.java index ac63d0280d1..48f3a7cec32 100644 --- a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamTest.java +++ b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintStreamTest.java @@ -41,7 +41,7 @@ protected OutputStream createOutputStreamWrapper() { } @Test - public void testFormat() throws Exception { + public void testFormat() { assertSame(this.print, this.print.format("[%s]", FIRST)); assertMessages(); this.print.println(); @@ -50,7 +50,7 @@ public void testFormat() throws Exception { } @Test - public void testPrint_boolean() throws Exception { + public void testPrint_boolean() { this.print.print(true); assertMessages(); this.print.println(); @@ -59,7 +59,7 @@ public void testPrint_boolean() throws Exception { } @Test - public void testPrint_char() throws Exception { + public void testPrint_char() { for (final char c : FIRST.toCharArray()) { this.print.print(c); assertMessages(); @@ -70,7 +70,7 @@ public void testPrint_char() throws Exception { } @Test - public void testPrint_CharacterArray() throws Exception { + public void testPrint_CharacterArray() { this.print.print(FIRST.toCharArray()); assertMessages(); this.print.println(); @@ -79,7 +79,7 @@ public void testPrint_CharacterArray() throws Exception { } @Test - public void testPrint_int() throws Exception { + public void testPrint_int() { this.print.print(12); assertMessages(); this.print.println(); @@ -88,7 +88,7 @@ public void testPrint_int() throws Exception { } @Test - public void testPrint_long() throws Exception { + public void testPrint_long() { this.print.print(12L); assertMessages(); this.print.println(); @@ -97,7 +97,7 @@ public void testPrint_long() throws Exception { } @Test - public void testPrint_Object() throws Exception { + public void testPrint_Object() { this.print.print((Object) FIRST); assertMessages(); this.print.println(); @@ -106,7 +106,7 @@ public void testPrint_Object() throws Exception { } @Test - public void testPrint_String() throws Exception { + public void testPrint_String() { this.print.print(FIRST); assertMessages(); this.print.println(); @@ -115,7 +115,7 @@ public void testPrint_String() throws Exception { } @Test - public void testPrintf() throws Exception { + public void testPrintf() { assertSame(this.print, this.print.printf("<<<%s>>>", FIRST)); assertMessages(); this.print.println(); diff --git a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterCallerInfoTest.java b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterCallerInfoTest.java index cf1f601ba86..8225c0ddaea 100644 --- a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterCallerInfoTest.java +++ b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterCallerInfoTest.java @@ -27,7 +27,7 @@ public class LoggerPrintWriterCallerInfoTest extends IoBuilderCallerInfoTesting private PrintWriter logOut; @Test - public void close() throws Exception { + public void close() { this.logOut.print("a\nb"); assertMessages("before close size", 1, "close"); this.logOut.close(); @@ -35,7 +35,7 @@ public void close() throws Exception { } @Test - public void print_boolean() throws Exception { + public void print_boolean() { this.logOut.print(true); assertMessages("print", 0, "print_boolean"); this.logOut.println(true); @@ -43,7 +43,7 @@ public void print_boolean() throws Exception { } @Test - public void print_char() throws Exception { + public void print_char() { this.logOut.print('a'); assertMessages("print", 0, "print_char"); this.logOut.println('b'); @@ -51,7 +51,7 @@ public void print_char() throws Exception { } @Test - public void print_chararray() throws Exception { + public void print_chararray() { this.logOut.print("a".toCharArray()); assertMessages("print", 0, "print_chararray"); this.logOut.println("b".toCharArray()); @@ -59,7 +59,7 @@ public void print_chararray() throws Exception { } @Test - public void print_double() throws Exception { + public void print_double() { this.logOut.print(1D); assertMessages("print", 0, "print_double"); this.logOut.println(2D); @@ -67,7 +67,7 @@ public void print_double() throws Exception { } @Test - public void print_float() throws Exception { + public void print_float() { this.logOut.print(1f); assertMessages("print", 0, "print_float"); this.logOut.println(2f); @@ -75,7 +75,7 @@ public void print_float() throws Exception { } @Test - public void print_int() throws Exception { + public void print_int() { this.logOut.print(1); assertMessages("print", 0, "print_int"); this.logOut.println(2); @@ -83,7 +83,7 @@ public void print_int() throws Exception { } @Test - public void print_long() throws Exception { + public void print_long() { this.logOut.print(1L); assertMessages("print", 0, "print_long"); this.logOut.println(2L); @@ -91,7 +91,7 @@ public void print_long() throws Exception { } @Test - public void print_object() throws Exception { + public void print_object() { this.logOut.print((Object) 'a'); assertMessages("print", 0, "print_object"); this.logOut.println((Object) 'b'); @@ -99,19 +99,19 @@ public void print_object() throws Exception { } @Test - public void print_printf() throws Exception { + public void print_printf() { this.logOut.printf("a\n"); assertMessages("println", 1, "print_printf"); } @Test - public void print_printf_locale() throws Exception { + public void print_printf_locale() { this.logOut.printf(Locale.getDefault(), "a\n"); assertMessages("println", 1, "print_printf_locale"); } @Test - public void print_string() throws Exception { + public void print_string() { this.logOut.print("a"); assertMessages("print", 0, "print_string"); this.logOut.println("b"); @@ -124,19 +124,19 @@ public void setupStreams() { } @Test - public void write_bytes() throws Exception { + public void write_bytes() { this.logOut.write("b\n".toCharArray()); assertMessages("write", 1, "write_bytes"); } @Test - public void write_bytes_offset() throws Exception { + public void write_bytes_offset() { this.logOut.write("c\n".toCharArray(), 0, 2); assertMessages("write", 1, "write_bytes_offset"); } @Test - public void write_int() throws Exception { + public void write_int() { this.logOut.write('a'); assertMessages("write int", 0, "write_int"); this.logOut.write('\n'); diff --git a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterJdbcH2Test.java b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterJdbcH2Test.java index 262623a79b8..11d72ff2167 100644 --- a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterJdbcH2Test.java +++ b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterJdbcH2Test.java @@ -61,7 +61,7 @@ private void setListAppender(final ListAppender listAppender) { } @Before - public void setUp() throws Exception { + public void setUp() { this.setListAppender(context.getListAppender("List").clear()); Assert.assertEquals(0, this.getListAppender().getMessages().size()); } @@ -78,7 +78,7 @@ public void testDataSource_setLogWriter() throws SQLException { try (final Connection conn = dataSource.getConnection()) { conn.prepareCall("select 1"); } - Assert.assertTrue(this.getListAppender().getMessages().size() > 0); + Assert.assertTrue(!this.getListAppender().getMessages().isEmpty()); } @Test @@ -90,6 +90,6 @@ public void testDriverManager_setLogWriter() throws SQLException { } finally { DriverManager.setLogWriter(null); } - Assert.assertTrue(this.getListAppender().getMessages().size() > 0); + Assert.assertTrue(!this.getListAppender().getMessages().isEmpty()); } } diff --git a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterTest.java b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterTest.java index 6c0f29c68cd..6375e6d1620 100644 --- a/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterTest.java +++ b/log4j-iostreams/src/test/java/org/apache/logging/log4j/io/LoggerPrintWriterTest.java @@ -42,7 +42,7 @@ protected Writer createWriterWrapper() { } @Test - public void testFormat() throws Exception { + public void testFormat() { assertSame(this.print, this.print.format("[%s]", FIRST)); assertMessages(); this.print.println(); @@ -51,7 +51,7 @@ public void testFormat() throws Exception { } @Test - public void testPrint_boolean() throws Exception { + public void testPrint_boolean() { this.print.print(true); assertMessages(); this.print.println(); @@ -60,7 +60,7 @@ public void testPrint_boolean() throws Exception { } @Test - public void testPrint_char() throws Exception { + public void testPrint_char() { for (final char c : FIRST.toCharArray()) { this.print.print(c); assertMessages(); @@ -71,7 +71,7 @@ public void testPrint_char() throws Exception { } @Test - public void testPrint_CharacterArray() throws Exception { + public void testPrint_CharacterArray() { this.print.print(FIRST.toCharArray()); assertMessages(); this.print.println(); @@ -80,7 +80,7 @@ public void testPrint_CharacterArray() throws Exception { } @Test - public void testPrint_int() throws Exception { + public void testPrint_int() { this.print.print(12); assertMessages(); this.print.println(); @@ -89,7 +89,7 @@ public void testPrint_int() throws Exception { } @Test - public void testPrint_long() throws Exception { + public void testPrint_long() { this.print.print(12L); assertMessages(); this.print.println(); @@ -98,7 +98,7 @@ public void testPrint_long() throws Exception { } @Test - public void testPrint_Object() throws Exception { + public void testPrint_Object() { this.print.print((Object) FIRST); assertMessages(); this.print.println(); @@ -107,7 +107,7 @@ public void testPrint_Object() throws Exception { } @Test - public void testPrint_String() throws Exception { + public void testPrint_String() { this.print.print(FIRST); assertMessages(); this.print.println(); @@ -116,7 +116,7 @@ public void testPrint_String() throws Exception { } @Test - public void testPrintf() throws Exception { + public void testPrintf() { assertSame(this.print, this.print.printf("<<<%s>>>", FIRST)); assertMessages(); this.print.println(); diff --git a/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderAsyncTest.java b/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderAsyncTest.java index f460c5c6079..19c291843e3 100644 --- a/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderAsyncTest.java +++ b/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderAsyncTest.java @@ -33,32 +33,32 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class SmtpAppenderAsyncTest { +class SmtpAppenderAsyncTest { private static int PORT; private SimpleSmtpServer smtpServer; @BeforeAll - public static void setupAll() { + static void setupAll() { PORT = AvailablePortFinder.getNextAvailable(); System.setProperty("smtp.port", String.valueOf(PORT)); } @BeforeEach - public void setup() { + void setup() { smtpServer = SimpleSmtpServer.start(PORT); } @Test @LoggerContextSource("SmtpAppenderAsyncTest.xml") - public void testSync(final LoggerContext ctx) { + void testSync(final LoggerContext ctx) { testSmtpAppender(ctx.getLogger("sync"), ctx); } @Test @LoggerContextSource("SmtpAppenderAsyncTest.xml") - public void testAsync(final LoggerContext ctx) { + void testAsync(final LoggerContext ctx) { testSmtpAppender(ctx.getLogger("async"), ctx); } @@ -83,14 +83,14 @@ private void testSmtpAppender(final Logger logger, final LoggerContext ctx) { } @AfterEach - public void teardown() { + void teardown() { if (smtpServer != null) { smtpServer.stop(); } } @AfterAll - public static void teardownAll() { + static void teardownAll() { System.clearProperty("smtp.port"); } } diff --git a/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderTest.java b/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderTest.java index 152fab22e83..2250a04e934 100644 --- a/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderTest.java +++ b/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpAppenderTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -40,12 +41,12 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Smtp") -public class SmtpAppenderTest { +class SmtpAppenderTest { private static final String HOST = "localhost"; @Test - public void testMessageFactorySetFrom() throws MessagingException { + void testMessageFactorySetFrom() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String address = "testing@example.com"; @@ -65,7 +66,7 @@ public void testMessageFactorySetFrom() throws MessagingException { } @Test - public void testMessageFactorySetReplyTo() throws MessagingException { + void testMessageFactorySetReplyTo() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String addresses = "testing1@example.com,testing2@example.com"; @@ -79,7 +80,7 @@ public void testMessageFactorySetReplyTo() throws MessagingException { } @Test - public void testMessageFactorySetRecipients() throws MessagingException { + void testMessageFactorySetRecipients() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String addresses = "testing1@example.com,testing2@example.com"; @@ -93,7 +94,7 @@ public void testMessageFactorySetRecipients() throws MessagingException { } @Test - public void testMessageFactorySetSubject() throws MessagingException { + void testMessageFactorySetSubject() throws MessagingException { final MimeMessageBuilder builder = new MimeMessageBuilder(null); final String subject = "Test Subject"; @@ -107,7 +108,7 @@ public void testMessageFactorySetSubject() throws MessagingException { } @Test - public void testDelivery() { + void testDelivery() { final String subjectKey = getClass().getName(); final String subjectValue = "SubjectValue1"; ThreadContext.put(subjectKey, subjectValue); @@ -125,7 +126,7 @@ public void testDelivery() { .setBufferSize(3) .build(); assertNotNull(appender); - assertTrue(appender.getManager() instanceof SmtpManager); + assertInstanceOf(SmtpManager.class, appender.getManager()); appender.start(); final LoggerContext context = LoggerContext.getContext(); @@ -144,7 +145,7 @@ public void testDelivery() { root.error("Error message #2"); server.stop(); - assertTrue(server.getReceivedEmailSize() == 2); + assertEquals(2, server.getReceivedEmailSize()); final Iterator messages = server.getReceivedEmail(); final SmtpMessage email = messages.next(); diff --git a/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpManagerTest.java b/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpManagerTest.java index d8017afe4e2..84c55e227d7 100644 --- a/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpManagerTest.java +++ b/log4j-jakarta-smtp/src/test/java/org/apache/logging/log4j/smtp/SmtpManagerTest.java @@ -33,7 +33,7 @@ import org.apache.logging.log4j.message.ReusableSimpleMessage; import org.junit.jupiter.api.Test; -public class SmtpManagerTest { +class SmtpManagerTest { private void testAdd(final LogEvent event) { final SmtpAppender appender = SmtpAppender.newBuilder() @@ -69,7 +69,7 @@ private void testAdd(final LogEvent event) { // LOG4J2-3172: make sure existing protections are not violated @Test - public void testAdd_WhereLog4jLogEventWithReusableMessage() { + void testAdd_WhereLog4jLogEventWithReusableMessage() { final LogEvent event = new Log4jLogEvent.Builder() .setMessage(getReusableMessage("test message")) .build(); @@ -78,14 +78,14 @@ public void testAdd_WhereLog4jLogEventWithReusableMessage() { // LOG4J2-3172: make sure existing protections are not violated @Test - public void testAdd_WhereMutableLogEvent() { + void testAdd_WhereMutableLogEvent() { final MutableLogEvent event = new MutableLogEvent(new StringBuilder("test message"), null); testAdd(event); } // LOG4J2-3172 @Test - public void testAdd_WhereRingBufferLogEvent() { + void testAdd_WhereRingBufferLogEvent() { final RingBufferLogEvent event = new RingBufferLogEvent(); event.setValues( null, diff --git a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java index e4e21c76f37..238ab440a23 100644 --- a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java +++ b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java @@ -47,7 +47,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jServletContainerInitializerTest { +class Log4jServletContainerInitializerTest { @Mock private ServletContext servletContext; @@ -63,19 +63,19 @@ public class Log4jServletContainerInitializerTest { private Log4jServletContainerInitializer containerInitializer; @BeforeEach - public void setUp() { + void setUp() { this.containerInitializer = new Log4jServletContainerInitializer(); } @Test - public void testOnStartupWithServletVersion2_x() throws Exception { + void testOnStartupWithServletVersion2_x() throws Exception { given(servletContext.getMajorVersion()).willReturn(2); this.containerInitializer.onStartup(null, this.servletContext); } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion2_x() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion2_x() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(2); @@ -83,7 +83,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion2_x() throws Excep } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTrue() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTrue() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED))) @@ -93,7 +93,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTrue() } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_xShutdownDisabled() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_xShutdownDisabled() throws Exception { final FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); @@ -119,7 +119,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_xShutdownDisable } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTRUE() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTRUE() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED))) @@ -129,7 +129,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTRUE() } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_x() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_x() throws Exception { final FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); @@ -160,7 +160,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_x() throws Excep } @Test - public void testOnStartupCanceledDueToPreExistingFilter() throws Exception { + void testOnStartupCanceledDueToPreExistingFilter() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED))) @@ -175,7 +175,7 @@ public void testOnStartupCanceledDueToPreExistingFilter() throws Exception { } @Test - public void testOnStartupFailedDueToInitializerFailure() throws Exception { + void testOnStartupFailedDueToInitializerFailure() throws Exception { final FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); final IllegalStateException exception = new IllegalStateException(Strings.EMPTY); given(servletContext.getMajorVersion()).willReturn(3); @@ -200,7 +200,7 @@ public void testOnStartupFailedDueToInitializerFailure() throws Exception { } @Test - public void testServiceIsDetected() { + void testServiceIsDetected() { final ServiceLoader loader = ServiceLoader.load(ServletContainerInitializer.class); final boolean found = StreamSupport.stream(loader.spliterator(), false) .anyMatch(s -> s instanceof Log4jServletContainerInitializer); diff --git a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java index 0082f2b4fa0..bc1a2800d1b 100644 --- a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java +++ b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java @@ -39,7 +39,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jServletContextListenerTest { +class Log4jServletContextListenerTest { /* event and servletContext are marked lenient because they aren't used in the * testDestroyWithNoInit but are only accessed during initialization */ @@ -55,7 +55,7 @@ public class Log4jServletContextListenerTest { private final AtomicReference count = new AtomicReference<>(); @BeforeEach - public void setUp() { + void setUp() { given(event.getServletContext()).willReturn(servletContext); given(servletContext.getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE)).willReturn(initializer); @@ -67,7 +67,7 @@ public void setUp() { @ParameterizedTest @ValueSource(ints = {1, 2, 3}) - public void testInitAndDestroy(final int listenerCount) throws Exception { + void testInitAndDestroy(final int listenerCount) { final Log4jServletContextListener[] listeners = new Log4jServletContextListener[listenerCount]; for (int idx = 0; idx < listenerCount; idx++) { final Log4jServletContextListener listener = new Log4jServletContextListener(); @@ -96,7 +96,7 @@ public void testInitAndDestroy(final int listenerCount) throws Exception { } @Test - public void testInitFailure() throws Exception { + void testInitFailure() { willThrow(new IllegalStateException(Strings.EMPTY)).given(initializer).start(); final Log4jServletContextListener listener = new Log4jServletContextListener(); @@ -107,14 +107,14 @@ public void testInitFailure() throws Exception { } @Test - public void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTrue() throws Exception { + void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTrue() { given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_SHUTDOWN_DISABLED))) .willReturn("true"); ensureInitializingFailsWhenAuthShutdownIsEnabled(); } @Test - public void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTRUE() throws Exception { + void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTRUE() { given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_SHUTDOWN_DISABLED))) .willReturn("TRUE"); ensureInitializingFailsWhenAuthShutdownIsEnabled(); diff --git a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java index 3f38270d819..2907c60c68f 100644 --- a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java +++ b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java @@ -35,7 +35,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jServletFilterTest { +class Log4jServletFilterTest { @Mock(lenient = true) // because filterConfig is not used in testDestroy private FilterConfig filterConfig; @@ -57,14 +57,14 @@ public class Log4jServletFilterTest { private Log4jServletFilter filter; @BeforeEach - public void setUp() { + void setUp() { given(filterConfig.getServletContext()).willReturn(servletContext); given(servletContext.getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE)).willReturn(initializer); this.filter = new Log4jServletFilter(); } @Test - public void testInitAndDestroy() throws Exception { + void testInitAndDestroy() throws Exception { this.filter.init(this.filterConfig); then(initializer).should().clearLoggerContext(); @@ -75,14 +75,14 @@ public void testInitAndDestroy() throws Exception { } @Test - public void testDestroy() { + void testDestroy() { assertThrows(IllegalStateException.class, () -> { this.filter.destroy(); }); } @Test - public void testDoFilterFirstTime() throws Exception { + void testDoFilterFirstTime() throws Exception { this.filter.init(this.filterConfig); then(initializer).should().clearLoggerContext(); @@ -102,7 +102,7 @@ public void testDoFilterFirstTime() throws Exception { } @Test - public void testDoFilterSecondTime() throws Exception { + void testDoFilterSecondTime() throws Exception { this.filter.init(this.filterConfig); then(initializer).should().clearLoggerContext(); diff --git a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java index be27e81be0b..f1b2b9d34c7 100644 --- a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java +++ b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java @@ -29,7 +29,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jShutdownOnContextDestroyedListenerTest { +class Log4jShutdownOnContextDestroyedListenerTest { @Mock(lenient = true) private ServletContextEvent event; @@ -41,7 +41,7 @@ public class Log4jShutdownOnContextDestroyedListenerTest { private Log4jShutdownOnContextDestroyedListener listener; - public void setUp(final boolean mockInitializer) { + void setUp(final boolean mockInitializer) { this.listener = new Log4jShutdownOnContextDestroyedListener(); given(event.getServletContext()).willReturn(servletContext); if (mockInitializer) { @@ -51,7 +51,7 @@ public void setUp(final boolean mockInitializer) { } @Test - public void testInitAndDestroy() throws Exception { + void testInitAndDestroy() { setUp(true); this.listener.contextInitialized(this.event); @@ -65,7 +65,7 @@ public void testInitAndDestroy() throws Exception { } @Test - public void testDestroy() throws Exception { + void testDestroy() { setUp(true); this.listener.contextDestroyed(this.event); @@ -74,7 +74,7 @@ public void testDestroy() throws Exception { } @Test - public void whenNoInitializerInContextTheContextInitializedShouldThrowAnException() { + void whenNoInitializerInContextTheContextInitializedShouldThrowAnException() { setUp(false); assertThrows(IllegalStateException.class, () -> { diff --git a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java index d5a1d5b948b..8fb6d4005c5 100644 --- a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java +++ b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java @@ -22,11 +22,11 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; @@ -48,7 +48,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jWebInitializerImplTest { +class Log4jWebInitializerImplTest { /* Marking servletContext lenient because otherwise testCompositeLocationParameterWithEmptyUriListSetsDefaultConfiguration fails * when null is passed in as the initial param because Mockito deciced null isn't a String rather than the absence of a string. */ @@ -64,7 +64,7 @@ public class Log4jWebInitializerImplTest { private Log4jWebInitializerImpl initializerImpl; @BeforeEach - public void setUp() { + void setUp() { given(servletContext.getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE)).willReturn(null); final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(this.servletContext); @@ -72,20 +72,20 @@ public void setUp() { then(servletContext).should().setAttribute(eq(Log4jWebSupport.SUPPORT_ATTRIBUTE), initializerCaptor.capture()); assertNotNull(initializer, "The initializer should not be null."); assertSame(initializer, initializerCaptor.getValue(), "The capture is not correct."); - assertTrue(initializer instanceof Log4jWebInitializerImpl, "The initializer is not correct."); + assertInstanceOf(Log4jWebInitializerImpl.class, initializer, "The initializer is not correct."); this.initializerImpl = (Log4jWebInitializerImpl) initializer; } @Test - public void testDeinitializeBeforeInitialize() { + void testDeinitializeBeforeInitialize() { assertThrows(IllegalStateException.class, () -> { this.initializerImpl.stop(); }); } @Test - public void testSetLoggerContextBeforeInitialize() { + void testSetLoggerContextBeforeInitialize() { assertNull(ContextAnchor.THREAD_CONTEXT.get(), "The context should be null."); this.initializerImpl.setLoggerContext(); @@ -94,7 +94,7 @@ public void testSetLoggerContextBeforeInitialize() { } @Test - public void testClearLoggerContextBeforeInitialize() { + void testClearLoggerContextBeforeInitialize() { assertNull(ContextAnchor.THREAD_CONTEXT.get(), "The context should be null."); this.initializerImpl.clearLoggerContext(); @@ -103,7 +103,7 @@ public void testClearLoggerContextBeforeInitialize() { } @Test - public void testInitializeWithNoParametersThenSetLoggerContextThenDeinitialize() { + void testInitializeWithNoParametersThenSetLoggerContextThenDeinitialize() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -145,7 +145,7 @@ public void testInitializeWithNoParametersThenSetLoggerContextThenDeinitialize() } @Test - public void testInitializeWithClassLoaderNoParametersThenSetLoggerContextThenDeinitialize() { + void testInitializeWithClassLoaderNoParametersThenSetLoggerContextThenDeinitialize() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -189,7 +189,7 @@ public void testInitializeWithClassLoaderNoParametersThenSetLoggerContextThenDei } @Test - public void testInitializeIsIdempotent() { + void testInitializeIsIdempotent() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -217,7 +217,7 @@ public void testInitializeIsIdempotent() { } @Test - public void testInitializeFailsAfterDeinitialize() { + void testInitializeFailsAfterDeinitialize() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -246,7 +246,7 @@ public void testInitializeFailsAfterDeinitialize() { } @Test - public void testDeinitializeIsIdempotent() { + void testDeinitializeIsIdempotent() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -272,7 +272,7 @@ public void testDeinitializeIsIdempotent() { } @Test - public void testInitializeUsingJndiSelectorFails() { + void testInitializeUsingJndiSelectorFails() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -288,7 +288,7 @@ public void testInitializeUsingJndiSelectorFails() { } @Test - public void testInitializeUsingJndiSelector() { + void testInitializeUsingJndiSelector() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn("helloWorld06"); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -325,7 +325,7 @@ public void testInitializeUsingJndiSelector() { } @Test - public void testWrapExecutionWithNoParameters() { + void testWrapExecutionWithNoParameters() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -368,7 +368,7 @@ public void testWrapExecutionWithNoParameters() { } @Test - public void testMissingLocationParameterWithNoMatchingResourceSetsNoConfigLocation() { + void testMissingLocationParameterWithNoMatchingResourceSetsNoConfigLocation() { given(servletContext.getResourcePaths("/WEB-INF/")).willReturn(new HashSet()); this.initializerImpl.start(); @@ -384,7 +384,7 @@ public void testMissingLocationParameterWithNoMatchingResourceSetsNoConfigLocati } @Test - public void testMissingLocationParameterWithOneMatchingResourceUsesResourceConfigLocation() throws Exception { + void testMissingLocationParameterWithOneMatchingResourceUsesResourceConfigLocation() throws Exception { given(servletContext.getResourcePaths("/WEB-INF/")) .willReturn(new HashSet<>(singletonList("/WEB-INF/log4j2.xml"))); given(servletContext.getResource("/WEB-INF/log4j2.xml")).willReturn(new URL("file:/a/b/c/WEB-INF/log4j2.xml")); @@ -403,7 +403,7 @@ public void testMissingLocationParameterWithOneMatchingResourceUsesResourceConfi } @Test - public void testMissingLocationParameterWithManyMatchingResourcesUsesFirstMatchingResourceConfigLocation() + void testMissingLocationParameterWithManyMatchingResourcesUsesFirstMatchingResourceConfigLocation() throws Exception { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn("mycontext"); @@ -428,7 +428,7 @@ public void testMissingLocationParameterWithManyMatchingResourcesUsesFirstMatchi } @Test - public void testCompositeLocationParameterWithEmptyUriListSetsDefaultConfiguration() { + void testCompositeLocationParameterWithEmptyUriListSetsDefaultConfiguration() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) .willReturn(",,,"); @@ -445,7 +445,7 @@ public void testCompositeLocationParameterWithEmptyUriListSetsDefaultConfigurati } @Test - public void testCompositeLocationParameterSetsCompositeConfiguration() { + void testCompositeLocationParameterSetsCompositeConfiguration() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn("mycontext"); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) diff --git a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java index 5e0d2202103..98457d15e64 100644 --- a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java +++ b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java @@ -27,17 +27,17 @@ /** * */ -public class PropertyTest { +class PropertyTest { @Test - public void testShutdownHookDisabled() { + void testShutdownHookDisabled() { assertFalse( ((Log4jContextFactory) LogManager.getFactory()).isShutdownHookEnabled(), "Shutdown hook should be disabled by default in web applications"); } @Test - public void testIsWebApp() { + void testIsWebApp() { assertTrue(Constants.IS_WEB_APP, "When servlet classes are available IS_WEB_APP should default to true"); } } diff --git a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java index 11c824c4507..4b990e9fbaa 100644 --- a/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java +++ b/log4j-jakarta-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java @@ -17,11 +17,9 @@ package org.apache.logging.log4j.web; import jakarta.servlet.AsyncContext; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -31,8 +29,7 @@ public class TestAsyncServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override - protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) { final AsyncContext asyncContext = req.startAsync(); asyncContext.start(WebLoggerContextUtils.wrapExecutionContext(this.getServletContext(), () -> { final Logger logger = LogManager.getLogger(TestAsyncServlet.class); @@ -41,8 +38,7 @@ protected void doGet(final HttpServletRequest req, final HttpServletResponse res } @Override - protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) { final AsyncContext asyncContext = req.startAsync(); asyncContext.start(() -> { final Log4jWebSupport webSupport = diff --git a/log4j-jcl/src/test/java/org/apache/logging/log4j/jcl/CallerInformationTest.java b/log4j-jcl/src/test/java/org/apache/logging/log4j/jcl/CallerInformationTest.java index ba6987b1372..188c78ee5d0 100644 --- a/log4j-jcl/src/test/java/org/apache/logging/log4j/jcl/CallerInformationTest.java +++ b/log4j-jcl/src/test/java/org/apache/logging/log4j/jcl/CallerInformationTest.java @@ -26,11 +26,11 @@ import org.apache.logging.log4j.core.test.junit.LoggerContextSource; import org.junit.jupiter.api.Test; -public class CallerInformationTest { +class CallerInformationTest { @Test @LoggerContextSource("CallerInformationTest.xml") - public void testClassLogger(final LoggerContext ctx) { + void testClassLogger(final LoggerContext ctx) { final ListAppender app = ctx.getConfiguration().getAppender("Class"); app.clear(); final Log logger = LogFactory.getLog("ClassLogger"); @@ -43,7 +43,7 @@ public void testClassLogger(final LoggerContext ctx) { @Test @LoggerContextSource("CallerInformationTest.xml") - public void testMethodLogger(final LoggerContext ctx) { + void testMethodLogger(final LoggerContext ctx) { final ListAppender app = ctx.getConfiguration().getAppender("Method"); app.clear(); final Log logger = LogFactory.getLog("MethodLogger"); diff --git a/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolableConnectionFactoryTest.java b/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolableConnectionFactoryTest.java index 2d73acb60a2..0ec7d41436b 100644 --- a/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolableConnectionFactoryTest.java +++ b/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolableConnectionFactoryTest.java @@ -24,12 +24,12 @@ import org.junit.jupiter.api.Test; @LoggerContextSource(value = "log4j2-jdbc-dbcp2.xml", timeout = 10) -public class PoolableConnectionFactoryTest { +class PoolableConnectionFactoryTest { private static final String REL_PATH = "src/test/resources/log4j2-jdbc-dbcp2.xml"; @Test - public void test(@Named("databaseAppender") final Appender appender) { + void test(@Named("databaseAppender") final Appender appender) { assertNotNull(appender, "Problem loading configuration from " + REL_PATH); } } diff --git a/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolingDriverConnectionSourceTest.java b/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolingDriverConnectionSourceTest.java index f89b6c844e8..04408e454cb 100644 --- a/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolingDriverConnectionSourceTest.java +++ b/log4j-jdbc-dbcp2/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/PoolingDriverConnectionSourceTest.java @@ -28,10 +28,10 @@ /** * Tests {@link PoolingDriverConnectionSource}. */ -public class PoolingDriverConnectionSourceTest { +class PoolingDriverConnectionSourceTest { @Test - public void testH2Properties() throws SQLException { + void testH2Properties() throws SQLException { final Property[] properties = new Property[] { // @formatter:off Property.createProperty("username", JdbcH2TestHelper.USER_NAME), @@ -49,7 +49,7 @@ public void testH2Properties() throws SQLException { } @Test - public void testH2PropertiesAndPoolName() throws SQLException { + void testH2PropertiesAndPoolName() throws SQLException { final Property[] properties = new Property[] { // @formatter:off Property.createProperty("username", JdbcH2TestHelper.USER_NAME), @@ -67,7 +67,7 @@ public void testH2PropertiesAndPoolName() throws SQLException { } @Test - public void testH2UserAndPassword() throws SQLException { + void testH2UserAndPassword() throws SQLException { // @formatter:off final PoolingDriverConnectionSource source = PoolingDriverConnectionSource.newPoolingDriverConnectionSourceBuilder() @@ -89,7 +89,7 @@ private void openAndClose(final PoolingDriverConnectionSource source) throws SQL } @Test - public void testH2UserPasswordAndPoolName() throws SQLException { + void testH2UserPasswordAndPoolName() throws SQLException { // @formatter:off final PoolingDriverConnectionSource source = PoolingDriverConnectionSource.newPoolingDriverConnectionSourceBuilder() @@ -103,7 +103,7 @@ public void testH2UserPasswordAndPoolName() throws SQLException { } @Test - public void testPoolableConnectionFactoryConfig() throws SQLException { + void testPoolableConnectionFactoryConfig() throws SQLException { final PoolableConnectionFactoryConfig poolableConnectionFactoryConfig = PoolableConnectionFactoryConfig.newBuilder() .setMaxConnLifetimeMillis(30000) diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/AbstractJpaAppenderTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/AbstractJpaAppenderTest.java index 6a66d279ca9..65c4794f0d5 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/AbstractJpaAppenderTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/AbstractJpaAppenderTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -68,7 +69,7 @@ public void tearDown() throws SQLException { final String appenderName = "databaseAppender"; final Appender appender = context.getConfiguration().getAppender(appenderName); assertNotNull(appender, "The appender '" + appenderName + "' should not be null."); - assertTrue(appender instanceof JpaAppender, "The appender should be a JpaAppender."); + assertInstanceOf(JpaAppender.class, appender, "The appender should be a JpaAppender."); ((JpaAppender) appender).getManager().close(); } finally { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); @@ -76,7 +77,7 @@ public void tearDown() throws SQLException { StatusLogger.getLogger().reset(); if (this.connection != null) { - try (final Statement statement = this.connection.createStatement(); ) { + try (final Statement statement = this.connection.createStatement()) { statement.execute("SHUTDOWN"); } this.connection.close(); diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaH2AppenderTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaH2AppenderTest.java index 3ec0c889773..0562447199d 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaH2AppenderTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaH2AppenderTest.java @@ -20,11 +20,10 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; -import org.apache.logging.log4j.core.test.categories.Appenders; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; -@Category(Appenders.Jpa.class) -public class JpaH2AppenderTest extends AbstractJpaAppenderTest { +@Tag("Appenders.Jpa") +class JpaH2AppenderTest extends AbstractJpaAppenderTest { private static final String USER_ID = "sa"; private static final String PASSWORD = "123"; diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaHsqldbAppenderTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaHsqldbAppenderTest.java index 46b4e47a96c..00ac7214854 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaHsqldbAppenderTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/JpaHsqldbAppenderTest.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class JpaHsqldbAppenderTest extends AbstractJpaAppenderTest { +class JpaHsqldbAppenderTest extends AbstractJpaAppenderTest { private static final String USER_ID = "sa"; private static final String PASSWORD = "123"; @@ -58,14 +58,14 @@ protected Connection setUpConnection() throws SQLException { } @Test - public void testNoEntityClassName() { + void testNoEntityClassName() { final JpaAppender appender = JpaAppender.createAppender("name", null, null, null, null, "jpaAppenderTestUnit"); assertNull(appender, "The appender should be null."); } @Test - public void testNoPersistenceUnitName() { + void testNoPersistenceUnitName() { final JpaAppender appender = JpaAppender.createAppender("name", null, null, null, TestBaseEntity.class.getName(), null); @@ -73,7 +73,7 @@ public void testNoPersistenceUnitName() { } @Test - public void testBadEntityClassName() { + void testBadEntityClassName() { final JpaAppender appender = JpaAppender.createAppender("name", null, null, null, "com.foo.Bar", "jpaAppenderTestUnit"); @@ -81,7 +81,7 @@ public void testBadEntityClassName() { } @Test - public void testNonLogEventEntity() { + void testNonLogEventEntity() { final JpaAppender appender = JpaAppender.createAppender("name", null, null, null, Object.class.getName(), "jpaAppenderTestUnit"); @@ -89,7 +89,7 @@ public void testNonLogEventEntity() { } @Test - public void testBadConstructorEntity01() { + void testBadConstructorEntity01() { final JpaAppender appender = JpaAppender.createAppender( "name", null, null, null, BadConstructorEntity1.class.getName(), "jpaAppenderTestUnit"); @@ -97,7 +97,7 @@ public void testBadConstructorEntity01() { } @Test - public void testBadConstructorEntity02() { + void testBadConstructorEntity02() { final JpaAppender appender = JpaAppender.createAppender( "name", null, null, null, BadConstructorEntity2.class.getName(), "jpaAppenderTestUnit"); diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/LogEventEntityTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/LogEventEntityTest.java index e3ed5f3e28f..9cb29fdb96c 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/LogEventEntityTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/LogEventEntityTest.java @@ -29,10 +29,10 @@ import org.apache.logging.log4j.message.Message; import org.junit.jupiter.api.Test; -public class LogEventEntityTest { +class LogEventEntityTest { @Test - public void testToImmutable_AbstractLogEventWrapperEntity() { + void testToImmutable_AbstractLogEventWrapperEntity() { final LogEvent logEvent = new AbstractLogEventWrapperEntity() { private static final long serialVersionUID = 1L; @@ -121,7 +121,7 @@ public long getTimeMillis() { } @Test - public void testToImmutable_TestBaseEntity() { + void testToImmutable_TestBaseEntity() { final LogEvent logEvent = new TestBaseEntity(); assertNotSame(logEvent, logEvent.toImmutable()); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataAttributeConverterTest.java index 1bdf8183254..501b82be8a1 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataAttributeConverterTest.java @@ -27,16 +27,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class ContextDataAttributeConverterTest { +class ContextDataAttributeConverterTest { private ContextDataAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new ContextDataAttributeConverter(); } @Test - public void testConvertToDatabaseColumn01() { + void testConvertToDatabaseColumn01() { final StringMap map = new SortedArrayStringMap(); map.putValue("test1", "another1"); map.putValue("key2", "value2"); @@ -46,7 +46,7 @@ public void testConvertToDatabaseColumn01() { } @Test - public void testConvertToDatabaseColumn02() { + void testConvertToDatabaseColumn02() { final StringMap map = new SortedArrayStringMap(); map.putValue("someKey", "coolValue"); map.putValue("anotherKey", "testValue"); @@ -57,12 +57,12 @@ public void testConvertToDatabaseColumn02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertToEntityAttribute() { + void testConvertToEntityAttribute() { assertThrows(UnsupportedOperationException.class, () -> this.converter.convertToEntityAttribute(null)); } } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataJsonAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataJsonAttributeConverterTest.java index f3702ad3572..6f186d6c660 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataJsonAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextDataJsonAttributeConverterTest.java @@ -28,16 +28,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class ContextDataJsonAttributeConverterTest { +class ContextDataJsonAttributeConverterTest { private ContextDataJsonAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new ContextDataJsonAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final StringMap map = new SortedArrayStringMap(); map.putValue("test1", "another1"); map.putValue("key2", "value2"); @@ -53,7 +53,7 @@ public void testConvert01() { } @Test - public void testConvert02() { + void testConvert02() { final StringMap map = new SortedArrayStringMap(); map.putValue("someKey", "coolValue"); map.putValue("anotherKey", "testValue"); @@ -70,12 +70,12 @@ public void testConvert02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapAttributeConverterTest.java index efd5c815b62..4125b83650e 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapAttributeConverterTest.java @@ -27,16 +27,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class ContextMapAttributeConverterTest { +class ContextMapAttributeConverterTest { private ContextMapAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new ContextMapAttributeConverter(); } @Test - public void testConvertToDatabaseColumn01() { + void testConvertToDatabaseColumn01() { final Map map = new HashMap<>(); map.put("test1", "another1"); map.put("key2", "value2"); @@ -46,7 +46,7 @@ public void testConvertToDatabaseColumn01() { } @Test - public void testConvertToDatabaseColumn02() { + void testConvertToDatabaseColumn02() { final Map map = new HashMap<>(); map.put("someKey", "coolValue"); map.put("anotherKey", "testValue"); @@ -57,12 +57,12 @@ public void testConvertToDatabaseColumn02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertToEntityAttribute() { + void testConvertToEntityAttribute() { assertThrows(UnsupportedOperationException.class, () -> this.converter.convertToEntityAttribute(null)); } } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapJsonAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapJsonAttributeConverterTest.java index b6081c97de2..154dee9bad1 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapJsonAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextMapJsonAttributeConverterTest.java @@ -27,16 +27,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class ContextMapJsonAttributeConverterTest { +class ContextMapJsonAttributeConverterTest { private ContextMapJsonAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new ContextMapJsonAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final Map map = new HashMap<>(); map.put("test1", "another1"); map.put("key2", "value2"); @@ -52,7 +52,7 @@ public void testConvert01() { } @Test - public void testConvert02() { + void testConvert02() { final Map map = new HashMap<>(); map.put("someKey", "coolValue"); map.put("anotherKey", "testValue"); @@ -69,12 +69,12 @@ public void testConvert02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackAttributeConverterTest.java index 1f367ccf02c..91b9ce44c9d 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackAttributeConverterTest.java @@ -28,16 +28,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class ContextStackAttributeConverterTest { +class ContextStackAttributeConverterTest { private ContextStackAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new ContextStackAttributeConverter(); } @Test - public void testConvertToDatabaseColumn01() { + void testConvertToDatabaseColumn01() { final ThreadContext.ContextStack stack = new MutableThreadContextStack(Arrays.asList("value1", "another2")); assertEquals( @@ -47,7 +47,7 @@ public void testConvertToDatabaseColumn01() { } @Test - public void testConvertToDatabaseColumn02() { + void testConvertToDatabaseColumn02() { final ThreadContext.ContextStack stack = new MutableThreadContextStack(Arrays.asList("key1", "value2", "my3")); assertEquals( @@ -57,12 +57,12 @@ public void testConvertToDatabaseColumn02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertToEntityAttribute() { + void testConvertToEntityAttribute() { assertThrows(UnsupportedOperationException.class, () -> this.converter.convertToEntityAttribute(null)); } } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackJsonAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackJsonAttributeConverterTest.java index 453e7c79f43..dd705216d00 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackJsonAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ContextStackJsonAttributeConverterTest.java @@ -30,16 +30,16 @@ @UsingThreadContextStack @Tag("Appenders.Jpa") -public class ContextStackJsonAttributeConverterTest { +class ContextStackJsonAttributeConverterTest { private ContextStackJsonAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new ContextStackJsonAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final ThreadContext.ContextStack stack = new MutableThreadContextStack(Arrays.asList("value1", "another2")); final String converted = this.converter.convertToDatabaseColumn(stack); @@ -53,7 +53,7 @@ public void testConvert01() { } @Test - public void testConvert02() { + void testConvert02() { final ThreadContext.ContextStack stack = new MutableThreadContextStack(Arrays.asList("key1", "value2", "my3")); final String converted = this.converter.convertToDatabaseColumn(stack); @@ -67,12 +67,12 @@ public void testConvert02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/InstantAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/InstantAttributeConverterTest.java index dfdbd23719a..5d728515dbf 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/InstantAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/InstantAttributeConverterTest.java @@ -28,18 +28,18 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class InstantAttributeConverterTest { +class InstantAttributeConverterTest { private static final StatusLogger LOGGER = StatusLogger.getLogger(); private InstantAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new InstantAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final MutableInstant instant = new MutableInstant(); instant.initFromEpochSecond(1234567, 89012); @@ -56,12 +56,12 @@ public void testConvert01() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MarkerAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MarkerAttributeConverterTest.java index 4688714c562..69a78353f0e 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MarkerAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MarkerAttributeConverterTest.java @@ -27,16 +27,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class MarkerAttributeConverterTest { +class MarkerAttributeConverterTest { private MarkerAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new MarkerAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final Marker marker = MarkerManager.getMarker("testConvert01"); final String converted = this.converter.convertToDatabaseColumn(marker); @@ -51,7 +51,7 @@ public void testConvert01() { } @Test - public void testConvert02() { + void testConvert02() { Marker marker = MarkerManager.getMarker("anotherConvert02").setParents(MarkerManager.getMarker("finalConvert03")); marker = MarkerManager.getMarker("testConvert02").setParents(marker); @@ -78,12 +78,12 @@ public void testConvert02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MessageAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MessageAttributeConverterTest.java index e21891a5c16..70aa0010428 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MessageAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MessageAttributeConverterTest.java @@ -27,18 +27,18 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class MessageAttributeConverterTest { +class MessageAttributeConverterTest { private static final StatusLogger LOGGER = StatusLogger.getLogger(); private MessageAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new MessageAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final Message message = LOGGER.getMessageFactory().newMessage("Message #{} said [{}].", 3, "Hello"); final String converted = this.converter.convertToDatabaseColumn(message); @@ -53,12 +53,12 @@ public void testConvert01() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/StackTraceElementAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/StackTraceElementAttributeConverterTest.java index 10a9267b896..dd721252cec 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/StackTraceElementAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/StackTraceElementAttributeConverterTest.java @@ -27,16 +27,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class StackTraceElementAttributeConverterTest { +class StackTraceElementAttributeConverterTest { private StackTraceElementAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new StackTraceElementAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final StackTraceElement element = new StackTraceElement("TestNoPackage", "testConvert01", "TestNoPackage.java", 1234); @@ -59,7 +59,7 @@ public void testConvert01() { } @Test - public void testConvert02() { + void testConvert02() { final StackTraceElement element = new StackTraceElement( "org.apache.logging.TestWithPackage", "testConvert02", "TestWithPackage.java", -1); @@ -82,7 +82,7 @@ public void testConvert02() { } @Test - public void testConvert03() { + void testConvert03() { final StackTraceElement element = new StackTraceElement("org.apache.logging.TestNoSource", "testConvert03", null, -1); @@ -99,13 +99,13 @@ public void testConvert03() { assertNotNull(reversed, "The reversed value should not be null."); assertEquals("org.apache.logging.TestNoSource", reversed.getClassName(), "The class name is not correct."); assertEquals("testConvert03", reversed.getMethodName(), "The method name is not correct."); - assertEquals(null, reversed.getFileName(), "The file name is not correct."); + assertNull(reversed.getFileName(), "The file name is not correct."); assertEquals(-1, reversed.getLineNumber(), "The line number is not correct."); assertFalse(reversed.isNativeMethod(), "The native flag should be false."); } @Test - public void testConvert04() { + void testConvert04() { final StackTraceElement element = new StackTraceElement("org.apache.logging.TestIsNativeMethod", "testConvert04", null, -2); @@ -123,18 +123,18 @@ public void testConvert04() { assertEquals( "org.apache.logging.TestIsNativeMethod", reversed.getClassName(), "The class name is not correct."); assertEquals("testConvert04", reversed.getMethodName(), "The method name is not correct."); - assertEquals(null, reversed.getFileName(), "The file name is not correct."); + assertNull(reversed.getFileName(), "The file name is not correct."); assertEquals(-2, reversed.getLineNumber(), "The line number is not correct."); assertTrue(reversed.isNativeMethod(), "The native flag should be true."); } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ThrowableAttributeConverterTest.java b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ThrowableAttributeConverterTest.java index c3726bb54a1..f57d1762edf 100644 --- a/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ThrowableAttributeConverterTest.java +++ b/log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/ThrowableAttributeConverterTest.java @@ -26,16 +26,16 @@ import org.junit.jupiter.api.Test; @Tag("Appenders.Jpa") -public class ThrowableAttributeConverterTest { +class ThrowableAttributeConverterTest { private ThrowableAttributeConverter converter; @BeforeEach - public void setUp() { + void setUp() { this.converter = new ThrowableAttributeConverter(); } @Test - public void testConvert01() { + void testConvert01() { final RuntimeException exception = new RuntimeException("My message 01."); final String stackTrace = getStackTrace(exception); @@ -52,7 +52,7 @@ public void testConvert01() { } @Test - public void testConvert02() { + void testConvert02() { final SQLException cause2 = new SQLException("This is a test cause."); final Error cause1 = new Error(cause2); final RuntimeException exception = new RuntimeException("My message 01.", cause1); @@ -71,12 +71,12 @@ public void testConvert02() { } @Test - public void testConvertNullToDatabaseColumn() { + void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test - public void testConvertNullOrBlankToEntityAttribute() { + void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } diff --git a/log4j-jpl/src/test/java/org/apache/logging/log4j/jpl/Log4jSystemLoggerTest.java b/log4j-jpl/src/test/java/org/apache/logging/log4j/jpl/Log4jSystemLoggerTest.java index cac01a7f154..8afedfa314b 100644 --- a/log4j-jpl/src/test/java/org/apache/logging/log4j/jpl/Log4jSystemLoggerTest.java +++ b/log4j-jpl/src/test/java/org/apache/logging/log4j/jpl/Log4jSystemLoggerTest.java @@ -34,7 +34,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class Log4jSystemLoggerTest { +class Log4jSystemLoggerTest { public static final String LOGGER_NAME = "Test"; protected Logger logger; @@ -42,7 +42,7 @@ public class Log4jSystemLoggerTest { protected ListAppender stringAppender; @BeforeEach - public void setUp() throws Exception { + void setUp() { logger = System.getLogger(LOGGER_NAME); assertThat(logger, instanceOf(Log4jSystemLogger.class)); eventAppender = ListAppender.getListAppender("TestAppender"); @@ -52,7 +52,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() throws Exception { + void tearDown() { if (eventAppender != null) { eventAppender.clear(); } @@ -62,17 +62,17 @@ public void tearDown() throws Exception { } @Test - public void testGetName() throws Exception { + void testGetName() { assertThat(logger.getName(), equalTo(LOGGER_NAME)); } @Test - public void testIsLoggable() throws Exception { + void testIsLoggable() { assertThat(logger.isLoggable(Logger.Level.ERROR), equalTo(true)); } @Test - public void testLog() throws Exception { + void testLog() { logger.log(Logger.Level.INFO, "Informative message here."); final List events = eventAppender.getEvents(); assertThat(events, hasSize(1)); @@ -85,7 +85,7 @@ public void testLog() throws Exception { } @Test - public void testParameterizedLogging() { + void testParameterizedLogging() { logger.log(Logger.Level.INFO, "Hello, {0}!", "World"); final List events = eventAppender.getEvents(); assertThat(events, hasSize(1)); @@ -98,7 +98,7 @@ public void testParameterizedLogging() { } @Test - public void testParameterizedLoggingWithThrowable() { + void testParameterizedLoggingWithThrowable() { final Throwable throwable = new RuntimeException(); logger.log(Logger.Level.INFO, "Hello, {0}!", "World", throwable); final List events = eventAppender.getEvents(); @@ -113,7 +113,7 @@ public void testParameterizedLoggingWithThrowable() { } @Test - public void testLogWithCallingClass() throws Exception { + void testLogWithCallingClass() { final Logger log = System.getLogger("Test.CallerClass"); log.log(Logger.Level.INFO, "Calling from LoggerTest"); final List messages = stringAppender.getMessages(); @@ -123,17 +123,17 @@ public void testLogWithCallingClass() throws Exception { } @Test - public void testCurlyBraces() { + void testCurlyBraces() { testMessage("{message}"); } @Test - public void testPercent() { + void testPercent() { testMessage("message%s"); } @Test - public void testPercentAndCurlyBraces() { + void testPercentAndCurlyBraces() { testMessage("message{%s}"); } diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AbstractLoggerTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AbstractLoggerTest.java index 9ddf62adfa0..8317a6620f3 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AbstractLoggerTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AbstractLoggerTest.java @@ -29,12 +29,12 @@ import org.apache.logging.log4j.core.test.appender.ListAppender; import org.apache.logging.log4j.jul.ApiLogger; import org.apache.logging.log4j.jul.LevelTranslator; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * */ -public abstract class AbstractLoggerTest { +abstract class AbstractLoggerTest { public static final String LOGGER_NAME = "Test"; static final java.util.logging.Level[] LEVELS = new java.util.logging.Level[] { @@ -64,12 +64,12 @@ static java.util.logging.Level getEffectiveLevel(final Logger logger) { protected ListAppender stringAppender; @Test - public void testGetName() { + void testGetName() { assertThat(logger.getName()).isEqualTo(LOGGER_NAME); } @Test - public void testGlobalLogger() { + void testGlobalLogger() { final Logger root = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); root.info("Test info message"); root.config("Test info message"); @@ -83,18 +83,18 @@ public void testGlobalLogger() { } @Test - public void testGlobalLoggerName() { + void testGlobalLoggerName() { final Logger root = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); assertThat(root.getName()).isEqualTo(Logger.GLOBAL_LOGGER_NAME); } @Test - public void testIsLoggable() { + void testIsLoggable() { assertThat(logger.isLoggable(java.util.logging.Level.SEVERE)).isTrue(); } @Test - public void testLog() { + void testLog() { logger.info("Informative message here."); final List events = eventAppender.getEvents(); assertThat(events).hasSize(1); @@ -107,7 +107,7 @@ public void testLog() { } @Test - public void testLogFilter() { + void testLogFilter() { logger.setFilter(record -> false); logger.severe("Informative message here."); logger.warning("Informative message here."); @@ -121,7 +121,7 @@ public void testLogFilter() { } @Test - public void testAlteringLogFilter() { + void testAlteringLogFilter() { logger.setFilter(record -> { record.setMessage("This is not the message you are looking for."); return true; @@ -138,7 +138,7 @@ public void testAlteringLogFilter() { } @Test - public void testLogParamMarkers() { + void testLogParamMarkers() { final Logger flowLogger = Logger.getLogger("TestFlow"); flowLogger.logp(java.util.logging.Level.FINER, "sourceClass", "sourceMethod", "ENTER {0}", "params"); final List events = flowAppender.getEvents(); @@ -146,7 +146,7 @@ public void testLogParamMarkers() { } @Test - public void testLogUsingCustomLevel() { + void testLogUsingCustomLevel() { logger.config("Config level"); final List events = eventAppender.getEvents(); assertThat(events).hasSize(1); @@ -155,7 +155,7 @@ public void testLogUsingCustomLevel() { } @Test - public void testLogWithCallingClass() { + void testLogWithCallingClass() { final Logger log = Logger.getLogger("Test.CallerClass"); log.config("Calling from LoggerTest"); final List messages = stringAppender.getMessages(); @@ -165,17 +165,17 @@ public void testLogWithCallingClass() { } @Test - public void testCurlyBraces() { + void testCurlyBraces() { testMessage("{message}"); } @Test - public void testPercent() { + void testPercent() { testMessage("message%s"); } @Test - public void testPercentAndCurlyBraces() { + void testPercentAndCurlyBraces() { testMessage("message{%s}"); } @@ -193,7 +193,7 @@ private void testMessage(final String string) { } @Test - public void testFlowMessages() { + void testFlowMessages() { final Logger flowLogger = Logger.getLogger("TestFlow"); flowLogger.entering("com.example.TestSourceClass1", "testSourceMethod1(String)"); flowLogger.entering("com.example.TestSourceClass2", "testSourceMethod2(String)", "TestParam"); @@ -207,22 +207,22 @@ public void testFlowMessages() { } @Test - public void testLambdasGlobalLogger() { + void testLambdasGlobalLogger() { testLambdaMessages("message"); } @Test - public void testLambdasCurlyBraces() { + void testLambdasCurlyBraces() { testLambdaMessages("{message}"); } @Test - public void testLambdasPercent() { + void testLambdasPercent() { testLambdaMessages("message%s"); } @Test - public void testLambdasPercentAndCurlyBraces() { + void testLambdasPercentAndCurlyBraces() { testLambdaMessages("message{%s}"); } @@ -232,7 +232,7 @@ public void testLambdasPercentAndCurlyBraces() { * @see GH issue #3119 */ @Test - public void testSetAndGetLevel() { + void testSetAndGetLevel() { final Logger logger = Logger.getLogger(AbstractLoggerTest.class.getName() + ".testSetAndGetLevel"); // The logger under test should have no explicit configuration assertThat(logger.getLevel()).isNull(); @@ -247,7 +247,7 @@ public void testSetAndGetLevel() { * The value of `useParentHandlers` should be recorded even if it is not effective. */ @Test - public void testSetUseParentHandlers() { + void testSetUseParentHandlers() { final Logger logger = Logger.getLogger(AbstractLoggerTest.class.getName() + ".testSetUseParentHandlers"); for (boolean useParentHandlers : new boolean[] {false, true}) { @@ -260,7 +260,7 @@ public void testSetUseParentHandlers() { * The programmatically configured handlers should be recorded, even if they are not used. */ @Test - public void testAddAndRemoveHandlers() { + void testAddAndRemoveHandlers() { final Logger logger = Logger.getLogger(AbstractLoggerTest.class.getName() + ".testAddAndRemoveHandlers"); assertThat(logger.getHandlers()).isEmpty(); @@ -277,7 +277,7 @@ public void testAddAndRemoveHandlers() { * The programmatically configured filters should be recorded, even if they are not used. */ @Test - public void testSetFilter() { + void testSetFilter() { final Logger logger = Logger.getLogger(AbstractLoggerTest.class.getName() + ".testSetFilter"); assertThat(logger.getFilter()).isNull(); @@ -294,7 +294,7 @@ public void testSetFilter() { * The programmatically configured resource bundles should be recorded, even if they are not used. */ @Test - public void testSetResourceBundle() { + void testSetResourceBundle() { final Logger logger = Logger.getLogger(AbstractLoggerTest.class.getName() + ".testSetResourceBundle"); assertThat(logger.getResourceBundle()).isNull(); diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/ApiLoggerTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/ApiLoggerTest.java index 6319e52292f..8db89b2068c 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/ApiLoggerTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/ApiLoggerTest.java @@ -16,36 +16,38 @@ */ package org.apache.logging.log4j.jul.test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.logging.Logger; import org.apache.logging.log4j.core.test.appender.ListAppender; import org.apache.logging.log4j.jul.LogManager; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ApiLoggerTest extends AbstractLoggerTest { +class ApiLoggerTest extends AbstractLoggerTest { - @BeforeClass - public static void setUpClass() { + @BeforeAll + static void setUpClass() { System.setProperty("java.util.logging.manager", LogManager.class.getName()); } - @AfterClass - public static void tearDownClass() { + @AfterAll + static void tearDownClass() { System.clearProperty("java.util.logging.manager"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { logger = Logger.getLogger(LOGGER_NAME); logger.setFilter(null); - assertThat(getEffectiveLevel(logger)).isEqualTo(java.util.logging.Level.FINE); + assertThat(getEffectiveLevel(logger), equalTo(java.util.logging.Level.FINE)); eventAppender = ListAppender.getListAppender("TestAppender"); flowAppender = ListAppender.getListAppender("FlowAppender"); stringAppender = ListAppender.getListAppender("StringAppender"); @@ -54,8 +56,8 @@ public void setUp() { assertNotNull(stringAppender); } - @After - public void tearDown() { + @AfterEach + void tearDown() { if (eventAppender != null) { eventAppender.clear(); } @@ -68,18 +70,18 @@ public void tearDown() { } @Test - public void testGetParent() { + void testGetParent() { final Logger parent = logger.getParent(); - assertNull("No parent logger should be automatically set up using log4j-api", parent); + assertNull(parent, "No parent logger should be automatically set up using log4j-api"); } - @Test(expected = UnsupportedOperationException.class) - public void testSetParentFails() { - logger.setParent(null); + @Test + void testSetParentFails() { + assertThrows(UnsupportedOperationException.class, () -> logger.setParent(null)); } @Test - public void testSetLevelFails() { + void testSetLevelFails() { logger.setLevel(null); } } diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AsyncLoggerThreadsTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AsyncLoggerThreadsTest.java index 0a04ba09013..fd17433f6ca 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AsyncLoggerThreadsTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/AsyncLoggerThreadsTest.java @@ -16,40 +16,40 @@ */ package org.apache.logging.log4j.jul.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.async.AsyncLoggerContextSelector; -import org.apache.logging.log4j.core.test.categories.AsyncLoggers; +import org.apache.logging.log4j.core.test.junit.Tags; import org.apache.logging.log4j.core.util.Constants; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Category(AsyncLoggers.class) -public class AsyncLoggerThreadsTest { +@Tag(Tags.ASYNC_LOGGERS) +class AsyncLoggerThreadsTest { - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, AsyncLoggerContextSelector.class.getName()); System.setProperty("java.util.logging.manager", org.apache.logging.log4j.jul.LogManager.class.getName()); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR); System.clearProperty("java.util.logging.manager"); } @Test - public void testAsyncLoggerThreads() { + void testAsyncLoggerThreads() { LogManager.getLogger("com.foo.Bar").info("log"); final List asyncLoggerThreads = Thread.getAllStackTraces().keySet().stream() .filter(thread -> thread.getName().matches("Log4j2-TF.*AsyncLogger.*")) .collect(Collectors.toList()); - assertEquals(asyncLoggerThreads.toString(), 1, asyncLoggerThreads.size()); + assertEquals(1, asyncLoggerThreads.size(), asyncLoggerThreads.toString()); } } diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/BracketInNotInterpolatedMessageTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/BracketInNotInterpolatedMessageTest.java index 18b382ad3be..71d56824520 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/BracketInNotInterpolatedMessageTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/BracketInNotInterpolatedMessageTest.java @@ -17,9 +17,9 @@ package org.apache.logging.log4j.jul.test; import static java.util.logging.Level.INFO; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.logging.LogRecord; @@ -27,24 +27,24 @@ import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.test.appender.ListAppender; import org.apache.logging.log4j.jul.LogManager; -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.Test; -public class BracketInNotInterpolatedMessageTest { +class BracketInNotInterpolatedMessageTest { - @BeforeClass - public static void setUpClass() { + @BeforeAll + static void setUpClass() { System.setProperty("java.util.logging.manager", LogManager.class.getName()); } - @AfterClass - public static void tearDownClass() { + @AfterAll + static void tearDownClass() { System.clearProperty("java.util.logging.manager"); } @Test - public void noInterpolation() { + void noInterpolation() { final Logger logger = Logger.getLogger("Test"); logger.info("{raw}"); logger.log( diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CallerInformationTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CallerInformationTest.java index ff644a40d35..1b57a3918d0 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CallerInformationTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CallerInformationTest.java @@ -47,7 +47,7 @@ public static void tearDownClass() { } @Test - public void testClassLogger() throws Exception { + public void testClassLogger() { final ListAppender app = ctx.getListAppender("Class").clear(); final Logger logger = Logger.getLogger("ClassLogger"); logger.info("Ignored message contents."); @@ -61,7 +61,7 @@ public void testClassLogger() throws Exception { } @Test - public void testMethodLogger() throws Exception { + public void testMethodLogger() { final ListAppender app = ctx.getListAppender("Method").clear(); final Logger logger = Logger.getLogger("MethodLogger"); logger.info("More messages."); diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CoreLoggerTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CoreLoggerTest.java index e6695c6fe02..0aeedb406d0 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CoreLoggerTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/CoreLoggerTest.java @@ -26,28 +26,28 @@ import org.apache.logging.log4j.jul.CoreLoggerAdapter; import org.apache.logging.log4j.jul.LogManager; import org.apache.logging.log4j.util.Strings; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class CoreLoggerTest extends AbstractLoggerTest { +class CoreLoggerTest extends AbstractLoggerTest { - @BeforeClass - public static void setUpClass() { + @BeforeAll + static void setUpClass() { System.setProperty("java.util.logging.manager", LogManager.class.getName()); System.setProperty(Constants.LOGGER_ADAPTOR_PROPERTY, CoreLoggerAdapter.class.getName()); } - @AfterClass - public static void tearDownClass() { + @AfterAll + static void tearDownClass() { System.clearProperty("java.util.logging.manager"); System.clearProperty(Constants.LOGGER_ADAPTOR_PROPERTY); } - @Before - public void setUp() { + @BeforeEach + void setUp() { // Reset the logger context LoggerContext.getContext(false).reconfigure(); @@ -62,8 +62,8 @@ public void setUp() { assertThat(stringAppender).isNotNull(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { if (eventAppender != null) { eventAppender.clear(); } @@ -76,7 +76,7 @@ public void tearDown() { } @Test - public void testRootSetLevelToNull() { + void testRootSetLevelToNull() { final Logger rootLogger = Logger.getLogger(Strings.EMPTY); assertThat(rootLogger.getLevel()).isEqualTo(Level.SEVERE); assertThat(getEffectiveLevel(rootLogger)).isEqualTo(Level.SEVERE); @@ -91,7 +91,7 @@ public void testRootSetLevelToNull() { } @Test - public void testSetLevel() { + void testSetLevel() { final Logger a = Logger.getLogger("a"); final Logger a_b = Logger.getLogger("a.b"); final Logger a_b_c = Logger.getLogger("a.b.c"); @@ -112,7 +112,7 @@ public void testSetLevel() { } @Test - public void testSetLevelToNull() { + void testSetLevelToNull() { final Logger childLogger = Logger.getLogger(LOGGER_NAME + ".NullChild"); assertThat(childLogger.getLevel()).isNull(); assertThat(getEffectiveLevel(childLogger)).isEqualTo(Level.FINE); diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterCustomJulLevelsTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterCustomJulLevelsTest.java index 14b6416eb70..4ad4011178b 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterCustomJulLevelsTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterCustomJulLevelsTest.java @@ -16,18 +16,19 @@ */ package org.apache.logging.log4j.jul.test; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.logging.log4j.Level; import org.apache.logging.log4j.jul.DefaultLevelConverter; import org.apache.logging.log4j.jul.LevelTranslator; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests {@link DefaultLevelConverter} for custom JUL levels. * * @since 2.4 */ -public class DefaultLevelConverterCustomJulLevelsTest { +class DefaultLevelConverterCustomJulLevelsTest { static class CustomLevel extends java.util.logging.Level { @@ -66,81 +67,81 @@ protected CustomLevel(final String name, final int value) { private final DefaultLevelConverter converter = new DefaultLevelConverter(); @Test - public void testCustomJulLevelNearAll() { + void testCustomJulLevelNearAll() { // Sanity check: - Assert.assertEquals(Level.ALL, converter.toLevel(java.util.logging.Level.ALL)); + assertEquals(Level.ALL, converter.toLevel(java.util.logging.Level.ALL)); // Test: - Assert.assertEquals(Level.ALL, converter.toLevel(CustomLevel.ALL_P_1)); + assertEquals(Level.ALL, converter.toLevel(CustomLevel.ALL_P_1)); } @Test - public void testCustomJulLevelNearFinest() { + void testCustomJulLevelNearFinest() { // Sanity check: - Assert.assertEquals(LevelTranslator.FINEST, converter.toLevel(java.util.logging.Level.FINEST)); + assertEquals(LevelTranslator.FINEST, converter.toLevel(java.util.logging.Level.FINEST)); // Test: - Assert.assertEquals(LevelTranslator.FINEST, converter.toLevel(CustomLevel.FINEST_P_1)); - Assert.assertEquals(LevelTranslator.FINEST, converter.toLevel(CustomLevel.FINEST_M_1)); + assertEquals(LevelTranslator.FINEST, converter.toLevel(CustomLevel.FINEST_P_1)); + assertEquals(LevelTranslator.FINEST, converter.toLevel(CustomLevel.FINEST_M_1)); } @Test - public void testCustomJulLevelNearFiner() { + void testCustomJulLevelNearFiner() { // Sanity check: - Assert.assertEquals(Level.TRACE, converter.toLevel(java.util.logging.Level.FINER)); + assertEquals(Level.TRACE, converter.toLevel(java.util.logging.Level.FINER)); // Test: - Assert.assertEquals(Level.TRACE, converter.toLevel(CustomLevel.FINER_P_1)); - Assert.assertEquals(Level.TRACE, converter.toLevel(CustomLevel.FINER_M_1)); + assertEquals(Level.TRACE, converter.toLevel(CustomLevel.FINER_P_1)); + assertEquals(Level.TRACE, converter.toLevel(CustomLevel.FINER_M_1)); } @Test - public void testCustomJulLevelNearFine() { + void testCustomJulLevelNearFine() { // Sanity check: - Assert.assertEquals(Level.DEBUG, converter.toLevel(java.util.logging.Level.FINE)); + assertEquals(Level.DEBUG, converter.toLevel(java.util.logging.Level.FINE)); // Test: - Assert.assertEquals(Level.DEBUG, converter.toLevel(CustomLevel.FINE_P_1)); - Assert.assertEquals(Level.DEBUG, converter.toLevel(CustomLevel.FINE_M_1)); + assertEquals(Level.DEBUG, converter.toLevel(CustomLevel.FINE_P_1)); + assertEquals(Level.DEBUG, converter.toLevel(CustomLevel.FINE_M_1)); } @Test - public void testCustomJulLevelNearConfig() { + void testCustomJulLevelNearConfig() { // Sanity check: - Assert.assertEquals(LevelTranslator.CONFIG, converter.toLevel(java.util.logging.Level.CONFIG)); + assertEquals(LevelTranslator.CONFIG, converter.toLevel(java.util.logging.Level.CONFIG)); // Test: - Assert.assertEquals(LevelTranslator.CONFIG, converter.toLevel(CustomLevel.CONFIG_P_1)); - Assert.assertEquals(LevelTranslator.CONFIG, converter.toLevel(CustomLevel.CONFIG_M_1)); + assertEquals(LevelTranslator.CONFIG, converter.toLevel(CustomLevel.CONFIG_P_1)); + assertEquals(LevelTranslator.CONFIG, converter.toLevel(CustomLevel.CONFIG_M_1)); } @Test - public void testCustomJulLevelNearInfo() { + void testCustomJulLevelNearInfo() { // Sanity check: - Assert.assertEquals(Level.INFO, converter.toLevel(java.util.logging.Level.INFO)); + assertEquals(Level.INFO, converter.toLevel(java.util.logging.Level.INFO)); // Test: - Assert.assertEquals(Level.INFO, converter.toLevel(CustomLevel.INFO_P_1)); - Assert.assertEquals(Level.INFO, converter.toLevel(CustomLevel.INFO_M_1)); + assertEquals(Level.INFO, converter.toLevel(CustomLevel.INFO_P_1)); + assertEquals(Level.INFO, converter.toLevel(CustomLevel.INFO_M_1)); } @Test - public void testCustomJulLevelNearWarning() { + void testCustomJulLevelNearWarning() { // Sanity check: - Assert.assertEquals(Level.WARN, converter.toLevel(java.util.logging.Level.WARNING)); + assertEquals(Level.WARN, converter.toLevel(java.util.logging.Level.WARNING)); // Test: - Assert.assertEquals(Level.WARN, converter.toLevel(CustomLevel.WARNING_P_1)); - Assert.assertEquals(Level.WARN, converter.toLevel(CustomLevel.WARNING_M_1)); + assertEquals(Level.WARN, converter.toLevel(CustomLevel.WARNING_P_1)); + assertEquals(Level.WARN, converter.toLevel(CustomLevel.WARNING_M_1)); } @Test - public void testCustomJulLevelNearSevere() { + void testCustomJulLevelNearSevere() { // Sanity check: - Assert.assertEquals(Level.ERROR, converter.toLevel(java.util.logging.Level.SEVERE)); + assertEquals(Level.ERROR, converter.toLevel(java.util.logging.Level.SEVERE)); // Test: - Assert.assertEquals(Level.ERROR, converter.toLevel(CustomLevel.SEVERE_P_1)); - Assert.assertEquals(Level.ERROR, converter.toLevel(CustomLevel.SEVERE_M_1)); + assertEquals(Level.ERROR, converter.toLevel(CustomLevel.SEVERE_P_1)); + assertEquals(Level.ERROR, converter.toLevel(CustomLevel.SEVERE_M_1)); } @Test - public void testCustomJulLevelNearOff() { + void testCustomJulLevelNearOff() { // Sanity check: - Assert.assertEquals(Level.OFF, converter.toLevel(java.util.logging.Level.OFF)); + assertEquals(Level.OFF, converter.toLevel(java.util.logging.Level.OFF)); // Test: - Assert.assertEquals(Level.OFF, converter.toLevel(CustomLevel.OFF_M_1)); + assertEquals(Level.OFF, converter.toLevel(CustomLevel.OFF_M_1)); } } diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterTest.java index dc7d334fa6b..3f54d569465 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/DefaultLevelConverterTest.java @@ -16,17 +16,18 @@ */ package org.apache.logging.log4j.jul.test; +import static org.junit.jupiter.api.Assertions.assertNull; + import org.apache.logging.log4j.jul.DefaultLevelConverter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class DefaultLevelConverterTest { +class DefaultLevelConverterTest { /** * (LOG4J2-1108) NullPointerException when passing null to java.util.logging.Logger.setLevel(). */ @Test - public void testJulSetNull() { - Assert.assertEquals(null, new DefaultLevelConverter().toLevel(null)); + void testJulSetNull() { + assertNull(new DefaultLevelConverter().toLevel(null)); } } diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/JavaLevelTranslatorTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/JavaLevelTranslatorTest.java index d000d258dc1..7d5dcc17b39 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/JavaLevelTranslatorTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/JavaLevelTranslatorTest.java @@ -16,31 +16,20 @@ */ package org.apache.logging.log4j.jul.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collection; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.jul.LevelTranslator; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests that all JUL levels are mapped to a Log4j level. */ -@RunWith(Parameterized.class) -public class JavaLevelTranslatorTest { +class JavaLevelTranslatorTest { - private final java.util.logging.Level javaLevel; - private final Level log4jLevel; - - public JavaLevelTranslatorTest(final java.util.logging.Level javaLevel, final Level log4jLevel) { - this.javaLevel = javaLevel; - this.log4jLevel = log4jLevel; - } - - @Parameterized.Parameters public static Collection data() { return Arrays.asList(new Object[][] { // All 9 JUL levels, All 8 Log4j levels and extras @@ -58,14 +47,16 @@ public static Collection data() { }); } - @Test - public void testToLevel() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testToLevel(final java.util.logging.Level javaLevel, final Level log4jLevel) { final Level actualLevel = LevelTranslator.toLevel(javaLevel); assertEquals(log4jLevel, actualLevel); } - @Test - public void testToJavaLevel() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testToJavaLevel(final java.util.logging.Level javaLevel, final Level log4jLevel) { final java.util.logging.Level actualLevel = LevelTranslator.toJavaLevel(log4jLevel); assertEquals(javaLevel, actualLevel); } diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jBridgeHandlerTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jBridgeHandlerTest.java index 1dd8833b82e..6b0b8fc1920 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jBridgeHandlerTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jBridgeHandlerTest.java @@ -16,9 +16,8 @@ */ package org.apache.logging.log4j.jul.test; -// note: NO import of Logger, Level, LogManager to prevent conflicts JUL/log4j -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; @@ -33,11 +32,12 @@ import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.config.Reconfigurable; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * Test the Log4jBridgeHandler. @@ -60,8 +60,8 @@ * The code also contains evaluation/test code for development time. It is not used for the unit tests * but kept here for reference and info. See field DEVTEST. */ -@FixMethodOrder(org.junit.runners.MethodSorters.NAME_ASCENDING) // is nicer for manually checking console output -public class Log4jBridgeHandlerTest { +@TestMethodOrder(MethodOrderer.MethodName.class) // is nicer for manually checking console output +class Log4jBridgeHandlerTest { /** Perform developer tests? */ private static final boolean DEVTEST = false; @@ -81,8 +81,8 @@ public class Log4jBridgeHandlerTest { private static final ByteArrayOutputStream sysoutBytes = new ByteArrayOutputStream(1024); private static PrintStream prevSysErrStream; - @BeforeClass - public static void beforeClass() { + @BeforeAll + static void beforeClass() { // debug output to easily recognize misconfig.: // System.out.println("sys-props:\n" + System.getProperties()); System.out.println("sysout: logging-cfg-file: " + System.getProperty("java.util.logging.config.file")); @@ -96,15 +96,15 @@ public static void beforeClass() { System.setErr(new PrintStream(sysoutBytes, true)); } - @AfterClass - public static void afterClass() { + @AfterAll + static void afterClass() { // reset sysout/err to original value System.setErr(prevSysErrStream); System.err.println("^^^--- END capturing output of stderr ---^^^"); } - @Before - public void beforeTest() { + @BeforeEach + void beforeTest() { // reset sysout collector sysoutBytes.reset(); } @@ -116,7 +116,7 @@ private void assertSysoutMatches(String regex) { if (OUTPUT_CAPTURED) prevSysErrStream.print(logOutput); logOutput = logOutput.replace("\r\n", "\n"); regex = regex + "(.|\\n)*"; // allow any text with NL afterwards - assertTrue("Unmatching output:\n" + logOutput + "\n-- vs: --\n" + regex + "\n----", logOutput.matches(regex)); + assertTrue(logOutput.matches(regex), "Unmatching output:\n" + logOutput + "\n-- vs: --\n" + regex + "\n----"); } /** Get regex for a JUL console output. Must match JUL-Console-Formatter! */ @@ -144,7 +144,7 @@ private String log4j( } @Test - public void test1SimpleLoggings1Jul() { + void test1SimpleLoggings1Jul() { julLog.info("Test-'Info'-Log with JUL"); julLog.fine("Test-'Fine'-Log with JUL"); julLog.finest("Test-'Finest'-Log with JUL"); // should not be logged because JUL-level is FINER @@ -160,7 +160,7 @@ public void test1SimpleLoggings1Jul() { } @Test - public void test1SimpleLoggings2Log4jDirect() { + void test1SimpleLoggings2Log4jDirect() { log4jLog.info("Test-'Info'-Log with log4j2"); log4jLog.debug("Test-'Debug'-Log with log4j2"); log4jLog.trace("Test-'Trace'-Log with log4j2"); @@ -171,7 +171,7 @@ public void test1SimpleLoggings2Log4jDirect() { } @Test - public void test2SubMethod() { + void test2SubMethod() { subMethodWithLogs(); // location info is sub method now final String methodRE = "subMethodWithLogs"; assertSysoutMatches( @@ -191,7 +191,7 @@ private void subMethodWithLogs() { } @Test - public void test3JulFlow1() { + void test3JulFlow1() { // note: manually given source information get lost in log4j! julLog.entering("enteringExampleClassParam", "enteringExampleMethodParam"); final String methodRE = "JulFlow"; @@ -204,7 +204,7 @@ public void test3JulFlow1() { } @Test - public void test3JulFlow2() { + void test3JulFlow2() { // note: manually given source information get lost in log4j! julLog.entering("enteringExampleClassParam", "enteringExampleMethodParam_withParams", new Object[] { "with some", "parameters", 42 @@ -220,7 +220,7 @@ public void test3JulFlow2() { } @Test - public void test3JulFlow3() { + void test3JulFlow3() { // note: manually given source information get lost in log4j! julLog.exiting( "exitingExampleClassParam", @@ -241,7 +241,7 @@ public void test3JulFlow3() { } @Test - public void test3JulFlow4() { + void test3JulFlow4() { // note: manually given source information get lost in log4j! julLog.throwing( "throwingExampleClassParam", @@ -262,7 +262,7 @@ public void test3JulFlow4() { } @Test - public void test4JulSpecials1() { + void test4JulSpecials1() { julLog.log( java.util.logging.Level.WARNING, "JUL-Test via log() as warning with exception", @@ -282,7 +282,7 @@ public void test4JulSpecials1() { } @Test - public void test4JulSpecials2() { + void test4JulSpecials2() { // test with MessageFormat julLog.log( java.util.logging.Level.INFO, @@ -308,11 +308,11 @@ public void test4JulSpecials2() { private void assertLogLevel(final String loggerName, final java.util.logging.Level julLevel) { final java.util.logging.Logger lg = java.util.logging.LogManager.getLogManager().getLogger(loggerName); - assertEquals("Logger '" + loggerName + "'", julLevel, (lg == null ? null : lg.getLevel())); + assertEquals(julLevel, (lg == null ? null : lg.getLevel()), "Logger '" + loggerName + "'"); } @Test - public void test5LevelPropFromConfigFile() { + void test5LevelPropFromConfigFile() { // JUL levels are set from config files and the initial propagation assertLogLevel("", java.util.logging.Level.FINE); assertLogLevel("log4j.Log4jBridgeHandlerTest.propagate1", java.util.logging.Level.FINE); @@ -330,7 +330,7 @@ public void test5LevelPropFromConfigFile() { } @Test - public void test5LevelPropSetLevel() { + void test5LevelPropSetLevel() { String name = "log4j.test.new_logger_level_set"; Configurator.setLevel(name, org.apache.logging.log4j.Level.DEBUG); assertLogLevel(name, java.util.logging.Level.FINE); @@ -348,7 +348,7 @@ public void test5LevelPropSetLevel() { } @Test - public void test5LevelPropGC() { + void test5LevelPropGC() { // this test will fail if you comment out "julLoggerRefs.add(julLog);" in propagateLogLevels() test5LevelPropFromConfigFile(); // at start, all should be fine final java.util.logging.Logger julLogRef = diff --git a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jLevelTranslatorTest.java b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jLevelTranslatorTest.java index 2d2d8c2ca30..7f21962e72b 100644 --- a/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jLevelTranslatorTest.java +++ b/log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/Log4jLevelTranslatorTest.java @@ -16,31 +16,20 @@ */ package org.apache.logging.log4j.jul.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collection; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.jul.LevelTranslator; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests that all Log4j levels are mapped to a JUL level. */ -@RunWith(Parameterized.class) -public class Log4jLevelTranslatorTest { +class Log4jLevelTranslatorTest { - private final java.util.logging.Level javaLevel; - private final Level log4jLevel; - - public Log4jLevelTranslatorTest(final java.util.logging.Level javaLevel, final Level log4jLevel) { - this.javaLevel = javaLevel; - this.log4jLevel = log4jLevel; - } - - @Parameterized.Parameters public static Collection data() { return Arrays.asList(new Object[][] { // Some JUL levels, All 8 Log4j levels @@ -57,8 +46,9 @@ public static Collection data() { }); } - @Test - public void testToJavaLevel() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testToJavaLevel(final java.util.logging.Level javaLevel, final Level log4jLevel) { final java.util.logging.Level actualLevel = LevelTranslator.toJavaLevel(log4jLevel); assertEquals(javaLevel, actualLevel); } diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutNullEventDelimiterTest.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutNullEventDelimiterTest.java index e17054c4079..dd390f5b305 100644 --- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutNullEventDelimiterTest.java +++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutNullEventDelimiterTest.java @@ -67,14 +67,14 @@ static void setup() throws IOException { } @AfterAll - static void cleanup() throws IOException { + static void cleanup() { // Stop the TCP server. server.close(); } @Test @LoggerContextSource - void test(final @Named("Socket") SocketAppender appender, final LoggerContext ctx) throws Exception { + void test(final @Named("Socket") SocketAppender appender, final LoggerContext ctx) { assertThat(appender).isNotNull(); appender.addFilter(new AbstractFilter() { @Override diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java index 17b83629755..f0c553b1611 100644 --- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java +++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/LogstashIT.java @@ -176,7 +176,7 @@ private static int readPort(final String propertyName) { } @BeforeAll - public static void initEsClient() { + static void initEsClient() { LOGGER.info(LOG_PREFIX + "instantiating the ES client"); final String hostUri = @@ -196,7 +196,7 @@ public static void initEsClient() { } @BeforeAll - public static void waitForLsInputSockets() { + static void waitForLsInputSockets() { waitForSocketBinding(MavenHardcodedConstants.LS_GELF_INPUT_PORT, "Logstash GELF input"); waitForSocketBinding(MavenHardcodedConstants.LS_TCP_INPUT_PORT, "Logstash TCP input"); } @@ -229,7 +229,7 @@ void deleteIndex() throws IOException { } @AfterAll - public static void stopClient() throws Exception { + static void stopClient() throws Exception { ES_TRANSPORT.close(); REST_CLIENT.close(); } diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/ThreadLocalRecyclerNestedLoggingTest.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/ThreadLocalRecyclerNestedLoggingTest.java index 09eed748fed..2b55549b5cd 100644 --- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/ThreadLocalRecyclerNestedLoggingTest.java +++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/ThreadLocalRecyclerNestedLoggingTest.java @@ -34,7 +34,7 @@ * * @see LOG4J2-2368 */ -public class ThreadLocalRecyclerNestedLoggingTest { +class ThreadLocalRecyclerNestedLoggingTest { private static final class ThrowableLoggingInGetMessage extends RuntimeException { @@ -55,7 +55,7 @@ public String getMessage() { @Test @LoggerContextSource("threadLocalRecyclerNestedLogging.xml") - public void nested_logging_should_not_pollute_thread_local( + void nested_logging_should_not_pollute_thread_local( final LoggerContext loggerContext, final @Named(value = "List1") ListAppender appender1, final @Named(value = "List2") ListAppender appender2) { diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/resolver/ReadOnlyStringMapResolverTest.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/resolver/ReadOnlyStringMapResolverTest.java index aa097cfca6a..422514e9f43 100644 --- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/resolver/ReadOnlyStringMapResolverTest.java +++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/resolver/ReadOnlyStringMapResolverTest.java @@ -141,7 +141,7 @@ void test_mdc_key_access() { } @Test - public void test_map_key_access() { + void test_map_key_access() { // Create the log event. final String directlyAccessedKey = "mapKey1"; @@ -210,7 +210,7 @@ void test_mdc_pattern() { } @Test - public void test_map_pattern() { + void test_map_pattern() { // Create the log event. final String patternMatchedKey = "mapKey1"; @@ -280,7 +280,7 @@ void test_mdc_flatten() { } @Test - public void test_map_flatten() { + void test_map_flatten() { // Create the log event. final String patternMatchedKey = "mapKey1"; diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/util/JsonReaderTest.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/util/JsonReaderTest.java index 2c0c598b7ef..8c184f70e65 100644 --- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/util/JsonReaderTest.java +++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/util/JsonReaderTest.java @@ -319,7 +319,7 @@ void test_conflicting_object_key_1(final String key, final int index, final Stri @Test @SuppressWarnings("DoubleBraceInitialization") - public void test_nesting() { + void test_nesting() { test( "{\"k1\": [true, null, 1e5, {\"k2\": \"v2\", \"k3\": {\"k4\": \"v4\"}}]}", Collections.singletonMap( diff --git a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/AbstractMongoDbCappedIT.java b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/AbstractMongoDbCappedIT.java index 56cf3a89bee..76ca21e54a5 100644 --- a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/AbstractMongoDbCappedIT.java +++ b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/AbstractMongoDbCappedIT.java @@ -16,13 +16,15 @@ */ package org.apache.logging.log4j.mongodb; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.bson.Document; -import org.junit.jupiter.api.Assertions; abstract class AbstractMongoDbCappedIT { @@ -30,12 +32,12 @@ protected void test(final LoggerContext ctx, final MongoClient mongoClient) { final Logger logger = ctx.getLogger(AbstractMongoDbCappedIT.class); logger.info("Hello log"); final MongoDatabase database = mongoClient.getDatabase(MongoDbTestConstants.DATABASE_NAME); - Assertions.assertNotNull(database); + assertNotNull(database); final MongoCollection collection = database.getCollection(getClass().getSimpleName()); - Assertions.assertNotNull(collection); + assertNotNull(collection); final Document first = collection.find().first(); - Assertions.assertNotNull(first); - Assertions.assertEquals("Hello log", first.getString("message"), first.toJson()); + assertNotNull(first); + assertEquals("Hello log", first.getString("message"), first.toJson()); } } diff --git a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbAuthFailureIT.java b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbAuthFailureIT.java index 5a44aa5456e..ee77fd373d2 100644 --- a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbAuthFailureIT.java +++ b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbAuthFailureIT.java @@ -43,7 +43,6 @@ void test(final LoggerContext ctx, final MongoClient mongoClient) { assertNotNull(database); final MongoCollection collection = database.getCollection(getClass().getSimpleName()); - ; assertNotNull(collection); final Document first = collection.find().first(); assertNull(first); diff --git a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbMapMessageIT.java b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbMapMessageIT.java index b285529c0ce..c2b30bf3da6 100644 --- a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbMapMessageIT.java +++ b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbMapMessageIT.java @@ -16,6 +16,9 @@ */ package org.apache.logging.log4j.mongodb; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -25,7 +28,6 @@ import org.apache.logging.log4j.message.MapMessage; import org.apache.logging.log4j.test.junit.UsingStatusListener; import org.bson.Document; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @UsingMongoDb @@ -42,14 +44,14 @@ void test(final LoggerContext ctx, final MongoClient mongoClient) { mapMessage.with("SomeInt", 1); logger.info(mapMessage); final MongoDatabase database = mongoClient.getDatabase(MongoDbTestConstants.DATABASE_NAME); - Assertions.assertNotNull(database); + assertNotNull(database); final MongoCollection collection = database.getCollection(getClass().getSimpleName()); - Assertions.assertNotNull(collection); + assertNotNull(collection); final Document first = collection.find().first(); - Assertions.assertNotNull(first); + assertNotNull(first); final String firstJson = first.toJson(); - Assertions.assertEquals("SomeValue", first.getString("SomeName"), firstJson); - Assertions.assertEquals(Integer.valueOf(1), first.getInteger("SomeInt"), firstJson); + assertEquals("SomeValue", first.getString("SomeName"), firstJson); + assertEquals(Integer.valueOf(1), first.getInteger("SomeInt"), firstJson); } } diff --git a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbResolver.java b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbResolver.java index 1246d48e496..e5b17e27db8 100644 --- a/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbResolver.java +++ b/log4j-mongodb/src/test/java/org/apache/logging/log4j/mongodb/MongoDbResolver.java @@ -37,7 +37,7 @@ public MongoDbResolver() { } @Override - public void beforeAll(ExtensionContext context) throws Exception { + public void beforeAll(ExtensionContext context) { ExtensionContextAnchor.setAttribute(MongoClientHolder.class, new MongoClientHolder(), context); } @@ -63,7 +63,7 @@ public MongoClient get() { } @Override - public void close() throws Exception { + public void close() { mongoClient.close(); } } diff --git a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/AbstractMongoDb4CappedIT.java b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/AbstractMongoDb4CappedIT.java index 6be4f7f6852..07483dd3cf2 100644 --- a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/AbstractMongoDb4CappedIT.java +++ b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/AbstractMongoDb4CappedIT.java @@ -16,13 +16,15 @@ */ package org.apache.logging.log4j.mongodb4; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.bson.Document; -import org.junit.jupiter.api.Assertions; abstract class AbstractMongoDb4CappedIT { @@ -30,12 +32,12 @@ protected void test(final LoggerContext ctx, final MongoClient mongoClient) { final Logger logger = ctx.getLogger(AbstractMongoDb4CappedIT.class); logger.info("Hello log"); final MongoDatabase database = mongoClient.getDatabase(MongoDb4TestConstants.DATABASE_NAME); - Assertions.assertNotNull(database); + assertNotNull(database); final MongoCollection collection = database.getCollection(getClass().getSimpleName()); - Assertions.assertNotNull(collection); + assertNotNull(collection); final Document first = collection.find().first(); - Assertions.assertNotNull(first); - Assertions.assertEquals("Hello log", first.getString("message"), first.toJson()); + assertNotNull(first); + assertEquals("Hello log", first.getString("message"), first.toJson()); } } diff --git a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4AuthFailureIT.java b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4AuthFailureIT.java index c5b5b15c6db..45f6636e667 100644 --- a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4AuthFailureIT.java +++ b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4AuthFailureIT.java @@ -43,7 +43,6 @@ void test(final LoggerContext ctx, final MongoClient mongoClient) { assertNotNull(database); final MongoCollection collection = database.getCollection(getClass().getSimpleName()); - ; assertNotNull(collection); final Document first = collection.find().first(); assertNull(first); diff --git a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4MapMessageIT.java b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4MapMessageIT.java index b7a384c23b1..90fc885e078 100644 --- a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4MapMessageIT.java +++ b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4MapMessageIT.java @@ -16,6 +16,9 @@ */ package org.apache.logging.log4j.mongodb4; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -25,7 +28,6 @@ import org.apache.logging.log4j.message.MapMessage; import org.apache.logging.log4j.test.junit.UsingStatusListener; import org.bson.Document; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @UsingMongoDb4 @@ -42,14 +44,14 @@ void test(final LoggerContext ctx, final MongoClient mongoClient) { mapMessage.with("SomeInt", 1); logger.info(mapMessage); final MongoDatabase database = mongoClient.getDatabase(MongoDb4TestConstants.DATABASE_NAME); - Assertions.assertNotNull(database); + assertNotNull(database); final MongoCollection collection = database.getCollection(getClass().getSimpleName()); - Assertions.assertNotNull(collection); + assertNotNull(collection); final Document first = collection.find().first(); - Assertions.assertNotNull(first); + assertNotNull(first); final String firstJson = first.toJson(); - Assertions.assertEquals("SomeValue", first.getString("SomeName"), firstJson); - Assertions.assertEquals(Integer.valueOf(1), first.getInteger("SomeInt"), firstJson); + assertEquals("SomeValue", first.getString("SomeName"), firstJson); + assertEquals(Integer.valueOf(1), first.getInteger("SomeInt"), firstJson); } } diff --git a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4Resolver.java b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4Resolver.java index e7994f10297..0534c09631a 100644 --- a/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4Resolver.java +++ b/log4j-mongodb4/src/test/java/org/apache/logging/log4j/mongodb4/MongoDb4Resolver.java @@ -37,7 +37,7 @@ public MongoDb4Resolver() { } @Override - public void beforeAll(ExtensionContext context) throws Exception { + public void beforeAll(ExtensionContext context) { ExtensionContextAnchor.setAttribute(MongoClientHolder.class, new MongoClientHolder(), context); } @@ -63,7 +63,7 @@ public MongoClient get() { } @Override - public void close() throws Exception { + public void close() { mongoClient.close(); } } diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java index a2b7c7f7595..9cad3cdafc3 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java @@ -30,23 +30,23 @@ /** * Test LoggerContext lookups by verifying the anchor class representing calling code. */ -public class LoggerContextAnchorTest { +class LoggerContextAnchorTest { private static final String PREFIX = "Log4jLoggerFactory.getContext() found anchor class "; @Test - public void testLoggerFactoryLookupClass() { + void testLoggerFactoryLookupClass() { final String fqcn = getAnchorFqcn(() -> LoggerFactory.getLogger(LoggerContextAnchorTest.class)); assertEquals(getClass().getName(), fqcn); } @Test - public void testLoggerFactoryLookupString() { + void testLoggerFactoryLookupString() { final String fqcn = getAnchorFqcn(() -> LoggerFactory.getLogger("custom.logger")); assertEquals(getClass().getName(), fqcn); } @Test - public void testLoggerFactoryGetILoggerFactoryLookup() { + void testLoggerFactoryGetILoggerFactoryLookup() { final String fqcn = getAnchorFqcn(() -> LoggerFactory.getILoggerFactory().getLogger("custom.logger")); assertEquals(getClass().getName(), fqcn); diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java index 3543bf32235..b2ccd8da303 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java @@ -27,10 +27,10 @@ import org.slf4j.LoggerFactory; @LoggerContextSource("log4j2-calling-class.xml") -public class CallerInformationTest { +class CallerInformationTest { @Test - public void testClassLogger(@Named("Class") final ListAppender app) throws Exception { + void testClassLogger(@Named("Class") final ListAppender app) { app.clear(); final Logger logger = LoggerFactory.getLogger("ClassLogger"); logger.info("Ignored message contents."); @@ -44,7 +44,7 @@ public void testClassLogger(@Named("Class") final ListAppender app) throws Excep } @Test - public void testMethodLogger(@Named("Method") final ListAppender app) throws Exception { + void testMethodLogger(@Named("Method") final ListAppender app) { app.clear(); final Logger logger = LoggerFactory.getLogger("MethodLogger"); logger.info("More messages."); diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java index 6b4e509f86c..09e9a0f070d 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java @@ -25,10 +25,10 @@ /** * Tests logging during shutdown. */ -public class Log4j1222Test { +class Log4j1222Test { @Test - public void homepageRendersSuccessfully() { + void homepageRendersSuccessfully() { System.setProperty("log4j.configurationFile", "log4j2-console.xml"); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); } diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java index 4926d3bcd9b..d6396cd600a 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java @@ -24,24 +24,24 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class Log4jMarkerTest { +class Log4jMarkerTest { private static Log4jMarkerFactory markerFactory; @BeforeAll - public static void startup() { + static void startup() { markerFactory = ((Log4jLoggerFactory) org.slf4j.LoggerFactory.getILoggerFactory()).getMarkerFactory(); } @Test - public void testEquals() { + void testEquals() { final Marker markerA = MarkerManager.getMarker(Log4jMarkerTest.class.getName() + "-A"); final Marker markerB = MarkerManager.getMarker(Log4jMarkerTest.class.getName() + "-B"); final Log4jMarker marker1 = new Log4jMarker(markerFactory, markerA); final Log4jMarker marker2 = new Log4jMarker(markerFactory, markerA); final Log4jMarker marker3 = new Log4jMarker(markerFactory, markerB); assertEquals(marker1, marker2); - assertNotEquals(marker1, null); + assertNotEquals(null, marker1); assertNotEquals(null, marker1); assertNotEquals(marker1, marker3); } diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java index 720bcfcb9a7..3b6ac024a90 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java @@ -28,10 +28,10 @@ /** * Tests cleanup of the LoggerContexts. */ -public class LoggerContextTest { +class LoggerContextTest { @Test - public void testCleanup() throws Exception { + void testCleanup() { final Log4jLoggerFactory factory = (Log4jLoggerFactory) LoggerFactory.getILoggerFactory(); factory.getLogger("test"); Set set = factory.getLoggerContexts(); diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java index c622aba475e..fb05f4964b6 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java @@ -39,7 +39,7 @@ * */ @LoggerContextSource("log4j-test1.xml") -public class LoggerTest { +class LoggerTest { private final Logger logger; private final LoggerContext ctx; @@ -50,13 +50,13 @@ public LoggerTest(final LoggerContext context) { } @Test - public void debug() { + void debug() { logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{}" + Strings.LINE_SEPARATOR); } @Test - public void debugNoParms() { + void debugNoParms() { logger.debug("Debug message {}"); verify("o.a.l.s.LoggerTest Debug message {} MDC{}" + Strings.LINE_SEPARATOR); logger.debug("Debug message {}", (Object[]) null); @@ -67,13 +67,13 @@ public void debugNoParms() { } @Test - public void debugWithParms() { + void debugWithParms() { logger.debug("Hello, {}", "World"); verify("o.a.l.s.LoggerTest Hello, World MDC{}" + Strings.LINE_SEPARATOR); } @Test - public void mdc() { + void mdc() { MDC.put("TestYear", "2010"); logger.debug("Debug message"); @@ -87,27 +87,27 @@ public void mdc() { * @see LOG4J2-793 */ @Test - public void supportsCustomSLF4JMarkers() { + void supportsCustomSLF4JMarkers() { final Marker marker = new CustomFlatMarker("TEST"); logger.debug(marker, "Test"); verify("o.a.l.s.LoggerTest Test MDC{}" + Strings.LINE_SEPARATOR); } @Test - public void testRootLogger() { + void testRootLogger() { final Logger l = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); assertNotNull(l, "No Root Logger"); assertEquals(Logger.ROOT_LOGGER_NAME, l.getName()); } @Test - public void doubleSubst() { + void doubleSubst() { logger.debug("Hello, {}", "Log4j {}"); verify("o.a.l.s.LoggerTest Hello, Log4j {} MDC{}" + Strings.LINE_SEPARATOR); } @Test - public void testThrowable() { + void testThrowable() { final Throwable expected = new RuntimeException(); logger.debug("Hello {}", expected); verifyThrowable(expected); @@ -166,8 +166,7 @@ private void verifyThrowable(final Throwable expected) { @BeforeEach @AfterEach - public void cleanup( - @Named("List") final ListAppender list, @Named("UnformattedList") final ListAppender unformattedList) { + void cleanup(@Named("List") final ListAppender list, @Named("UnformattedList") final ListAppender unformattedList) { MDC.clear(); list.clear(); unformattedList.clear(); diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java index c81045aa5c8..e3f42a9cc84 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java @@ -33,25 +33,25 @@ /** * */ -public class MarkerTest { +class MarkerTest { private static final String CHILD_MAKER_NAME = MarkerTest.class.getSimpleName() + "-TEST"; private static final String PARENT_MARKER_NAME = MarkerTest.class.getSimpleName() + "-PARENT"; private static Log4jMarkerFactory markerFactory; @BeforeAll - public static void startup() { + static void startup() { markerFactory = ((Log4jLoggerFactory) org.slf4j.LoggerFactory.getILoggerFactory()).getMarkerFactory(); } @BeforeEach @AfterEach - public void clearMarkers() { + void clearMarkers() { MarkerManager.clear(); } @Test - public void testAddMarker() { + void testAddMarker() { final String childMakerName = CHILD_MAKER_NAME + "-AM"; final String parentMarkerName = PARENT_MARKER_NAME + "-AM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMakerName); @@ -74,7 +74,7 @@ public void testAddMarker() { } @Test - public void testAddNullMarker() { + void testAddNullMarker() { final String childMarkerName = CHILD_MAKER_NAME + "-ANM"; final String parentMakerName = PARENT_MARKER_NAME + "-ANM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -100,7 +100,7 @@ public void testAddNullMarker() { } @Test - public void testAddSameMarker() { + void testAddSameMarker() { final String childMarkerName = CHILD_MAKER_NAME + "-ASM"; final String parentMakerName = PARENT_MARKER_NAME + "-ASM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -122,7 +122,7 @@ public void testAddSameMarker() { } @Test - public void testEquals() { + void testEquals() { final String childMarkerName = CHILD_MAKER_NAME + "-ASM"; final String parentMakerName = PARENT_MARKER_NAME + "-ASM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -139,7 +139,7 @@ public void testEquals() { } @Test - public void testContainsNullMarker() { + void testContainsNullMarker() { final String childMarkerName = CHILD_MAKER_NAME + "-CM"; final String parentMakerName = PARENT_MARKER_NAME + "-CM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -165,7 +165,7 @@ public void testContainsNullMarker() { } @Test - public void testContainsNullString() { + void testContainsNullString() { final String childMarkerName = CHILD_MAKER_NAME + "-CS"; final String parentMakerName = PARENT_MARKER_NAME + "-CS"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -181,7 +181,7 @@ public void testContainsNullString() { } @Test - public void testRemoveNullMarker() { + void testRemoveNullMarker() { final String childMakerName = CHILD_MAKER_NAME + "-CM"; final String parentMakerName = PARENT_MARKER_NAME + "-CM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMakerName); diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OptionalTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OptionalTest.java index 582c60027c1..102df24f09f 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OptionalTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OptionalTest.java @@ -17,7 +17,6 @@ package org.apache.logging.slf4j; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import org.apache.logging.log4j.core.LoggerContext; @@ -37,7 +36,7 @@ * */ @LoggerContextSource(value = "log4j-test1.xml") -public class OptionalTest { +class OptionalTest { Logger logger = LoggerFactory.getLogger("EventLogger"); Marker marker = MarkerFactory.getMarker("EVENT"); @@ -48,7 +47,7 @@ public OptionalTest(final LoggerContext context) { } @Test - public void testEventLogger() { + void testEventLogger() { logger.info(marker, "This is a test"); MDC.clear(); verify("EventLogger", "o.a.l.s.OptionalTest This is a test" + Strings.LINE_SEPARATOR); @@ -57,14 +56,14 @@ public void testEventLogger() { private void verify(final String name, final String expected) { final ListAppender listApp = CTX.getConfiguration().getAppender(name); final List events = listApp.getMessages(); - assertTrue(events.size() == 1, "Incorrect number of messages. Expected 1 Actual " + events.size()); + assertEquals(1, events.size(), "Incorrect number of messages. Expected 1 Actual " + events.size()); final String actual = events.get(0); assertEquals(expected, actual, "Incorrect message. Expected " + expected + ". Actual " + actual); listApp.clear(); } @BeforeEach - public void cleanup(@Named("List") final ListAppender list, @Named("EventLogger") final ListAppender eventLogger) { + void cleanup(@Named("List") final ListAppender list, @Named("EventLogger") final ListAppender eventLogger) { list.clear(); eventLogger.clear(); } diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java index d3c78712723..1f8fee2e2eb 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java @@ -25,10 +25,10 @@ /** * Tests StackOverflow when slf4j-impl and to-slf4j are both present. */ -public class OverflowTest { +class OverflowTest { @Test - public void log() { + void log() { try { LoggerFactory.getLogger(OverflowTest.class); fail("Failed to detect inclusion of log4j-to-slf4j"); diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java index b92bb7de9d8..d8633a1863b 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java @@ -29,12 +29,12 @@ * */ @LoggerContextSource("log4j-test1.xml") -public class SerializeTest { +class SerializeTest { Logger logger = LoggerFactory.getLogger("LoggerTest"); @Test - public void testLogger() throws Exception { + void testLogger() { assertThat((Serializable) logger, serializesRoundTrip()); } } diff --git a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java index 2a111be434c..2faca8ac5f0 100644 --- a/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java +++ b/log4j-slf4j-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java @@ -22,7 +22,7 @@ import org.apache.logging.log4j.message.MessageFactory2; import org.junit.jupiter.api.Test; -public class ThrowableConsumingMessageFactoryTest { +class ThrowableConsumingMessageFactoryTest { private static final String MESSAGE = "MESSAGE"; private static final Object P0 = new Object(); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java index a2b7c7f7595..9cad3cdafc3 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/other/pkg/LoggerContextAnchorTest.java @@ -30,23 +30,23 @@ /** * Test LoggerContext lookups by verifying the anchor class representing calling code. */ -public class LoggerContextAnchorTest { +class LoggerContextAnchorTest { private static final String PREFIX = "Log4jLoggerFactory.getContext() found anchor class "; @Test - public void testLoggerFactoryLookupClass() { + void testLoggerFactoryLookupClass() { final String fqcn = getAnchorFqcn(() -> LoggerFactory.getLogger(LoggerContextAnchorTest.class)); assertEquals(getClass().getName(), fqcn); } @Test - public void testLoggerFactoryLookupString() { + void testLoggerFactoryLookupString() { final String fqcn = getAnchorFqcn(() -> LoggerFactory.getLogger("custom.logger")); assertEquals(getClass().getName(), fqcn); } @Test - public void testLoggerFactoryGetILoggerFactoryLookup() { + void testLoggerFactoryGetILoggerFactoryLookup() { final String fqcn = getAnchorFqcn(() -> LoggerFactory.getILoggerFactory().getLogger("custom.logger")); assertEquals(getClass().getName(), fqcn); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java index b0bc3e2f13a..4fb6446697e 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java @@ -29,10 +29,10 @@ import org.slf4j.spi.LoggingEventBuilder; @LoggerContextSource("log4j2-calling-class.xml") -public class CallerInformationTest { +class CallerInformationTest { @Test - public void testClassLogger(@Named("Class") final ListAppender app) throws Exception { + void testClassLogger(@Named("Class") final ListAppender app) { app.clear(); final Logger logger = LoggerFactory.getLogger("ClassLogger"); logger.info("Ignored message contents."); @@ -49,7 +49,7 @@ public void testClassLogger(@Named("Class") final ListAppender app) throws Excep } @Test - public void testMethodLogger(@Named("Method") final ListAppender app) throws Exception { + void testMethodLogger(@Named("Method") final ListAppender app) { app.clear(); final Logger logger = LoggerFactory.getLogger("MethodLogger"); logger.info("More messages."); @@ -70,7 +70,7 @@ public void testMethodLogger(@Named("Method") final ListAppender app) throws Exc } @Test - public void testFqcnLogger(@Named("Fqcn") final ListAppender app) throws Exception { + void testFqcnLogger(@Named("Fqcn") final ListAppender app) { app.clear(); final Logger logger = LoggerFactory.getLogger("FqcnLogger"); LoggingEventBuilder loggingEventBuilder = logger.atInfo(); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java index 6b4e509f86c..09e9a0f070d 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4j1222Test.java @@ -25,10 +25,10 @@ /** * Tests logging during shutdown. */ -public class Log4j1222Test { +class Log4j1222Test { @Test - public void homepageRendersSuccessfully() { + void homepageRendersSuccessfully() { System.setProperty("log4j.configurationFile", "log4j2-console.xml"); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); } diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jEventBuilderTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jEventBuilderTest.java index 8441bb1c92f..32c30386c21 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jEventBuilderTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jEventBuilderTest.java @@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory; @LoggerContextSource("log4j2-config.xml") -public class Log4jEventBuilderTest { +class Log4jEventBuilderTest { private final Logger logger; private final ListAppender appender; @@ -41,12 +41,12 @@ public Log4jEventBuilderTest(@Named("List") final Appender appender) { } @BeforeEach - public void setUp() { + void setUp() { appender.clear(); } @Test - public void testKeyValuePairs() { + void testKeyValuePairs() { logger.atDebug().addKeyValue("testKeyValuePairs", "ok").log(); final List events = appender.getEvents(); assertThat(events).hasSize(1); @@ -54,7 +54,7 @@ public void testKeyValuePairs() { } @Test - public void testArguments() { + void testArguments() { logger.atDebug().setMessage("{}-{}").addArgument("a").addArgument("b").log(); logger.atDebug().log("{}-{}", "a", "b"); logger.atDebug().addArgument("a").log("{}-{}", "b"); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMDCAdapterTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMDCAdapterTest.java index 0559608f467..d3f15f73201 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMDCAdapterTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMDCAdapterTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -public class Log4jMDCAdapterTest { +class Log4jMDCAdapterTest { private static final Log4jMDCAdapter MDC_ADAPTER = new Log4jMDCAdapter(); private static final String KEY = "Log4j2"; @@ -51,7 +51,7 @@ static Stream keys() { @ParameterizedTest @MethodSource("keys") - public void testPushPopByKey(final String key) { + void testPushPopByKey(final String key) { MDC_ADAPTER.clearDequeByKey(key); final Deque expectedValues = createDeque(100); expectedValues.descendingIterator().forEachRemaining(v -> MDC_ADAPTER.pushByKey(key, v)); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java index 4926d3bcd9b..d6396cd600a 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/Log4jMarkerTest.java @@ -24,24 +24,24 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -public class Log4jMarkerTest { +class Log4jMarkerTest { private static Log4jMarkerFactory markerFactory; @BeforeAll - public static void startup() { + static void startup() { markerFactory = ((Log4jLoggerFactory) org.slf4j.LoggerFactory.getILoggerFactory()).getMarkerFactory(); } @Test - public void testEquals() { + void testEquals() { final Marker markerA = MarkerManager.getMarker(Log4jMarkerTest.class.getName() + "-A"); final Marker markerB = MarkerManager.getMarker(Log4jMarkerTest.class.getName() + "-B"); final Log4jMarker marker1 = new Log4jMarker(markerFactory, markerA); final Log4jMarker marker2 = new Log4jMarker(markerFactory, markerA); final Log4jMarker marker3 = new Log4jMarker(markerFactory, markerB); assertEquals(marker1, marker2); - assertNotEquals(marker1, null); + assertNotEquals(null, marker1); assertNotEquals(null, marker1); assertNotEquals(marker1, marker3); } diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java index 720bcfcb9a7..3b6ac024a90 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerContextTest.java @@ -28,10 +28,10 @@ /** * Tests cleanup of the LoggerContexts. */ -public class LoggerContextTest { +class LoggerContextTest { @Test - public void testCleanup() throws Exception { + void testCleanup() { final Log4jLoggerFactory factory = (Log4jLoggerFactory) LoggerFactory.getILoggerFactory(); factory.getLogger("test"); Set set = factory.getLoggerContexts(); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java index 86e6cb267a8..ee32fe2b7e6 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java @@ -43,13 +43,13 @@ * */ @LoggerContextSource("log4j-test1.xml") -public class LoggerTest { +class LoggerTest { private final Logger logger; private final LoggerContext ctx; @Test - public void debug() { + void debug() { logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{}" + Strings.LINE_SEPARATOR); } @@ -60,7 +60,7 @@ public LoggerTest(final LoggerContext context) { } @Test - public void debugNoParms() { + void debugNoParms() { logger.debug("Debug message {}"); verify("o.a.l.s.LoggerTest Debug message {} MDC{}" + Strings.LINE_SEPARATOR); logger.debug("Debug message {}", (Object[]) null); @@ -71,13 +71,13 @@ public void debugNoParms() { } @Test - public void debugWithParms() { + void debugWithParms() { logger.debug("Hello, {}", "World"); verify("o.a.l.s.LoggerTest Hello, World MDC{}" + Strings.LINE_SEPARATOR); } @Test - public void mdc() { + void mdc() { MDC.put("TestYear", "2010"); logger.debug("Debug message"); @@ -88,7 +88,7 @@ public void mdc() { } @Test - public void mdcStack() { + void mdcStack() { MDC.pushByKey("TestYear", "2010"); logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{TestYear=2010}" + Strings.LINE_SEPARATOR); @@ -107,27 +107,27 @@ public void mdcStack() { * @see LOG4J2-793 */ @Test - public void supportsCustomSLF4JMarkers() { + void supportsCustomSLF4JMarkers() { final Marker marker = new CustomFlatMarker("TEST"); logger.debug(marker, "Test"); verify("o.a.l.s.LoggerTest Test MDC{}" + Strings.LINE_SEPARATOR); } @Test - public void testRootLogger() { + void testRootLogger() { final Logger l = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); assertNotNull(l, "No Root Logger"); assertEquals(Logger.ROOT_LOGGER_NAME, l.getName()); } @Test - public void doubleSubst() { + void doubleSubst() { logger.debug("Hello, {}", "Log4j {}"); verify("o.a.l.s.LoggerTest Hello, Log4j {} MDC{}" + Strings.LINE_SEPARATOR); } @Test - public void testThrowable() { + void testThrowable() { final Throwable expected = new RuntimeException(); logger.debug("Hello {}", expected); verifyThrowable(expected); @@ -161,7 +161,7 @@ public void testThrowable() { } @Test - public void testLazyLoggingEventBuilder() { + void testLazyLoggingEventBuilder() { final ListAppender appender = ctx.getConfiguration().getAppender("UnformattedList"); final Level oldLevel = ctx.getRootLogger().getLevel(); try { @@ -201,8 +201,7 @@ private void verifyThrowable(final Throwable expected) { @BeforeEach @AfterEach - public void cleanup( - @Named("List") final ListAppender list, @Named("UnformattedList") final ListAppender unformattedList) { + void cleanup(@Named("List") final ListAppender list, @Named("UnformattedList") final ListAppender unformattedList) { MDC.clear(); list.clear(); unformattedList.clear(); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java index c81045aa5c8..e3f42a9cc84 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/MarkerTest.java @@ -33,25 +33,25 @@ /** * */ -public class MarkerTest { +class MarkerTest { private static final String CHILD_MAKER_NAME = MarkerTest.class.getSimpleName() + "-TEST"; private static final String PARENT_MARKER_NAME = MarkerTest.class.getSimpleName() + "-PARENT"; private static Log4jMarkerFactory markerFactory; @BeforeAll - public static void startup() { + static void startup() { markerFactory = ((Log4jLoggerFactory) org.slf4j.LoggerFactory.getILoggerFactory()).getMarkerFactory(); } @BeforeEach @AfterEach - public void clearMarkers() { + void clearMarkers() { MarkerManager.clear(); } @Test - public void testAddMarker() { + void testAddMarker() { final String childMakerName = CHILD_MAKER_NAME + "-AM"; final String parentMarkerName = PARENT_MARKER_NAME + "-AM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMakerName); @@ -74,7 +74,7 @@ public void testAddMarker() { } @Test - public void testAddNullMarker() { + void testAddNullMarker() { final String childMarkerName = CHILD_MAKER_NAME + "-ANM"; final String parentMakerName = PARENT_MARKER_NAME + "-ANM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -100,7 +100,7 @@ public void testAddNullMarker() { } @Test - public void testAddSameMarker() { + void testAddSameMarker() { final String childMarkerName = CHILD_MAKER_NAME + "-ASM"; final String parentMakerName = PARENT_MARKER_NAME + "-ASM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -122,7 +122,7 @@ public void testAddSameMarker() { } @Test - public void testEquals() { + void testEquals() { final String childMarkerName = CHILD_MAKER_NAME + "-ASM"; final String parentMakerName = PARENT_MARKER_NAME + "-ASM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -139,7 +139,7 @@ public void testEquals() { } @Test - public void testContainsNullMarker() { + void testContainsNullMarker() { final String childMarkerName = CHILD_MAKER_NAME + "-CM"; final String parentMakerName = PARENT_MARKER_NAME + "-CM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -165,7 +165,7 @@ public void testContainsNullMarker() { } @Test - public void testContainsNullString() { + void testContainsNullString() { final String childMarkerName = CHILD_MAKER_NAME + "-CS"; final String parentMakerName = PARENT_MARKER_NAME + "-CS"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMarkerName); @@ -181,7 +181,7 @@ public void testContainsNullString() { } @Test - public void testRemoveNullMarker() { + void testRemoveNullMarker() { final String childMakerName = CHILD_MAKER_NAME + "-CM"; final String parentMakerName = PARENT_MARKER_NAME + "-CM"; final org.slf4j.Marker slf4jMarker = org.slf4j.MarkerFactory.getMarker(childMakerName); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java index d3c78712723..1f8fee2e2eb 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/OverflowTest.java @@ -25,10 +25,10 @@ /** * Tests StackOverflow when slf4j-impl and to-slf4j are both present. */ -public class OverflowTest { +class OverflowTest { @Test - public void log() { + void log() { try { LoggerFactory.getLogger(OverflowTest.class); fail("Failed to detect inclusion of log4j-to-slf4j"); diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java index 320e424ab8a..cdea35ada64 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/SerializeTest.java @@ -29,12 +29,12 @@ * */ @LoggerContextSource(value = "log4j-test1.xml") -public class SerializeTest { +class SerializeTest { Logger logger = LoggerFactory.getLogger("LoggerTest"); @Test - public void testLogger() throws Exception { + void testLogger() { assertThat((Serializable) logger, serializesRoundTrip()); } } diff --git a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java index 2a111be434c..2faca8ac5f0 100644 --- a/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java +++ b/log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/message/ThrowableConsumingMessageFactoryTest.java @@ -22,7 +22,7 @@ import org.apache.logging.log4j.message.MessageFactory2; import org.junit.jupiter.api.Test; -public class ThrowableConsumingMessageFactoryTest { +class ThrowableConsumingMessageFactoryTest { private static final String MESSAGE = "MESSAGE"; private static final Object P0 = new Object(); diff --git a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootInitTest.java b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootInitTest.java index 70002ab6afc..e97dcbd6a21 100644 --- a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootInitTest.java +++ b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootInitTest.java @@ -36,10 +36,10 @@ key = "log4j2.loggerContextFactory", value = "org.apache.logging.log4j.core.impl.Log4jContextFactory") @SpringBootTest -public class Log4j2SpringBootInitTest { +class Log4j2SpringBootInitTest { @Test - public void testEnvironment() { + void testEnvironment() { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final ListAppender app = context.getConfiguration().getAppender("Out"); assertNotNull(app); @@ -56,7 +56,7 @@ public static void main(final String[] args) { } @Override - public void run(final ApplicationArguments args) throws Exception { + public void run(final ApplicationArguments args) { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final SpringLookup lookup = new SpringLookup(); lookup.setLoggerContext(context); diff --git a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootLoggingSystemTest.java b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootLoggingSystemTest.java index 072ccf950b3..5c7626c95ba 100644 --- a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootLoggingSystemTest.java +++ b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/Log4j2SpringBootLoggingSystemTest.java @@ -16,6 +16,7 @@ */ package org.apache.logging.log4j.spring.boot; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; @@ -28,10 +29,10 @@ import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem; -public class Log4j2SpringBootLoggingSystemTest { +class Log4j2SpringBootLoggingSystemTest { @Test - public void getStandardConfigLocations() { + void getStandardConfigLocations() { final String customLog4j2Location = "classpath:my_custom_log4j2.properties"; final LoggerContext lc = LogManager.getContext(); // Initialize LogManager to here to prevent a failure trying to @@ -45,14 +46,14 @@ public void getStandardConfigLocations() { @Test @SetSystemProperty(key = Log4j2SpringBootLoggingSystem.LOG4J2_DISABLE_CLOUD_CONFIG_LOGGING_SYSTEM, value = "true") - public void testUseLog4j2LoggingSystem() { + void testUseLog4j2LoggingSystem() { final LoggingSystem loggingSystem = LoggingSystem.get(getClass().getClassLoader()); - assertTrue(loggingSystem.getClass().equals(Log4J2LoggingSystem.class)); + assertEquals(Log4J2LoggingSystem.class, loggingSystem.getClass()); } @Test - public void testLoggingSystemEnabled() { + void testLoggingSystemEnabled() { final LoggingSystem loggingSystem = LoggingSystem.get(getClass().getClassLoader()); - assertTrue(loggingSystem.getClass().equals(Log4j2SpringBootLoggingSystem.class)); + assertEquals(Log4j2SpringBootLoggingSystem.class, loggingSystem.getClass()); } } diff --git a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringLookupTest.java b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringLookupTest.java index 5cbcad68bd6..1f2fc3d057e 100644 --- a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringLookupTest.java +++ b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringLookupTest.java @@ -27,10 +27,10 @@ /** * Test SpringLookup. */ -public class SpringLookupTest { +class SpringLookupTest { @Test - public void testLookup() { + void testLookup() { final MockEnvironment env = new MockEnvironment(); env.setActiveProfiles("test"); env.setDefaultProfiles("one", "two"); @@ -53,7 +53,7 @@ public void testLookup() { } @Test - public void testSpringLookupWithDefaultInterpolator() { + void testSpringLookupWithDefaultInterpolator() { final MockEnvironment env = new MockEnvironment(); env.setActiveProfiles("test"); env.setProperty("app.property", "test"); diff --git a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringProfileTest.java b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringProfileTest.java index 056a194e1db..e32d3820539 100644 --- a/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringProfileTest.java +++ b/log4j-spring-boot/src/test/java/org/apache/logging/log4j/spring/boot/SpringProfileTest.java @@ -34,7 +34,7 @@ * Tests basic condition processing. */ @UsingStatusListener -public class SpringProfileTest { +class SpringProfileTest { private static final String CONFIG = "log4j2-springProfile.xml"; private static final MockEnvironment env = new MockEnvironment(); diff --git a/log4j-spring-cloud-config-client/src/test/java/org/apache/logging/log4j/spring/cloud/config/client/Log4j2EventListenerTest.java b/log4j-spring-cloud-config-client/src/test/java/org/apache/logging/log4j/spring/cloud/config/client/Log4j2EventListenerTest.java index 8182cec6adb..57749b2de80 100644 --- a/log4j-spring-cloud-config-client/src/test/java/org/apache/logging/log4j/spring/cloud/config/client/Log4j2EventListenerTest.java +++ b/log4j-spring-cloud-config-client/src/test/java/org/apache/logging/log4j/spring/cloud/config/client/Log4j2EventListenerTest.java @@ -57,7 +57,7 @@ public class Log4j2EventListenerTest { private ApplicationEventPublisher publisher; @Test - public void test() throws Exception { + public void test() { final AtomicInteger count = new AtomicInteger(0); final Source source = new Source(new File("test.java")); loggerContextRule diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/DumpTagTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/DumpTagTest.java index 8e7c148e4cf..c36d759ed2a 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/DumpTagTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/DumpTagTest.java @@ -16,7 +16,7 @@ */ package org.apache.logging.log4j.taglib; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; @@ -26,23 +26,23 @@ import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockJspWriter; import org.springframework.mock.web.MockPageContext; /** * */ -public class DumpTagTest { +class DumpTagTest { private static final Charset UTF8 = StandardCharsets.UTF_8; private Writer writer; private ByteArrayOutputStream output; private MockPageContext context; private DumpTag tag; - @Before - public void setUp() { + @BeforeEach + void setUp() { this.output = new ByteArrayOutputStream(); this.writer = new OutputStreamWriter(this.output, UTF8); @@ -60,64 +60,64 @@ public JspWriter getOut() { } @Test - public void testDoEndTagDefaultPageScopeNoAttributes() throws Exception { + void testDoEndTagDefaultPageScopeNoAttributes() throws Exception { final int returnValue = this.tag.doEndTag(); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, returnValue); + assertEquals(Tag.EVAL_PAGE, returnValue, "The return value is not correct."); this.writer.flush(); final String output = new String(this.output.toByteArray(), UTF8); - assertEquals("The output is not correct.", "
", output); + assertEquals("
", output, "The output is not correct."); } @Test - public void testDoEndTagDefaultPageScope() throws Exception { + void testDoEndTagDefaultPageScope() throws Exception { this.context.setAttribute("testAttribute01", "testValue01", PageContext.PAGE_SCOPE); this.context.setAttribute("anotherAttribute02", "finalValue02", PageContext.PAGE_SCOPE); this.context.setAttribute("badAttribute03", "skippedValue03", PageContext.SESSION_SCOPE); final int returnValue = this.tag.doEndTag(); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, returnValue); + assertEquals(Tag.EVAL_PAGE, returnValue, "The return value is not correct."); this.writer.flush(); final String output = new String(this.output.toByteArray(), UTF8); assertEquals( - "The output is not correct.", "
" + "
testAttribute01
testValue01
" + "
anotherAttribute02
finalValue02
" + "
", - output); + output, + "The output is not correct."); } @Test - public void testDoEndTagSessionScopeNoAttributes() throws Exception { + void testDoEndTagSessionScopeNoAttributes() throws Exception { this.context.setAttribute("badAttribute01", "skippedValue01", PageContext.PAGE_SCOPE); this.tag.setScope("session"); final int returnValue = this.tag.doEndTag(); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, returnValue); + assertEquals(Tag.EVAL_PAGE, returnValue, "The return value is not correct."); this.writer.flush(); final String output = new String(this.output.toByteArray(), UTF8); - assertEquals("The output is not correct.", "
", output); + assertEquals("
", output, "The output is not correct."); } @Test - public void testDoEndTagSessionScope() throws Exception { + void testDoEndTagSessionScope() throws Exception { this.context.setAttribute("otherAttribute03", "lostValue03", PageContext.PAGE_SCOPE); this.context.setAttribute("coolAttribute01", "weirdValue01", PageContext.SESSION_SCOPE); this.context.setAttribute("testAttribute02", "testValue02", PageContext.SESSION_SCOPE); this.tag.setScope("session"); final int returnValue = this.tag.doEndTag(); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, returnValue); + assertEquals(Tag.EVAL_PAGE, returnValue, "The return value is not correct."); this.writer.flush(); final String output = new String(this.output.toByteArray(), UTF8); assertEquals( - "The output is not correct.", "
" + "
coolAttribute01
weirdValue01
" + "
testAttribute02
testValue02
" + "
", - output); + output, + "The output is not correct."); } } diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/ExceptionAwareTagSupportTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/ExceptionAwareTagSupportTest.java index a377d5c421b..b3b9d0a45fa 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/ExceptionAwareTagSupportTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/ExceptionAwareTagSupportTest.java @@ -16,38 +16,38 @@ */ package org.apache.logging.log4j.taglib; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * */ -public class ExceptionAwareTagSupportTest { +class ExceptionAwareTagSupportTest { private ExceptionAwareTagSupport tag; - @Before - public void setUp() { + @BeforeEach + void setUp() { this.tag = new ExceptionAwareTagSupport() { private static final long serialVersionUID = 1L; }; } @Test - public void testException() { - assertNull("The exception should be null (1).", this.tag.getException()); + void testException() { + assertNull(this.tag.getException(), "The exception should be null (1)."); Exception e = new Exception(); this.tag.setException(e); - assertSame("The exception is not correct (1).", e, this.tag.getException()); + assertSame(e, this.tag.getException(), "The exception is not correct (1)."); this.tag.init(); - assertNull("The exception should be null (2).", this.tag.getException()); + assertNull(this.tag.getException(), "The exception should be null (2)."); e = new RuntimeException(); this.tag.setException(e); - assertSame("The exception is not correct (2).", e, this.tag.getException()); + assertSame(e, this.tag.getException(), "The exception is not correct (2)."); } } diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LogTagTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LogTagTest.java index faabe7b1c68..918c48d33e7 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LogTagTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LogTagTest.java @@ -16,35 +16,35 @@ */ package org.apache.logging.log4j.taglib; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import org.apache.logging.log4j.Level; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * */ -public class LogTagTest { +class LogTagTest { private LogTag tag; - @Before - public void setUp() { + @BeforeEach + void setUp() { this.tag = new LogTag(); } @Test - public void testLevel() { - assertNull("The level should be null (1).", this.tag.getLevel()); + void testLevel() { + assertNull(this.tag.getLevel(), "The level should be null (1)."); this.tag.setLevel(Level.INFO); - assertEquals("The level is not correct (1).", Level.INFO, this.tag.getLevel()); + assertEquals(Level.INFO, this.tag.getLevel(), "The level is not correct (1)."); this.tag.init(); - assertNull("The level should be null (2).", this.tag.getLevel()); + assertNull(this.tag.getLevel(), "The level should be null (2)."); this.tag.setLevel("WARN"); - assertEquals("The level is not correct (2).", Level.WARN, this.tag.getLevel()); + assertEquals(Level.WARN, this.tag.getLevel(), "The level is not correct (2)."); } } diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LoggerAwareTagSupportTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LoggerAwareTagSupportTest.java index d8e117a4ba1..388973be79e 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LoggerAwareTagSupportTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/LoggerAwareTagSupportTest.java @@ -16,22 +16,22 @@ */ package org.apache.logging.log4j.taglib; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.spi.AbstractLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockPageContext; /** * */ -public class LoggerAwareTagSupportTest { +class LoggerAwareTagSupportTest { private MockPageContext context; private LoggerAwareTagSupport tag; @@ -49,7 +49,7 @@ public Object getPage() { } @Test - public void testGetLoggerWithGenericLogger() throws Exception { + void testGetLoggerWithGenericLogger() throws Exception { this.setUp(null); final Logger logger = LogManager.getLogger("testGetLoggerWithGenericLogger"); @@ -57,25 +57,25 @@ public void testGetLoggerWithGenericLogger() throws Exception { this.tag.setLogger(logger); final Log4jTaglibLogger returned = this.tag.getLogger(); - assertNotNull("The first returned logger should not be null.", returned); - assertNotSame("The first returned logger should not be the same as the set.", logger, returned); - assertEquals("The name is not correct.", "testGetLoggerWithGenericLogger", returned.getName()); + assertNotNull(returned, "The first returned logger should not be null."); + assertNotSame(logger, returned, "The first returned logger should not be the same as the set."); + assertEquals("testGetLoggerWithGenericLogger", returned.getName(), "The name is not correct."); final Log4jTaglibLogger returned2 = this.tag.getLogger(); - assertNotNull("The second returned logger should not be null.", returned2); - assertSame("The second returned logger should be the same as the first.", returned, returned2); + assertNotNull(returned2, "The second returned logger should not be null."); + assertSame(returned, returned2, "The second returned logger should be the same as the first."); this.tag.release(); final Log4jTaglibLogger returned3 = this.tag.getLogger(); - assertNotNull("The third returned logger should not be null.", returned3); - assertNotSame("The third returned logger should not be the same as the first.", returned, returned3); + assertNotNull(returned3, "The third returned logger should not be null."); + assertNotSame(returned, returned3, "The third returned logger should not be the same as the first."); } @Test - public void testGetLoggerWithTaglibLogger() throws Exception { + void testGetLoggerWithTaglibLogger() throws Exception { this.setUp(null); final AbstractLogger wrapped = (AbstractLogger) LogManager.getLogger("testGetLoggerWithTaglibLogger"); @@ -84,71 +84,71 @@ public void testGetLoggerWithTaglibLogger() throws Exception { this.tag.setLogger(logger); Log4jTaglibLogger returned = this.tag.getLogger(); - assertNotNull("The first returned logger should not be null.", returned); - assertSame("The first returned logger should be the same as the set.", logger, returned); - assertEquals("The name is not correct.", "testGetLoggerWithTaglibLogger", returned.getName()); + assertNotNull(returned, "The first returned logger should not be null."); + assertSame(logger, returned, "The first returned logger should be the same as the set."); + assertEquals("testGetLoggerWithTaglibLogger", returned.getName(), "The name is not correct."); returned = this.tag.getLogger(); - assertNotNull("The second returned logger should not be null.", returned); - assertSame("The second returned logger should be the same as the set.", logger, returned); + assertNotNull(returned, "The second returned logger should not be null."); + assertSame(logger, returned, "The second returned logger should be the same as the set."); } @Test - public void testGetLoggerWithStringLogger() throws Exception { + void testGetLoggerWithStringLogger() throws Exception { this.setUp(null); this.tag.setLogger("testGetLoggerWithStringLogger"); final Log4jTaglibLogger returned = this.tag.getLogger(); - assertNotNull("The first returned logger should not be null.", returned); - assertEquals("The name is not correct.", "testGetLoggerWithStringLogger", returned.getName()); + assertNotNull(returned, "The first returned logger should not be null."); + assertEquals("testGetLoggerWithStringLogger", returned.getName(), "The name is not correct."); final Log4jTaglibLogger returned2 = this.tag.getLogger(); - assertNotNull("The second returned logger should not be null.", returned2); - assertSame("The second returned logger should be the same as the first.", returned, returned2); + assertNotNull(returned2, "The second returned logger should not be null."); + assertSame(returned, returned2, "The second returned logger should be the same as the first."); } @Test - public void testGetDefaultLogger01() throws Exception { + void testGetDefaultLogger01() throws Exception { final Object page = new Object() {}; this.setUp(page); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); final Log4jTaglibLogger returned = this.tag.getLogger(); - assertNotNull("The first returned logger should not be null.", returned); - assertEquals("The logger name is not correct.", page.getClass().getName(), returned.getName()); + assertNotNull(returned, "The first returned logger should not be null."); + assertEquals(page.getClass().getName(), returned.getName(), "The logger name is not correct."); final Log4jTaglibLogger defaultLogger = TagUtils.getDefaultLogger(this.context); - assertNotNull("The default logger should not be null anymore.", defaultLogger); - assertSame("The default logger should be the same as the returned logger.", returned, defaultLogger); + assertNotNull(defaultLogger, "The default logger should not be null anymore."); + assertSame(returned, defaultLogger, "The default logger should be the same as the returned logger."); final Log4jTaglibLogger returned2 = this.tag.getLogger(); - assertNotNull("The second returned logger should not be null.", returned2); - assertSame("The second returned logger should be the same as the first.", returned, returned2); + assertNotNull(returned2, "The second returned logger should not be null."); + assertSame(returned, returned2, "The second returned logger should be the same as the first."); } @Test - public void testGetDefaultLogger02() throws Exception { + void testGetDefaultLogger02() throws Exception { final Object page = new Object() {}; this.setUp(page); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); final Log4jTaglibLogger returned = this.tag.getLogger(); - assertNotNull("The first returned logger should not be null.", returned); - assertEquals("The logger name is not correct.", page.getClass().getName(), returned.getName()); + assertNotNull(returned, "The first returned logger should not be null."); + assertEquals(page.getClass().getName(), returned.getName(), "The logger name is not correct."); final Log4jTaglibLogger defaultLogger = TagUtils.getDefaultLogger(this.context); - assertNotNull("The default logger should not be null anymore.", defaultLogger); - assertSame("The default logger should be the same as the returned logger.", returned, defaultLogger); + assertNotNull(defaultLogger, "The default logger should not be null anymore."); + assertSame(returned, defaultLogger, "The default logger should be the same as the returned logger."); final Log4jTaglibLogger returned2 = this.tag.getLogger(); - assertNotNull("The second returned logger should not be null.", returned2); - assertSame("The second returned logger should be the same as the first.", returned, returned2); + assertNotNull(returned2, "The second returned logger should not be null."); + assertSame(returned, returned2, "The second returned logger should be the same as the first."); } } diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/SetLoggerTagTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/SetLoggerTagTest.java index db7f2a41b2d..a02403a1535 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/SetLoggerTagTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/SetLoggerTagTest.java @@ -16,10 +16,10 @@ */ package org.apache.logging.log4j.taglib; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; @@ -29,62 +29,62 @@ import org.apache.logging.log4j.message.StringFormatterMessageFactory; import org.apache.logging.log4j.spi.AbstractLogger; import org.apache.logging.log4j.spi.MessageFactory2Adapter; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockPageContext; /** * */ -public class SetLoggerTagTest { +class SetLoggerTagTest { private MockPageContext context; private SetLoggerTag tag; - @Before - public void setUp() { + @BeforeEach + void setUp() { this.context = new MockPageContext(); this.tag = new SetLoggerTag(); this.tag.setPageContext(this.context); } @Test - public void testDoEndTagLoggerVarPageScope() throws Exception { + void testDoEndTagLoggerVarPageScope() throws Exception { this.tag.setLogger(LogManager.getLogger("testDoEndTagLoggerVarPageScope")); this.tag.setVar("helloWorld"); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); - assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should still be null."); final Object attribute = this.context.getAttribute("helloWorld", PageContext.PAGE_SCOPE); - assertNotNull("The attribute should not be null.", attribute); - assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger); + assertNotNull(attribute, "The attribute should not be null."); + assertInstanceOf(Log4jTaglibLogger.class, attribute, "The attribute should be a Log4jTaglibLogger."); final Log4jTaglibLogger logger = (Log4jTaglibLogger) attribute; - assertEquals("The logger name is not correct.", "testDoEndTagLoggerVarPageScope", logger.getName()); + assertEquals("testDoEndTagLoggerVarPageScope", logger.getName(), "The logger name is not correct."); } @Test - public void testDoEndTagStringVarPageScope() throws Exception { + void testDoEndTagStringVarPageScope() throws Exception { this.tag.setLogger("testDoEndTagStringVarPageScope"); this.tag.setVar("goodbyeCruelWorld"); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); - assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should still be null."); final Object attribute = this.context.getAttribute("goodbyeCruelWorld", PageContext.PAGE_SCOPE); - assertNotNull("The attribute should not be null.", attribute); - assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger); + assertNotNull(attribute, "The attribute should not be null."); + assertInstanceOf(Log4jTaglibLogger.class, attribute, "The attribute should be a Log4jTaglibLogger."); final Log4jTaglibLogger logger = (Log4jTaglibLogger) attribute; - assertEquals("The logger name is not correct.", "testDoEndTagStringVarPageScope", logger.getName()); + assertEquals("testDoEndTagStringVarPageScope", logger.getName(), "The logger name is not correct."); } @Test - public void testDoEndTagStringFactoryVarPageScope() throws Exception { + void testDoEndTagStringFactoryVarPageScope() throws Exception { this.tag.setLogger("testDoEndTagStringFactoryVarPageScope"); final MessageFactory factory = new StringFormatterMessageFactory(); @@ -92,59 +92,59 @@ public void testDoEndTagStringFactoryVarPageScope() throws Exception { this.tag.setFactory(factory); this.tag.setVar("goodbyeCruelWorld"); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); - assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should still be null."); final Object attribute = this.context.getAttribute("goodbyeCruelWorld", PageContext.PAGE_SCOPE); - assertNotNull("The attribute should not be null.", attribute); - assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger); + assertNotNull(attribute, "The attribute should not be null."); + assertInstanceOf(Log4jTaglibLogger.class, attribute, "The attribute should be a Log4jTaglibLogger."); final Log4jTaglibLogger logger = (Log4jTaglibLogger) attribute; - assertEquals("The logger name is not correct.", "testDoEndTagStringFactoryVarPageScope", logger.getName()); + assertEquals("testDoEndTagStringFactoryVarPageScope", logger.getName(), "The logger name is not correct."); checkMessageFactory("The message factory is not correct.", factory, logger); } @Test - public void testDoEndTagLoggerVarSessionScope() throws Exception { + void testDoEndTagLoggerVarSessionScope() throws Exception { this.tag.setLogger(LogManager.getLogger("testDoEndTagLoggerVarSessionScope")); this.tag.setVar("helloWorld"); this.tag.setScope("session"); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); - assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should still be null."); final Object attribute = this.context.getAttribute("helloWorld", PageContext.SESSION_SCOPE); - assertNotNull("The attribute should not be null.", attribute); - assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger); + assertNotNull(attribute, "The attribute should not be null."); + assertInstanceOf(Log4jTaglibLogger.class, attribute, "The attribute should be a Log4jTaglibLogger."); final Log4jTaglibLogger logger = (Log4jTaglibLogger) attribute; - assertEquals("The logger name is not correct.", "testDoEndTagLoggerVarSessionScope", logger.getName()); + assertEquals("testDoEndTagLoggerVarSessionScope", logger.getName(), "The logger name is not correct."); } @Test - public void testDoEndTagStringVarRequestScope() throws Exception { + void testDoEndTagStringVarRequestScope() throws Exception { this.tag.setLogger("testDoEndTagStringVarRequestScope"); this.tag.setVar("goodbyeCruelWorld"); this.tag.setScope("request"); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); - assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should still be null."); final Object attribute = this.context.getAttribute("goodbyeCruelWorld", PageContext.REQUEST_SCOPE); - assertNotNull("The attribute should not be null.", attribute); - assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger); + assertNotNull(attribute, "The attribute should not be null."); + assertInstanceOf(Log4jTaglibLogger.class, attribute, "The attribute should be a Log4jTaglibLogger."); final Log4jTaglibLogger logger = (Log4jTaglibLogger) attribute; - assertEquals("The logger name is not correct.", "testDoEndTagStringVarRequestScope", logger.getName()); + assertEquals("testDoEndTagStringVarRequestScope", logger.getName(), "The logger name is not correct."); } @Test - public void testDoEndTagStringFactoryVarApplicationScope() throws Exception { + void testDoEndTagStringFactoryVarApplicationScope() throws Exception { this.tag.setLogger("testDoEndTagStringFactoryVarApplicationScope"); final MessageFactory factory = new StringFormatterMessageFactory(); @@ -153,17 +153,17 @@ public void testDoEndTagStringFactoryVarApplicationScope() throws Exception { this.tag.setVar("goodbyeCruelWorld"); this.tag.setScope("application"); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); - assertNull("The default logger should still be null.", TagUtils.getDefaultLogger(this.context)); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should still be null."); final Object attribute = this.context.getAttribute("goodbyeCruelWorld", PageContext.APPLICATION_SCOPE); - assertNotNull("The attribute should not be null.", attribute); - assertTrue("The attribute should be a Log4jTaglibLogger.", attribute instanceof Log4jTaglibLogger); + assertNotNull(attribute, "The attribute should not be null."); + assertInstanceOf(Log4jTaglibLogger.class, attribute, "The attribute should be a Log4jTaglibLogger."); final Log4jTaglibLogger logger = (Log4jTaglibLogger) attribute; assertEquals( - "The logger name is not correct.", "testDoEndTagStringFactoryVarApplicationScope", logger.getName()); + "testDoEndTagStringFactoryVarApplicationScope", logger.getName(), "The logger name is not correct."); checkMessageFactory("The message factory is not correct.", factory, logger); } @@ -171,56 +171,56 @@ private static void checkMessageFactory( final String msg, final MessageFactory messageFactory1, final Logger testLogger1) { if (messageFactory1 == null) { assertEquals( - msg, AbstractLogger.DEFAULT_MESSAGE_FACTORY_CLASS, - testLogger1.getMessageFactory().getClass()); + testLogger1.getMessageFactory().getClass(), + msg); } else { MessageFactory actual = testLogger1.getMessageFactory(); if (actual instanceof MessageFactory2Adapter) { actual = ((MessageFactory2Adapter) actual).getOriginal(); } - assertEquals(msg, messageFactory1, actual); + assertEquals(messageFactory1, actual, msg); } } @Test - public void testDoEndTagLoggerDefault() throws Exception { + void testDoEndTagLoggerDefault() throws Exception { this.tag.setLogger(LogManager.getLogger("testDoEndTagLoggerDefault")); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); final Log4jTaglibLogger logger = TagUtils.getDefaultLogger(this.context); - assertNotNull("The default logger should not be null anymore.", logger); - assertEquals("The logger name is not correct.", "testDoEndTagLoggerDefault", logger.getName()); + assertNotNull(logger, "The default logger should not be null anymore."); + assertEquals("testDoEndTagLoggerDefault", logger.getName(), "The logger name is not correct."); } @Test - public void testDoEndTagStringDefault() throws Exception { + void testDoEndTagStringDefault() throws Exception { this.tag.setLogger("testDoEndTagStringDefault"); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); final Log4jTaglibLogger logger = TagUtils.getDefaultLogger(this.context); - assertNotNull("The default logger should not be null anymore.", logger); - assertEquals("The logger name is not correct.", "testDoEndTagStringDefault", logger.getName()); + assertNotNull(logger, "The default logger should not be null anymore."); + assertEquals("testDoEndTagStringDefault", logger.getName(), "The logger name is not correct."); } @Test - public void testDoEndTagStringFactoryDefault() throws Exception { + void testDoEndTagStringFactoryDefault() throws Exception { this.tag.setLogger("testDoEndTagStringFactoryDefault"); final MessageFactory factory = new StringFormatterMessageFactory(); this.tag.setFactory(factory); - assertNull("The default logger should be null.", TagUtils.getDefaultLogger(this.context)); - assertEquals("The return value is not correct.", Tag.EVAL_PAGE, this.tag.doEndTag()); + assertNull(TagUtils.getDefaultLogger(this.context), "The default logger should be null."); + assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag(), "The return value is not correct."); final Log4jTaglibLogger logger = TagUtils.getDefaultLogger(this.context); - assertNotNull("The default logger should not be null anymore.", logger); - assertEquals("The logger name is not correct.", "testDoEndTagStringFactoryDefault", logger.getName()); + assertNotNull(logger, "The default logger should not be null anymore."); + assertEquals("testDoEndTagStringFactoryDefault", logger.getName(), "The logger name is not correct."); checkMessageFactory("The message factory is not correct.", factory, logger); } } diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagLevelTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagLevelTest.java index 71d15b9e33d..244ae5df384 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagLevelTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagLevelTest.java @@ -16,27 +16,16 @@ */ package org.apache.logging.log4j.taglib; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collection; import org.apache.logging.log4j.Level; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class TagLevelTest { - private final Class cls; - private final Level level; - - public TagLevelTest(final Class cls, final Level level) { - this.cls = cls; - this.level = level; - } - - @Parameterized.Parameters public static Collection data() { return Arrays.asList(new Object[][] { {DebugTag.class, Level.DEBUG}, @@ -48,8 +37,9 @@ public static Collection data() { }); } - @Test - public void testGetLevel() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testGetLevel(final Class cls, final Level level) throws Exception { assertEquals(level, cls.newInstance().getLevel()); } } diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsLevelTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsLevelTest.java index 96672059595..b6a95256e7e 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsLevelTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsLevelTest.java @@ -17,27 +17,16 @@ package org.apache.logging.log4j.taglib; import static org.apache.logging.log4j.util.Strings.toRootLowerCase; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Collection; import org.apache.logging.log4j.Level; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class TagUtilsLevelTest { - private final Level level; - private final String levelName; - - public TagUtilsLevelTest(final Level level, final String levelName) { - this.level = level; - this.levelName = levelName; - } - - @Parameterized.Parameters public static Collection data() { final Collection params = new ArrayList<>(); // this is perhaps the laziest way to test all the known levels @@ -47,13 +36,15 @@ public static Collection data() { return params; } - @Test - public void testResolveLevelName() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testResolveLevelName(final Level level, final String levelName) { assertEquals(level, TagUtils.resolveLevel(levelName)); } - @Test - public void testResolveLevelEnum() throws Exception { + @MethodSource("data") + @ParameterizedTest + void testResolveLevelEnum(final Level level, final String levelName) { assertEquals(level, TagUtils.resolveLevel(level)); } } diff --git a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsScopeTest.java b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsScopeTest.java index e7bbb2cf726..fb7bbdecdfe 100644 --- a/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsScopeTest.java +++ b/log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/TagUtilsScopeTest.java @@ -16,27 +16,16 @@ */ package org.apache.logging.log4j.taglib; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collection; import javax.servlet.jsp.PageContext; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class TagUtilsScopeTest { - private final int scope; - private final String scopeName; - - public TagUtilsScopeTest(final int scope, final String scopeName) { - this.scope = scope; - this.scopeName = scopeName; - } - - @Parameterized.Parameters public static Collection data() { return Arrays.asList(new Object[][] { {PageContext.APPLICATION_SCOPE, "application"}, @@ -47,8 +36,9 @@ public static Collection data() { }); } - @Test - public void testGetScope() throws Exception { - assertEquals("The scope is not correct.", scope, TagUtils.getScope(scopeName)); + @MethodSource("data") + @ParameterizedTest + void testGetScope(final int scope, final String scopeName) { + assertEquals(scope, TagUtils.getScope(scopeName), "The scope is not correct."); } } diff --git a/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/JULLoggerTest.java b/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/JULLoggerTest.java index 9f70a01b28b..d166631f818 100644 --- a/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/JULLoggerTest.java +++ b/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/JULLoggerTest.java @@ -21,10 +21,10 @@ import org.apache.logging.log4j.Level; import org.junit.jupiter.api.Test; -public class JULLoggerTest { +class JULLoggerTest { @Test - public void testNotNullEffectiveLevel() { + void testNotNullEffectiveLevel() { // Emulates the root logger found in Tomcat, with a null level // See: https://bz.apache.org/bugzilla/show_bug.cgi?id=66184 final java.util.logging.Logger julLogger = new java.util.logging.Logger("", null) {}; diff --git a/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/LoggerTest.java b/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/LoggerTest.java index c2d65199aae..e66619404d4 100644 --- a/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/LoggerTest.java +++ b/log4j-to-jul/src/test/java/org/apache/logging/log4j/tojul/LoggerTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class LoggerTest { +class LoggerTest { // Save levels so that we can reset them @After clearLogs() private static final java.util.logging.Logger globalLogger = java.util.logging.Logger.getGlobal(); @@ -44,7 +44,7 @@ public class LoggerTest { private TestLogHandler handler; @BeforeEach - public void setupLogCapture() { + void setupLogCapture() { handler = new TestLogHandler(); // Beware, the order here should not be changed! // Let the bridge do whatever it does BEFORE we create a JUL Logger (which SHOULD be the same) @@ -62,7 +62,7 @@ public void setupLogCapture() { } @AfterEach - public void clearLogs() { + void clearLogs() { julLogger.removeHandler(handler); // Reset all Levels what any tests set anymore julLogger.setLevel(julLoggerDefaultLevel); @@ -71,7 +71,7 @@ public void clearLogs() { } @Test - public void infoAtInfo() { + void infoAtInfo() { julLogger.setLevel(Level.INFO); log4jLogger.info("hello, world"); @@ -88,7 +88,7 @@ public void infoAtInfo() { } @Test - public void infoAtInfoWithParameters() { + void infoAtInfoWithParameters() { julLogger.setLevel(Level.INFO); log4jLogger.info("hello, {}", "world"); @@ -101,7 +101,7 @@ public void infoAtInfoWithParameters() { } @Test - public void errorAtSevereWithException() { + void errorAtSevereWithException() { julLogger.setLevel(Level.SEVERE); log4jLogger.error("hello, {}", "world", new IOException("Testing, testing")); @@ -114,77 +114,77 @@ public void errorAtSevereWithException() { } @Test - public void infoAtInfoWithLogBuilder() { + void infoAtInfoWithLogBuilder() { julLogger.setLevel(Level.INFO); log4jLogger.atInfo().log("hello, world"); assertThat(handler.getStoredLogRecords()).hasSize(1); } @Test - public void infoAtInfoOnParent() { + void infoAtInfoOnParent() { julLogger.getParent().setLevel(Level.INFO); log4jLogger.info("hello, world"); assertThat(handler.getStoredLogRecords()).hasSize(1); } @Test - public void infoWithoutAnyLevel() { + void infoWithoutAnyLevel() { // We're not setting any level. log4jLogger.info("hello, world"); assertThat(handler.getStoredLogRecords()).hasSize(1); } @Test - public void debugAtInfo() { + void debugAtInfo() { julLogger.setLevel(Level.INFO); log4jLogger.debug("hello, world"); assertThat(handler.getStoredLogRecords()).isEmpty(); } @Test - public void debugAtFiner() { + void debugAtFiner() { julLogger.setLevel(Level.FINER); log4jLogger.debug("hello, world"); assertThat(handler.getStoredLogRecords()).hasSize(1); } @Test - public void traceAtFine() { + void traceAtFine() { julLogger.setLevel(Level.FINE); log4jLogger.trace("hello, world"); assertThat(handler.getStoredLogRecords()).isEmpty(); } @Test - public void traceAtAllOnParent() { + void traceAtAllOnParent() { julLogger.getParent().setLevel(Level.ALL); log4jLogger.trace("hello, world"); assertThat(handler.getStoredLogRecords()).hasSize(1); } @Test - public void fatalAtOff() { + void fatalAtOff() { julLogger.getParent().setLevel(Level.OFF); log4jLogger.fatal("hello, world"); assertThat(handler.getStoredLogRecords()).isEmpty(); } @Test - public void fatalAtSevere() { + void fatalAtSevere() { julLogger.getParent().setLevel(Level.SEVERE); log4jLogger.atFatal().log("hello, world"); assertThat(handler.getStoredLogRecords()).hasSize(1); } @Test - public void warnAtFatal() { + void warnAtFatal() { julLogger.getParent().setLevel(Level.SEVERE); log4jLogger.atWarn().log("hello, world"); assertThat(handler.getStoredLogRecords()).isEmpty(); } @Test - public void customLevelJustUnderWarning() { + void customLevelJustUnderWarning() { julLogger.getParent().setLevel(new CustomLevel("Just under Warning", Level.WARNING.intValue() - 1)); log4jLogger.info("hello, world"); @@ -198,7 +198,7 @@ public void customLevelJustUnderWarning() { } @Test - public void customLevelJustAboveWarning() { + void customLevelJustAboveWarning() { julLogger.getParent().setLevel(new CustomLevel("Just above Warning", Level.WARNING.intValue() + 1)); log4jLogger.info("hello, world"); @@ -223,7 +223,7 @@ private static class CustomLevel extends Level { * also works as expected if the logging happened in a class that we have called (indirect), not in the test method itself. */ @Test - public void indirectSource() { + void indirectSource() { java.util.logging.Logger.getLogger(Another.class.getName()).setLevel(Level.INFO); new Another(handler); final List logs = handler.getStoredLogRecords(); @@ -245,7 +245,7 @@ static class Another { } @Test - public void placeholdersInFormat() { + void placeholdersInFormat() { julLogger.setLevel(Level.INFO); log4jLogger.info("hello, {0} {}", "world"); @@ -257,7 +257,7 @@ public void placeholdersInFormat() { } @Test - public void placeholdersInFormattedMessage() { + void placeholdersInFormattedMessage() { julLogger.setLevel(Level.INFO); log4jLogger.info("hello, {}", "{0} world"); diff --git a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java index ab6c5bc0409..0efaeedbf68 100644 --- a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java +++ b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/CallerInformationTest.java @@ -27,10 +27,10 @@ @UsingStatusListener @LoggerContextSource -public class CallerInformationTest { +class CallerInformationTest { @Test - public void testClassLogger() throws Exception { + void testClassLogger() { final SLF4JLogger logger = (SLF4JLogger) LogManager.getLogger("ClassLogger"); final StringListAppender app = TestUtil.getListAppender(logger, "Class"); logger.info("Ignored message contents."); @@ -44,7 +44,7 @@ public void testClassLogger() throws Exception { } @Test - public void testMethodLogger() throws Exception { + void testMethodLogger() { final SLF4JLogger logger = (SLF4JLogger) LogManager.getLogger("MethodLogger"); final StringListAppender app = TestUtil.getListAppender(logger, "Method"); logger.info("More messages."); diff --git a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/Log4j2Jira1688Test.java b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/Log4j2Jira1688Test.java index 18779b11eeb..3d72a59e064 100644 --- a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/Log4j2Jira1688Test.java +++ b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/Log4j2Jira1688Test.java @@ -26,10 +26,10 @@ /** * Tests LOG4J2-1688 Multiple loggings of arguments are setting these arguments to null. */ -public class Log4j2Jira1688Test { +class Log4j2Jira1688Test { @Test - public void testLog4j2() { + void testLog4j2() { // Argument-array creation final int limit = 37; diff --git a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LogBuilderTest.java b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LogBuilderTest.java index 8d073072b9e..cf80edc62af 100644 --- a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LogBuilderTest.java +++ b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LogBuilderTest.java @@ -37,7 +37,7 @@ @UsingStatusListener @LoggerContextSource -public class LogBuilderTest { +class LogBuilderTest { private static final CharSequence CHAR_SEQUENCE = "CharSequence"; private static final String STRING = "String"; @@ -52,7 +52,7 @@ public class LogBuilderTest { private static StringListAppender list; @BeforeAll - public static void setUp() throws Exception { + static void setUp() { final org.slf4j.Logger slf4jLogger = context.getLogger(LogBuilderTest.class); logger = LogManager.getLogger(LogBuilderTest.class); assertThat(slf4jLogger).isSameAs(((SLF4JLogger) logger).getLogger()); diff --git a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerContextResolver.java b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerContextResolver.java index dc9dd5d343b..f6eba69597a 100644 --- a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerContextResolver.java +++ b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerContextResolver.java @@ -42,7 +42,7 @@ class LoggerContextResolver extends TypeBasedParameterResolver private static final Object KEY = LoggerContextHolder.class; @Override - public void beforeEach(ExtensionContext extensionContext) throws Exception { + public void beforeEach(ExtensionContext extensionContext) { final Class testClass = extensionContext.getRequiredTestClass(); if (AnnotationSupport.isAnnotated(testClass, LoggerContextSource.class)) { final LoggerContextHolder holder = @@ -77,7 +77,7 @@ public void beforeEach(ExtensionContext extensionContext) throws Exception { } @Override - public void beforeAll(ExtensionContext extensionContext) throws Exception { + public void beforeAll(ExtensionContext extensionContext) { final Class testClass = extensionContext.getRequiredTestClass(); AnnotationSupport.findAnnotation(testClass, LoggerContextSource.class).ifPresent(testSource -> { final LoggerContextHolder holder = new LoggerContextHolder(testSource, extensionContext); diff --git a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerResolver.java b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerResolver.java index 28f94113a30..cf5dcbd604f 100644 --- a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerResolver.java +++ b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerResolver.java @@ -43,7 +43,7 @@ public Logger resolveParameter(ParameterContext parameterContext, ExtensionConte } @Override - public void beforeAll(ExtensionContext extensionContext) throws Exception { + public void beforeAll(ExtensionContext extensionContext) { final LoggerContextHolder holder = ExtensionContextAnchor.getAttribute(KEY, LoggerContextHolder.class, extensionContext); if (holder != null) { @@ -63,7 +63,7 @@ public void beforeAll(ExtensionContext extensionContext) throws Exception { } @Override - public void beforeEach(ExtensionContext extensionContext) throws Exception { + public void beforeEach(ExtensionContext extensionContext) { final LoggerContextHolder holder = ExtensionContextAnchor.getAttribute(KEY, LoggerContextHolder.class, extensionContext); if (holder != null) { diff --git a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerTest.java b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerTest.java index c6a3cecc6ca..6c378ad9583 100644 --- a/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerTest.java +++ b/log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerTest.java @@ -51,7 +51,7 @@ @UsingStatusListener @LoggerContextSource -public class LoggerTest { +class LoggerTest { private static final Object OBJ = new Object(); // Log4j objects @@ -61,7 +61,7 @@ public class LoggerTest { private StringListAppender list; @BeforeEach - public void setUp() throws Exception { + void setUp() { final org.slf4j.Logger slf4jLogger = context.getLogger(getClass()); logger = LogManager.getLogger(); assertThat(slf4jLogger, is(theInstance(((SLF4JLogger) logger).getLogger()))); @@ -74,41 +74,41 @@ public void setUp() throws Exception { } @Test - public void basicFlow() { + void basicFlow() { logger.traceEntry(); logger.traceExit(); assertThat(list.strList, hasSize(2)); } @Test - public void basicFlowDepreacted() { + void basicFlowDepreacted() { logger.entry(); logger.exit(); assertThat(list.strList, hasSize(2)); } @Test - public void simpleFlowDeprecated() { + void simpleFlowDeprecated() { logger.entry(OBJ); logger.exit(0); assertThat(list.strList, hasSize(2)); } @Test - public void simpleFlow() { + void simpleFlow() { logger.entry(OBJ); logger.traceExit(0); assertThat(list.strList, hasSize(2)); } @Test - public void throwing() { + void throwing() { logger.throwing(new IllegalArgumentException("Test Exception")); assertThat(list.strList, hasSize(1)); } @Test - public void catching() { + void catching() { try { throw new NullPointerException(); } catch (final Exception e) { @@ -118,13 +118,13 @@ public void catching() { } @Test - public void debug() { + void debug() { logger.debug("Debug message"); assertThat(list.strList, hasSize(1)); } @Test - public void getLogger_String_MessageFactoryMismatch() { + void getLogger_String_MessageFactoryMismatch() { final Logger testLogger = testMessageFactoryMismatch( "getLogger_String_MessageFactoryMismatch", StringFormatterMessageFactory.INSTANCE, @@ -135,7 +135,7 @@ public void getLogger_String_MessageFactoryMismatch() { } @Test - public void getLogger_String_MessageFactoryMismatchNull() { + void getLogger_String_MessageFactoryMismatchNull() { final Logger testLogger = testMessageFactoryMismatch( "getLogger_String_MessageFactoryMismatchNull", StringFormatterMessageFactory.INSTANCE, null); testLogger.debug("%,d", Integer.MAX_VALUE); @@ -168,13 +168,13 @@ private static void checkMessageFactory(final MessageFactory messageFactory1, fi } @Test - public void debugObject() { + void debugObject() { logger.debug(new Date()); assertThat(list.strList, hasSize(1)); } @Test - public void debugWithParms() { + void debugWithParms() { logger.debug("Hello, {}", "World"); assertThat(list.strList, hasSize(1)); final String message = list.strList.get(0); @@ -182,7 +182,7 @@ public void debugWithParms() { } @Test - public void paramIncludesSubstitutionMarker_locationAware() { + void paramIncludesSubstitutionMarker_locationAware() { logger.info("Hello, {}", "foo {} bar"); assertThat(list.strList, hasSize(1)); final String message = list.strList.get(0); @@ -190,7 +190,7 @@ public void paramIncludesSubstitutionMarker_locationAware() { } @Test - public void paramIncludesSubstitutionMarker_nonLocationAware() { + void paramIncludesSubstitutionMarker_nonLocationAware() { final org.slf4j.Logger slf4jLogger = context.getLogger(getClass()); final Logger nonLocationAwareLogger = new SLF4JLogger(slf4jLogger.getName(), (org.slf4j.Logger) Proxy.newProxyInstance( @@ -208,7 +208,7 @@ public void paramIncludesSubstitutionMarker_nonLocationAware() { } @Test - public void testImpliedThrowable() { + void testImpliedThrowable() { logger.debug("This is a test", new Throwable("Testing")); final List msgs = list.strList; assertThat(msgs, hasSize(1)); @@ -218,7 +218,7 @@ public void testImpliedThrowable() { @SuppressWarnings("unchecked") @Test - public void mdc() { + void mdc() { ThreadContext.put("TestYear", Integer.toString(2010)); logger.debug("Debug message"); ThreadContext.clearMap(); @@ -228,25 +228,25 @@ public void mdc() { } @Test - public void mdcNullBackedIsEmpty() { + void mdcNullBackedIsEmpty() { assertNull(MDC.getCopyOfContextMap(), "Setup wrong"); assertTrue(ThreadContext.isEmpty()); } @Test - public void mdcNullBackedContainsKey() { + void mdcNullBackedContainsKey() { assertNull(MDC.getCopyOfContextMap(), "Setup wrong"); assertFalse(ThreadContext.containsKey("something")); } @Test - public void mdcNullBackedContainsNullKey() { + void mdcNullBackedContainsNullKey() { assertNull(MDC.getCopyOfContextMap(), "Setup wrong"); assertFalse(ThreadContext.containsKey(null)); } @Test - public void mdcContainsNullKey() { + void mdcContainsNullKey() { try { ThreadContext.put("some", "thing"); assertNotNull(MDC.getCopyOfContextMap(), "Setup wrong"); @@ -257,7 +257,7 @@ public void mdcContainsNullKey() { } @Test - public void mdcCannotContainNullKey() { + void mdcCannotContainNullKey() { try { ThreadContext.put(null, "something"); fail("should throw"); diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java index c8b09ca73b2..f016adf321d 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContainerInitializerTest.java @@ -43,7 +43,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jServletContainerInitializerTest { +class Log4jServletContainerInitializerTest { @Mock private ServletContext servletContext; @@ -59,19 +59,19 @@ public class Log4jServletContainerInitializerTest { private Log4jServletContainerInitializer containerInitializer; @BeforeEach - public void setUp() { + void setUp() { this.containerInitializer = new Log4jServletContainerInitializer(); } @Test - public void testOnStartupWithServletVersion2_x() throws Exception { + void testOnStartupWithServletVersion2_x() throws Exception { given(servletContext.getMajorVersion()).willReturn(2); this.containerInitializer.onStartup(null, this.servletContext); } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion2_x() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion2_x() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(2); @@ -79,7 +79,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion2_x() throws Excep } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTrue() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTrue() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED))) @@ -89,7 +89,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTrue() } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_xShutdownDisabled() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_xShutdownDisabled() throws Exception { final FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); @@ -115,7 +115,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_xShutdownDisable } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTRUE() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTRUE() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED))) @@ -125,7 +125,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_xDisabledTRUE() } @Test - public void testOnStartupWithServletVersion3_xEffectiveVersion3_x() throws Exception { + void testOnStartupWithServletVersion3_xEffectiveVersion3_x() throws Exception { final FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); @@ -156,7 +156,7 @@ public void testOnStartupWithServletVersion3_xEffectiveVersion3_x() throws Excep } @Test - public void testOnStartupCanceledDueToPreExistingFilter() throws Exception { + void testOnStartupCanceledDueToPreExistingFilter() throws Exception { given(servletContext.getMajorVersion()).willReturn(3); given(servletContext.getEffectiveMajorVersion()).willReturn(3); given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED))) @@ -171,7 +171,7 @@ public void testOnStartupCanceledDueToPreExistingFilter() throws Exception { } @Test - public void testOnStartupFailedDueToInitializerFailure() throws Exception { + void testOnStartupFailedDueToInitializerFailure() throws Exception { final FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); final IllegalStateException exception = new IllegalStateException(Strings.EMPTY); given(servletContext.getMajorVersion()).willReturn(3); diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java index 2e29e862ed9..f48c3f7c80d 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletContextListenerTest.java @@ -39,7 +39,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jServletContextListenerTest { +class Log4jServletContextListenerTest { /* event and servletContext are marked lenient because they aren't used in the * testDestroyWithNoInit but are only accessed during initialization */ @@ -55,7 +55,7 @@ public class Log4jServletContextListenerTest { private final AtomicReference count = new AtomicReference<>(); @BeforeEach - public void setUp() { + void setUp() { given(event.getServletContext()).willReturn(servletContext); given(servletContext.getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE)).willReturn(initializer); @@ -67,7 +67,7 @@ public void setUp() { @ParameterizedTest @ValueSource(ints = {1, 2, 3}) - public void testInitAndDestroy(final int listenerCount) throws Exception { + void testInitAndDestroy(final int listenerCount) { final Log4jServletContextListener[] listeners = new Log4jServletContextListener[listenerCount]; for (int idx = 0; idx < listenerCount; idx++) { final Log4jServletContextListener listener = new Log4jServletContextListener(); @@ -96,7 +96,7 @@ public void testInitAndDestroy(final int listenerCount) throws Exception { } @Test - public void testInitFailure() throws Exception { + void testInitFailure() { willThrow(new IllegalStateException(Strings.EMPTY)).given(initializer).start(); final Log4jServletContextListener listener = new Log4jServletContextListener(); @@ -107,14 +107,14 @@ public void testInitFailure() throws Exception { } @Test - public void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTrue() throws Exception { + void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTrue() { given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_SHUTDOWN_DISABLED))) .willReturn("true"); ensureInitializingFailsWhenAuthShutdownIsEnabled(); } @Test - public void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTRUE() throws Exception { + void initializingLog4jServletContextListenerShouldFaileWhenAutoShutdownIsTRUE() { given(servletContext.getInitParameter(eq(Log4jWebSupport.IS_LOG4J_AUTO_SHUTDOWN_DISABLED))) .willReturn("TRUE"); ensureInitializingFailsWhenAuthShutdownIsEnabled(); diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java index e1a8dbc39b9..a6c87ac29de 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jServletFilterTest.java @@ -35,7 +35,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jServletFilterTest { +class Log4jServletFilterTest { @Mock(lenient = true) // because filterConfig is not used in testDestroy private FilterConfig filterConfig; @@ -57,14 +57,14 @@ public class Log4jServletFilterTest { private Log4jServletFilter filter; @BeforeEach - public void setUp() { + void setUp() { given(filterConfig.getServletContext()).willReturn(servletContext); given(servletContext.getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE)).willReturn(initializer); this.filter = new Log4jServletFilter(); } @Test - public void testInitAndDestroy() throws Exception { + void testInitAndDestroy() throws Exception { this.filter.init(this.filterConfig); then(initializer).should().clearLoggerContext(); @@ -75,14 +75,14 @@ public void testInitAndDestroy() throws Exception { } @Test - public void testDestroy() { + void testDestroy() { assertThrows(IllegalStateException.class, () -> { this.filter.destroy(); }); } @Test - public void testDoFilterFirstTime() throws Exception { + void testDoFilterFirstTime() throws Exception { this.filter.init(this.filterConfig); then(initializer).should().clearLoggerContext(); @@ -102,7 +102,7 @@ public void testDoFilterFirstTime() throws Exception { } @Test - public void testDoFilterSecondTime() throws Exception { + void testDoFilterSecondTime() throws Exception { this.filter.init(this.filterConfig); then(initializer).should().clearLoggerContext(); diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java index 634d61d8c5b..d1127698537 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jShutdownOnContextDestroyedListenerTest.java @@ -41,7 +41,7 @@ public class Log4jShutdownOnContextDestroyedListenerTest { private Log4jShutdownOnContextDestroyedListener listener; - public void setUp(final boolean mockInitializer) { + void setUp(final boolean mockInitializer) { this.listener = new Log4jShutdownOnContextDestroyedListener(); given(event.getServletContext()).willReturn(servletContext); if (mockInitializer) { @@ -51,7 +51,7 @@ public void setUp(final boolean mockInitializer) { } @Test - public void testInitAndDestroy() throws Exception { + void testInitAndDestroy() { setUp(true); this.listener.contextInitialized(this.event); @@ -65,7 +65,7 @@ public void testInitAndDestroy() throws Exception { } @Test - public void testDestroy() throws Exception { + void testDestroy() { setUp(true); this.listener.contextDestroyed(this.event); @@ -74,7 +74,7 @@ public void testDestroy() throws Exception { } @Test - public void whenNoInitializerInContextTheContextInitializedShouldThrowAnException() { + void whenNoInitializerInContextTheContextInitializedShouldThrowAnException() { setUp(false); assertThrows(IllegalStateException.class, () -> { diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java index 19ee48f9c9c..69778124c7f 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/Log4jWebInitializerImplTest.java @@ -22,11 +22,11 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; @@ -48,7 +48,7 @@ import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -public class Log4jWebInitializerImplTest { +class Log4jWebInitializerImplTest { /* Marking servletContext lenient because otherwise testCompositeLocationParameterWithEmptyUriListSetsDefaultConfiguration fails * when null is passed in as the initial param because Mockito deciced null isn't a String rather than the absence of a string. */ @@ -64,7 +64,7 @@ public class Log4jWebInitializerImplTest { private Log4jWebInitializerImpl initializerImpl; @BeforeEach - public void setUp() { + void setUp() { given(servletContext.getAttribute(Log4jWebSupport.SUPPORT_ATTRIBUTE)).willReturn(null); final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(this.servletContext); @@ -72,20 +72,20 @@ public void setUp() { then(servletContext).should().setAttribute(eq(Log4jWebSupport.SUPPORT_ATTRIBUTE), initializerCaptor.capture()); assertNotNull(initializer, "The initializer should not be null."); assertSame(initializer, initializerCaptor.getValue(), "The capture is not correct."); - assertTrue(initializer instanceof Log4jWebInitializerImpl, "The initializer is not correct."); + assertInstanceOf(Log4jWebInitializerImpl.class, initializer, "The initializer is not correct."); this.initializerImpl = (Log4jWebInitializerImpl) initializer; } @Test - public void testDeinitializeBeforeInitialize() { + void testDeinitializeBeforeInitialize() { assertThrows(IllegalStateException.class, () -> { this.initializerImpl.stop(); }); } @Test - public void testSetLoggerContextBeforeInitialize() { + void testSetLoggerContextBeforeInitialize() { assertNull(ContextAnchor.THREAD_CONTEXT.get(), "The context should be null."); this.initializerImpl.setLoggerContext(); @@ -94,7 +94,7 @@ public void testSetLoggerContextBeforeInitialize() { } @Test - public void testClearLoggerContextBeforeInitialize() { + void testClearLoggerContextBeforeInitialize() { assertNull(ContextAnchor.THREAD_CONTEXT.get(), "The context should be null."); this.initializerImpl.clearLoggerContext(); @@ -103,7 +103,7 @@ public void testClearLoggerContextBeforeInitialize() { } @Test - public void testInitializeWithNoParametersThenSetLoggerContextThenDeinitialize() { + void testInitializeWithNoParametersThenSetLoggerContextThenDeinitialize() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -145,7 +145,7 @@ public void testInitializeWithNoParametersThenSetLoggerContextThenDeinitialize() } @Test - public void testInitializeWithClassLoaderNoParametersThenSetLoggerContextThenDeinitialize() { + void testInitializeWithClassLoaderNoParametersThenSetLoggerContextThenDeinitialize() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -189,7 +189,7 @@ public void testInitializeWithClassLoaderNoParametersThenSetLoggerContextThenDei } @Test - public void testInitializeIsIdempotent() { + void testInitializeIsIdempotent() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -217,7 +217,7 @@ public void testInitializeIsIdempotent() { } @Test - public void testInitializeFailsAfterDeinitialize() { + void testInitializeFailsAfterDeinitialize() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -246,7 +246,7 @@ public void testInitializeFailsAfterDeinitialize() { } @Test - public void testDeinitializeIsIdempotent() { + void testDeinitializeIsIdempotent() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -272,7 +272,7 @@ public void testDeinitializeIsIdempotent() { } @Test - public void testInitializeUsingJndiSelectorFails() { + void testInitializeUsingJndiSelectorFails() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -288,7 +288,7 @@ public void testInitializeUsingJndiSelectorFails() { } @Test - public void testInitializeUsingJndiSelector() { + void testInitializeUsingJndiSelector() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn("helloWorld06"); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -325,7 +325,7 @@ public void testInitializeUsingJndiSelector() { } @Test - public void testWrapExecutionWithNoParameters() { + void testWrapExecutionWithNoParameters() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn(null); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) @@ -368,7 +368,7 @@ public void testWrapExecutionWithNoParameters() { } @Test - public void testMissingLocationParameterWithNoMatchingResourceSetsNoConfigLocation() { + void testMissingLocationParameterWithNoMatchingResourceSetsNoConfigLocation() { given(servletContext.getResourcePaths("/WEB-INF/")).willReturn(new HashSet()); this.initializerImpl.start(); @@ -384,7 +384,7 @@ public void testMissingLocationParameterWithNoMatchingResourceSetsNoConfigLocati } @Test - public void testMissingLocationParameterWithOneMatchingResourceUsesResourceConfigLocation() throws Exception { + void testMissingLocationParameterWithOneMatchingResourceUsesResourceConfigLocation() throws Exception { given(servletContext.getResourcePaths("/WEB-INF/")) .willReturn(new HashSet<>(singletonList("/WEB-INF/log4j2.xml"))); given(servletContext.getResource("/WEB-INF/log4j2.xml")).willReturn(new URL("file:/a/b/c/WEB-INF/log4j2.xml")); @@ -403,7 +403,7 @@ public void testMissingLocationParameterWithOneMatchingResourceUsesResourceConfi } @Test - public void testMissingLocationParameterWithManyMatchingResourcesUsesFirstMatchingResourceConfigLocation() + void testMissingLocationParameterWithManyMatchingResourcesUsesFirstMatchingResourceConfigLocation() throws Exception { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn("mycontext"); @@ -428,7 +428,7 @@ public void testMissingLocationParameterWithManyMatchingResourcesUsesFirstMatchi } @Test - public void testCompositeLocationParameterWithEmptyUriListSetsDefaultConfiguration() { + void testCompositeLocationParameterWithEmptyUriListSetsDefaultConfiguration() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) .willReturn(",,,"); @@ -445,7 +445,7 @@ public void testCompositeLocationParameterWithEmptyUriListSetsDefaultConfigurati } @Test - public void testCompositeLocationParameterSetsCompositeConfiguration() { + void testCompositeLocationParameterSetsCompositeConfiguration() { given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONTEXT_NAME))) .willReturn("mycontext"); given(servletContext.getInitParameter(eq(Log4jWebSupport.LOG4J_CONFIG_LOCATION))) diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java index 5e0d2202103..98457d15e64 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/PropertyTest.java @@ -27,17 +27,17 @@ /** * */ -public class PropertyTest { +class PropertyTest { @Test - public void testShutdownHookDisabled() { + void testShutdownHookDisabled() { assertFalse( ((Log4jContextFactory) LogManager.getFactory()).isShutdownHookEnabled(), "Shutdown hook should be disabled by default in web applications"); } @Test - public void testIsWebApp() { + void testIsWebApp() { assertTrue(Constants.IS_WEB_APP, "When servlet classes are available IS_WEB_APP should default to true"); } } diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/ServletAppenderTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/ServletAppenderTest.java index 909419d1f8e..923abd16b05 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/ServletAppenderTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/ServletAppenderTest.java @@ -32,12 +32,12 @@ /** * */ -public class ServletAppenderTest { +class ServletAppenderTest { private static final String CONFIG = "WEB-INF/classes/log4j-servlet.xml"; @Test - public void testAppender() throws Exception { + void testAppender() { ContextAnchor.THREAD_CONTEXT.remove(); final ServletContext servletContext = new MockServletContext(); servletContext.setAttribute("TestAttr", "AttrValue"); diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java index 9c1c4e1c16d..098c9dc1430 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/TestAsyncServlet.java @@ -16,9 +16,7 @@ */ package org.apache.logging.log4j.web; -import java.io.IOException; import javax.servlet.AsyncContext; -import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -31,8 +29,7 @@ public class TestAsyncServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override - protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) - throws ServletException, IOException { + protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) { final AsyncContext asyncContext = req.startAsync(); asyncContext.start(WebLoggerContextUtils.wrapExecutionContext(this.getServletContext(), () -> { final Logger logger = LogManager.getLogger(TestAsyncServlet.class); @@ -41,8 +38,7 @@ protected void doGet(final HttpServletRequest req, final HttpServletResponse res } @Override - protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) { final AsyncContext asyncContext = req.startAsync(); asyncContext.start(() -> { final Log4jWebSupport webSupport = diff --git a/log4j-web/src/test/java/org/apache/logging/log4j/web/WebLookupTest.java b/log4j-web/src/test/java/org/apache/logging/log4j/web/WebLookupTest.java index 6e278f739f5..4973d179d40 100644 --- a/log4j-web/src/test/java/org/apache/logging/log4j/web/WebLookupTest.java +++ b/log4j-web/src/test/java/org/apache/logging/log4j/web/WebLookupTest.java @@ -31,10 +31,10 @@ import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockServletContext; -public class WebLookupTest { +class WebLookupTest { @Test - public void testLookup() throws Exception { + void testLookup() { ContextAnchor.THREAD_CONTEXT.remove(); final ServletContext servletContext = new MockServletContext(); ((MockServletContext) servletContext).setContextPath("/WebApp"); @@ -76,7 +76,7 @@ public void testLookup() throws Exception { } @Test - public void testLookup2() throws Exception { + void testLookup2() { ContextAnchor.THREAD_CONTEXT.remove(); final ServletContext servletContext = new MockServletContext(); ((MockServletContext) servletContext).setContextPath("/");