diff --git a/authme-core/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java b/authme-core/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java index f90ad0695a..9a97e9f5ae 100644 --- a/authme-core/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java +++ b/authme-core/src/main/java/fr/xephi/authme/command/help/HelpMessagesService.java @@ -24,7 +24,7 @@ public class HelpMessagesService { private final HelpMessagesFileHandler helpMessagesFileHandler; @Inject - HelpMessagesService(HelpMessagesFileHandler helpMessagesFileHandler) { + public HelpMessagesService(HelpMessagesFileHandler helpMessagesFileHandler) { this.helpMessagesFileHandler = helpMessagesFileHandler; } diff --git a/authme-core/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java b/authme-core/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java index 2dffc80add..ca029ee764 100644 --- a/authme-core/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java +++ b/authme-core/src/main/java/fr/xephi/authme/message/AbstractMessageFileHandler.java @@ -12,7 +12,6 @@ import org.bukkit.configuration.file.YamlConfiguration; import javax.annotation.PostConstruct; -import javax.inject.Inject; import java.io.File; import java.util.concurrent.ConcurrentHashMap; @@ -27,19 +26,17 @@ public abstract class AbstractMessageFileHandler implements Reloadable { private final ConsoleLogger logger = ConsoleLoggerFactory.get(AbstractMessageFileHandler.class); - @DataFolder - @Inject - private File dataFolder; - - @Inject - private Settings settings; + private final File dataFolder; + private final Settings settings; private String filename; private FileConfiguration configuration; private final String defaultFile; private final ConcurrentHashMap languageCache = new ConcurrentHashMap<>(); - protected AbstractMessageFileHandler() { + protected AbstractMessageFileHandler(@DataFolder File dataFolder, Settings settings) { + this.dataFolder = dataFolder; + this.settings = settings; this.defaultFile = createFilePath(DEFAULT_LANGUAGE); } diff --git a/authme-core/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java b/authme-core/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java index 89dc522453..c0004ec08f 100644 --- a/authme-core/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java +++ b/authme-core/src/main/java/fr/xephi/authme/message/HelpMessagesFileHandler.java @@ -1,12 +1,15 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.output.ConsoleLoggerFactory; +import fr.xephi.authme.settings.Settings; import fr.xephi.authme.util.FileUtils; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import javax.inject.Inject; +import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; @@ -21,8 +24,9 @@ public class HelpMessagesFileHandler extends AbstractMessageFileHandler { private FileConfiguration defaultConfiguration; - @Inject // Trigger injection in the superclass - HelpMessagesFileHandler() { + @Inject + public HelpMessagesFileHandler(@DataFolder File dataFolder, Settings settings) { + super(dataFolder, settings); } /** diff --git a/authme-core/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java b/authme-core/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java index 18b7764642..08f8bd85be 100644 --- a/authme-core/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java +++ b/authme-core/src/main/java/fr/xephi/authme/message/MessagesFileHandler.java @@ -1,11 +1,15 @@ package fr.xephi.authme.message; import fr.xephi.authme.ConsoleLogger; +import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.output.ConsoleLoggerFactory; import fr.xephi.authme.message.updater.MessageUpdater; +import fr.xephi.authme.settings.Settings; import javax.inject.Inject; +import java.io.File; + import static fr.xephi.authme.message.MessagePathHelper.DEFAULT_LANGUAGE; /** @@ -15,10 +19,12 @@ public class MessagesFileHandler extends AbstractMessageFileHandler { private final ConsoleLogger logger = ConsoleLoggerFactory.get(MessagesFileHandler.class); - @Inject - private MessageUpdater messageUpdater; + private final MessageUpdater messageUpdater; - MessagesFileHandler() { + @Inject + MessagesFileHandler(@DataFolder File dataFolder, Settings settings, MessageUpdater messageUpdater) { + super(dataFolder, settings); + this.messageUpdater = messageUpdater; } @Override diff --git a/authme-core/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java b/authme-core/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java index e1c8c5ba76..2d1239244b 100644 --- a/authme-core/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java +++ b/authme-core/src/main/java/fr/xephi/authme/service/HelpTranslationGenerator.java @@ -29,18 +29,19 @@ */ public class HelpTranslationGenerator { - @Inject - private CommandInitializer commandInitializer; - - @Inject - private HelpMessagesService helpMessagesService; + private final CommandInitializer commandInitializer; + private final HelpMessagesService helpMessagesService; + private final Settings settings; + private final File dataFolder; @Inject - private Settings settings; - - @DataFolder - @Inject - private File dataFolder; + HelpTranslationGenerator(CommandInitializer commandInitializer, HelpMessagesService helpMessagesService, + Settings settings, @DataFolder File dataFolder) { + this.commandInitializer = commandInitializer; + this.helpMessagesService = helpMessagesService; + this.settings = settings; + this.dataFolder = dataFolder; + } /** * Updates the help file to contain entries for all commands. diff --git a/authme-core/src/main/java/fr/xephi/authme/service/ValidationService.java b/authme-core/src/main/java/fr/xephi/authme/service/ValidationService.java index ad99e066f4..a976a52100 100644 --- a/authme-core/src/main/java/fr/xephi/authme/service/ValidationService.java +++ b/authme-core/src/main/java/fr/xephi/authme/service/ValidationService.java @@ -152,11 +152,12 @@ public boolean isUnrestricted(String name) { * @return true if the player may join, false if the player does not satisfy the name restrictions */ public boolean fulfillsNameRestrictions(Player player) { - InetSocketAddress socketAddress = player.getAddress(); Collection restrictions = restrictedNames.get(player.getName().toLowerCase(Locale.ROOT)); if (Utils.isCollectionEmpty(restrictions)) { return true; } + + InetSocketAddress socketAddress = player.getAddress(); String ip = socketAddress.getAddress().getHostAddress(); String domain = getHostName(socketAddress); return matchesRestrictions(restrictions, ip, domain); diff --git a/authme-core/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java b/authme-core/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java index 4c495be748..9272bd9b21 100644 --- a/authme-core/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/AuthMeInitializationTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.configme.resource.PropertyReader; import ch.jalu.configme.resource.PropertyResource; import ch.jalu.injector.Injector; @@ -17,6 +13,7 @@ import fr.xephi.authme.listener.LegacyPlayerLoginListener; import fr.xephi.authme.listener.LegacyPlayerSpawnLocationListener; import fr.xephi.authme.listener.PlayerListener; +import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.platform.ChatAdapter; import fr.xephi.authme.platform.CommandRegistrationAdapter; import fr.xephi.authme.platform.DialogAdapter; @@ -25,7 +22,6 @@ import fr.xephi.authme.platform.PlatformAdapter; import fr.xephi.authme.platform.SchedulingAdapter; import fr.xephi.authme.platform.TeleportAdapter; -import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.process.Management; import fr.xephi.authme.process.login.ProcessSyncPlayerLogin; import fr.xephi.authme.security.PasswordSecurity; @@ -43,22 +39,20 @@ import org.bukkit.scheduler.BukkitScheduler; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; -import org.mockito.ArgumentCaptor; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; -import java.util.Collections; import java.util.List; import java.util.logging.Logger; import static fr.xephi.authme.settings.properties.AuthMeSettingsRetriever.buildConfigurationData; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -68,8 +62,7 @@ * with the {@link Injector}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AuthMeInitializationTest { +class AuthMeInitializationTest { @Mock private Server server; @@ -78,12 +71,12 @@ public class AuthMeInitializationTest { private PluginManager pluginManager; private AuthMe authMe; - private File dataFolder; - public TempFolder temporaryFolder = new TempFolder(); + + @TempDir + File dataFolder; @BeforeEach - public void initAuthMe() throws IOException { - dataFolder = temporaryFolder.newFolder(); + void initAuthMe() throws IOException { File settingsFile = new File(dataFolder, "config.yml"); given(server.getLogger()).willReturn(Logger.getAnonymousLogger()); JavaPluginLoader pluginLoader = new JavaPluginLoader(server); @@ -101,19 +94,19 @@ public void initAuthMe() throws IOException { } @Test - public void shouldInitializeAllServices() { + void shouldInitializeAllServices() { // given PropertyReader reader = mock(PropertyReader.class); PropertyResource resource = mock(PropertyResource.class); given(resource.createReader()).willReturn(reader); Settings settings = new Settings(dataFolder, resource, null, buildConfigurationData()); + given(server.getPluginManager()).willReturn(pluginManager); TestHelper.setupLogger(); Injector injector = new InjectorBuilder() .addDefaultHandlers("fr.xephi.authme") .create(); - given(server.getPluginManager()).willReturn(pluginManager); injector.provide(DataFolder.class, dataFolder); injector.register(Server.class, server); injector.register(PluginManager.class, pluginManager); @@ -152,7 +145,7 @@ public void shouldInitializeAllServices() { } @Test - public void shouldRegisterPlatformListenersFromAdapter() { + void shouldRegisterPlatformListenersFromAdapter() { // given Injector injector = mock(Injector.class); PlatformAdapter platformAdapter = mock(PlatformAdapter.class); @@ -180,7 +173,7 @@ public void shouldRegisterPlatformListenersFromAdapter() { } @Test - public void shouldHandlePrematureShutdownGracefully() { + void shouldHandlePrematureShutdownGracefully() { // given BukkitScheduler scheduler = mock(BukkitScheduler.class); given(server.getScheduler()).willReturn(scheduler); @@ -195,5 +188,3 @@ public void shouldHandlePrematureShutdownGracefully() { verify(scheduler).getActiveWorkers(); // via TaskCloser } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java index 4ac728d406..58ee365374 100644 --- a/authme-core/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java @@ -4,8 +4,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import fr.xephi.authme.data.captcha.CaptchaCodeStorage; import fr.xephi.authme.command.PlayerCommand; +import fr.xephi.authme.data.captcha.CaptchaCodeStorage; import fr.xephi.authme.datasource.AbstractSqlDataSource; import fr.xephi.authme.datasource.Columns; import fr.xephi.authme.datasource.columnshandler.DataSourceColumn; @@ -14,7 +14,6 @@ import fr.xephi.authme.security.crypts.AbstractPbkdf2; import fr.xephi.authme.initialization.HasCleanup; import fr.xephi.authme.process.register.executors.RegistrationMethod; - import fr.xephi.authme.util.expiring.ExpiringMap; import fr.xephi.authme.util.expiring.ExpiringSet; import fr.xephi.authme.util.expiring.TimedCounter; @@ -34,14 +33,14 @@ import java.util.Set; import java.util.stream.Collectors; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.fail; /** * Contains consistency tests across all AuthMe classes. */ -public class ClassesConsistencyTest { +class ClassesConsistencyTest { /** Contains all production classes. */ private static final List> ALL_CLASSES = @@ -74,7 +73,7 @@ int.class, long.class, float.class, String.class, File.class, Enum.class, collec * Checks that there aren't two classes with the same name; this is confusing and should be avoided. */ @Test - public void shouldNotHaveSameName() { + void shouldNotHaveSameName() { // given Set names = new HashSet<>(); @@ -90,7 +89,7 @@ public void shouldNotHaveSameName() { * Checks that fields of classes are either private or static final fields of an immutable type. */ @Test - public void shouldHaveNonPrivateConstantsOnly() { + void shouldHaveNonPrivateConstantsOnly() { // given / when Set invalidFields = ALL_CLASSES.stream() .filter(clz -> !CLASSES_EXCLUDED_FROM_VISIBILITY_TEST.contains(clz)) @@ -123,7 +122,7 @@ private static boolean hasIllegalFieldVisibility(Field field) { Object value = ReflectionTestUtils.getFieldValue(field, null); valueType = value.getClass(); } else { - valueType = field.getType(); + valueType = field.getType(); } // Field is static, final, and not private -> check that it is immutable type @@ -148,7 +147,7 @@ private static String formatField(Field field) { * interface to regularly clean up expired data. */ @Test - public void shouldImplementHasCleanup() { + void shouldImplementHasCleanup() { // given / when / then for (Class clazz : ALL_CLASSES) { if (hasExpiringCollectionAsField(clazz) && !EXPIRING_STRUCTURES.contains(clazz)) { @@ -174,4 +173,3 @@ private static Class collectionsUnmodifiableList() { return Collections.unmodifiableList(new ArrayList<>()).getClass(); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java b/authme-core/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java index da556005a6..f1dc20202f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/CodeClimateConfigTest.java @@ -7,21 +7,21 @@ import java.io.File; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; /** * Consistency test for the CodeClimate configuration file. */ -public class CodeClimateConfigTest { +class CodeClimateConfigTest { private static final String CONFIG_FILE = "../.codeclimate.yml"; @Test - public void shouldHaveExistingClassesInExclusions() { + void shouldHaveExistingClassesInExclusions() { // given / when FileConfiguration configuration = YamlConfiguration.loadConfiguration(new File(CONFIG_FILE)); List excludePaths = configuration.getStringList("exclude_patterns"); @@ -42,4 +42,3 @@ private static void removeTestsExclusionOrThrow(List excludePaths) { wasRemoved, equalTo(true)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java b/authme-core/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java index 80c2052436..986266d631 100644 --- a/authme-core/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/ConsoleLoggerTest.java @@ -1,19 +1,17 @@ package fr.xephi.authme; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.output.LogLevel; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.SecuritySettings; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.FileWriter; @@ -23,17 +21,16 @@ import java.util.List; import java.util.logging.Logger; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -43,21 +40,21 @@ * Test for {@link ConsoleLogger}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class ConsoleLoggerTest { +class ConsoleLoggerTest { private ConsoleLogger consoleLogger; @Mock private Logger logger; - public TempFolder temporaryFolder = new TempFolder(); + + @TempDir + File tempFolder; private File logFile; @BeforeEach - public void setMockLogger() throws IOException { - File folder = temporaryFolder.newFolder(); - File logFile = new File(folder, "authme.log"); + void setMockLogger() throws IOException { + File logFile = new File(tempFolder, "authme.log"); if (!logFile.createNewFile()) { throw new IOException("Could not create file '" + logFile.getPath() + "'"); } @@ -67,7 +64,7 @@ public void setMockLogger() throws IOException { } @AfterEach - public void closeFileHandlers() { + void closeFileHandlers() { ConsoleLogger.closeFileWriter(); } @@ -77,12 +74,12 @@ public void closeFileHandlers() { * be around after this test class has finished. */ @AfterAll - public static void resetConsoleToDefault() { + static void resetConsoleToDefault() { ConsoleLogger.initializeSharedSettings(newSettings(false, LogLevel.INFO)); } @Test - public void shouldLogToFile() throws IOException { + void shouldLogToFile() throws IOException { // given Settings settings = newSettings(true, LogLevel.FINE); ConsoleLogger.initializeSharedSettings(settings); @@ -103,7 +100,7 @@ public void shouldLogToFile() throws IOException { } @Test - public void shouldNotLogToFile() { + void shouldNotLogToFile() { // given Settings settings = newSettings(false, LogLevel.DEBUG); ConsoleLogger.initializeSharedSettings(settings); @@ -121,9 +118,10 @@ public void shouldNotLogToFile() { } @Test - public void shouldLogStackTraceToFile() throws IOException { + void shouldLogStackTraceToFile() throws IOException { // given - Settings settings = newSettings(true, LogLevel.INFO); + Settings settings = mock(Settings.class); + given(settings.getProperty(SecuritySettings.USE_LOGGING)).willReturn(true); ConsoleLogger.initializeSharedSettings(settings); Exception e = new IllegalStateException("Test exception message"); @@ -147,7 +145,7 @@ public void shouldLogStackTraceToFile() throws IOException { } @Test - public void shouldSupportVariousDebugMethods() throws IOException { + void shouldSupportVariousDebugMethods() throws IOException { // given Settings settings = newSettings(true, LogLevel.DEBUG); ConsoleLogger.initializeSharedSettings(settings); @@ -175,7 +173,7 @@ public void shouldSupportVariousDebugMethods() throws IOException { } @Test - public void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException { + void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException { // given FileWriter fileWriter = mock(FileWriter.class); doThrow(new IOException("Error during flush")).when(fileWriter).flush(); @@ -191,7 +189,7 @@ public void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException { } @Test - public void shouldHandleExceptionOnFileWriterClose() throws IOException { + void shouldHandleExceptionOnFileWriterClose() throws IOException { // given FileWriter fileWriter = mock(FileWriter.class); doThrow(new IOException("Cannot close")).when(fileWriter).close(); @@ -208,8 +206,8 @@ public void shouldHandleExceptionOnFileWriterClose() throws IOException { private static Settings newSettings(boolean logToFile, LogLevel logLevel) { Settings settings = mock(Settings.class); - lenient().when(settings.getProperty(SecuritySettings.USE_LOGGING)).thenReturn(logToFile); - lenient().when(settings.getProperty(PluginSettings.LOG_LEVEL)).thenReturn(logLevel); + given(settings.getProperty(SecuritySettings.USE_LOGGING)).willReturn(logToFile); + given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(logLevel); return settings; } @@ -226,5 +224,3 @@ public String toString() { } } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/DelayedInjectionExtension.java b/authme-core/src/test/java/fr/xephi/authme/DelayedInjectionExtension.java deleted file mode 100644 index 7793fd87cd..0000000000 --- a/authme-core/src/test/java/fr/xephi/authme/DelayedInjectionExtension.java +++ /dev/null @@ -1,205 +0,0 @@ -package fr.xephi.authme; - -import ch.jalu.injector.Injector; -import ch.jalu.injector.InjectorBuilder; -import ch.jalu.injector.context.ResolutionContext; -import ch.jalu.injector.exceptions.InjectorException; -import ch.jalu.injector.handlers.Handler; -import ch.jalu.injector.handlers.instantiation.Resolution; -import ch.jalu.injector.handlers.instantiation.SimpleResolution; -import ch.jalu.injector.handlers.postconstruct.PostConstructMethodInvoker; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; -import org.junit.jupiter.api.extension.AfterEachCallback; -import org.junit.jupiter.api.extension.BeforeEachCallback; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - -import javax.inject.Inject; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * JUnit 5 equivalent of Jalu Injector's DelayedInjectionRunner. - */ -public class DelayedInjectionExtension implements BeforeEachCallback, AfterEachCallback { - - private static final ExtensionContext.Namespace NAMESPACE = - ExtensionContext.Namespace.create(DelayedInjectionExtension.class); - - @Override - public void beforeEach(ExtensionContext context) throws Exception { - Object testInstance = context.getRequiredTestInstance(); - AutoCloseable mocks = MockitoAnnotations.openMocks(testInstance); - context.getStore(NAMESPACE).put(testInstance, mocks); - - invokeBeforeInjectingMethods(testInstance); - injectDelayedFields(testInstance); - } - - @Override - public void afterEach(ExtensionContext context) throws Exception { - Object testInstance = context.getRequiredTestInstance(); - AutoCloseable mocks = context.getStore(NAMESPACE).remove(testInstance, AutoCloseable.class); - if (mocks != null) { - mocks.close(); - } - } - - private static void invokeBeforeInjectingMethods(Object testInstance) throws ReflectiveOperationException { - for (Method method : getAnnotatedMethods(testInstance.getClass(), BeforeInjecting.class)) { - method.setAccessible(true); - method.invoke(testInstance); - } - } - - private static void injectDelayedFields(Object testInstance) throws ReflectiveOperationException { - List delayedFields = getAnnotatedFields(testInstance.getClass(), InjectDelayed.class); - if (delayedFields.isEmpty()) { - return; - } - - Injector injector = new InjectorBuilder() - .addHandlers( - new TestAnnotationResolver(testInstance.getClass(), testInstance), - new MockDependencyHandler(testInstance.getClass(), testInstance, delayedFields), - new PostConstructMethodInvoker()) - .addHandlers(InjectorBuilder.createInstantiationProviders("")) - .create(); - - for (Field field : delayedFields) { - field.setAccessible(true); - if (field.get(testInstance) != null) { - throw new IllegalStateException("Field with @InjectDelayed must be null on startup. Field '" - + field.getName() + "' is not null"); - } - field.set(testInstance, injector.getSingleton(field.getType())); - } - } - - private static List getAnnotatedMethods(Class type, Class annotationType) { - List methods = new ArrayList<>(); - Class current = type; - while (current != null && current != Object.class) { - for (Method method : current.getDeclaredMethods()) { - if (method.isAnnotationPresent(annotationType)) { - methods.add(0, method); - } - } - current = current.getSuperclass(); - } - return methods; - } - - private static List getAnnotatedFields(Class type, Class annotationType) { - List fields = new ArrayList<>(); - Class current = type; - while (current != null && current != Object.class) { - for (Field field : current.getDeclaredFields()) { - if (field.isAnnotationPresent(annotationType)) { - fields.add(field); - } - } - current = current.getSuperclass(); - } - return fields; - } - - private static final class MockDependencyHandler implements Handler { - - private final Class testClass; - private final Object target; - private final Set> fieldsToInject; - - private boolean areMocksRegistered; - - private MockDependencyHandler(Class testClass, Object target, List delayedFields) { - this.testClass = testClass; - this.target = target; - this.fieldsToInject = new HashSet<>(); - for (Field field : delayedFields) { - fieldsToInject.add(field.getType()); - } - } - - @Override - public Resolution resolve(ResolutionContext context) throws IllegalAccessException { - Injector injector = context.getInjector(); - if (!areMocksRegistered) { - registerAllMocks(injector); - areMocksRegistered = true; - } - - Class requestedType = context.getIdentifier().getTypeAsClass(); - Object existingObject = injector.getIfAvailable(requestedType); - if (existingObject != null) { - return new SimpleResolution<>(existingObject); - } - if (fieldsToInject.contains(requestedType)) { - return null; - } - throw new InjectorException("No mock found for '" + requestedType - + "'. All dependencies of @InjectDelayed must be provided as @Mock or @InjectDelayed fields"); - } - - private void registerAllMocks(Injector injector) throws IllegalAccessException { - for (Field field : getAnnotatedFields(testClass, Mock.class)) { - field.setAccessible(true); - registerMock(injector, field, field.get(target)); - } - } - - @SuppressWarnings("unchecked") - private static void registerMock(Injector injector, Field field, Object mock) { - injector.register((Class) field.getType(), (T) mock); - } - } - - private static final class TestAnnotationResolver implements Handler { - - private static final Set> IGNORED_ANNOTATIONS = Set.of( - Inject.class, org.mockito.InjectMocks.class, Mock.class, Spy.class, InjectDelayed.class); - - private final Class testClass; - private final Object target; - - private TestAnnotationResolver(Class testClass, Object target) { - this.testClass = testClass; - this.target = target; - } - - @Override - public Resolution resolve(ResolutionContext context) throws IllegalAccessException { - Class requestedType = context.getIdentifier().getTypeAsClass(); - for (Annotation annotation : context.getIdentifier().getAnnotations()) { - Object resolvedValue = resolveByAnnotation(annotation.annotationType(), requestedType); - if (resolvedValue != null) { - return new SimpleResolution<>(resolvedValue); - } - } - return null; - } - - private Object resolveByAnnotation(Class annotationType, Class requestedType) - throws IllegalAccessException { - if (IGNORED_ANNOTATIONS.contains(annotationType)) { - return null; - } - - for (Field field : getAnnotatedFields(testClass, annotationType)) { - if (requestedType.isAssignableFrom(field.getType())) { - field.setAccessible(true); - return field.get(target); - } - } - return null; - } - } -} diff --git a/authme-core/src/test/java/fr/xephi/authme/TempFolder.java b/authme-core/src/test/java/fr/xephi/authme/TempFolder.java deleted file mode 100644 index 9ff91a1546..0000000000 --- a/authme-core/src/test/java/fr/xephi/authme/TempFolder.java +++ /dev/null @@ -1,38 +0,0 @@ -package fr.xephi.authme; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; - -/** - * Minimal test helper replacing JUnit 4's TemporaryFolder rule. - */ -public class TempFolder { - - private final File root; - - public TempFolder() { - try { - root = Files.createTempDirectory("authme-tests-").toFile(); - root.deleteOnExit(); - } catch (IOException e) { - throw new IllegalStateException("Could not create temporary folder", e); - } - } - - public File newFolder() throws IOException { - File folder = Files.createTempDirectory(root.toPath(), "folder-").toFile(); - folder.deleteOnExit(); - return folder; - } - - public File newFile() throws IOException { - File file = Files.createTempFile(root.toPath(), "file-", ".tmp").toFile(); - file.deleteOnExit(); - return file; - } - - public File getRoot() { - return root; - } -} diff --git a/authme-core/src/test/java/fr/xephi/authme/TestHelper.java b/authme-core/src/test/java/fr/xephi/authme/TestHelper.java index 6c797fda12..1afabe6b0c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/TestHelper.java +++ b/authme-core/src/test/java/fr/xephi/authme/TestHelper.java @@ -19,7 +19,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.lenient; /** * AuthMe test utilities. @@ -104,7 +103,7 @@ public static void mockIpAddressToPlayer(Player player, String ip) { try { InetAddress inetAddress = InetAddress.getByName(ip); InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 8093); - lenient().when(player.getAddress()).thenReturn(inetSocketAddress); + given(player.getAddress()).willReturn(inetSocketAddress); } catch (UnknownHostException e) { throw new IllegalStateException("Invalid IP address: " + ip, e); } diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java index 914ebd8d48..1b6450991f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/authme/RegisterAdminCommandTest.java @@ -24,7 +24,7 @@ import java.util.Locale; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskOptionallyAsync; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; @@ -163,7 +163,7 @@ void shouldRegisterOnlinePlayer() { String kickForAdminRegister = "Admin registered you -- log in again"; given(commandService.retrieveSingleMessage(player, MessageKey.KICK_FOR_ADMIN_REGISTER)).willReturn(kickForAdminRegister); CommandSender sender = mock(CommandSender.class); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); setBukkitServiceToRunTaskOptionallyAsync(bukkitService); // when diff --git a/authme-core/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java b/authme-core/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java index 30aabaefe0..b40a1d0998 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java @@ -1,39 +1,33 @@ package fr.xephi.authme.command.executable.email; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; import ch.jalu.datasourcecolumns.data.DataSourceValueImpl; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.mail.EmailService; import fr.xephi.authme.message.MessageKey; -import fr.xephi.authme.message.Messages; -import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.PasswordRecoveryService; import fr.xephi.authme.service.RecoveryCodeService; import fr.xephi.authme.service.ValidationService; -import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; import java.util.Locale; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.anyString; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -41,17 +35,14 @@ /** * Test for {@link RecoverEmailCommand}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class RecoverEmailCommandTest { +@ExtendWith(MockitoExtension.class) +class RecoverEmailCommandTest { private static final String DEFAULT_EMAIL = "your@email.com"; - @InjectDelayed + @InjectMocks private RecoverEmailCommand command; - @Mock - private PasswordSecurity passwordSecurity; - @Mock private CommonService commonService; @@ -76,26 +67,13 @@ public class RecoverEmailCommandTest { @Mock private ValidationService validationService; - @Mock - private Messages messages; - @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void initSettings() { - given(commonService.getProperty(SecuritySettings.EMAIL_RECOVERY_COOLDOWN_SECONDS)).willReturn(40); - } - - @BeforeEach - public void allowValidEmailsByDefault() { - lenient().when(validationService.validateEmail(anyString())).thenReturn(true); - } - @Test - public void shouldHandleMissingMailProperties() { + void shouldHandleMissingMailProperties() { // given given(emailService.hasAllInformation()).willReturn(false); Player sender = mock(Player.class); @@ -105,11 +83,11 @@ public void shouldHandleMissingMailProperties() { // then verify(commonService).send(sender, MessageKey.INCOMPLETE_EMAIL_SETTINGS); - verifyNoInteractions(dataSource, passwordSecurity); + verifyNoInteractions(dataSource); } @Test - public void shouldShowErrorForAuthenticatedUser() { + void shouldShowErrorForAuthenticatedUser() { // given String name = "Bobby"; Player sender = mock(Player.class); @@ -127,7 +105,7 @@ public void shouldShowErrorForAuthenticatedUser() { } @Test - public void shouldRejectInvalidEmailFormat() { + void shouldRejectInvalidEmailFormat() { // given String name = "SomePlayer"; Player sender = mock(Player.class); @@ -145,100 +123,93 @@ public void shouldRejectInvalidEmailFormat() { } @Test - public void shouldShowRegisterMessageForUnregisteredPlayer() { + void shouldShowRegisterMessageForUnregisteredPlayer() { // given String name = "Player123"; Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); + given(validationService.validateEmail("someone@example.com")).willReturn(true); given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.unknownRow()); // when command.executeCommand(sender, Collections.singletonList("someone@example.com")); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); verifyNoMoreInteractions(dataSource); verify(commonService).send(sender, MessageKey.USAGE_REGISTER); } @Test - public void shouldHandleDefaultEmail() { + void shouldHandleDefaultEmail() { // given String name = "Tract0r"; Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); + given(validationService.validateEmail(DEFAULT_EMAIL)).willReturn(true); given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of(DEFAULT_EMAIL)); // when command.executeCommand(sender, Collections.singletonList(DEFAULT_EMAIL)); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); verifyNoMoreInteractions(dataSource); verify(commonService).send(sender, MessageKey.INVALID_EMAIL); } @Test - public void shouldHandleInvalidEmailInput() { + void shouldHandleInvalidEmailInput() { // given String name = "Rapt0r"; Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); + given(validationService.validateEmail("wrong-email@example.com")).willReturn(true); given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of("raptor@example.org")); // when command.executeCommand(sender, Collections.singletonList("wrong-email@example.com")); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); verifyNoMoreInteractions(dataSource); verify(commonService).send(sender, MessageKey.INVALID_EMAIL); } @Test - public void shouldGenerateRecoveryCode() { + void shouldGenerateRecoveryCode() { // given String name = "Vultur3"; Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); - given(emailService.sendRecoveryCode(anyString(), anyString(), anyString())).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); String email = "v@example.com"; + given(validationService.validateEmail("V@EXAMPLE.COM")).willReturn(true); given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of(email)); - String code = "a94f37"; given(recoveryCodeService.isRecoveryCodeNeeded()).willReturn(true); - given(recoveryCodeService.generateCode(name)).willReturn(code); setBukkitServiceToRunTaskAsynchronously(bukkitService); // when command.executeCommand(sender, Collections.singletonList(email.toUpperCase(Locale.ROOT))); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); - verify(recoveryService).createAndSendRecoveryCode(sender, email); + verify(recoveryService, only()).createAndSendRecoveryCode(sender, email); } @Test - public void shouldGenerateNewPasswordWithoutRecoveryCode() { + void shouldGenerateNewPasswordWithoutRecoveryCode() { // given String name = "Vultur3"; Player sender = mock(Player.class); given(sender.getName()).willReturn(name); given(emailService.hasAllInformation()).willReturn(true); - given(emailService.sendPasswordMail(anyString(), anyString(), anyString())).willReturn(true); given(playerCache.isAuthenticated(name)).willReturn(false); String email = "vulture@example.com"; + given(validationService.validateEmail(email)).willReturn(true); given(dataSource.getEmail(name)).willReturn(DataSourceValueImpl.of(email)); given(recoveryCodeService.isRecoveryCodeNeeded()).willReturn(false); setBukkitServiceToRunTaskAsynchronously(bukkitService); @@ -247,16 +218,12 @@ public void shouldGenerateNewPasswordWithoutRecoveryCode() { command.executeCommand(sender, Collections.singletonList(email)); // then - verify(emailService).hasAllInformation(); - verify(dataSource).getEmail(name); - verify(recoveryService).generateAndSendNewPassword(sender, email); + verify(recoveryService, only()).generateAndSendNewPassword(sender, email); } @Test - public void shouldDefineArgumentMismatchMessage() { + void shouldDefineArgumentMismatchMessage() { // given / when / then assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_RECOVER_EMAIL)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java index b2d970e8c8..1c874c552d 100644 --- a/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java @@ -5,7 +5,6 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandDescription; import fr.xephi.authme.command.TestCommandsUtil; -import fr.xephi.authme.message.AbstractMessageFileHandler; import fr.xephi.authme.message.HelpMessagesFileHandler; import fr.xephi.authme.message.MessagePathHelper; import fr.xephi.authme.permission.DefaultPermission; @@ -148,9 +147,7 @@ private HelpMessagesFileHandler createMessagesFileHandler() { Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); - HelpMessagesFileHandler messagesFileHandler = ReflectionTestUtils.newInstance(HelpMessagesFileHandler.class); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "settings", settings); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "dataFolder", dataFolder); + HelpMessagesFileHandler messagesFileHandler = new HelpMessagesFileHandler(dataFolder, settings); ReflectionTestUtils.invokePostConstructMethods(messagesFileHandler); return messagesFileHandler; } diff --git a/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java index d0091b4049..fc2f72e3e3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/data/TempbanManagerTest.java @@ -21,7 +21,7 @@ import java.util.Map; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunOnGlobalRegion; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; @@ -154,7 +154,7 @@ void shouldBanPlayerIp() { Settings settings = mockSettings(2, 100, ""); TempbanManager manager = new TempbanManager(bukkitService, messages, settings); setBukkitServiceToRunOnGlobalRegion(bukkitService); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when manager.tempbanPlayer(player); @@ -204,7 +204,7 @@ void shouldResetCountAfterBan() { manager.increaseCount(ip, "name2"); manager.increaseCount(ip, "user"); setBukkitServiceToRunOnGlobalRegion(bukkitService); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when manager.tempbanPlayer(player); diff --git a/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AuthPlusConverterTest.java b/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AuthPlusConverterTest.java index c645f00871..caa01d2765 100644 --- a/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AuthPlusConverterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/datasource/converter/AuthPlusConverterTest.java @@ -1,23 +1,26 @@ package fr.xephi.authme.datasource.converter; -import ch.jalu.injector.testing.InjectDelayed; -import fr.xephi.authme.DelayedInjectionExtension; +import com.google.common.io.Files; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; -import fr.xephi.authme.initialization.DataFolder; +import fr.xephi.authme.util.FileUtils; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; +import java.io.IOException; import java.util.List; import java.util.UUID; @@ -32,25 +35,25 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; /** * Test for {@link AuthPlusConverter}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class AuthPlusConverterTest { +@ExtendWith(MockitoExtension.class) +class AuthPlusConverterTest { private static final UUID UUID_TESTPLAYER = UUID.fromString("a811b264-a1da-42dd-b1b7-b601234b7cc7"); private static final UUID UUID_EXISTINGPLAYER = UUID.fromString("b922c375-b2eb-53ee-c2c8-c712345c8dd8"); private static final UUID UUID_UNKNOWNPLAYER = UUID.fromString("cc033486-c3fc-64ff-d3d9-d823456d9ee9"); - @InjectDelayed private AuthPlusConverter converter; @Mock private DataSource dataSource; - @DataFolder - private File dataFolder = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "datasource/converter/"); + @TempDir + File tempFolder; @Captor private ArgumentCaptor authCaptor; @@ -60,11 +63,24 @@ public static void initLogger() { TestHelper.setupLogger(); } + @BeforeEach + void setUpConverter() { + File authMeDataFolder = new File(tempFolder, "AuthMe"); + authMeDataFolder.mkdir(); + converter = new AuthPlusConverter(authMeDataFolder, dataSource); + new File(tempFolder, "Auth").mkdir(); + } + @Test - public void shouldImportAndSkipAccordingly() { + void shouldImportAndSkipAccordingly() throws IOException { // given + File playersYml = new File(tempFolder, "Auth/players.yml"); + FileUtils.create(playersYml); + Files.copy(TestHelper.getJarFile("datasource/Auth/players.yml"), playersYml); + CommandSender sender = mock(CommandSender.class); given(dataSource.isAuthAvailable("existingplayer")).willReturn(true); + given(dataSource.isAuthAvailable("testplayer")).willReturn(false); OfflinePlayer testPlayer = offlinePlayerWithName("TestPlayer"); OfflinePlayer existingPlayer = offlinePlayerWithName("ExistingPlayer"); @@ -89,24 +105,20 @@ public void shouldImportAndSkipAccordingly() { assertThat(saved.get(0).getUuid(), equalTo(UUID_TESTPLAYER)); assertThat(saved.get(0).getPassword(), equalToHash("pbkdf2$120000$JddgMm9rNhbYNfEmf4pOKA==$RcAMtgm/KnKFxfNOpg95tb7s5OzB2Fv4Wj1HOAI/TWY=")); - verify(sender).sendMessage( - org.mockito.hamcrest.MockitoHamcrest.argThat(containsString("1 account(s) imported"))); + verify(sender).sendMessage(argThat(containsString("1 account(s) imported"))); } @Test - public void shouldReportMissingFile() { + void shouldReportMissingFile() { // given CommandSender sender = mock(CommandSender.class); - File missingFolder = new File("non/existent/path"); - AuthPlusConverter missingConverter = new AuthPlusConverter(missingFolder, dataSource); // when - missingConverter.execute(sender); + converter.execute(sender); // then verifyNoInteractions(dataSource); - verify(sender).sendMessage( - org.mockito.hamcrest.MockitoHamcrest.argThat(containsString("does not exist"))); + verify(sender).sendMessage(argThat(containsString("does not exist"))); } private static OfflinePlayer offlinePlayerWithName(String name) { diff --git a/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java b/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java index 5ae950142e..bf88b1a5b6 100644 --- a/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/listener/PlayerListenerTest.java @@ -73,7 +73,7 @@ import static com.google.common.collect.Sets.newHashSet; import static fr.xephi.authme.listener.EventCancelVerifier.withServiceMock; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; @@ -1039,7 +1039,7 @@ void shouldCancelInventoryOpen() { InventoryOpenEvent event = new InventoryOpenEvent(transaction); given(event.getPlayer()).willReturn(player); given(listenerService.shouldCancelEvent(player)).willReturn(true); - setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); // when listener.onPlayerInventoryOpen(event); diff --git a/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java index 5fb74ab28c..11572fe9d7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/message/MessagesIntegrationTest.java @@ -351,19 +351,13 @@ private MessagesFileHandler createMessagesFileHandler() { Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); - MessagesFileHandler messagesFileHandler = new MessagesFileHandler(); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "settings", settings); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "dataFolder", dataFolder); - ReflectionTestUtils.setField(MessagesFileHandler.class, messagesFileHandler, "messageUpdater", mock(MessageUpdater.class)); + MessagesFileHandler messagesFileHandler = new MessagesFileHandler(dataFolder, settings, mock(MessageUpdater.class)); ReflectionTestUtils.invokePostConstructMethods(messagesFileHandler); return messagesFileHandler; } private MessagesFileHandler createMessagesFileHandlerForLanguage(String language, Settings settings) { - MessagesFileHandler messagesFileHandler = new MessagesFileHandler(); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "settings", settings); - ReflectionTestUtils.setField(AbstractMessageFileHandler.class, messagesFileHandler, "dataFolder", dataFolder); - ReflectionTestUtils.setField(MessagesFileHandler.class, messagesFileHandler, "messageUpdater", mock(MessageUpdater.class)); + MessagesFileHandler messagesFileHandler = new MessagesFileHandler(dataFolder, settings, mock(MessageUpdater.class)); ReflectionTestUtils.invokePostConstructMethods(messagesFileHandler); return messagesFileHandler; } diff --git a/authme-core/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java b/authme-core/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java index f2c74a5e1c..8e38362eca 100644 --- a/authme-core/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/output/ConsoleFilterTest.java @@ -5,8 +5,8 @@ import java.util.logging.LogRecord; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -14,7 +14,7 @@ /** * Test for {@link ConsoleFilter}. */ -public class ConsoleFilterTest { +class ConsoleFilterTest { private final ConsoleFilter filter = new ConsoleFilter(); @@ -23,7 +23,7 @@ public class ConsoleFilterTest { @Test - public void shouldReplaceSensitiveRecord() { + void shouldReplaceSensitiveRecord() { // given LogRecord record = createRecord(SENSITIVE_COMMAND); @@ -36,7 +36,7 @@ public void shouldReplaceSensitiveRecord() { } @Test - public void shouldNotFilterRegularCommand() { + void shouldNotFilterRegularCommand() { // given LogRecord record = createRecord(NORMAL_COMMAND); @@ -49,7 +49,7 @@ public void shouldNotFilterRegularCommand() { } @Test - public void shouldManageRecordWithNullMessage() { + void shouldManageRecordWithNullMessage() { // given LogRecord record = createRecord(null); @@ -75,4 +75,3 @@ private static LogRecord createRecord(String message) { return record; } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java b/authme-core/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java index bd27fa6bcb..83440ea798 100644 --- a/authme-core/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/output/ConsoleLoggerFactoryTest.java @@ -13,27 +13,27 @@ import java.util.Map; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link ConsoleLoggerFactory}. */ -public class ConsoleLoggerFactoryTest { +class ConsoleLoggerFactoryTest { @BeforeAll - public static void initLogger() { + static void initLogger() { removeSettingsAndClearMap(); TestHelper.setupLogger(); } @AfterEach - public void resetConsoleLoggerFactoryToDefaults() { + void resetConsoleLoggerFactoryToDefaults() { removeSettingsAndClearMap(); } @@ -43,7 +43,7 @@ private static void removeSettingsAndClearMap() { } @Test - public void shouldCreateLoggerWithProperNameAndDefaultLogLevel() { + void shouldCreateLoggerWithProperNameAndDefaultLogLevel() { // given / when ConsoleLogger logger = ConsoleLoggerFactory.get(AuthMe.class); @@ -54,7 +54,7 @@ public void shouldCreateLoggerWithProperNameAndDefaultLogLevel() { } @Test - public void shouldReturnSameInstanceForName() { + void shouldReturnSameInstanceForName() { // given / when ConsoleLogger logger1 = ConsoleLoggerFactory.get(String.class); ConsoleLogger logger2 = ConsoleLoggerFactory.get(Number.class); @@ -67,7 +67,7 @@ public void shouldReturnSameInstanceForName() { } @Test - public void shouldInitializeAccordingToSettings() { + void shouldInitializeAccordingToSettings() { // given Settings settings = mock(Settings.class); given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.FINE); @@ -91,4 +91,3 @@ private static Map getConsoleLoggerMap() { return ReflectionTestUtils.getFieldValue(ConsoleLoggerFactory.class, null, "consoleLoggers"); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java b/authme-core/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java index 621dd9368d..3642dbf230 100644 --- a/authme-core/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/output/Log4JFilterTest.java @@ -1,234 +1,230 @@ package fr.xephi.authme.output; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.when; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.core.Filter.Result; import org.apache.logging.log4j.core.LogEvent; -import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.message.Message; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.when; + /** * Test for {@link Log4JFilter}. */ -public class Log4JFilterTest { - - private final Log4JFilter log4JFilter = new Log4JFilter(); - - private static final String SENSITIVE_COMMAND = "User issued server command: /login pass pass"; - private static final String NORMAL_COMMAND = "User issued server command: /help"; - private static final String OTHER_COMMAND = "Starting the server... Write /l for logs"; - - // --------- - // Test the filter(LogEvent) method - // --------- - @Test - public void shouldFilterSensitiveLogEvent() { - // given - Message message = mockMessage(SENSITIVE_COMMAND); - LogEvent event = Mockito.mock(LogEvent.class); - when(event.getMessage()).thenReturn(message); - - // when - Result result = log4JFilter.filter(event); - - // then - assertThat(result, equalTo(Result.DENY)); - } - - @Test - public void shouldNotFilterIrrelevantLogEvent() { - // given - Message message = mockMessage(NORMAL_COMMAND); - LogEvent event = Mockito.mock(LogEvent.class); - when(event.getMessage()).thenReturn(message); - - // when - Result result = log4JFilter.filter(event); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterNonCommandLogEvent() { - // given - Message message = mockMessage(OTHER_COMMAND); - LogEvent event = Mockito.mock(LogEvent.class); - when(event.getMessage()).thenReturn(message); - - // when - Result result = log4JFilter.filter(event); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterLogEventWithNullMessage() { - // given - Message message = mockMessage(null); - LogEvent event = Mockito.mock(LogEvent.class); - when(event.getMessage()).thenReturn(message); - - // when - Result result = log4JFilter.filter(event); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterWhenLogEventIsNull() { - // given / when - Result result = log4JFilter.filter(null); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - // ---------- - // Test filter(Logger, Level, Marker, String, Object...) - // ---------- - @Test - public void shouldFilterSensitiveStringMessage() { - // given / when - Result result = log4JFilter.filter(null, null, null, SENSITIVE_COMMAND); - - // then - assertThat(result, equalTo(Result.DENY)); - } - - @Test - public void shouldNotFilterNormalStringMessage() { - // given / when - Result result = log4JFilter.filter(null, null, null, NORMAL_COMMAND); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterNonCommandStringMessage() { - // given / when - Result result = log4JFilter.filter(null, null, null, OTHER_COMMAND); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldReturnNeutralForNullMessage() { - // given / when - Result result = log4JFilter.filter(null, null, null, null); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - // -------- - // Test filter(Logger, Level, Marker, Object, Throwable) - // -------- - @Test - public void shouldFilterSensitiveObjectMessage() { - // given / when - Result result = log4JFilter.filter(null, null, null, (Object) SENSITIVE_COMMAND, new Exception()); - - // then - assertThat(result, equalTo(Result.DENY)); - } - - @Test - public void shouldNotFilterNullObjectParam() { - // given / when - Result result = log4JFilter.filter(null, null, null, (Object) null, new Exception()); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterIrrelevantMessage() { - // given / when - Result result = log4JFilter.filter(null, null, null, (Object) OTHER_COMMAND, new Exception()); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterNonSensitiveCommand() { - // given / when - Result result = log4JFilter.filter(null, null, null, (Object) NORMAL_COMMAND, new Exception()); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - // -------- - // Test filter(Logger, Level, Marker, Message, Throwable) - // -------- - @Test - public void shouldFilterSensitiveMessage() { - // given - Message message = mockMessage(SENSITIVE_COMMAND); - - // when - Result result = log4JFilter.filter(null, null, null, message, new Exception()); - - // then - assertThat(result, equalTo(Result.DENY)); - } - - @Test - public void shouldNotFilterNonSensitiveMessage() { - // given - Message message = mockMessage(NORMAL_COMMAND); - - // when - Result result = log4JFilter.filter(null, null, null, message, new Exception()); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterNonCommandMessage() { - // given - Message message = mockMessage(OTHER_COMMAND); - - // when - Result result = log4JFilter.filter(null, null, null, message, new Exception()); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - @Test - public void shouldNotFilterNullMessage() { - // given / when - Result result = log4JFilter.filter(null, null, null, (Object) null, new Exception()); - - // then - assertThat(result, equalTo(Result.NEUTRAL)); - } - - /** - * Mocks a {@link Message} object and makes it return the given formatted message. - * - * @param formattedMessage the formatted message the mock should return - * @return Message mock +class Log4JFilterTest { + + private final Log4JFilter log4JFilter = new Log4JFilter(); + + private static final String SENSITIVE_COMMAND = "User issued server command: /login pass pass"; + private static final String NORMAL_COMMAND = "User issued server command: /help"; + private static final String OTHER_COMMAND = "Starting the server... Write /l for logs"; + + // --------- + // Test the filter(LogEvent) method + // --------- + @Test + void shouldFilterSensitiveLogEvent() { + // given + Message message = mockMessage(SENSITIVE_COMMAND); + LogEvent event = Mockito.mock(LogEvent.class); + when(event.getMessage()).thenReturn(message); + + // when + Result result = log4JFilter.filter(event); + + // then + assertThat(result, equalTo(Result.DENY)); + } + + @Test + void shouldNotFilterIrrelevantLogEvent() { + // given + Message message = mockMessage(NORMAL_COMMAND); + LogEvent event = Mockito.mock(LogEvent.class); + when(event.getMessage()).thenReturn(message); + + // when + Result result = log4JFilter.filter(event); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterNonCommandLogEvent() { + // given + Message message = mockMessage(OTHER_COMMAND); + LogEvent event = Mockito.mock(LogEvent.class); + when(event.getMessage()).thenReturn(message); + + // when + Result result = log4JFilter.filter(event); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterLogEventWithNullMessage() { + // given + Message message = mockMessage(null); + LogEvent event = Mockito.mock(LogEvent.class); + when(event.getMessage()).thenReturn(message); + + // when + Result result = log4JFilter.filter(event); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterWhenLogEventIsNull() { + // given / when + Result result = log4JFilter.filter(null); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + // ---------- + // Test filter(Logger, Level, Marker, String, Object...) + // ---------- + @Test + void shouldFilterSensitiveStringMessage() { + // given / when + Result result = log4JFilter.filter(null, null, null, SENSITIVE_COMMAND); + + // then + assertThat(result, equalTo(Result.DENY)); + } + + @Test + void shouldNotFilterNormalStringMessage() { + // given / when + Result result = log4JFilter.filter(null, null, null, NORMAL_COMMAND); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterNonCommandStringMessage() { + // given / when + Result result = log4JFilter.filter(null, null, null, OTHER_COMMAND); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldReturnNeutralForNullMessage() { + // given / when + Result result = log4JFilter.filter(null, null, null, null); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + // -------- + // Test filter(Logger, Level, Marker, Object, Throwable) + // -------- + @Test + void shouldFilterSensitiveObjectMessage() { + // given / when + Result result = log4JFilter.filter(null, null, null, (Object) SENSITIVE_COMMAND, new Exception()); + + // then + assertThat(result, equalTo(Result.DENY)); + } + + @Test + void shouldNotFilterNullObjectParam() { + // given / when + Result result = log4JFilter.filter(null, null, null, (Object) null, new Exception()); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterIrrelevantMessage() { + // given / when + Result result = log4JFilter.filter(null, null, null, (Object) OTHER_COMMAND, new Exception()); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterNonSensitiveCommand() { + // given / when + Result result = log4JFilter.filter(null, null, null, (Object) NORMAL_COMMAND, new Exception()); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + // -------- + // Test filter(Logger, Level, Marker, Message, Throwable) + // -------- + @Test + void shouldFilterSensitiveMessage() { + // given + Message message = mockMessage(SENSITIVE_COMMAND); + + // when + Result result = log4JFilter.filter(null, null, null, message, new Exception()); + + // then + assertThat(result, equalTo(Result.DENY)); + } + + @Test + void shouldNotFilterNonSensitiveMessage() { + // given + Message message = mockMessage(NORMAL_COMMAND); + + // when + Result result = log4JFilter.filter(null, null, null, message, new Exception()); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterNonCommandMessage() { + // given + Message message = mockMessage(OTHER_COMMAND); + + // when + Result result = log4JFilter.filter(null, null, null, message, new Exception()); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + @Test + void shouldNotFilterNullMessage() { + // given / when + Result result = log4JFilter.filter(null, null, null, (Object) null, new Exception()); + + // then + assertThat(result, equalTo(Result.NEUTRAL)); + } + + /** + * Mocks a {@link Message} object and makes it return the given formatted message. + * + * @param formattedMessage the formatted message the mock should return + * @return Message mock */ - private static Message mockMessage(String formattedMessage) { - Message message = Mockito.mock(Message.class); - when(message.getFormattedMessage()).thenReturn(formattedMessage); - return message; - } + private static Message mockMessage(String formattedMessage) { + Message message = Mockito.mock(Message.class); + when(message.getFormattedMessage()).thenReturn(formattedMessage); + return message; + } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java b/authme-core/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java index efc14f6078..8fb53f7fa4 100644 --- a/authme-core/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/output/LogFilterHelperTest.java @@ -9,13 +9,13 @@ import java.util.List; import java.util.stream.Collectors; -import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; /** * Test for {@link LogFilterHelper}. */ -public class LogFilterHelperTest { +class LogFilterHelperTest { private static final List ALL_COMMANDS = new CommandInitializer().getCommands(); @@ -24,7 +24,7 @@ public class LogFilterHelperTest { * (commands with password argument). */ @Test - public void shouldBlacklistAllSensitiveCommands() { + void shouldBlacklistAllSensitiveCommands() { // given List sensitiveCommands = Arrays.asList( getCommand("register"), getCommand("login"), getCommand("changepassword"), getCommand("unregister"), @@ -87,4 +87,3 @@ private static List getCommandPrefixes(CommandDescription command) { .collect(Collectors.toList()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/output/LogLevelTest.java b/authme-core/src/test/java/fr/xephi/authme/output/LogLevelTest.java index 92595d6642..41d80cade8 100644 --- a/authme-core/src/test/java/fr/xephi/authme/output/LogLevelTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/output/LogLevelTest.java @@ -3,16 +3,16 @@ import org.junit.jupiter.api.Test; import static java.lang.String.format; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link LogLevel}. */ -public class LogLevelTest { +class LogLevelTest { @Test - public void shouldIncludeProperLevels() { + void shouldIncludeProperLevels() { checkLevelInclusion(LogLevel.INFO, true, false, false); checkLevelInclusion(LogLevel.FINE, true, true, false); checkLevelInclusion(LogLevel.DEBUG, true, true, true); @@ -29,4 +29,3 @@ private void checkLevelInclusion(LogLevel level, boolean... expectedValues) { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java index 53658dda63..71799d842a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/AbstractPermissionsEnumTest.java @@ -13,7 +13,7 @@ public abstract class AbstractPermissionsEnumTest { @Test - public void shouldAllStartWitRequiredPrefix() { + void shouldAllStartWitRequiredPrefix() { // given String requiredPrefix = getRequiredPrefix(); @@ -27,7 +27,7 @@ public void shouldAllStartWitRequiredPrefix() { } @Test - public void shouldHaveUniqueNodes() { + void shouldHaveUniqueNodes() { // given Set nodes = new HashSet<>(); @@ -50,4 +50,3 @@ public void shouldHaveUniqueNodes() { protected abstract String getRequiredPrefix(); } - diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java index f3e4f1fde8..f98f6452a1 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/AdminPermissionTest.java @@ -3,7 +3,7 @@ /** * Test for {@link AdminPermission}. */ -public class AdminPermissionTest extends AbstractPermissionsEnumTest { +class AdminPermissionTest extends AbstractPermissionsEnumTest { @Override protected PermissionNode[] getPermissionNodes() { diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java index 3e0a9f0136..2da9aa1ce4 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/DebugSectionPermissionsTest.java @@ -3,7 +3,7 @@ /** * Test for {@link DebugSectionPermissions}. */ -public class DebugSectionPermissionsTest extends AbstractPermissionsEnumTest { +class DebugSectionPermissionsTest extends AbstractPermissionsEnumTest { @Override protected PermissionNode[] getPermissionNodes() { diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java index 61f1bacec1..728f684d79 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionConsistencyTest.java @@ -27,7 +27,7 @@ /** * Tests that the permissions listed in plugin.yml correspond to the ones in the code. */ -public class PermissionConsistencyTest { +class PermissionConsistencyTest { /** Wildcard permissions (present in plugin.yml but not in the codebase). */ private static final Set PLUGIN_YML_PERMISSIONS_WILDCARDS = @@ -46,7 +46,7 @@ public class PermissionConsistencyTest { private static Map pluginYmlPermissions; @BeforeAll - public static void gatherPermissionNodes() { + static void gatherPermissionNodes() { permissionClasses = new ClassCollector(TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT + "permission") .collectClasses(PermissionNode.class).stream() .filter(clz -> !clz.isInterface()) @@ -56,7 +56,7 @@ public static void gatherPermissionNodes() { } @Test - public void shouldHaveAllPermissionsInPluginYml() { + void shouldHaveAllPermissionsInPluginYml() { // given List errors = new ArrayList<>(); @@ -77,7 +77,7 @@ public void shouldHaveAllPermissionsInPluginYml() { } @Test - public void shouldNotHaveUnknownPermissionsInPluginYml() { + void shouldNotHaveUnknownPermissionsInPluginYml() { // given List errors = new ArrayList<>(); @@ -281,4 +281,3 @@ private static Set removeStart(String start, List list) { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java index c9695f733b..6dcde9b4ae 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerInitializationTest.java @@ -17,21 +17,22 @@ import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicesManager; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; + import java.util.Map; import java.util.stream.Stream; import static com.google.common.collect.Sets.newHashSet; import static fr.xephi.authme.permission.PermissionsSystemType.LUCK_PERMS; import static fr.xephi.authme.permission.PermissionsSystemType.VAULT; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; @@ -40,7 +41,7 @@ /** * Tests the initialization of {@link PermissionHandler} in {@link PermissionsManager}. */ -public class PermissionsManagerInitializationTest { +class PermissionsManagerInitializationTest { private Settings settings = mock(Settings.class); private ServicesManager servicesManager = mock(ServicesManager.class); @@ -49,19 +50,19 @@ public class PermissionsManagerInitializationTest { private PermissionsManager permissionsManager = new PermissionsManager(server, pluginManager, settings); @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @BeforeEach - public void setUp() { + void setUp() { ReflectionTestUtils.setField(Bukkit.class, null, "server", server); given(server.getServicesManager()).willReturn(servicesManager); } @ParameterizedTest(name = "{0}") @MethodSource("createParameters") - public void shouldInitializeHandler(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { + void shouldInitializeHandler(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given setUpForPermissionSystemTest(permissionsSystemType); given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(false); @@ -80,8 +81,7 @@ public void shouldInitializeHandler(PermissionsSystemType permissionsSystemType, @ParameterizedTest(name = "{0}") @MethodSource("createParameters") - public void shouldInitializeToVaultIfSoConfigured(PermissionsSystemType permissionsSystemType, - Class expectedHandlerType) { + void shouldInitializeToVaultIfSoConfigured(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given setUpForVault(); given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(true); @@ -100,8 +100,7 @@ public void shouldInitializeToVaultIfSoConfigured(PermissionsSystemType permissi @ParameterizedTest(name = "{0}") @MethodSource("createParameters") - public void shouldNotHookIntoDisabledPlugin(PermissionsSystemType permissionsSystemType, - Class expectedHandlerType) { + void shouldNotHookIntoDisabledPlugin(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(false); Plugin plugin = mock(Plugin.class); @@ -117,8 +116,7 @@ public void shouldNotHookIntoDisabledPlugin(PermissionsSystemType permissionsSys @ParameterizedTest(name = "{0}") @MethodSource("createParameters") - public void shouldCatchInitializationException(PermissionsSystemType permissionsSystemType, - Class expectedHandlerType) { + void shouldCatchInitializationException(PermissionsSystemType permissionsSystemType, Class expectedHandlerType) { // given given(settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)).willReturn(false); Plugin plugin = mock(Plugin.class); @@ -133,7 +131,7 @@ public void shouldCatchInitializationException(PermissionsSystemType permissions assertThat(getHandlerFieldValue(), nullValue()); } - public static Stream createParameters() { + static Stream createParameters() { Map> handlersByPermissionSystemType = ImmutableMap.of( LUCK_PERMS, LuckPermsHandler.class, VAULT, VaultHandler.class); @@ -144,7 +142,6 @@ public static Stream createParameters() { + PermissionsSystemType.class.getSimpleName() + " entries"); } - // Wrap the above map in a Collection to satisfy JUnit return handlersByPermissionSystemType.entrySet().stream() .map(e -> Arguments.of(e.getKey(), e.getValue())); } @@ -171,4 +168,3 @@ private PermissionHandler getHandlerFieldValue() { return ReflectionTestUtils.getFieldValue(PermissionsManager.class, permissionsManager, "handler"); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java index 60c9592167..cd4373794f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsManagerTest.java @@ -1,19 +1,17 @@ package fr.xephi.authme.permission; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -21,8 +19,7 @@ * Test for {@link PermissionsManager}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PermissionsManagerTest { +class PermissionsManagerTest { @InjectMocks private PermissionsManager permissionsManager; @@ -34,7 +31,7 @@ public class PermissionsManagerTest { private PluginManager pluginManager; @Test - public void shouldUseDefaultPermissionForCommandSender() { + void shouldUseDefaultPermissionForCommandSender() { // given PermissionNode node = TestPermissions.LOGIN; CommandSender sender = mock(CommandSender.class); @@ -47,7 +44,7 @@ public void shouldUseDefaultPermissionForCommandSender() { } @Test - public void shouldGrantToOpCommandSender() { + void shouldGrantToOpCommandSender() { // given PermissionNode node = TestPermissions.DELETE_USER; CommandSender sender = mock(CommandSender.class); @@ -61,7 +58,7 @@ public void shouldGrantToOpCommandSender() { } @Test - public void shouldDenyPermissionEvenForOpCommandSender() { + void shouldDenyPermissionEvenForOpCommandSender() { // given PermissionNode node = TestPermissions.WORLD_DOMINATION; CommandSender sender = mock(CommandSender.class); @@ -74,7 +71,7 @@ public void shouldDenyPermissionEvenForOpCommandSender() { } @Test - public void shouldAllowForNonOpPlayer() { + void shouldAllowForNonOpPlayer() { // given PermissionNode node = TestPermissions.LOGIN; Player player = mock(Player.class); @@ -87,7 +84,7 @@ public void shouldAllowForNonOpPlayer() { } @Test - public void shouldDenyForNonOpPlayer() { + void shouldDenyForNonOpPlayer() { // given PermissionNode node = TestPermissions.DELETE_USER; Player player = mock(Player.class); @@ -100,7 +97,7 @@ public void shouldDenyForNonOpPlayer() { } @Test - public void shouldAllowForOpPlayer() { + void shouldAllowForOpPlayer() { // given PermissionNode node = TestPermissions.DELETE_USER; Player player = mock(Player.class); @@ -114,7 +111,7 @@ public void shouldAllowForOpPlayer() { } @Test - public void shouldDenyEvenForOpPlayer() { + void shouldDenyEvenForOpPlayer() { // given PermissionNode node = TestPermissions.WORLD_DOMINATION; Player player = mock(Player.class); @@ -127,7 +124,7 @@ public void shouldDenyEvenForOpPlayer() { } @Test - public void shouldHandleNullPermissionForCommandSender() { + void shouldHandleNullPermissionForCommandSender() { // given PermissionNode node = null; CommandSender sender = mock(CommandSender.class); @@ -140,7 +137,7 @@ public void shouldHandleNullPermissionForCommandSender() { } @Test - public void shouldHandleNullPermissionForPlayer() { + void shouldHandleNullPermissionForPlayer() { // given PermissionNode node = null; Player player = mock(Player.class); @@ -152,5 +149,3 @@ public void shouldHandleNullPermissionForPlayer() { assertThat(result, equalTo(true)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java index 66a3eeb30a..7530603061 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/PermissionsSystemTypeTest.java @@ -5,19 +5,19 @@ import java.util.ArrayList; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link PermissionsSystemType}. */ -public class PermissionsSystemTypeTest { +class PermissionsSystemTypeTest { @Test - public void shouldHaveDefinedAndUniqueNames() { + void shouldHaveDefinedAndUniqueNames() { // given / when / then List names = new ArrayList<>(PermissionsSystemType.values().length); List pluginNames = new ArrayList<>(PermissionsSystemType.values().length); @@ -37,10 +37,9 @@ public void shouldHaveDefinedAndUniqueNames() { } @Test - public void shouldRecognizePermissionSystemType() { + void shouldRecognizePermissionSystemType() { assertThat(PermissionsSystemType.isPermissionSystem("bogus"), equalTo(false)); assertThat(PermissionsSystemType.isPermissionSystem("LuckPerms"), equalTo(true)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java index 32a45b98de..f4822d2ef7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/PlayerPermissionTest.java @@ -3,7 +3,7 @@ /** * Test for {@link PlayerPermission}. */ -public class PlayerPermissionTest extends AbstractPermissionsEnumTest { +class PlayerPermissionTest extends AbstractPermissionsEnumTest { @Override protected PermissionNode[] getPermissionNodes() { diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java index c22db23acf..9ebc3bf04a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/PlayerStatePermissionTest.java @@ -11,10 +11,10 @@ /** * Test for {@link PlayerStatePermission}. */ -public class PlayerStatePermissionTest extends AbstractPermissionsEnumTest { +class PlayerStatePermissionTest extends AbstractPermissionsEnumTest { @Test - public void shouldNotStartWithOtherPrefixes() { + void shouldNotStartWithOtherPrefixes() { // given Set forbiddenPrefixes = newHashSet("authme.player", "authme.admin", "authme.debug"); @@ -45,4 +45,3 @@ private static boolean startsWithAny(String node, Collection prefixes) { return false; } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java b/authme-core/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java index 62a406b00e..e559a6971e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/permission/handlers/VaultHandlerTest.java @@ -7,12 +7,11 @@ import org.junit.jupiter.api.Test; import java.util.List; -import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -20,12 +19,12 @@ /** * Test for {@link VaultHandler}. */ -public class VaultHandlerTest { +class VaultHandlerTest { private VaultHandlerTestImpl vaultHandlerTest = VaultHandlerTestImpl.create(); @Test - public void shouldReturnGroups() { + void shouldReturnGroups() { // given Permission permissionMock = vaultHandlerTest.permissionMock; Player player = mock(Player.class); @@ -44,7 +43,7 @@ public void shouldReturnGroups() { * Bug #1702: VaultHandler may return null for groups list. */ @Test - public void shouldHandleNullAsGroups() { + void shouldHandleNullAsGroups() { // given Permission permissionMock = vaultHandlerTest.permissionMock; Player player = mock(Player.class); @@ -82,4 +81,3 @@ Permission getVaultPermission(Server server) { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java b/authme-core/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java index 97ffbe3435..9606572495 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/changepassword/AsyncChangePasswordTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.process.changepassword; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; @@ -15,8 +11,10 @@ import org.bukkit.command.CommandSender; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -27,8 +25,7 @@ * Test for {@link AsyncChangePassword}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AsyncChangePasswordTest { +class AsyncChangePasswordTest { @InjectMocks private AsyncChangePassword asyncChangePassword; @@ -45,12 +42,12 @@ public class AsyncChangePasswordTest { private BungeeSender bungeeSender; @BeforeEach - public void setUpLogger() { + void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldRejectCommandForUnknownUser() { + void shouldRejectCommandForUnknownUser() { // given CommandSender sender = mock(CommandSender.class); String player = "player"; @@ -67,7 +64,7 @@ public void shouldRejectCommandForUnknownUser() { } @Test - public void shouldUpdatePasswordOfLoggedInUser() { + void shouldUpdatePasswordOfLoggedInUser() { // given CommandSender sender = mock(CommandSender.class); String player = "my_user12"; @@ -88,7 +85,7 @@ public void shouldUpdatePasswordOfLoggedInUser() { } @Test - public void shouldUpdatePasswordOfOfflineUser() { + void shouldUpdatePasswordOfOfflineUser() { // given CommandSender sender = mock(CommandSender.class); String player = "my_user12"; @@ -110,7 +107,7 @@ public void shouldUpdatePasswordOfOfflineUser() { } @Test - public void shouldReportWhenSaveFailed() { + void shouldReportWhenSaveFailed() { // given CommandSender sender = mock(CommandSender.class); String player = "my_user12"; @@ -131,5 +128,3 @@ public void shouldReportWhenSaveFailed() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java b/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java index 1191c2f3d0..894b0e5680 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncAddEmailTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.process.email; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; @@ -19,8 +15,11 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + import java.util.function.Function; import static org.mockito.ArgumentMatchers.any; @@ -36,8 +35,7 @@ * Test for {@link AsyncAddEmail}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AsyncAddEmailTest { +class AsyncAddEmailTest { @InjectMocks private AsyncAddEmail asyncAddEmail; @@ -70,12 +68,12 @@ public class AsyncAddEmailTest { private PendingEmailVerificationCache pendingEmailVerificationCache; @BeforeAll - public static void setUp() { + static void setUp() { TestHelper.setupLogger(); } @Test - public void shouldAddEmail() { + void shouldAddEmail() { // given String email = "my.mail@example.org"; given(player.getName()).willReturn("testEr"); @@ -101,7 +99,7 @@ public void shouldAddEmail() { } @Test - public void shouldSendConfirmationCodeWhenEmailIsConfigured() { + void shouldSendConfirmationCodeWhenEmailIsConfigured() { // given String email = "my.mail@example.org"; given(player.getName()).willReturn("testEr"); @@ -126,7 +124,7 @@ public void shouldSendConfirmationCodeWhenEmailIsConfigured() { } @Test - public void shouldReturnErrorWhenMailCannotBeSaved() { + void shouldReturnErrorWhenMailCannotBeSaved() { // given String email = "my.mail@example.org"; given(player.getName()).willReturn("testEr"); @@ -150,7 +148,7 @@ public void shouldReturnErrorWhenMailCannotBeSaved() { } @Test - public void shouldNotAddMailIfPlayerAlreadyHasEmail() { + void shouldNotAddMailIfPlayerAlreadyHasEmail() { // given given(player.getName()).willReturn("my_Player"); given(playerCache.isAuthenticated("my_player")).willReturn(true); @@ -167,7 +165,7 @@ public void shouldNotAddMailIfPlayerAlreadyHasEmail() { } @Test - public void shouldNotAddMailIfItIsInvalid() { + void shouldNotAddMailIfItIsInvalid() { // given String email = "invalid_mail"; given(player.getName()).willReturn("my_Player"); @@ -186,7 +184,7 @@ public void shouldNotAddMailIfItIsInvalid() { } @Test - public void shouldNotAddMailIfAlreadyUsed() { + void shouldNotAddMailIfAlreadyUsed() { // given String email = "player@mail.tld"; given(player.getName()).willReturn("TestName"); @@ -206,7 +204,7 @@ public void shouldNotAddMailIfAlreadyUsed() { } @Test - public void shouldShowLoginMessage() { + void shouldShowLoginMessage() { // given given(player.getName()).willReturn("Username12"); given(playerCache.isAuthenticated("username12")).willReturn(false); @@ -221,7 +219,7 @@ public void shouldShowLoginMessage() { } @Test - public void shouldShowRegisterMessage() { + void shouldShowRegisterMessage() { // given given(player.getName()).willReturn("user"); given(playerCache.isAuthenticated("user")).willReturn(false); @@ -236,7 +234,7 @@ public void shouldShowRegisterMessage() { } @Test - public void shouldNotAddOnCancelledEvent() { + void shouldNotAddOnCancelledEvent() { // given String email = "player@mail.tld"; given(player.getName()).willReturn("TestName"); @@ -259,5 +257,3 @@ public void shouldNotAddOnCancelledEvent() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java b/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java index 0152273616..ff7496275f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/email/AsyncChangeEmailTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.process.email; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; @@ -19,8 +15,10 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; @@ -36,8 +34,7 @@ * Test for {@link AsyncChangeEmail}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AsyncChangeEmailTest { +class AsyncChangeEmailTest { @InjectMocks private AsyncChangeEmail process; @@ -70,12 +67,12 @@ public class AsyncChangeEmailTest { private PendingEmailVerificationCache pendingEmailVerificationCache; @BeforeAll - public static void setUp() { + static void setUp() { TestHelper.setupLogger(); } @Test - public void shouldChangeEmail() { + void shouldChangeEmail() { // given String newEmail = "new@mail.tld"; given(player.getName()).willReturn("Bobby"); @@ -99,7 +96,7 @@ public void shouldChangeEmail() { } @Test - public void shouldNotBeCaseSensitiveWhenComparingEmails() { + void shouldNotBeCaseSensitiveWhenComparingEmails() { // given String newEmail = "newmail@example.com"; given(player.getName()).willReturn("Debra"); @@ -124,7 +121,7 @@ public void shouldNotBeCaseSensitiveWhenComparingEmails() { } @Test - public void shouldShowErrorIfSaveFails() { + void shouldShowErrorIfSaveFails() { // given String newEmail = "new@mail.tld"; given(player.getName()).willReturn("Bobby"); @@ -148,7 +145,7 @@ public void shouldShowErrorIfSaveFails() { } @Test - public void shouldShowAddEmailUsage() { + void shouldShowAddEmailUsage() { // given given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(true); @@ -165,7 +162,7 @@ public void shouldShowAddEmailUsage() { } @Test - public void shouldRejectInvalidNewMail() { + void shouldRejectInvalidNewMail() { // given String newEmail = "bogus"; given(player.getName()).willReturn("Bobby"); @@ -184,7 +181,7 @@ public void shouldRejectInvalidNewMail() { } @Test - public void shouldRejectInvalidOldEmail() { + void shouldRejectInvalidOldEmail() { // given String newEmail = "new@mail.tld"; given(player.getName()).willReturn("Bobby"); @@ -203,7 +200,7 @@ public void shouldRejectInvalidOldEmail() { } @Test - public void shouldRejectAlreadyUsedEmail() { + void shouldRejectAlreadyUsedEmail() { // given String newEmail = "new@example.com"; given(player.getName()).willReturn("Username"); @@ -223,7 +220,7 @@ public void shouldRejectAlreadyUsedEmail() { } @Test - public void shouldSendLoginMessage() { + void shouldSendLoginMessage() { // given given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(false); @@ -239,7 +236,7 @@ public void shouldSendLoginMessage() { } @Test - public void shouldShowRegistrationMessage() { + void shouldShowRegistrationMessage() { // given given(player.getName()).willReturn("Bobby"); given(playerCache.isAuthenticated("bobby")).willReturn(false); @@ -255,7 +252,7 @@ public void shouldShowRegistrationMessage() { } @Test - public void shouldNotChangeOnCancelledEvent() { + void shouldNotChangeOnCancelledEvent() { // given String newEmail = "new@example.com"; String oldEmail = "old@example.com"; @@ -285,5 +282,3 @@ private static PlayerAuth authWithMail(String email) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/process/join/AsynchronousJoinTest.java b/authme-core/src/test/java/fr/xephi/authme/process/join/AsynchronousJoinTest.java index 7c7cddb69f..3ab80f0ce0 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/join/AsynchronousJoinTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/join/AsynchronousJoinTest.java @@ -10,15 +10,15 @@ import fr.xephi.authme.platform.DialogWindowSpec; import fr.xephi.authme.process.login.AsynchronousLogin; import fr.xephi.authme.process.register.AsyncRegister; -import fr.xephi.authme.service.PreJoinDialogService; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; -import fr.xephi.authme.service.PendingPremiumCache; -import fr.xephi.authme.service.PremiumLoginVerifier; -import fr.xephi.authme.service.PremiumService; import fr.xephi.authme.service.DialogStateService; import fr.xephi.authme.service.DialogWindowService; +import fr.xephi.authme.service.PendingPremiumCache; import fr.xephi.authme.service.PluginHookService; +import fr.xephi.authme.service.PreJoinDialogService; +import fr.xephi.authme.service.PremiumLoginVerifier; +import fr.xephi.authme.service.PremiumService; import fr.xephi.authme.service.ProxyLoginRequestValidator; import fr.xephi.authme.service.SessionService; import fr.xephi.authme.service.ValidationService; @@ -40,13 +40,13 @@ import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -import java.util.UUID; import java.util.Set; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskLater; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskOptionallyAsync; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -114,7 +114,7 @@ public static void initLogger() { @BeforeEach public void setUp() { - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); setBukkitServiceToRunTaskOptionallyAsync(bukkitService); setBukkitServiceToRunTaskLater(bukkitService); given(service.getProperty(PremiumSettings.ENABLE_PREMIUM)).willReturn(false); diff --git a/authme-core/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java b/authme-core/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java index 7622d26264..728e39b8dc 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/login/AsynchronousLoginTest.java @@ -1,10 +1,7 @@ package fr.xephi.authme.process.login; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; +import fr.xephi.authme.data.TempbanManager; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.captcha.LoginCaptchaManager; @@ -21,31 +18,32 @@ import fr.xephi.authme.platform.DialogWindowSpec; import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.service.BukkitService; -import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.CancellableTask; +import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.DialogStateService; import fr.xephi.authme.service.DialogWindowService; import fr.xephi.authme.service.SessionService; import fr.xephi.authme.service.bungeecord.BungeeSender; -import fr.xephi.authme.settings.properties.RegistrationSettings; -import fr.xephi.authme.data.TempbanManager; import fr.xephi.authme.settings.properties.DatabaseSettings; import fr.xephi.authme.settings.properties.HooksSettings; import fr.xephi.authme.settings.properties.PluginSettings; +import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.Arrays; import java.util.List; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -54,16 +52,15 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.only; /** * Test for {@link AsynchronousLogin}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AsynchronousLoginTest { +class AsynchronousLoginTest { @InjectMocks @Spy @@ -97,12 +94,12 @@ public class AsynchronousLoginTest { private DialogStateService dialogStateService; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldNotForceLoginAlreadyLoggedInPlayer() { + void shouldNotForceLoginAlreadyLoggedInPlayer() { // given String name = "bobby"; Player player = mockPlayer(name); @@ -118,7 +115,7 @@ public void shouldNotForceLoginAlreadyLoggedInPlayer() { } @Test - public void shouldNotForceLoginNonExistentUser() { + void shouldNotForceLoginNonExistentUser() { // given String name = "oscar"; Player player = mockPlayer(name); @@ -135,7 +132,7 @@ public void shouldNotForceLoginNonExistentUser() { } @Test - public void shouldNotForceLoginInactiveUser() { + void shouldNotForceLoginInactiveUser() { // given String name = "oscar"; Player player = mockPlayer(name); @@ -156,7 +153,7 @@ public void shouldNotForceLoginInactiveUser() { } @Test - public void shouldNotForceLoginUserWithAlreadyOnlineIp() { + void shouldNotForceLoginUserWithAlreadyOnlineIp() { // given String name = "oscar"; String ip = "1.1.1.245"; @@ -179,7 +176,7 @@ public void shouldNotForceLoginUserWithAlreadyOnlineIp() { } @Test - public void shouldNotForceLoginForCanceledEvent() { + void shouldNotForceLoginForCanceledEvent() { // given String name = "oscar"; String ip = "1.1.1.245"; @@ -205,11 +202,10 @@ public void shouldNotForceLoginForCanceledEvent() { verify(asynchronousLogin).hasReachedMaxLoggedInPlayersForIp(player, ip); } - @Test - public void shouldPassMaxLoginPerIpCheck() { + void shouldPassMaxLoginPerIpCheck() { // given - Player player = mockPlayer("Carl"); + Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(2); given(commonService.hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)).willReturn(false); mockOnlinePlayersInBukkitService("1.1.1.1"); @@ -224,7 +220,7 @@ public void shouldPassMaxLoginPerIpCheck() { } @Test - public void shouldSkipIpCheckForZeroThreshold() { + void shouldSkipIpCheckForZeroThreshold() { // given Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(0); @@ -238,7 +234,7 @@ public void shouldSkipIpCheckForZeroThreshold() { } @Test - public void shouldSkipIpCheckForPlayerWithMultipleAccountsPermission() { + void shouldSkipIpCheckForPlayerWithMultipleAccountsPermission() { // given Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(1); @@ -254,9 +250,9 @@ public void shouldSkipIpCheckForPlayerWithMultipleAccountsPermission() { } @Test - public void shouldFailIpCheckForIpWithTooManyPlayersOnline() { + void shouldFailIpCheckForIpWithTooManyPlayersOnline() { // given - Player player = mockPlayer("Ian"); + Player player = mock(Player.class); given(commonService.getProperty(RestrictionSettings.MAX_LOGIN_PER_IP)).willReturn(2); given(commonService.hasPermission(player, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)).willReturn(false); mockOnlinePlayersInBukkitService("2.2.2.2"); @@ -271,7 +267,7 @@ public void shouldFailIpCheckForIpWithTooManyPlayersOnline() { } @Test - public void shouldShowTotpDialogAfterSuccessfulPasswordCheckWhenDialogsAreEnabled() { + void shouldShowTotpDialogAfterSuccessfulPasswordCheckWhenDialogsAreEnabled() { // given Player player = mockPlayer("bobby"); TestHelper.mockIpAddressToPlayer(player, "203.0.113.5"); @@ -305,7 +301,7 @@ public void shouldShowTotpDialogAfterSuccessfulPasswordCheckWhenDialogsAreEnable } @Test - public void shouldNotShowTotpDialogWhenDialogsAreDisabled() { + void shouldNotShowTotpDialogWhenDialogsAreDisabled() { // given Player player = mockPlayer("bobby"); TestHelper.mockIpAddressToPlayer(player, "203.0.113.5"); @@ -383,7 +379,4 @@ private void mockOnlinePlayersInBukkitService(String checkedIp) { List onlinePlayers = Arrays.asList(primaryOnline, primaryOffline, extraSameIpOnline, otherIpPlayer); given(bukkitService.getOnlinePlayers()).willReturn(onlinePlayers); } - } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java b/authme-core/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java index 8d5bcc7fa1..e2e7656d63 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/register/AsyncRegisterTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.process.register; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.injector.factory.SingletonStore; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; @@ -20,8 +16,10 @@ import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; @@ -36,8 +34,7 @@ * Test for {@link AsyncRegister}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AsyncRegisterTest { +class AsyncRegisterTest { @InjectMocks private AsyncRegister asyncRegister; @@ -54,7 +51,7 @@ public class AsyncRegisterTest { private SingletonStore registrationExecutorStore; @Test - public void shouldDetectAlreadyLoggedInPlayer() { + void shouldDetectAlreadyLoggedInPlayer() { // given String name = "robert"; Player player = mockPlayerWithName(name); @@ -65,11 +62,11 @@ public void shouldDetectAlreadyLoggedInPlayer() { // then verify(commonService).send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); - verifyNoInteractions(dataSource); + verifyNoInteractions(dataSource, registrationExecutorStore); } @Test - public void shouldStopForDisabledRegistration() { + void shouldStopForDisabledRegistration() { // given String name = "albert"; Player player = mockPlayerWithName(name); @@ -81,11 +78,11 @@ public void shouldStopForDisabledRegistration() { // then verify(commonService).send(player, MessageKey.REGISTRATION_DISABLED); - verifyNoInteractions(dataSource); + verifyNoInteractions(dataSource, registrationExecutorStore); } @Test - public void shouldStopForAlreadyRegisteredName() { + void shouldStopForAlreadyRegisteredName() { // given String name = "dilbert"; Player player = mockPlayerWithName(name); @@ -99,11 +96,12 @@ public void shouldStopForAlreadyRegisteredName() { // then verify(commonService).send(player, MessageKey.NAME_ALREADY_REGISTERED); verify(dataSource, only()).isAuthAvailable(name); + verifyNoInteractions(registrationExecutorStore); } @Test @SuppressWarnings("unchecked") - public void shouldStopForCanceledEvent() { + void shouldStopForCanceledEvent() { // given String name = "edbert"; Player player = mockPlayerWithName(name); @@ -121,11 +119,12 @@ public void shouldStopForCanceledEvent() { // then verify(dataSource, only()).isAuthAvailable(name); + verifyNoInteractions(registrationExecutorStore); } @Test @SuppressWarnings("unchecked") - public void shouldStopForFailedExecutorCheck() { + void shouldStopForFailedExecutorCheck() { // given String name = "edbert"; Player player = mockPlayerWithName(name); @@ -162,5 +161,3 @@ private static void singletonStoreWillReturn(SingletonStore new HashedPassword(invocation.getArgument(0))); @@ -114,13 +111,13 @@ public void shouldCreatePlayerAuth() { } @Test - public void shouldLogPlayerIn() { + void shouldLogPlayerIn() { // given given(commonService.getProperty(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER)).willReturn(false); given(commonService.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(false); Player player = mock(Player.class); PasswordRegisterParams params = PasswordRegisterParams.of(player, "pass", "mail@example.org"); - setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); // when executor.executePostPersistAction(params); @@ -131,7 +128,7 @@ public void shouldLogPlayerIn() { } @Test - public void shouldNotLogPlayerIn() { + void shouldNotLogPlayerIn() { // given given(commonService.getProperty(RegistrationSettings.FORCE_LOGIN_AFTER_REGISTER)).willReturn(true); Player player = mock(Player.class); @@ -155,5 +152,3 @@ private static void assertIsCloseTo(long value1, long value2, long tolerance) { assertThat(Math.abs(value1 - value2), not(greaterThan(tolerance))); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java b/authme-core/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java index 9d708a381a..6ec0fed1b4 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/register/executors/PlayerAuthBuilderHelperTest.java @@ -8,19 +8,19 @@ import static fr.xephi.authme.AuthMeMatchers.equalToHash; import static fr.xephi.authme.AuthMeMatchers.hasAuthBasicData; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link PlayerAuthBuilderHelper}. */ -public class PlayerAuthBuilderHelperTest { +class PlayerAuthBuilderHelperTest { @Test - public void shouldConstructPlayerAuth() { + void shouldConstructPlayerAuth() { // given Player player = mock(Player.class); given(player.getName()).willReturn("Noah"); @@ -39,4 +39,3 @@ public void shouldConstructPlayerAuth() { assertThat(auth.getPassword(), equalToHash("myHash0001")); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java b/authme-core/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java index 39f4131140..ea1cab86e9 100644 --- a/authme-core/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/process/unregister/AsynchronousUnregisterTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.process.unregister; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; @@ -23,19 +19,19 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; -import static org.hamcrest.Matchers.equalTo; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -48,8 +44,7 @@ * Test for {@link AsynchronousUnregister}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class AsynchronousUnregisterTest { +class AsynchronousUnregisterTest { @InjectMocks private AsynchronousUnregister asynchronousUnregister; @@ -72,16 +67,14 @@ public class AsynchronousUnregisterTest { private CommandManager commandManager; @Mock private BungeeSender bungeeSender; - @Captor - private ArgumentCaptor> eventFunctionCaptor; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldRejectWrongPassword() { + void shouldRejectWrongPassword() { // given Player player = mock(Player.class); String name = "Bobby"; @@ -104,7 +97,7 @@ public void shouldRejectWrongPassword() { } @Test - public void shouldPerformUnregister() { + void shouldPerformUnregister() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -120,7 +113,7 @@ public void shouldPerformUnregister() { given(service.getProperty(RegistrationSettings.FORCE)).willReturn(true); given(service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)).willReturn(true); given(service.getProperty(RestrictionSettings.REGISTER_TIMEOUT)).willReturn(21); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); given(bukkitService.createBlindnessEffect(21 * 20)).willReturn(mock(PotionEffect.class)); // when @@ -137,7 +130,7 @@ public void shouldPerformUnregister() { } @Test - public void shouldPerformUnregisterAndNotApplyBlindEffect() { + void shouldPerformUnregisterAndNotApplyBlindEffect() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -152,7 +145,7 @@ public void shouldPerformUnregisterAndNotApplyBlindEffect() { given(dataSource.removeAuth(name)).willReturn(true); given(service.getProperty(RegistrationSettings.FORCE)).willReturn(true); given(service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)).willReturn(false); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when asynchronousUnregister.unregister(player, userPassword); @@ -169,7 +162,7 @@ public void shouldPerformUnregisterAndNotApplyBlindEffect() { } @Test - public void shouldNotApplyUnregisteredEffectsForNotForcedRegistration() { + void shouldNotApplyUnregisteredEffectsForNotForcedRegistration() { // given Player player = mock(Player.class); String name = "__FranK"; @@ -182,7 +175,7 @@ public void shouldNotApplyUnregisteredEffectsForNotForcedRegistration() { given(passwordSecurity.comparePassword(userPassword, password, name)).willReturn(true); given(dataSource.removeAuth(name)).willReturn(true); given(service.getProperty(RegistrationSettings.FORCE)).willReturn(false); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when asynchronousUnregister.unregister(player, userPassword); @@ -198,7 +191,7 @@ public void shouldNotApplyUnregisteredEffectsForNotForcedRegistration() { } @Test - public void shouldHandleDatabaseError() { + void shouldHandleDatabaseError() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -222,7 +215,7 @@ public void shouldHandleDatabaseError() { } @Test - public void shouldNotTeleportOfflinePlayer() { + void shouldNotTeleportOfflinePlayer() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -249,7 +242,7 @@ public void shouldNotTeleportOfflinePlayer() { // Initiator known and Player object available @Test - public void shouldPerformAdminUnregister() { + void shouldPerformAdminUnregister() { // given Player player = mock(Player.class); String name = "Frank21"; @@ -258,7 +251,7 @@ public void shouldPerformAdminUnregister() { given(service.getProperty(RegistrationSettings.FORCE)).willReturn(true); given(service.getProperty(RegistrationSettings.APPLY_BLIND_EFFECT)).willReturn(false); CommandSender initiator = mock(CommandSender.class); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when asynchronousUnregister.adminUnregister(initiator, name, player); @@ -274,7 +267,7 @@ public void shouldPerformAdminUnregister() { } @Test - public void shouldPerformAdminUnregisterWithoutInitiatorOrPlayer() { + void shouldPerformAdminUnregisterWithoutInitiatorOrPlayer() { // given String name = "billy"; given(dataSource.removeAuth(name)).willReturn(true); @@ -290,7 +283,7 @@ public void shouldPerformAdminUnregisterWithoutInitiatorOrPlayer() { } @Test - public void shouldHandleDatabaseErrorForAdminUnregister() { + void shouldHandleDatabaseErrorForAdminUnregister() { // given String name = "TtOoLl"; CommandSender initiator = mock(CommandSender.class); @@ -307,10 +300,10 @@ public void shouldHandleDatabaseErrorForAdminUnregister() { @SuppressWarnings("unchecked") private void verifyCalledUnregisterEventFor(Player player) { + ArgumentCaptor> eventFunctionCaptor = + ArgumentCaptor.forClass(Function.class); verify(bukkitService).createAndCallEvent(eventFunctionCaptor.capture()); AbstractUnregisterEvent event = eventFunctionCaptor.getValue().apply(true); assertThat(event.getPlayer(), equalTo(player)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java index fa94ef48ab..71576e0e39 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/HashAlgorithmIntegrationTest.java @@ -19,8 +19,8 @@ import java.util.List; import java.util.Set; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -28,12 +28,12 @@ /** * Integration test for {@link HashAlgorithm}. */ -public class HashAlgorithmIntegrationTest { +class HashAlgorithmIntegrationTest { private static Injector injector; @BeforeAll - public static void setUpConfigAndInjector() { + static void setUpConfigAndInjector() { Settings settings = mock(Settings.class); given(settings.getProperty(HooksSettings.BCRYPT_LOG2_ROUND)).willReturn(8); given(settings.getProperty(SecuritySettings.DOUBLE_MD5_SALT_LENGTH)).willReturn(16); @@ -44,7 +44,7 @@ public static void setUpConfigAndInjector() { } @Test - public void shouldHaveUniqueClassForEntries() { + void shouldHaveUniqueClassForEntries() { // given Set> classes = new HashSet<>(); @@ -59,7 +59,7 @@ public void shouldHaveUniqueClassForEntries() { } @Test - public void shouldBeAbleToInstantiateEncryptionAlgorithms() { + void shouldBeAbleToInstantiateEncryptionAlgorithms() { // given / when / then for (HashAlgorithm algorithm : HashAlgorithm.values()) { if (!HashAlgorithm.CUSTOM.equals(algorithm) && !HashAlgorithm.PLAINTEXT.equals(algorithm)) { @@ -77,7 +77,7 @@ public void shouldBeAbleToInstantiateEncryptionAlgorithms() { } @Test - public void shouldBeDeprecatedIfEncryptionClassIsDeprecated() throws NoSuchFieldException { + void shouldBeDeprecatedIfEncryptionClassIsDeprecated() throws NoSuchFieldException { // given List failedEntries = new LinkedList<>(); @@ -102,4 +102,3 @@ public void shouldBeDeprecatedIfEncryptionClassIsDeprecated() throws NoSuchField } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/HashUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/security/HashUtilsTest.java index 763586c64e..6f86aebe0f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/HashUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/HashUtilsTest.java @@ -6,14 +6,14 @@ import java.util.ArrayList; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link HashUtils}. */ -public class HashUtilsTest { +class HashUtilsTest { /** * List of passwords whose hash is provided to the class to test against. @@ -21,7 +21,7 @@ public class HashUtilsTest { private static final String[] GIVEN_PASSWORDS = {"", "password", "PassWord1", "&^%te$t?Pw@_"}; @Test - public void shouldHashMd5() { + void shouldHashMd5() { // given String[] correctHashes = { "d41d8cd98f00b204e9800998ecf8427e", // empty string @@ -41,7 +41,7 @@ public void shouldHashMd5() { } @Test - public void shouldHashSha1() { + void shouldHashSha1() { // given String[] correctHashes = { "da39a3ee5e6b4b0d3255bfef95601890afd80709", // empty string @@ -61,7 +61,7 @@ public void shouldHashSha1() { } @Test - public void shouldHashSha256() { + void shouldHashSha256() { // given String[] correctHashes = { "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", // empty string @@ -82,7 +82,7 @@ public void shouldHashSha256() { @Test - public void shouldHashSha512() { + void shouldHashSha512() { // given String[] correctHashes = { "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", // empty string @@ -102,7 +102,7 @@ public void shouldHashSha512() { } @Test - public void shouldRetrieveMd5Instance() { + void shouldRetrieveMd5Instance() { // given MessageDigestAlgorithm algorithm = MessageDigestAlgorithm.MD5; @@ -114,7 +114,7 @@ public void shouldRetrieveMd5Instance() { } @Test - public void shouldCheckForValidBcryptHashStart() { + void shouldCheckForValidBcryptHashStart() { // given / when / then assertThat(HashUtils.isValidBcryptHash(""), equalTo(false)); assertThat(HashUtils.isValidBcryptHash("$2"), equalTo(false)); @@ -125,7 +125,7 @@ public void shouldCheckForValidBcryptHashStart() { } @Test - public void shouldCompareStrings() { + void shouldCompareStrings() { // given / when / then assertThat(HashUtils.isEqual("test", "test"), equalTo(true)); assertThat(HashUtils.isEqual("test", "Test"), equalTo(false)); @@ -134,4 +134,3 @@ public void shouldCompareStrings() { assertThat(HashUtils.isEqual("test", "tëst"), equalTo(false)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java b/authme-core/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java index 529952f554..7c372d79e8 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/PasswordSecurityTest.java @@ -1,12 +1,8 @@ package fr.xephi.authme.security; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; import ch.jalu.injector.Injector; import ch.jalu.injector.InjectorBuilder; import ch.jalu.injector.factory.Factory; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; @@ -21,9 +17,13 @@ import org.bukkit.event.Event; import org.bukkit.plugin.PluginManager; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.Collections; @@ -31,10 +31,10 @@ import java.util.Set; import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -48,10 +48,10 @@ /** * Test for {@link PasswordSecurity}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class PasswordSecurityTest { +@ExtendWith(MockitoExtension.class) +class PasswordSecurityTest { - @InjectDelayed + @InjectMocks private PasswordSecurity passwordSecurity; @Mock @@ -64,7 +64,7 @@ public class PasswordSecurityTest { private DataSource dataSource; @Mock - private Factory hashAlgorithmFactory; + private Factory encryptionMethodFactory; @Mock private EncryptionMethod method; @@ -72,12 +72,12 @@ public class PasswordSecurityTest { private Class caughtClassInEvent; @BeforeAll - public static void setUpTest() { + static void setUpTest() { TestHelper.setupLogger(); } - @BeforeInjecting - public void setUpMocks() { + @BeforeEach + void setUpMocks() { caughtClassInEvent = null; // When the password encryption event is emitted, replace the encryption method with our mock. @@ -103,18 +103,20 @@ public Void answer(InvocationOnMock invocation) throws Throwable { .create(); injector.register(Settings.class, settings); - given(hashAlgorithmFactory.newInstance(any(Class.class))).willAnswer(invocation -> { - Object o = injector.createIfHasDependencies(invocation.getArgument(0)); - if (o == null) { - throw new IllegalArgumentException("Cannot create object of class '" + invocation.getArgument(0) - + "': missing class that needs to be provided?"); - } - return o; + given(encryptionMethodFactory.newInstance(any(Class.class))).willAnswer(invocation -> { + Object o = injector.createIfHasDependencies(invocation.getArgument(0)); + if (o == null) { + throw new IllegalArgumentException("Cannot create object of class '" + invocation.getArgument(0) + + "': missing class that needs to be provided?"); + } + return o; }); + + ReflectionTestUtils.invokePostConstructMethods(passwordSecurity); } @Test - public void shouldReturnPasswordMatch() { + void shouldReturnPasswordMatch() { // given HashedPassword password = new HashedPassword("$TEST$10$SOME_HASH", null); String playerName = "Tester"; @@ -136,7 +138,7 @@ public void shouldReturnPasswordMatch() { } @Test - public void shouldReturnPasswordMismatch() { + void shouldReturnPasswordMismatch() { // given HashedPassword password = new HashedPassword("$TEST$10$SOME_HASH", null); String playerName = "My_PLayer"; @@ -157,7 +159,7 @@ public void shouldReturnPasswordMismatch() { } @Test - public void shouldReturnFalseIfPlayerDoesNotExist() { + void shouldReturnFalseIfPlayerDoesNotExist() { // given String playerName = "bobby"; String clearTextPass = "tables"; @@ -173,7 +175,7 @@ public void shouldReturnFalseIfPlayerDoesNotExist() { } @Test - public void shouldTryOtherMethodsForFailedPassword() { + void shouldTryOtherMethodsForFailedPassword() { // given // BCRYPT hash for "Test" HashedPassword password = @@ -206,7 +208,7 @@ public void shouldTryOtherMethodsForFailedPassword() { } @Test - public void shouldTryLegacyMethodsAndFail() { + void shouldTryLegacyMethodsAndFail() { // given HashedPassword password = new HashedPassword("hashNotMatchingAnyMethod", "someBogusSalt"); String playerName = "asfd"; @@ -227,7 +229,7 @@ public void shouldTryLegacyMethodsAndFail() { } @Test - public void shouldHashPassword() { + void shouldHashPassword() { // given String password = "MyP@ssword"; String username = "theUserInTest"; @@ -248,7 +250,7 @@ public void shouldHashPassword() { } @Test - public void shouldSkipCheckIfMandatorySaltIsUnavailable() { + void shouldSkipCheckIfMandatorySaltIsUnavailable() { // given String password = "?topSecretPass\\"; String username = "someone12"; @@ -269,7 +271,7 @@ public void shouldSkipCheckIfMandatorySaltIsUnavailable() { } @Test - public void shouldReloadSettings() { + void shouldReloadSettings() { // given given(settings.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.MD5); given(settings.getProperty(SecuritySettings.LEGACY_HASHES)) @@ -287,5 +289,3 @@ public void shouldReloadSettings() { equalTo(legacyHashesSet)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java index d0dad37ea1..91bb549550 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/AbstractEncryptionMethodTest.java @@ -11,11 +11,9 @@ import java.util.Locale; import java.util.Map; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assumptions.assumeFalse; /** * Test for implementations of {@link EncryptionMethod}. @@ -98,11 +96,11 @@ public AbstractEncryptionMethodTest(EncryptionMethod method, HashedPassword resu } @BeforeAll - public static void setupLogger() { + static void setupLogger() { TestHelper.setupLogger(); } - protected void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isConstructorWithSalt) { + void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isConstructorWithSalt) { if (isConstructorWithSalt && !method.hasSeparateSalt()) { throw new UnsupportedOperationException("Salt is not stored separately, so test should be initialized" + " with the password hashes only. Use the other constructor"); @@ -113,14 +111,14 @@ protected void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean i } @Test - public void testGivenPasswords() { + void testGivenPasswords() { // Start with the 2nd to last password if we skip long tests int start = SKIP_LONG_TESTS ? GIVEN_PASSWORDS.length - 2 : 0; // Test entries in GIVEN_PASSWORDS except the last one for (int i = start; i < GIVEN_PASSWORDS.length - 1; ++i) { String password = GIVEN_PASSWORDS[i]; - assertTrue(doesGivenHashMatch(password, method), - "Hash for password '" + password + "' should match"); + assertThat("Hash for password '" + password + "' should match", + doesGivenHashMatch(password, method), equalTo(true)); } // Note #375: Windows console seems to use its own character encoding (Windows-1252?) and it seems impossible to @@ -135,7 +133,7 @@ public void testGivenPasswords() { } @Test - public void testPasswordEquality() { + void testPasswordEquality() { List internalPasswords = method.getClass().isAnnotationPresent(AsciiRestricted.class) ? INTERNAL_PASSWORDS.subList(0, INTERNAL_PASSWORDS.size() - 1) : INTERNAL_PASSWORDS; @@ -151,30 +149,30 @@ public void testPasswordEquality() { hash, equalTo(method.computeHash(password, salt, USERNAME))); } - assertTrue(method.comparePassword(password, hashedPassword, USERNAME), - "Generated hash for '" + password + "' should match password (hash = '" + hash + "')"); - assumeTrue(!SKIP_LONG_TESTS); + assertThat("Generated hash for '" + password + "' should match password (hash = '" + hash + "')", + method.comparePassword(password, hashedPassword, USERNAME), equalTo(true)); + assumeFalse(SKIP_LONG_TESTS); if (!password.equals(password.toLowerCase(Locale.ROOT))) { - assertFalse(method.comparePassword(password.toLowerCase(Locale.ROOT), hashedPassword, USERNAME), - "Lower-case of '" + password + "' should not match generated hash '" + hash + "'"); + assertThat("Lower-case of '" + password + "' should not match generated hash '" + hash + "'", + method.comparePassword(password.toLowerCase(), hashedPassword, USERNAME), equalTo(false)); } if (!password.equals(password.toUpperCase(Locale.ROOT))) { - assertFalse(method.comparePassword(password.toUpperCase(Locale.ROOT), hashedPassword, USERNAME), - "Upper-case of '" + password + "' should not match generated hash '" + hash + "'"); + assertThat("Upper-case of '" + password + "' should not match generated hash '" + hash + "'", + method.comparePassword(password.toUpperCase(), hashedPassword, USERNAME), equalTo(false)); } } } /** Tests various strings to ensure that encryption methods don't rely on the hash's format too much. */ @Test - public void testMalformedHashes() { - assumeTrue(!SKIP_LONG_TESTS); + void testMalformedHashes() { + assumeFalse(SKIP_LONG_TESTS); String salt = method.hasSeparateSalt() ? "testSalt" : null; for (String bogusHash : BOGUS_HASHES) { HashedPassword hashedPwd = new HashedPassword(bogusHash, salt); - assertFalse(method.comparePassword("Password", hashedPwd, "player"), - "Passing bogus hash '" + bogusHash + "' does not result in an error"); + assertThat("Passing bogus hash '" + bogusHash + "' does not result in an error", + method.comparePassword("Password", hashedPwd, "player"), equalTo(false)); } } @@ -237,4 +235,3 @@ protected boolean testHashEqualityForSameSalt() { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java index 0a46003c72..003697aa45 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Argon2Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Argon2}. */ -public class Argon2Test extends AbstractEncryptionMethodTest { +class Argon2Test extends AbstractEncryptionMethodTest { - public Argon2Test() { + Argon2Test() { super(new Argon2(), "$argon2i$v=19$m=65536,t=2,p=1$dOP8NiXsPTcMgzI4Z8Rbew$ShdowtoTEWTL5UTFz1UgQOigb9JOlm4ZxWPA6WbIeUw", // password "$argon2i$v=19$m=65536,t=2,p=1$amZHbPfgc5peKd/4w1AI1g$Q2PUiOVw47TACijP57U0xf7QfiZ00HV4eFzMDA6yKRE", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java index e5a381259b..291d6baf7c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCrypt2yTest.java @@ -2,16 +2,16 @@ import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link BCrypt2y}. */ -public class BCrypt2yTest extends AbstractEncryptionMethodTest { +class BCrypt2yTest extends AbstractEncryptionMethodTest { - public BCrypt2yTest() { + BCrypt2yTest() { super(new BCrypt2y(), "$2y$10$da641e404b982edf1c7c0uTU9BcKzfA2vWKV05q6r.dCvm/93wqVK", // password "$2y$10$e52c48a76f5b86f5da899uiK/HYocyPsfQXESNbP278rIz08LKEP2", // PassWord1 @@ -20,7 +20,7 @@ public BCrypt2yTest() { } @Test - public void shouldGenerateWith2yPrefixAndCostFactor10() { + void shouldGenerateWith2yPrefixAndCostFactor10() { // given BCrypt2y bCrypt2y = new BCrypt2y(); @@ -32,4 +32,3 @@ public void shouldGenerateWith2yPrefixAndCostFactor10() { assertThat(result.getSalt(), nullValue()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java index db58ea78c5..8a62070469 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/BCryptTest.java @@ -4,17 +4,17 @@ import fr.xephi.authme.settings.properties.HooksSettings; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.startsWith; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link BCrypt}. */ -public class BCryptTest extends AbstractEncryptionMethodTest { +class BCryptTest extends AbstractEncryptionMethodTest { - public BCryptTest() { + BCryptTest() { super(new BCrypt(mockSettings()), "$2a$10$6iATmYgwJVc3YONhVcZFve3Cfb5GnwvKhJ20r.hMjmcNkIT9.Uh9K", // password "$2a$10$LOhUxhEcS0vgDPv/jkXvCurNb7LjP9xUlEolJGk.Uhgikqc6FtIOi", // PassWord1 @@ -24,7 +24,7 @@ public BCryptTest() { } @Test - public void shouldGenerateWith2aPrefix() { + void shouldGenerateWith2aPrefix() { // given BCrypt bCrypt = new BCrypt(mockSettings()); @@ -41,4 +41,3 @@ private static Settings mockSettings() { return settings; } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java index 7c6652db1f..8ac0300c4e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/CmwCryptTest.java @@ -3,9 +3,9 @@ /** * Test for {@link CmwCrypt}. */ -public class CmwCryptTest extends AbstractEncryptionMethodTest { +class CmwCryptTest extends AbstractEncryptionMethodTest { - public CmwCryptTest() { + CmwCryptTest() { super(new CmwCrypt(), "1619d7adc23f4f633f11014d2f22b7d8", // password "c651798d2d9da38f86654107ae60c86a", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java index f98ece5ab4..ed195201d6 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/CrazyCrypt1Test.java @@ -3,9 +3,9 @@ /** * Test for {@link CrazyCrypt1}. */ -public class CrazyCrypt1Test extends AbstractEncryptionMethodTest { +class CrazyCrypt1Test extends AbstractEncryptionMethodTest { - public CrazyCrypt1Test() { + CrazyCrypt1Test() { super(new CrazyCrypt1(), "d5c76eb36417d4e97ec62609619e40a9e549a2598d0dab5a7194fd997a9305af78de2b93f958e150d19dd1e7f821043379ddf5f9c7f352bf27df91ae4913f3e8", // password "49c63f827c88196871e344e589bd46cc4fa6db3c27801bbad5374c0d216381977627c1d76f2114667d5dd117e046f7493eb06e4f461f4f848aa08f6f40a3e934", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java index cc12df9e5a..415e537c7a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/DoubleMd5Test.java @@ -3,9 +3,9 @@ /** * Test for {@link DoubleMd5}. */ -public class DoubleMd5Test extends AbstractEncryptionMethodTest { +class DoubleMd5Test extends AbstractEncryptionMethodTest { - public DoubleMd5Test() { + DoubleMd5Test() { super(new DoubleMd5(), "696d29e0940a4957748fe3fc9efd22a3", // password "c77aa2024d9fb7233a2872452d601aba", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java index 984f3d2179..c0d53319a3 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb3Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Ipb3}. */ -public class Ipb3Test extends AbstractEncryptionMethodTest { +class Ipb3Test extends AbstractEncryptionMethodTest { - public Ipb3Test() { + Ipb3Test() { super(new Ipb3(), new HashedPassword("f8ecea1ce42b5babef369ff7692dbe3f", "1715b"), //password new HashedPassword("40a93731a931352e0619cdf09b975040", "ba91c"), //PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java index adcdd72e31..d8e775b4c7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Ipb4Test.java @@ -3,17 +3,17 @@ import org.junit.jupiter.api.Test; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link Ipb4}. */ -public class Ipb4Test extends AbstractEncryptionMethodTest { +class Ipb4Test extends AbstractEncryptionMethodTest { - public Ipb4Test() { + Ipb4Test() { super(new Ipb4(), new HashedPassword("$2a$13$leEvXu77OIwPwNvtZIJvaeAx8EItGHuR3nIlq8416g0gXeJaQdrr2", "leEvXu77OIwPwNvtZIJval"), //password new HashedPassword("$2a$13$xyTTP9zhQQtRRKIJPv5AuuOGJ6Ni9FLbDhcuIAcPjt3XzCxIWe3Uu", "xyTTP9zhQQtRRKIJPv5Au3"), //PassWord1 @@ -22,7 +22,7 @@ public Ipb4Test() { } @Test - public void shouldCreateHashesWith2aAndCostFactor13() { + void shouldCreateHashesWith2aAndCostFactor13() { // given Ipb4 hashMethod = new Ipb4(); @@ -35,7 +35,7 @@ public void shouldCreateHashesWith2aAndCostFactor13() { } @Test - public void shouldThrowForInvalidSalt() { + void shouldThrowForInvalidSalt() { // given Ipb4 hashMethod = new Ipb4(); @@ -50,4 +50,3 @@ public void shouldThrowForInvalidSalt() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java index d2673b34c9..089dda93f5 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/JoomlaTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Joomla}. */ -public class JoomlaTest extends AbstractEncryptionMethodTest { +class JoomlaTest extends AbstractEncryptionMethodTest { - public JoomlaTest() { + JoomlaTest() { super(new Joomla(), "b18c99813cd96df3a706652f47177490:377c4aaf92c5ed57711306909e6065ca", // password "c5af71da91a8841d95937ba24a5b7fdb:07068e5850930b794526a614438cafc7", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java index c079183715..86fbe895b4 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Md5}. */ -public class Md5Test extends AbstractEncryptionMethodTest { +class Md5Test extends AbstractEncryptionMethodTest { - public Md5Test() { + Md5Test() { super(new Md5(), "5f4dcc3b5aa765d61d8327deb882cf99", // password "f2126d405f46ed603ff5b2950f062c96", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java index eac20fcd13..5a9d268c87 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Md5vBTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Md5vB}. */ -public class Md5vBTest extends AbstractEncryptionMethodTest { +class Md5vBTest extends AbstractEncryptionMethodTest { - public Md5vBTest() { + Md5vBTest() { super(new Md5vB(), "$MD5vb$bd9832fffa287321$5006d371fcb813f2347987f902a024ad", // password "$MD5vb$5e492c1166b5a828$c954fa5ee561700a097826971653b57f", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java index fabd9f35df..f13fa72201 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/MyBBTest.java @@ -3,9 +3,9 @@ /** * Test for {@link MyBB}. */ -public class MyBBTest extends AbstractEncryptionMethodTest { +class MyBBTest extends AbstractEncryptionMethodTest { - public MyBBTest() { + MyBBTest() { super(new MyBB(), new HashedPassword("57c7a16d860833db5030738f5a465d2b", "acdc14e6"), //password new HashedPassword("08fbdf721f2c42d9780b7d66df0ba830", "792fd7fb"), //PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Base64Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Base64Test.java index 4edc80cc4c..770863ad12 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Base64Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Base64Test.java @@ -12,9 +12,9 @@ /** * Test for {@link Pbkdf2Base64}. */ -public class Pbkdf2Base64Test extends AbstractEncryptionMethodTest { +class Pbkdf2Base64Test extends AbstractEncryptionMethodTest { - public Pbkdf2Base64Test() { + Pbkdf2Base64Test() { super(new Pbkdf2Base64(mockSettings()), "pbkdf2$4128$JddgMm9rNhbYNfEmf4pOKA==$9Q7QyaEDhqAj8KfF7FdPRq6f9uAWhMwioKvzAWMxSu8=", // password "pbkdf2$4128$obLD1OX2p7jJ0OHyo7TF1g==$dyEnM1cYBRhXl0bDgxfQ3p7Jecj4VerT1Vsag5HJTmo=", // PassWord1 @@ -23,7 +23,7 @@ public Pbkdf2Base64Test() { } @Test - public void shouldMatchHashWithDifferentRoundNumber() { + void shouldMatchHashWithDifferentRoundNumber() { // given / when / then — verifies that stored iterations override the configured value Pbkdf2Base64 pbkdf2Base64 = new Pbkdf2Base64(mockSettings()); String hash = "pbkdf2$120000$JddgMm9rNhbYNfEmf4pOKA==$RcAMtgm/KnKFxfNOpg95tb7s5OzB2Fv4Wj1HOAI/TWY="; diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java index a5a1af6160..040697a0f5 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2DjangoTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Pbkdf2Django}. */ -public class Pbkdf2DjangoTest extends AbstractEncryptionMethodTest { +class Pbkdf2DjangoTest extends AbstractEncryptionMethodTest { - public Pbkdf2DjangoTest() { + Pbkdf2DjangoTest() { super(new Pbkdf2Django(), "pbkdf2_sha256$15000$50a7ff2d7e00$t7Qx2CfzMhGEbyCa3Wk5nJvNjj3N+FdxhpwJDerl4Fs=", // password "pbkdf2_sha256$15000$f9d8a58f3fe2$oMqmMGuJetdubW0cpubmT8CltQLjHT+L2GuwKsaWLx8=", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java index 121d1bb618..aa4f7f5c6e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Pbkdf2Test.java @@ -4,17 +4,17 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link Pbkdf2}. */ -public class Pbkdf2Test extends AbstractEncryptionMethodTest { +class Pbkdf2Test extends AbstractEncryptionMethodTest { - public Pbkdf2Test() { + Pbkdf2Test() { super(new Pbkdf2(mockSettings()), "pbkdf2_sha256$10000$b25801311edf$093E38B16DFF13FCE5CD64D5D888EE6E0376A3E572FE5DA6749515EA0F384413223A21C464B0BE899E64084D1FFEFD44F2AC768453C87F41B42CC6954C416900", // password "pbkdf2_sha256$10000$fe705da06c57$A41527BD58FED9C9E6F452FC1BA8B0C4C4224ECC63E37F71EB1A0865D2AB81BBFEBCA9B7B6A6E8AEF4717B43F8EB6FB4EDEFFBB399D9D991EF7E23013595BAF0", // PassWord1 @@ -23,7 +23,7 @@ public Pbkdf2Test() { } @Test - public void shouldDetectMatchForHashWithOtherRoundNumber() { + void shouldDetectMatchForHashWithOtherRoundNumber() { // given Pbkdf2 pbkdf2 = new Pbkdf2(mockSettings()); String hash = "pbkdf2_sha256$4128$3469b0d48b702046$DC8A54351008C6054E12FB19E0BF8A4EA6D4165E0EDC97A1ECD15231037C382DE5BF85D07D5BC9D1ADF9BBFE4CE257C6059FB1B9FF65DB69D8B205F064BE0DA9"; @@ -42,4 +42,3 @@ private static Settings mockSettings() { return settings; } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java index bdf133c26d..271073ecb0 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpBBTest.java @@ -10,9 +10,9 @@ /** * Test for {@link PhpBB}. */ -public class PhpBBTest extends AbstractEncryptionMethodTest { +class PhpBBTest extends AbstractEncryptionMethodTest { - public PhpBBTest() { + PhpBBTest() { super(new PhpBB(), "$2a$10$1rnuna3GBduBy1NQuOpnWODqBfl8CZHeULuBThNfAvkOYDRRQR1Zi", // password "$2a$10$F6LVgXa8.t95H0Fikr6nG.aEMgIQRXlFpzMvAjbO7ag3fny9GGS3i", // PassWord1 @@ -21,7 +21,7 @@ public PhpBBTest() { } @Test - public void shouldMatchPhpassSaltedMd5Hashes() { + void shouldMatchPhpassSaltedMd5Hashes() { // given Map givenHashes = ImmutableMap.of( "password", "$H$7MaSGQb0xe3Fp/a.Q.Ewpw.UKfCv.t0", @@ -39,7 +39,7 @@ public void shouldMatchPhpassSaltedMd5Hashes() { } @Test - public void shouldMatchUnsaltedMd5Hashes() { + void shouldMatchUnsaltedMd5Hashes() { // given Map givenHashes = ImmutableMap.of( "password", "5f4dcc3b5aa765d61d8327deb882cf99", @@ -57,4 +57,3 @@ public void shouldMatchUnsaltedMd5Hashes() { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java index a08a6ad8c4..ff520fdd3e 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/PhpFusionTest.java @@ -3,9 +3,9 @@ /** * Test for {@link PhpFusion}. */ -public class PhpFusionTest extends AbstractEncryptionMethodTest { +class PhpFusionTest extends AbstractEncryptionMethodTest { - public PhpFusionTest() { + PhpFusionTest() { super(new PhpFusion(), new HashedPassword("f7a606c4eb3fcfbc382906476e05b06f21234a77d1a4eacc0f93f503deb69e70", "6cd1c97c55cb"), // password new HashedPassword("8a9b7bb706a3347e5f684a7cb905bfb26b9a0d099358064139ab3ed1a66aeb2b", "d6012370b73f"), // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java index 7734dc03ad..06bc087c1c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/RoyalAuthTest.java @@ -3,9 +3,9 @@ /** * Test for {@link RoyalAuth}. */ -public class RoyalAuthTest extends AbstractEncryptionMethodTest { +class RoyalAuthTest extends AbstractEncryptionMethodTest { - public RoyalAuthTest() { + RoyalAuthTest() { super(new RoyalAuth(), "5d21ef9236896bc4ac508e524e2da8a0def555dac1cdfc7259d62900d1d3f553826210c369870673ae2cf1c41abcf4f92670d76af1db044d33559324f5c2a339", // password "ecc685f4328bc54093c086ced66c5c11855e117ea22940632d5c0f55fff84d94bfdcc74e05f5d95bbdd052823a7057910748bc1c7a07af96b3e86731a4f11794", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java index fc34a13fca..7463d332db 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Salted2Md5Test.java @@ -9,9 +9,9 @@ /** * Test for {@link Salted2Md5}. */ -public class Salted2Md5Test extends AbstractEncryptionMethodTest { +class Salted2Md5Test extends AbstractEncryptionMethodTest { - public Salted2Md5Test() { + Salted2Md5Test() { super(new Salted2Md5(mockSettings()), new HashedPassword("9f3d13dc01a6fe61fd669954174399f3", "9b5f5749"), // password new HashedPassword("b28c32f624a4eb161d6adc9acb5bfc5b", "f750ba32"), // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java index 98ab061532..44614fedad 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/SaltedSha512Test.java @@ -3,9 +3,9 @@ /** * Test for {@link SaltedSha512}. */ -public class SaltedSha512Test extends AbstractEncryptionMethodTest { +class SaltedSha512Test extends AbstractEncryptionMethodTest { - public SaltedSha512Test() { + SaltedSha512Test() { super(new SaltedSha512(), new HashedPassword("dea7a37cecf5384ae8e347fd1411efb51364b6ba1b328695de3b354612c1d7010807e8b7051c40f740e498490e1f133e2c2408327d13fbdd68e1b1f6d548e624", "29f8a3c52147f987fee7ba3e0fb311bd"), // password new HashedPassword("7c06225aac574d2dc7c81a2ed306637adf025715f52083e05bdab014faaa234e24a97d0e69ea0108dfa77cc9228e58be319ee677e679b5d1ad168d40e50a42f6", "8ea37b85d020b98f60c0fe9b8ec9296c"), // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java index 2bd5543f38..f3240a6b7a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha1Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Sha1}. */ -public class Sha1Test extends AbstractEncryptionMethodTest { +class Sha1Test extends AbstractEncryptionMethodTest { - public Sha1Test() { + Sha1Test() { super(new Sha1(), "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", // password "285d0c707f9644b75e1a87a62f25d0efb56800f0", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java index b9f751654b..9d55b38919 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha256Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Sha256}. */ -public class Sha256Test extends AbstractEncryptionMethodTest { +class Sha256Test extends AbstractEncryptionMethodTest { - public Sha256Test() { + Sha256Test() { super(new Sha256(), "$SHA$11aa0706173d7272$dbba96681c2ae4e0bfdf226d70fbbc5e4ee3d8071faa613bc533fe8a64817d10", // password "$SHA$3c72a18a29b08d40$8e50a7a4f69a80f4893dc921eac84bd74b3f9ebfa22908302c9965eac3aa45e5", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java index 2871cd3a2e..ec98a48289 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Sha512Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Sha512}. */ -public class Sha512Test extends AbstractEncryptionMethodTest { +class Sha512Test extends AbstractEncryptionMethodTest { - public Sha512Test() { + Sha512Test() { super(new Sha512(), "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86", // password "ae9942149995a8171391625b36da134d5e288c721650d7c8d2d464fb49a49f3f551e4916ab1e097d9dd1201b01d69b1dccdefa3d2524a66092fb61b3df6e7e71", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java index a71a12c87e..8092f46c01 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/SmfTest.java @@ -3,15 +3,15 @@ import org.junit.jupiter.api.Test; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link Smf}. */ -public class SmfTest extends AbstractEncryptionMethodTest { +class SmfTest extends AbstractEncryptionMethodTest { - public SmfTest() { + SmfTest() { super(new Smf(), "9b361c66977bb059d460a20d3c21fb3394772df5", // password "31a560bdd095a837945d46add1605108ba87b268", // PassWord1 @@ -20,14 +20,14 @@ public SmfTest() { } @Override - protected void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isSaltConstructor) { + void verifyCorrectConstructorIsUsed(EncryptionMethod method, boolean isSaltConstructor) { // Smf declares to use a separate salt, but it's not used in the actual hashing mechanism, see Smf class Javadoc assertThat(method.hasSeparateSalt(), equalTo(true)); assertThat(isSaltConstructor, equalTo(false)); } @Test - public void shouldGenerateFourCharSalt() { + void shouldGenerateFourCharSalt() { // given EncryptionMethod method = new Smf(); @@ -41,4 +41,3 @@ public void shouldGenerateFourCharSalt() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java index adee202959..85785df9cb 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/TwoFactorTest.java @@ -4,21 +4,21 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link TwoFactor}. */ -public class TwoFactorTest { +class TwoFactorTest { @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldGenerateBarcodeUrl() { + void shouldGenerateBarcodeUrl() { // given String user = "tester"; String host = "192.168.0.4"; @@ -34,7 +34,7 @@ public void shouldGenerateBarcodeUrl() { } @Test - public void shouldHandleInvalidHash() { + void shouldHandleInvalidHash() { // given HashedPassword password = new HashedPassword("!@&#@!(*&@"); String inputPassword = "12345"; @@ -48,7 +48,7 @@ public void shouldHandleInvalidHash() { } @Test - public void shouldHandleInvalidInput() { + void shouldHandleInvalidInput() { // given HashedPassword password = new HashedPassword("3AK6Y4KWGRLJMEQW"); String inputPassword = "notA_number!"; @@ -61,4 +61,3 @@ public void shouldHandleInvalidInput() { assertThat(result, equalTo(false)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java index 7443253fe3..21b37c3608 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb3Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Wbb3}. */ -public class Wbb3Test extends AbstractEncryptionMethodTest { +class Wbb3Test extends AbstractEncryptionMethodTest { - public Wbb3Test() { + Wbb3Test() { super(new Wbb3(), new HashedPassword("8df818ef7d56075ab2744f74b98ad68a375ccac4", "b7415b355492ea60314f259a35733a3092c03e3f"), // password new HashedPassword("106da5cf5df92cb845e12cf62cbdb5235b6dc693", "6110f19b2b52910dccf592a19c59126873f42e69"), // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java index 6c5459f609..e588e95f8d 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/Wbb4Test.java @@ -3,9 +3,9 @@ /** * Test for {@link Wbb4}. */ -public class Wbb4Test extends AbstractEncryptionMethodTest { +class Wbb4Test extends AbstractEncryptionMethodTest { - public Wbb4Test() { + Wbb4Test() { super(new Wbb4(), "$2a$08$7DGr.wROqEPe0Z3XJS7n5.k.QWehovLHbpI.UkdfRb4ns268WsR6C", // password "$2a$08$yWWVUA4PB4mqW.0wyIvV3OdoH492HuLk5L3iaqUrpRK2.2zn08d/K", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java index 0c444c2f8a..1a7c379cfa 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/WordpressTest.java @@ -3,9 +3,9 @@ /** * Test for {@link Wordpress}. */ -public class WordpressTest extends AbstractEncryptionMethodTest { +class WordpressTest extends AbstractEncryptionMethodTest { - public WordpressTest() { + WordpressTest() { super(new Wordpress(), "$P$B9wyjxuU4yrfjnnHNGSzH9ti9CC0Os1", // password "$P$BjzPjjzPjjkRzvGGRTyYu0sNqcz6Ci0", // PassWord1 diff --git a/authme-core/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java b/authme-core/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java index 5d7d71bfa6..4c05cc3775 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/crypts/XfBCryptTest.java @@ -2,16 +2,16 @@ import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link XfBCrypt}. */ -public class XfBCryptTest extends AbstractEncryptionMethodTest { +class XfBCryptTest extends AbstractEncryptionMethodTest { - public XfBCryptTest() { + XfBCryptTest() { super(new XfBCrypt(), "$2a$10$UtuON/ZG.x8EWG/zQbryB.BHfQVrfxk3H7qykzP.UJQ8YiLjZyfqq", // password "$2a$10$Q.ocUo.YtHTdI4nu3pcpKun6BILcmWHm541ANULucmuU/ps1QKY4K", // PassWord1 @@ -20,7 +20,7 @@ public XfBCryptTest() { } @Test - public void shouldGenerateWith2aPrefixAndCostFactor10() { + void shouldGenerateWith2aPrefixAndCostFactor10() { // given XfBCrypt xfBCrypt = new XfBCrypt(); @@ -32,4 +32,3 @@ public void shouldGenerateWith2aPrefixAndCostFactor10() { assertThat(result.getSalt(), nullValue()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java index 8ba80b5967..add9f4dfe7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/totp/GenerateTotpServiceTest.java @@ -1,32 +1,28 @@ package fr.xephi.authme.security.totp; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.security.totp.TotpAuthenticator.TotpGenerationResult; import fr.xephi.authme.util.expiring.ExpiringMap; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; /** * Test for {@link GenerateTotpService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class GenerateTotpServiceTest { +class GenerateTotpServiceTest { @InjectMocks private GenerateTotpService generateTotpService; @@ -35,7 +31,7 @@ public class GenerateTotpServiceTest { private TotpAuthenticator totpAuthenticator; @Test - public void shouldGenerateTotpKey() { + void shouldGenerateTotpKey() { // given TotpGenerationResult givenGenerationResult = new TotpGenerationResult("1234", "http://example.com/link/to/chart"); Player player = mockPlayerWithName("Spencer"); @@ -50,7 +46,7 @@ public void shouldGenerateTotpKey() { } @Test - public void shouldRemoveGeneratedTotpKey() { + void shouldRemoveGeneratedTotpKey() { // given TotpGenerationResult givenGenerationResult = new TotpGenerationResult("1234", "http://example.com/link/to/chart"); Player player = mockPlayerWithName("Hanna"); @@ -65,7 +61,7 @@ public void shouldRemoveGeneratedTotpKey() { } @Test - public void shouldCheckGeneratedTotpKey() { + void shouldCheckGeneratedTotpKey() { // given String generatedKey = "ASLO43KDF2J"; TotpGenerationResult givenGenerationResult = new TotpGenerationResult(generatedKey, "url"); @@ -73,8 +69,8 @@ public void shouldCheckGeneratedTotpKey() { given(totpAuthenticator.generateTotpKey(player)).willReturn(givenGenerationResult); generateTotpService.generateTotpKey(player); String validCode = "928374"; - given(totpAuthenticator.checkCode("Aria", generatedKey, "000000")).willReturn(false); given(totpAuthenticator.checkCode("Aria", generatedKey, validCode)).willReturn(true); + given(totpAuthenticator.checkCode("Aria", generatedKey, "000000")).willReturn(false); // when boolean invalidCodeResult = generateTotpService.isTotpCodeCorrectForGeneratedTotpKey(player, "000000"); @@ -85,12 +81,10 @@ public void shouldCheckGeneratedTotpKey() { assertThat(invalidCodeResult, equalTo(false)); assertThat(validCodeResult, equalTo(true)); assertThat(unknownPlayerResult, equalTo(false)); - verify(totpAuthenticator).checkCode("Aria", generatedKey, "000000"); - verify(totpAuthenticator).checkCode("Aria", generatedKey, validCode); } @Test - public void shouldRemoveExpiredEntries() throws InterruptedException { + void shouldRemoveExpiredEntries() throws InterruptedException { // given TotpGenerationResult generationResult = new TotpGenerationResult("key", "url"); ExpiringMap generatedKeys = @@ -115,5 +109,3 @@ private static Player mockPlayerWithName(String name) { return player; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java b/authme-core/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java index a3004ea7ab..da45004cf6 100644 --- a/authme-core/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/security/totp/TotpAuthenticatorTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.security.totp; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import com.google.common.collect.Table; import com.warrenstrange.googleauth.IGoogleAuthenticator; import fr.xephi.authme.ReflectionTestUtils; @@ -15,14 +11,16 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -32,8 +30,7 @@ * Test for {@link TotpAuthenticator}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class TotpAuthenticatorTest { +class TotpAuthenticatorTest { private TotpAuthenticator totpAuthenticator; @@ -44,12 +41,12 @@ public class TotpAuthenticatorTest { private IGoogleAuthenticator googleAuthenticator; @BeforeEach - public void initializeTotpAuthenticator() { + void initializeTotpAuthenticator() { totpAuthenticator = new TotpAuthenticatorTestImpl(settings); } @Test - public void shouldGenerateTotpKey() { + void shouldGenerateTotpKey() { // given // Use the GoogleAuthenticator instance the TotpAuthenticator normally creates to test its parameters totpAuthenticator = new TotpAuthenticator(settings); @@ -73,7 +70,7 @@ public void shouldGenerateTotpKey() { } @Test - public void shouldCheckCodeAndDeclareItValidOnlyOnce() { + void shouldCheckCodeAndDeclareItValidOnlyOnce() { // given String secret = "the_secret"; int code = 21398; @@ -90,7 +87,7 @@ public void shouldCheckCodeAndDeclareItValidOnlyOnce() { } @Test - public void shouldHandleInvalidNumberInput() { + void shouldHandleInvalidNumberInput() { // given / when boolean result = totpAuthenticator.checkCode("foo", "Some_Secret", "123ZZ"); @@ -100,7 +97,7 @@ public void shouldHandleInvalidNumberInput() { } @Test - public void shouldVerifyCode() { + void shouldVerifyCode() { // given String totpKey = "ASLO43KDF2J"; PlayerAuth auth = PlayerAuth.builder() @@ -119,7 +116,7 @@ public void shouldVerifyCode() { } @Test - public void shouldRemoveOldEntries() { + void shouldRemoveOldEntries() { // given Table usedCodes = ReflectionTestUtils.getFieldValue( TotpAuthenticator.class, totpAuthenticator, "usedCodes"); @@ -147,5 +144,3 @@ protected IGoogleAuthenticator createGoogleAuthenticator() { } } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java index b576548e9d..20c9f1d436 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/AntiBotServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.service; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.AdminPermission; @@ -11,35 +7,38 @@ import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.ProtectionSettings; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunOnGlobalRegion; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskLaterOnGlobalRegion; -import static org.hamcrest.Matchers.equalTo; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Test for {@link AntiBotService}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class AntiBotServiceTest { +@ExtendWith(MockitoExtension.class) +class AntiBotServiceTest { - @InjectDelayed private AntiBotService antiBotService; @Mock @@ -50,28 +49,26 @@ public class AntiBotServiceTest { private PermissionsManager permissionsManager; @Mock private BukkitService bukkitService; - @Captor - private ArgumentCaptor runnableCaptor; - @BeforeInjecting - public void initSettings() { + @BeforeEach + void initSettingsAndService() { given(settings.getProperty(ProtectionSettings.ANTIBOT_DURATION)).willReturn(10); given(settings.getProperty(ProtectionSettings.ANTIBOT_INTERVAL)).willReturn(5); given(settings.getProperty(ProtectionSettings.ANTIBOT_SENSIBILITY)).willReturn(5); given(settings.getProperty(ProtectionSettings.ENABLE_ANTIBOT)).willReturn(true); given(settings.getProperty(ProtectionSettings.ANTIBOT_DELAY)).willReturn(8); setBukkitServiceToRunTaskLaterOnGlobalRegion(bukkitService); - setBukkitServiceToRunOnGlobalRegion(bukkitService); + antiBotService = new AntiBotService(settings, messages, permissionsManager, bukkitService); } @Test - public void shouldStartListenerOnStartup() { + void shouldStartListenerOnStartup() { // given / when / then assertThat(antiBotService.getAntiBotStatus(), equalTo(AntiBotService.AntiBotStatus.LISTENING)); } @Test - public void shouldNotListenForDisabledSetting() { + void shouldNotListenForDisabledSetting() { // given reset(bukkitService); given(settings.getProperty(ProtectionSettings.ENABLE_ANTIBOT)).willReturn(false); @@ -85,7 +82,7 @@ public void shouldNotListenForDisabledSetting() { } @Test - public void shouldActivateAntibot() { + void shouldActivateAntibot() { // given - listening antibot CancellableTask task = mock(CancellableTask.class); given(bukkitService.runTaskLaterOnGlobalRegion(any(Runnable.class), anyLong())).willReturn(task); @@ -96,13 +93,14 @@ public void shouldActivateAntibot() { // then assertThat(antiBotService.getAntiBotStatus(), equalTo(AntiBotService.AntiBotStatus.ACTIVE)); // Check that a task is scheduled to disable again - verify(bukkitService, org.mockito.Mockito.times(2)).runTaskLaterOnGlobalRegion(runnableCaptor.capture(), anyLong()); + ArgumentCaptor runnableCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(bukkitService, times(2)).runTaskLaterOnGlobalRegion(runnableCaptor.capture(), anyLong()); runnableCaptor.getAllValues().get(1).run(); assertThat(antiBotService.getAntiBotStatus(), equalTo(AntiBotService.AntiBotStatus.LISTENING)); } @Test - public void shouldNotActivateAntibotForDisabledSetting() { + void shouldNotActivateAntibotForDisabledSetting() { // given - disabled antibot given(settings.getProperty(ProtectionSettings.ENABLE_ANTIBOT)).willReturn(false); AntiBotService antiBotService = new AntiBotService(settings, messages, permissionsManager, bukkitService); @@ -115,7 +113,7 @@ public void shouldNotActivateAntibotForDisabledSetting() { } @Test - public void shouldKeepTrackOfKickedPlayers() { + void shouldKeepTrackOfKickedPlayers() { // given String name = "eratic"; antiBotService.addPlayerKick(name); @@ -130,7 +128,7 @@ public void shouldKeepTrackOfKickedPlayers() { } @Test - public void shouldAcceptPlayerToJoin() { + void shouldAcceptPlayerToJoin() { // given / when boolean result = antiBotService.shouldKick(); @@ -139,7 +137,7 @@ public void shouldAcceptPlayerToJoin() { } @Test - public void shouldActivateAntibotAfterThreshold() { + void shouldActivateAntibotAfterThreshold() { // given int sensitivity = 10; given(settings.getProperty(ProtectionSettings.ANTIBOT_SENSIBILITY)).willReturn(sensitivity); @@ -158,29 +156,27 @@ public void shouldActivateAntibotAfterThreshold() { } @Test - public void shouldInformPlayersOnActivation() { + void shouldInformPlayersOnActivation() { // given - listening antibot List players = Arrays.asList(mock(Player.class), mock(Player.class)); given(bukkitService.getOnlinePlayers()).willReturn(players); given(permissionsManager.hasPermission(players.get(0), AdminPermission.ANTIBOT_MESSAGES)).willReturn(false); given(permissionsManager.hasPermission(players.get(1), AdminPermission.ANTIBOT_MESSAGES)).willReturn(true); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); setBukkitServiceToRunOnGlobalRegion(bukkitService); // when antiBotService.overrideAntiBotStatus(true); // then - verify(permissionsManager).hasPermission(players.get(0), AdminPermission.ANTIBOT_MESSAGES); - verify(permissionsManager).hasPermission(players.get(1), AdminPermission.ANTIBOT_MESSAGES); - verify(bukkitService).scheduleSyncTaskFromOptionallyAsyncTask(org.mockito.ArgumentMatchers.eq(players.get(0)), any(Runnable.class)); - verify(bukkitService).scheduleSyncTaskFromOptionallyAsyncTask(org.mockito.ArgumentMatchers.eq(players.get(1)), any(Runnable.class)); + verify(messages, only()).send(players.get(1), MessageKey.ANTIBOT_AUTO_ENABLED_MESSAGE, new String[0]); + verify(bukkitService).scheduleSyncTaskFromOptionallyAsyncTask(eq(players.get(0)), any(Runnable.class)); + verify(bukkitService).scheduleSyncTaskFromOptionallyAsyncTask(eq(players.get(1)), any(Runnable.class)); } @Test - public void shouldImmediatelyStartAfterFirstStartup() { + void shouldImmediatelyStartAfterFirstStartup() { // given - listening antibot - given(bukkitService.runTaskLaterOnGlobalRegion(any(Runnable.class), anyLong())).willReturn(mock(CancellableTask.class)); antiBotService.overrideAntiBotStatus(true); // when @@ -191,5 +187,3 @@ public void shouldImmediatelyStartAfterFirstStartup() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java index 61987d95b7..1152bd870a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.service; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.events.FailedLoginEvent; @@ -22,15 +18,15 @@ import org.bukkit.scheduler.BukkitTask; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.any; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; @@ -40,8 +36,7 @@ * Test for {@link BukkitService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class BukkitServiceTest { +class BukkitServiceTest { private BukkitService bukkitService; @@ -59,16 +54,14 @@ public class BukkitServiceTest { private SchedulingAdapter schedulingAdapter; @BeforeEach - public void constructBukkitService() { + void constructBukkitService() { ReflectionTestUtils.setField(Bukkit.class, null, "server", server); - lenient().when(server.getScheduler()).thenReturn(scheduler); - lenient().when(server.getPluginManager()).thenReturn(pluginManager); - lenient().when(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).thenReturn(true); + given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(true); bukkitService = new BukkitService(authMe, settings, schedulingAdapter); } @Test - public void shouldDispatchCommand() { + void shouldDispatchCommand() { // given CommandSender sender = mock(CommandSender.class); String command = "help test abc"; @@ -81,7 +74,7 @@ public void shouldDispatchCommand() { } @Test - public void shouldDispatchConsoleCommand() { + void shouldDispatchConsoleCommand() { // given ConsoleCommandSender consoleSender = mock(ConsoleCommandSender.class); given(server.getConsoleSender()).willReturn(consoleSender); @@ -95,10 +88,11 @@ public void shouldDispatchConsoleCommand() { } @Test - public void shouldScheduleSyncDelayedTask() { + void shouldScheduleSyncDelayedTask() { // given Runnable task = () -> {/* noop */}; given(scheduler.scheduleSyncDelayedTask(authMe, task)).willReturn(123); + given(server.getScheduler()).willReturn(scheduler); // when int taskId = bukkitService.scheduleSyncDelayedTask(task); @@ -109,11 +103,12 @@ public void shouldScheduleSyncDelayedTask() { } @Test - public void shouldScheduleSyncDelayedTaskWithDelay() { + void shouldScheduleSyncDelayedTaskWithDelay() { // given Runnable task = () -> {/* noop */}; int delay = 3; given(scheduler.scheduleSyncDelayedTask(authMe, task, delay)).willReturn(44); + given(server.getScheduler()).willReturn(scheduler); // when int taskId = bukkitService.scheduleSyncDelayedTask(task, delay); @@ -124,7 +119,7 @@ public void shouldScheduleSyncDelayedTaskWithDelay() { } @Test - public void shouldScheduleSyncTask() { + void shouldScheduleSyncTask() { // given Runnable task = mock(Runnable.class); given(schedulingAdapter.isGlobalThread()).willReturn(false); @@ -138,7 +133,7 @@ public void shouldScheduleSyncTask() { } @Test - public void shouldRunTaskDirectly() { + void shouldRunTaskDirectly() { // given given(schedulingAdapter.isGlobalThread()).willReturn(true); bukkitService.reload(settings); @@ -153,7 +148,7 @@ public void shouldRunTaskDirectly() { } @Test - public void shouldScheduleEntityTask() { + void shouldScheduleEntityTask() { // given Entity entity = mock(Player.class); Runnable task = mock(Runnable.class); @@ -168,7 +163,7 @@ public void shouldScheduleEntityTask() { } @Test - public void shouldRunEntityTaskDirectly() { + void shouldRunEntityTaskDirectly() { // given Entity entity = mock(Player.class); Runnable task = mock(Runnable.class); @@ -182,11 +177,12 @@ public void shouldRunEntityTaskDirectly() { } @Test - public void shouldRunTask() { + void shouldRunTask() { // given Runnable task = () -> {/* noop */}; BukkitTask bukkitTask = mock(BukkitTask.class); given(scheduler.runTask(authMe, task)).willReturn(bukkitTask); + given(server.getScheduler()).willReturn(scheduler); // when BukkitTask resultingTask = bukkitService.runTask(task); @@ -197,12 +193,13 @@ public void shouldRunTask() { } @Test - public void shouldRunTaskLater() { + void shouldRunTaskLater() { // given Runnable task = () -> {/* noop */}; BukkitTask bukkitTask = mock(BukkitTask.class); long delay = 400; given(scheduler.runTaskLater(authMe, task, delay)).willReturn(bukkitTask); + given(server.getScheduler()).willReturn(scheduler); // when BukkitTask resultingTask = bukkitService.runTaskLater(task, delay); @@ -213,7 +210,7 @@ public void shouldRunTaskLater() { } @Test - public void shouldRunTaskInAsync() { + void shouldRunTaskInAsync() { // given Runnable task = mock(Runnable.class); BukkitService spy = Mockito.spy(bukkitService); @@ -228,7 +225,7 @@ public void shouldRunTaskInAsync() { } @Test - public void shouldRunTaskDirectlyIfConfigured() { + void shouldRunTaskDirectlyIfConfigured() { // given given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(false); bukkitService.reload(settings); @@ -244,7 +241,7 @@ public void shouldRunTaskDirectlyIfConfigured() { } @Test - public void shouldRunTaskAsynchronously() { + void shouldRunTaskAsynchronously() { // given Runnable task = () -> {/* noop */}; CancellableTask cancellableTask = mock(CancellableTask.class); @@ -259,7 +256,7 @@ public void shouldRunTaskAsynchronously() { } @Test - public void shouldRunTaskTimerAsynchronously() { + void shouldRunTaskTimerAsynchronously() { // given Runnable task = mock(Runnable.class); long delay = 20L; @@ -276,7 +273,7 @@ public void shouldRunTaskTimerAsynchronously() { } @Test - public void shouldRunTaskTimer() { + void shouldRunTaskTimer() { // given BukkitRunnable bukkitRunnable = mock(BukkitRunnable.class); long delay = 20; @@ -293,7 +290,7 @@ public void shouldRunTaskTimer() { } @Test - public void shouldBroadcastMessage() { + void shouldBroadcastMessage() { // given String message = "Important message to all"; given(server.broadcastMessage(message)).willReturn(24); @@ -307,11 +304,12 @@ public void shouldBroadcastMessage() { } @Test - public void shouldCreateAndEmitSyncEvent() { + void shouldCreateAndEmitSyncEvent() { // given given(settings.getProperty(PluginSettings.USE_ASYNC_TASKS)).willReturn(false); bukkitService.reload(settings); Player player = mock(Player.class); + given(server.getPluginManager()).willReturn(pluginManager); // when FailedLoginEvent event = bukkitService.createAndCallEvent(isAsync -> new FailedLoginEvent(player, isAsync)); @@ -323,9 +321,10 @@ public void shouldCreateAndEmitSyncEvent() { } @Test - public void shouldCreateAndEmitAsyncEvent() { + void shouldCreateAndEmitAsyncEvent() { // given Player player = mock(Player.class); + given(server.getPluginManager()).willReturn(pluginManager); // when FailedLoginEvent event = bukkitService.createAndCallEvent(isAsync -> new FailedLoginEvent(player, isAsync)); @@ -337,7 +336,7 @@ public void shouldCreateAndEmitAsyncEvent() { } @Test - public void shouldReturnServerIp() { + void shouldReturnServerIp() { // given String ip = "99.99.99.99"; given(server.getIp()).willReturn(ip); @@ -349,5 +348,3 @@ public void shouldReturnServerIp() { assertThat(result, equalTo(ip)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java b/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java index 99bb0ac7f1..08307528c7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/BukkitServiceTestHelper.java @@ -1,11 +1,11 @@ package fr.xephi.authme.service; +import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; /** @@ -18,22 +18,30 @@ private BukkitServiceTestHelper() { /** * Sets a BukkitService mock to run any Runnable it is passed to its method - * {@link BukkitService#scheduleSyncTaskFromOptionallyAsyncTask}. + * {@link BukkitService#scheduleSyncTaskFromOptionallyAsyncTask(Runnable)}. * * @param bukkitService the mock to set behavior on */ public static void setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); return null; }).when(bukkitService).scheduleSyncTaskFromOptionallyAsyncTask(any(Runnable.class)); + } - lenient().doAnswer(invocation -> { + /** + * Sets a BukkitService mock to run any Runnable it is passed to its method + * {@link BukkitService#scheduleSyncTaskFromOptionallyAsyncTask(org.bukkit.entity.Entity, Runnable)}. + * + * @param bukkitService the mock to set behavior on + */ + public static void setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(BukkitService bukkitService) { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(1); runnable.run(); return null; - }).when(bukkitService).scheduleSyncTaskFromOptionallyAsyncTask(any(Player.class), any(Runnable.class)); + }).when(bukkitService).scheduleSyncTaskFromOptionallyAsyncTask(any(Entity.class), any(Runnable.class)); } /** @@ -43,7 +51,7 @@ public static void setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(Buk * @param bukkitService the mock to set behavior on */ public static void setBukkitServiceToRunTaskAsynchronously(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); return null; @@ -57,7 +65,7 @@ public static void setBukkitServiceToRunTaskAsynchronously(BukkitService bukkitS * @param bukkitService the mock to set behavior on */ public static void setBukkitServiceToRunTaskOptionallyAsync(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); return null; @@ -71,7 +79,7 @@ public static void setBukkitServiceToRunTaskOptionallyAsync(BukkitService bukkit * @param bukkitService the mock to set behavior on */ public static void setBukkitServiceToScheduleSyncDelayedTask(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); return null; @@ -85,21 +93,29 @@ public static void setBukkitServiceToScheduleSyncDelayedTask(BukkitService bukki * @param bukkitService the mock to set behavior on */ public static void setBukkitServiceToScheduleSyncDelayedTaskWithDelay(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); return null; }).when(bukkitService).scheduleSyncDelayedTask(any(Runnable.class), anyLong()); + } - lenient().doAnswer(invocation -> { + /** + * Sets a BukkitService mock to run any Runnable it is passed to its method + * {@link BukkitService#scheduleSyncDelayedTask(Entity, Runnable, long)}. + * + * @param bukkitService the mock to set behavior on + */ + public static void setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(BukkitService bukkitService) { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(1); runnable.run(); return null; - }).when(bukkitService).scheduleSyncDelayedTask(any(Player.class), any(Runnable.class), anyLong()); + }).when(bukkitService).scheduleSyncDelayedTask(any(Entity.class), any(Runnable.class), anyLong()); } public static void setBukkitServiceToRunOnGlobalRegion(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); return null; @@ -107,7 +123,7 @@ public static void setBukkitServiceToRunOnGlobalRegion(BukkitService bukkitServi } public static void setBukkitServiceToRunTaskLaterOnGlobalRegion(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(0); runnable.run(); return mock(CancellableTask.class); @@ -115,7 +131,7 @@ public static void setBukkitServiceToRunTaskLaterOnGlobalRegion(BukkitService bu } public static void setBukkitServiceToRunTaskLater(BukkitService bukkitService) { - lenient().doAnswer(invocation -> { + doAnswer(invocation -> { Runnable runnable = invocation.getArgument(1); runnable.run(); return mock(CancellableTask.class); diff --git a/authme-core/src/test/java/fr/xephi/authme/service/CommonServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/CommonServiceTest.java index 9a5079b566..33af3a7c6c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/CommonServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/CommonServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.service; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.message.Messages; import fr.xephi.authme.permission.PermissionNode; @@ -14,11 +10,13 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -27,8 +25,7 @@ * Test for {@link CommonService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class CommonServiceTest { +class CommonServiceTest { @InjectMocks private CommonService commonService; @@ -43,7 +40,7 @@ public class CommonServiceTest { private PermissionsManager permissionsManager; @Test - public void shouldGetProperty() { + void shouldGetProperty() { // given given(settings.getProperty(SecuritySettings.CAPTCHA_LENGTH)).willReturn(8); @@ -56,7 +53,7 @@ public void shouldGetProperty() { } @Test - public void shouldSendMessageToPlayer() { + void shouldSendMessageToPlayer() { // given CommandSender sender = mock(CommandSender.class); MessageKey key = MessageKey.ACCOUNT_NOT_ACTIVATED; @@ -69,7 +66,7 @@ public void shouldSendMessageToPlayer() { } @Test - public void shouldSendMessageWithReplacements() { + void shouldSendMessageWithReplacements() { // given CommandSender sender = mock(CommandSender.class); MessageKey key = MessageKey.ACCOUNT_NOT_ACTIVATED; @@ -83,7 +80,7 @@ public void shouldSendMessageWithReplacements() { } @Test - public void shouldRetrieveSingleMessage() { + void shouldRetrieveSingleMessage() { // given MessageKey key = MessageKey.ACCOUNT_NOT_ACTIVATED; Player player = mock(Player.class); @@ -99,7 +96,7 @@ public void shouldRetrieveSingleMessage() { } @Test - public void shouldCheckPermission() { + void shouldCheckPermission() { // given Player player = mock(Player.class); PermissionNode permission = PlayerPermission.CHANGE_PASSWORD; @@ -113,5 +110,3 @@ public void shouldCheckPermission() { assertThat(result, equalTo(true)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/DialogWindowServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/DialogWindowServiceTest.java index 1ae633eb5c..a03aef01ee 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/DialogWindowServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/DialogWindowServiceTest.java @@ -13,8 +13,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -25,9 +23,11 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; +/** + * Test for {@link DialogWindowService}. + */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class DialogWindowServiceTest { +class DialogWindowServiceTest { @InjectMocks private DialogWindowService dialogWindowService; @@ -42,7 +42,7 @@ public class DialogWindowServiceTest { private EmailService emailService; @Test - public void shouldBuildPostJoinLoginDialogWithForgotPasswordButtonWhenEmailServiceConfigured() { + void shouldBuildPostJoinLoginDialogWithForgotPasswordButtonWhenEmailServiceConfigured() { // given Player player = org.mockito.Mockito.mock(Player.class); given(commonService.retrieveSingleMessage(eq(player), any(MessageKey.class))) @@ -66,7 +66,7 @@ public void shouldBuildPostJoinLoginDialogWithForgotPasswordButtonWhenEmailServi } @Test - public void shouldNotShowForgotPasswordButtonWhenEmailServiceNotConfigured() { + void shouldNotShowForgotPasswordButtonWhenEmailServiceNotConfigured() { // given Player player = org.mockito.Mockito.mock(Player.class); given(commonService.retrieveSingleMessage(eq(player), any(MessageKey.class))) @@ -85,14 +85,13 @@ public void shouldNotShowForgotPasswordButtonWhenEmailServiceNotConfigured() { } @Test - public void shouldBuildPostJoinLoginDialogWithoutForgotPasswordButtonWhenDisabledByConfig() { + void shouldBuildPostJoinLoginDialogWithoutForgotPasswordButtonWhenDisabledByConfig() { // given Player player = org.mockito.Mockito.mock(Player.class); given(commonService.retrieveSingleMessage(eq(player), any(MessageKey.class))) .willAnswer(invocation -> invocation.getArgument(1, MessageKey.class).getKey()); given(commonService.getProperty(RegistrationSettings.DIALOG_SHOW_FORGOT_PASSWORD_BUTTON)).willReturn(false); given(commonService.getProperty(RegistrationSettings.DIALOG_SHOW_BODY)).willReturn(false); - given(emailService.hasAllInformation()).willReturn(true); // when — disabled by config even when email service is available DialogWindowSpec dialog = dialogWindowService.createLoginDialog(player); @@ -105,7 +104,7 @@ public void shouldBuildPostJoinLoginDialogWithoutForgotPasswordButtonWhenDisable } @Test - public void shouldBuildPostJoinRegisterDialogWithEmailBeforePasswordForMandatoryEmailFlow() { + void shouldBuildPostJoinRegisterDialogWithEmailBeforePasswordForMandatoryEmailFlow() { // given Player player = org.mockito.Mockito.mock(Player.class); given(commonService.retrieveSingleMessage(eq(player), any(MessageKey.class))) @@ -121,7 +120,7 @@ public void shouldBuildPostJoinRegisterDialogWithEmailBeforePasswordForMandatory } @Test - public void shouldBuildPostJoinRegisterDialogForOptionalEmailFlow() { + void shouldBuildPostJoinRegisterDialogForOptionalEmailFlow() { // given Player player = org.mockito.Mockito.mock(Player.class); given(commonService.retrieveSingleMessage(eq(player), any(MessageKey.class))) @@ -141,7 +140,7 @@ public void shouldBuildPostJoinRegisterDialogForOptionalEmailFlow() { } @Test - public void shouldBuildPreJoinLoginDialogWithCancelButtonWhenEmailServiceNotConfigured() { + void shouldBuildPreJoinLoginDialogWithCancelButtonWhenEmailServiceNotConfigured() { // given given(messages.retrieveSingle(eq("Bobby"), any(MessageKey.class))) .willAnswer(invocation -> invocation.getArgument(1, MessageKey.class).getKey()); @@ -166,7 +165,7 @@ public void shouldBuildPreJoinLoginDialogWithCancelButtonWhenEmailServiceNotConf } @Test - public void shouldBuildPreJoinLoginDialogWithRecoveryButtonWhenEmailServiceConfigured() { + void shouldBuildPreJoinLoginDialogWithRecoveryButtonWhenEmailServiceConfigured() { // given given(messages.retrieveSingle(eq("Bobby"), any(MessageKey.class))) .willAnswer(invocation -> invocation.getArgument(1, MessageKey.class).getKey()); diff --git a/authme-core/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java index c726b6b234..802b9d76ec 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/GeoIpServiceTest.java @@ -1,16 +1,5 @@ package fr.xephi.authme.service; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; -import java.io.File; -import java.io.IOException; -import java.net.InetAddress; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import com.google.common.collect.ImmutableMap; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CountryResponse; @@ -20,15 +9,21 @@ import fr.xephi.authme.settings.properties.ProtectionSettings; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.File; +import java.net.InetAddress; +import java.util.Collections; +import java.util.List; +import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; - -import static org.hamcrest.Matchers.equalTo; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -37,11 +32,13 @@ * Test for {@link GeoIpService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class GeoIpServiceTest { +class GeoIpServiceTest { private GeoIpService geoIpService; + @TempDir + File dataFolder; + @Mock private DatabaseReader lookupService; @@ -50,16 +47,14 @@ public class GeoIpServiceTest { @Mock private Settings settings; - public TempFolder temporaryFolder = new TempFolder(); @BeforeEach - public void initializeGeoLiteApi() throws IOException { - File dataFolder = temporaryFolder.newFolder(); + void initializeGeoLiteApi() { geoIpService = new GeoIpService(dataFolder, bukkitService, settings, lookupService); } @Test - public void shouldGetCountry() throws Exception { + void shouldGetCountry() throws Exception { // given InetAddress ip = InetAddress.getByName("123.45.67.89"); String countryCode = "XX"; @@ -76,7 +71,7 @@ public void shouldGetCountry() throws Exception { } @Test - public void shouldNotLookUpCountryForLocalhostIp() throws Exception { + void shouldNotLookUpCountryForLocalhostIp() throws Exception { // given String ip = "127.0.0.1"; @@ -89,7 +84,7 @@ public void shouldNotLookUpCountryForLocalhostIp() throws Exception { } @Test - public void shouldLookUpCountryName() throws Exception { + void shouldLookUpCountryName() throws Exception { // given InetAddress ip = InetAddress.getByName("24.45.167.89"); String countryName = "Ecuador"; @@ -106,7 +101,7 @@ public void shouldLookUpCountryName() throws Exception { } @Test - public void shouldNotLookUpCountryNameForLocalhostIp() throws Exception { + void shouldNotLookUpCountryNameForLocalhostIp() throws Exception { // given InetAddress ip = InetAddress.getByName("127.0.0.1"); @@ -119,7 +114,7 @@ public void shouldNotLookUpCountryNameForLocalhostIp() throws Exception { } @Test - public void shouldNotLookUpCountryNameIfDisabled() throws Exception { + void shouldNotLookUpCountryNameIfDisabled() throws Exception { // given InetAddress ip = InetAddress.getByName("24.45.167.89"); given(settings.getProperty(ProtectionSettings.ENABLE_GEOIP)).willReturn(false); @@ -141,5 +136,3 @@ private static CountryResponse createCountryResponse(String countryCode, String return new CountryResponse(continent, country, null, country, null, null); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java index 9d66eec3c1..81d01402f4 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/HelpTranslationGeneratorIntegrationTest.java @@ -1,16 +1,12 @@ package fr.xephi.authme.service; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.command.CommandInitializer; import fr.xephi.authme.command.help.HelpMessage; import fr.xephi.authme.command.help.HelpMessagesService; import fr.xephi.authme.command.help.HelpSection; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.message.HelpMessagesFileHandler; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.PluginSettings; @@ -18,60 +14,60 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.BDDMockito.given; /** * Integration test for {@link HelpTranslationGenerator}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class HelpTranslationGeneratorIntegrationTest { +@ExtendWith(MockitoExtension.class) +class HelpTranslationGeneratorIntegrationTest { - @InjectDelayed private HelpTranslationGenerator helpTranslationGenerator; - @InjectDelayed - private HelpMessagesService helpMessagesService; - @InjectDelayed - private HelpMessagesFileHandler helpMessagesFileHandler; - @InjectDelayed - private CommandInitializer commandInitializer; - - @DataFolder - private File dataFolder; + + @TempDir + File dataFolder; private File helpMessagesFile; @Mock private Settings settings; - public TempFolder temporaryFolder = new TempFolder(); @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void setUpClasses() throws IOException { - dataFolder = temporaryFolder.newFolder(); + @BeforeEach + void setUpClasses() throws IOException { File messagesFolder = new File(dataFolder, "messages"); messagesFolder.mkdir(); helpMessagesFile = new File(messagesFolder, "help_test.yml"); Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "message/help_test.yml"), helpMessagesFile); given(settings.getProperty(PluginSettings.MESSAGES_LANGUAGE)).willReturn("test"); + + CommandInitializer commandInitializer = new CommandInitializer(); + HelpMessagesFileHandler helpMessagesFileHandler = new HelpMessagesFileHandler(dataFolder, settings); + HelpMessagesService helpMessagesService = new HelpMessagesService(helpMessagesFileHandler); + helpTranslationGenerator = new HelpTranslationGenerator(commandInitializer, helpMessagesService, settings, dataFolder); + ReflectionTestUtils.invokePostConstructMethods(helpMessagesFileHandler); } @Test - public void shouldUpdateCurrentHelpFile() throws IOException { + void shouldUpdateCurrentHelpFile() throws IOException { // given / when helpTranslationGenerator.updateHelpFile(); @@ -181,5 +177,3 @@ private static final class Argument { } } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java index fcfddde994..5f00f06557 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/MigrationServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.service; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; @@ -14,14 +10,16 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Locale; import static fr.xephi.authme.AuthMeMatchers.equalToHash; -import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -34,8 +32,7 @@ * Test for {@link MigrationService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class MigrationServiceTest { +class MigrationServiceTest { @Mock private Settings settings; @@ -47,12 +44,12 @@ public class MigrationServiceTest { private Sha256 sha256; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldMigratePlaintextHashes() { + void shouldMigratePlaintextHashes() { // given PlayerAuth auth1 = authWithNickAndHash("bobby", "test"); PlayerAuth auth2 = authWithNickAndHash("user", "myPassword"); @@ -78,7 +75,7 @@ public void shouldMigratePlaintextHashes() { } @Test - public void shouldNotMigrateShaHashes() { + void shouldNotMigrateShaHashes() { // given PlayerAuth auth1 = authWithNickAndHash("testUser", "abc1234"); PlayerAuth auth2 = authWithNickAndHash("minecraft", "$SHA$f28930ae09823eba4cd98a3"); @@ -100,7 +97,7 @@ public void shouldNotMigrateShaHashes() { } @Test - public void shouldNotMigrateForHashOtherThanPlaintext() { + void shouldNotMigrateForHashOtherThanPlaintext() { // given given(settings.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT); @@ -126,5 +123,3 @@ private static void setSha256MockToUppercase(Sha256 sha256) { }); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java index d6ced51ea4..5c0aad6214 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/PasswordRecoveryServiceTest.java @@ -1,9 +1,6 @@ package fr.xephi.authme.service; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.mail.EmailService; @@ -12,11 +9,15 @@ import fr.xephi.authme.security.PasswordSecurity; import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -24,10 +25,10 @@ /** * Tests for {@link PasswordRecoveryService}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class PasswordRecoveryServiceTest { +@ExtendWith(MockitoExtension.class) +class PasswordRecoveryServiceTest { - @InjectDelayed + @InjectMocks private PasswordRecoveryService recoveryService; @Mock @@ -48,14 +49,15 @@ public class PasswordRecoveryServiceTest { @Mock private Messages messages; - @BeforeInjecting - public void initSettings() { + @BeforeEach + void runPostConstructMethod() { given(commonService.getProperty(SecuritySettings.EMAIL_RECOVERY_COOLDOWN_SECONDS)).willReturn(40); given(commonService.getProperty(SecuritySettings.PASSWORD_CHANGE_TIMEOUT)).willReturn(2); + ReflectionTestUtils.invokePostConstructMethods(recoveryService); } @Test - public void shouldSendRecoveryCode() { + void shouldSendRecoveryCode() { // given Player player = mock(Player.class); String name = "Carl"; @@ -75,7 +77,7 @@ public void shouldSendRecoveryCode() { } @Test - public void shouldKeepTrackOfSuccessfulRecoversByIp() { + void shouldKeepTrackOfSuccessfulRecoversByIp() { // given Player bobby = mock(Player.class); TestHelper.mockIpAddressToPlayer(bobby, "192.168.8.8"); @@ -99,7 +101,7 @@ public void shouldKeepTrackOfSuccessfulRecoversByIp() { } @Test - public void shouldRemovePlayerFromSuccessfulRecovers() { + void shouldRemovePlayerFromSuccessfulRecovers() { // given Player bobby = mock(Player.class); TestHelper.mockIpAddressToPlayer(bobby, "192.168.8.8"); @@ -120,5 +122,3 @@ public void shouldRemovePlayerFromSuccessfulRecovers() { assertThat(recoveryService.canChangePassword(other), equalTo(false)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java index b3e43c6950..24765b0075 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/PluginHookServiceTest.java @@ -5,21 +5,22 @@ import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; - +import org.bukkit.plugin.java.JavaPlugin; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.File; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; @@ -30,7 +31,7 @@ /** * Test for {@link PluginHookService}. */ -public class PluginHookServiceTest { +class PluginHookServiceTest { /** The plugin name of Essentials. */ private static final String ESSENTIALS = "Essentials"; @@ -40,12 +41,12 @@ public class PluginHookServiceTest { private static final String MULTIVERSE = "Multiverse-Core"; @BeforeAll - public static void setLogger() { + static void setLogger() { TestHelper.setupLogger(); } @Test - public void shouldHookIntoEssentials() { + void shouldHookIntoEssentials() { // given PluginManager pluginManager = mock(PluginManager.class); PluginHookService pluginHookService = new PluginHookService(pluginManager); @@ -60,7 +61,7 @@ public void shouldHookIntoEssentials() { } @Test - public void shouldHookIntoEssentialsAtInitialization() { + void shouldHookIntoEssentialsAtInitialization() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, ESSENTIALS, Essentials.class); @@ -73,7 +74,7 @@ public void shouldHookIntoEssentialsAtInitialization() { } @Test - public void shouldHookIntoCmiAtInitialization() { + void shouldHookIntoCmiAtInitialization() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, CMI, Plugin.class); @@ -86,7 +87,7 @@ public void shouldHookIntoCmiAtInitialization() { } @Test - public void shouldHookIntoMultiverseAtInitialization() { + void shouldHookIntoMultiverseAtInitialization() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, MULTIVERSE, MultiverseCore.class); @@ -99,12 +100,13 @@ public void shouldHookIntoMultiverseAtInitialization() { } @Test - public void shouldReturnEssentialsDataFolder() { + void shouldReturnEssentialsDataFolder() { // given Essentials ess = mock(Essentials.class); File essDataFolder = new File("test/data-folder"); - // Need to stub getDataFolder() because getDataFolder() is declared final - given(ess.getDataFolder()).willReturn(essDataFolder); + // Need to set the data folder with reflections because getDataFolder() is declared final + ReflectionTestUtils.setField(JavaPlugin.class, ess, "dataFolder", essDataFolder); + given(ess.getDataFolder()).willCallRealMethod(); // Needed because static/final methods can be mocked PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, ESSENTIALS, ess); @@ -118,7 +120,7 @@ public void shouldReturnEssentialsDataFolder() { } @Test - public void shouldReturnNullForUnhookedEssentials() { + void shouldReturnNullForUnhookedEssentials() { // given PluginManager pluginManager = mock(PluginManager.class); PluginHookService pluginHookService = new PluginHookService(pluginManager); @@ -131,7 +133,7 @@ public void shouldReturnNullForUnhookedEssentials() { } @Test - public void shouldSetSocialSpyStatus() { + void shouldSetSocialSpyStatus() { // given Player player = mock(Player.class); @@ -152,7 +154,7 @@ public void shouldSetSocialSpyStatus() { } @Test - public void shouldNotDoAnythingForUnhookedEssentials() { + void shouldNotDoAnythingForUnhookedEssentials() { // given PluginHookService pluginHookService = new PluginHookService(mock(PluginManager.class)); @@ -161,7 +163,7 @@ public void shouldNotDoAnythingForUnhookedEssentials() { } @Test - public void shouldUnhookEssentialsAndMultiverse() { + void shouldUnhookEssentialsAndMultiverse() { // given PluginManager pluginManager = mock(PluginManager.class); setPluginAvailable(pluginManager, ESSENTIALS, Essentials.class); @@ -178,7 +180,7 @@ public void shouldUnhookEssentialsAndMultiverse() { } @Test - public void shouldHandlePluginRetrievalError() { + void shouldHandlePluginRetrievalError() { // given PluginManager pluginManager = mock(PluginManager.class); given(pluginManager.isPluginEnabled(anyString())).willReturn(true); @@ -194,7 +196,7 @@ public void shouldHandlePluginRetrievalError() { } @Test - public void shouldReturnNullForUnavailableMultiverse() { + void shouldReturnNullForUnavailableMultiverse() { // given PluginManager pluginManager = mock(PluginManager.class); PluginHookService pluginHookService = new PluginHookService(pluginManager); @@ -208,7 +210,7 @@ public void shouldReturnNullForUnavailableMultiverse() { } @Test - public void shouldGetMultiverseSpawn() { + void shouldGetMultiverseSpawn() { // given Location location = mock(Location.class); MultiverseWorld multiverseWorld = mock(MultiverseWorld.class); @@ -236,7 +238,7 @@ public void shouldGetMultiverseSpawn() { } @Test - public void shouldReturnNullForNonMvWorld() { + void shouldReturnNullForNonMvWorld() { // given World world = mock(World.class); MVWorldManager mvWorldManager = mock(MVWorldManager.class); @@ -268,4 +270,3 @@ private static void setPluginAvailable(PluginManager managerM } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/ProxyLoginRequestValidatorTest.java b/authme-core/src/test/java/fr/xephi/authme/service/ProxyLoginRequestValidatorTest.java index 84deda026d..1465bf0e2a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/ProxyLoginRequestValidatorTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/ProxyLoginRequestValidatorTest.java @@ -11,8 +11,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; import java.util.UUID; @@ -22,8 +20,10 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +/** + * Test for {@link ProxyLoginRequestValidator}. + */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) class ProxyLoginRequestValidatorTest { @InjectMocks diff --git a/authme-core/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java index 59faa6fda3..678a08aa2a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/RecoveryCodeServiceTest.java @@ -1,43 +1,43 @@ package fr.xephi.authme.service; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.util.expiring.ExpiringMap; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import static fr.xephi.authme.AuthMeMatchers.stringWithLength; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; /** * Test for {@link RecoveryCodeService}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class RecoveryCodeServiceTest { +@ExtendWith(MockitoExtension.class) +class RecoveryCodeServiceTest { - @InjectDelayed private RecoveryCodeService recoveryCodeService; @Mock private Settings settings; - @BeforeInjecting - public void initSettings() { + @BeforeEach + void initService() { given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(4); given(settings.getProperty(SecuritySettings.RECOVERY_CODE_LENGTH)).willReturn(5); given(settings.getProperty(SecuritySettings.RECOVERY_CODE_MAX_TRIES)).willReturn(3); + + recoveryCodeService = new RecoveryCodeService(settings); } @Test - public void shouldBeDisabledForNonPositiveLength() { + void shouldBeDisabledForNonPositiveLength() { assertThat(recoveryCodeService.isRecoveryCodeNeeded(), equalTo(true)); // given @@ -51,7 +51,7 @@ public void shouldBeDisabledForNonPositiveLength() { } @Test - public void shouldGenerateAndStoreCode() { + void shouldGenerateAndStoreCode() { // given String name = "Bobbers"; @@ -64,7 +64,7 @@ public void shouldGenerateAndStoreCode() { } @Test - public void playerHasTriesLeft() { + void playerHasTriesLeft() { // given String player = "Dusty"; recoveryCodeService.generateCode(player); @@ -77,7 +77,7 @@ public void playerHasTriesLeft() { } @Test - public void playerHasNoTriesLeft() { + void playerHasNoTriesLeft() { // given String player = "Dusty"; recoveryCodeService.generateCode(player); @@ -93,7 +93,7 @@ public void playerHasNoTriesLeft() { } @Test - public void shouldRecognizeCorrectCode() { + void shouldRecognizeCorrectCode() { // given String player = "dragon"; String code = recoveryCodeService.generateCode(player); @@ -106,7 +106,7 @@ public void shouldRecognizeCorrectCode() { } @Test - public void shouldRemoveCode() { + void shouldRemoveCode() { // given String player = "Tester"; String code = recoveryCodeService.generateCode(player); @@ -129,5 +129,3 @@ private ExpiringMap getTriesCounter() { return ReflectionTestUtils.getFieldValue(RecoveryCodeService.class, recoveryCodeService, "playerTries"); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/SessionServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/SessionServiceTest.java index c1c241224f..01cd1e9cf7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/SessionServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/SessionServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.service; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.datasource.DataSource; @@ -12,13 +8,16 @@ import fr.xephi.authme.settings.properties.PluginSettings; import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.function.Function; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -31,10 +30,9 @@ /** * Test for {@link SessionService}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class SessionServiceTest { +@ExtendWith(MockitoExtension.class) +class SessionServiceTest { - @InjectDelayed private SessionService sessionService; @Mock @@ -45,17 +43,18 @@ public class SessionServiceTest { private BukkitService bukkitService; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } - @BeforeInjecting - public void setUpEnabledProperty() { + @BeforeEach + void createSessionService() { given(commonService.getProperty(PluginSettings.SESSIONS_ENABLED)).willReturn(true); + sessionService = new SessionService(commonService, bukkitService, dataSource); } @Test - public void shouldCheckSessionsEnabledSetting() { + void shouldCheckSessionsEnabledSetting() { // given Player player = mock(Player.class); given(commonService.getProperty(PluginSettings.SESSIONS_ENABLED)).willReturn(false); @@ -70,7 +69,7 @@ public void shouldCheckSessionsEnabledSetting() { } @Test - public void shouldCheckIfUserHasSession() { + void shouldCheckIfUserHasSession() { // given String name = "Bobby"; Player player = mock(Player.class); @@ -87,7 +86,7 @@ public void shouldCheckIfUserHasSession() { } @Test - public void shouldCheckLastLoginDate() { + void shouldCheckLastLoginDate() { // given String name = "Bobby"; String ip = "127.3.12.15"; @@ -105,19 +104,16 @@ public void shouldCheckLastLoginDate() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); } @Test - public void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { + void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { // given String name = "Bobby"; String ip = "127.3.12.15"; Player player = mockPlayerWithNameAndIp(name, ip); - given(commonService.getProperty(PluginSettings.SESSIONS_TIMEOUT)).willReturn(8); given(dataSource.hasSession(name)).willReturn(true); PlayerAuth auth = PlayerAuth.builder() .name(name) @@ -130,14 +126,12 @@ public void shouldRefuseSessionForAuthWithNullLastLoginTimestamp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); } @Test - public void shouldCheckLastLoginIp() { + void shouldCheckLastLoginIp() { // given String name = "Bobby"; String ip = "127.3.12.15"; @@ -155,15 +149,13 @@ public void shouldCheckLastLoginIp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); verify(commonService).send(player, MessageKey.SESSION_EXPIRED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); } @Test - public void shouldEmitEventForValidSession() { + void shouldEmitEventForValidSession() { // given String name = "Bobby"; String ip = "127.3.12.15"; @@ -186,14 +178,13 @@ public void shouldEmitEventForValidSession() { verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); verify(commonService).getProperty(PluginSettings.SESSIONS_TIMEOUT); verifyNoMoreInteractions(commonService); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); verify(event).isCancelled(); } @Test - public void shouldHandleNullPlayerAuth() { + void shouldHandleNullPlayerAuth() { // given String name = "Bobby"; Player player = mockPlayerWithNameAndIp(name, "127.3.12.15"); @@ -205,15 +196,12 @@ public void shouldHandleNullPlayerAuth() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); - verify(dataSource).getAuth(name); } @Test - public void shouldHandlePlayerAuthWithNullLastIp() { + void shouldHandlePlayerAuthWithNullLastIp() { // given String name = "Charles"; Player player = mockPlayerWithNameAndIp(name, "144.117.118.145"); @@ -222,7 +210,7 @@ public void shouldHandlePlayerAuthWithNullLastIp() { PlayerAuth auth = PlayerAuth.builder() .name(name) .lastIp(null) - .lastLogin(System.currentTimeMillis()).build(); + .lastLogin(System.currentTimeMillis() - 2).build(); given(dataSource.getAuth(name)).willReturn(auth); // when @@ -230,11 +218,8 @@ public void shouldHandlePlayerAuthWithNullLastIp() { // then assertThat(result, equalTo(false)); - verify(commonService).getProperty(PluginSettings.SESSIONS_ENABLED); - verify(dataSource).hasSession(name); verify(dataSource).setUnlogged(name); verify(dataSource).revokeSession(name); - verify(dataSource).getAuth(name); } private static Player mockPlayerWithNameAndIp(String name, String ip) { @@ -244,5 +229,3 @@ private static Player mockPlayerWithNameAndIp(String name, String ip) { return player; } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java index 293f450380..af91f7dd73 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/TeleportationServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.service; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.data.auth.PlayerAuth; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.data.limbo.LimboPlayer; @@ -20,24 +16,23 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -45,8 +40,7 @@ * Test for {@link TeleportationService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class TeleportationServiceTest { +class TeleportationServiceTest { @InjectMocks private TeleportationService teleportationService; @@ -68,24 +62,21 @@ public class TeleportationServiceTest { @Mock private PlatformAdapter platformAdapter; - @Captor - private ArgumentCaptor locationCaptor; @BeforeEach - public void setUpForcedWorlds() { - lenient().when(settings.getProperty(RestrictionSettings.FORCE_SPAWN_ON_WORLDS)) - .thenReturn(Arrays.asList("forced1", "OtherForced")); + void setUpForcedWorlds() { + given(settings.getProperty(RestrictionSettings.FORCE_SPAWN_ON_WORLDS)) + .willReturn(Arrays.asList("forced1", "OtherForced")); teleportationService.reload(); - lenient().when(settings.getProperty(RestrictionSettings.NO_TELEPORT)).thenReturn(false); - lenient().when(settings.getProperty(RegistrationSettings.FORCE)).thenReturn(true); + given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(false); } // ----------- // JOINING // ----------- @Test - public void shouldNotTeleportPlayerOnJoin() { + void shouldNotTeleportPlayerOnJoin() { // given given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(true); Player player = mock(Player.class); @@ -99,14 +90,14 @@ public void shouldNotTeleportPlayerOnJoin() { } @Test - public void shouldTeleportPlayerToFirstSpawn() { + void shouldTeleportPlayerToFirstSpawn() { // given Player player = mock(Player.class); given(player.hasPlayedBefore()).willReturn(false); given(player.isOnline()).willReturn(true); Location firstSpawn = mockLocation(); given(spawnLoader.getFirstSpawn()).willReturn(firstSpawn); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportNewPlayerToFirstSpawn(player); @@ -119,14 +110,15 @@ public void shouldTeleportPlayerToFirstSpawn() { } @Test - public void shouldTeleportPlayerToSpawn() { + void shouldTeleportPlayerToSpawn() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); + given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); Player player = mock(Player.class); given(player.isOnline()).willReturn(true); Location spawn = mockLocation(); given(spawnLoader.getSpawnLocation(player)).willReturn(spawn); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnJoin(player); @@ -139,7 +131,7 @@ public void shouldTeleportPlayerToSpawn() { @Test // No first spawn defined, no teleport settings enabled - public void shouldNotTeleportNewPlayer() { + void shouldNotTeleportNewPlayer() { // given Player player = mock(Player.class); given(spawnLoader.getFirstSpawn()).willReturn(null); @@ -155,7 +147,7 @@ public void shouldNotTeleportNewPlayer() { } @Test - public void shouldNotTeleportPlayerToFirstSpawnIfNoTeleportEnabled() { + void shouldNotTeleportPlayerToFirstSpawnIfNoTeleportEnabled() { // given Player player = mock(Player.class); given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(true); @@ -169,7 +161,7 @@ public void shouldNotTeleportPlayerToFirstSpawnIfNoTeleportEnabled() { } @Test - public void shouldNotTeleportNotNewPlayerToFirstSpawn() { + void shouldNotTeleportNotNewPlayerToFirstSpawn() { // given Player player = mock(Player.class); given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(false); @@ -183,19 +175,20 @@ public void shouldNotTeleportNotNewPlayerToFirstSpawn() { } @Test - public void shouldNotTeleportPlayerForRemovedLocationInEvent() { + void shouldNotTeleportPlayerForRemovedLocationInEvent() { // given final Player player = mock(Player.class); Location spawn = mockLocation(); given(spawnLoader.getSpawnLocation(player)).willReturn(spawn); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); + given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); doAnswer(invocation -> { SpawnTeleportEvent event = (SpawnTeleportEvent) invocation.getArguments()[0]; assertThat(event.getPlayer(), equalTo(player)); event.setTo(null); return null; }).when(bukkitService).callEvent(any(SpawnTeleportEvent.class)); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnJoin(player); @@ -206,19 +199,20 @@ public void shouldNotTeleportPlayerForRemovedLocationInEvent() { } @Test - public void shouldNotTeleportPlayerForCanceledEvent() { + void shouldNotTeleportPlayerForCanceledEvent() { // given final Player player = mock(Player.class); Location spawn = mockLocation(); given(spawnLoader.getSpawnLocation(player)).willReturn(spawn); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); + given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); doAnswer(invocation -> { SpawnTeleportEvent event = (SpawnTeleportEvent) invocation.getArguments()[0]; assertThat(event.getPlayer(), equalTo(player)); event.setCancelled(true); return null; }).when(bukkitService).callEvent(any(SpawnTeleportEvent.class)); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnJoin(player); @@ -262,9 +256,10 @@ public void shouldNotTeleportUnregisteredPlayerViaPrepareOnJoinIfRegistrationOpt } @Test - public void shouldPrepareCustomSpawnLocationWithoutPlayerInstance() { + void shouldPrepareCustomSpawnLocationWithoutPlayerInstance() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); + given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); World world = mock(World.class); Location spawn = mockLocation(); given(spawnLoader.getSpawnLocation(world)).willReturn(spawn); @@ -279,9 +274,10 @@ public void shouldPrepareCustomSpawnLocationWithoutPlayerInstance() { } @Test - public void shouldRememberOriginalJoinLocationForAsyncJoinEvent() { + void shouldRememberOriginalJoinLocationForAsyncJoinEvent() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); + given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); World world = mock(World.class); Location originalSpawn = new Location(world, 1.0, 64.0, 1.0); Location spawn = mockLocation(); @@ -296,9 +292,10 @@ public void shouldRememberOriginalJoinLocationForAsyncJoinEvent() { } @Test - public void shouldUseModifiedSpawnLocationFromJoinEvent() { + void shouldUseModifiedSpawnLocationFromJoinEvent() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); + given(settings.getProperty(RegistrationSettings.FORCE)).willReturn(true); Player player = mock(Player.class); given(player.getName()).willReturn("Bobby"); Location originalSpawn = mockLocation(); @@ -321,7 +318,7 @@ public void shouldUseModifiedSpawnLocationFromJoinEvent() { // LOGIN // --------- @Test - public void shouldNotTeleportUponLogin() { + void shouldNotTeleportUponLogin() { // given given(settings.getProperty(RestrictionSettings.NO_TELEPORT)).willReturn(true); Player player = mock(Player.class); @@ -336,7 +333,7 @@ public void shouldNotTeleportUponLogin() { } @Test - public void shouldTeleportPlayerToSpawnAfterLogin() { + void shouldTeleportPlayerToSpawnAfterLogin() { // given given(settings.getProperty(RestrictionSettings.FORCE_SPAWN_LOCATION_AFTER_LOGIN)).willReturn(true); Player player = mock(Player.class); @@ -348,7 +345,7 @@ public void shouldTeleportPlayerToSpawnAfterLogin() { Location limboLocation = mockLocation(); given(limboLocation.getWorld().getName()).willReturn("forced1"); given(limbo.getLocation()).willReturn(limboLocation); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnLogin(player, auth, limbo); @@ -357,9 +354,9 @@ public void shouldTeleportPlayerToSpawnAfterLogin() { verify(platformAdapter).teleportPlayer(player, spawn); } - @Test // Check that the worlds for "force spawn loc after login" are case-sensitive - public void shouldNotTeleportToSpawnForOtherCaseInWorld() { + @Test + void shouldNotTeleportToSpawnForOtherCaseInWorld() { // given given(settings.getProperty(RestrictionSettings.FORCE_SPAWN_LOCATION_AFTER_LOGIN)).willReturn(true); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(false); @@ -380,7 +377,7 @@ public void shouldNotTeleportToSpawnForOtherCaseInWorld() { } @Test - public void shouldTeleportBackToPlayerAuthLocation() { + void shouldTeleportBackToPlayerAuthLocation() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -395,18 +392,19 @@ public void shouldTeleportBackToPlayerAuthLocation() { LimboPlayer limbo = mock(LimboPlayer.class); Location limboLocation = mockLocation(); given(limbo.getLocation()).willReturn(limboLocation); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnLogin(player, auth, limbo); // then + ArgumentCaptor locationCaptor = ArgumentCaptor.forClass(Location.class); verify(platformAdapter).teleportPlayer(eq(player), locationCaptor.capture()); assertCorrectLocation(locationCaptor.getValue(), auth, world); } @Test - public void shouldTeleportAccordingToPlayerAuthAndPlayerWorldAsFallback() { + void shouldTeleportAccordingToPlayerAuthAndPlayerWorldAsFallback() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -422,18 +420,19 @@ public void shouldTeleportAccordingToPlayerAuthAndPlayerWorldAsFallback() { LimboPlayer limbo = mock(LimboPlayer.class); Location limboLocation = mockLocation(); given(limbo.getLocation()).willReturn(limboLocation); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnLogin(player, auth, limbo); // then + ArgumentCaptor locationCaptor = ArgumentCaptor.forClass(Location.class); verify(platformAdapter).teleportPlayer(eq(player), locationCaptor.capture()); assertCorrectLocation(locationCaptor.getValue(), auth, world); } @Test - public void shouldNotTeleportIfPlayerIsAlreadyAtQuitLocation() { + void shouldNotTeleportIfPlayerIsAlreadyAtQuitLocation() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -457,7 +456,7 @@ public void shouldNotTeleportIfPlayerIsAlreadyAtQuitLocation() { } @Test - public void shouldUseRememberedJoinLocationIfQuitLocationIsStillAtSchemaDefaults() { + void shouldUseRememberedJoinLocationIfQuitLocationIsStillAtSchemaDefaults() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -471,19 +470,20 @@ public void shouldUseRememberedJoinLocationIfQuitLocationIsStillAtSchemaDefaults World world = mock(World.class); Location rememberedJoinLocation = new Location(world, 12.0, 70.0, -8.0); teleportationService.rememberOriginalJoinLocation("Bobby", rememberedJoinLocation); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnLogin(player, auth, null); // then + ArgumentCaptor locationCaptor = ArgumentCaptor.forClass(Location.class); verify(platformAdapter).teleportPlayer(eq(player), locationCaptor.capture()); assertThat(locationCaptor.getValue(), equalTo(rememberedJoinLocation)); verifyNoInteractions(spawnLoader); } @Test - public void shouldUseLimboLocationIfQuitLocationIsStillAtSchemaDefaults() { + void shouldUseLimboLocationIfQuitLocationIsStillAtSchemaDefaults() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(true); @@ -496,7 +496,7 @@ public void shouldUseLimboLocationIfQuitLocationIsStillAtSchemaDefaults() { LimboPlayer limbo = mock(LimboPlayer.class); Location limboLocation = mockLocation(); given(limbo.getLocation()).willReturn(limboLocation); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnLogin(player, auth, limbo); @@ -507,7 +507,7 @@ public void shouldUseLimboLocationIfQuitLocationIsStillAtSchemaDefaults() { } @Test - public void shouldTeleportWithLimboPlayerIfSaveQuitLocIsDisabled() { + void shouldTeleportWithLimboPlayerIfSaveQuitLocIsDisabled() { // given given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(false); @@ -518,7 +518,7 @@ public void shouldTeleportWithLimboPlayerIfSaveQuitLocIsDisabled() { LimboPlayer limbo = mock(LimboPlayer.class); Location location = mockLocation(); given(limbo.getLocation()).willReturn(location); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); // when teleportationService.teleportOnLogin(player, auth, limbo); @@ -528,7 +528,7 @@ public void shouldTeleportWithLimboPlayerIfSaveQuitLocIsDisabled() { } @Test - public void shouldNotTeleportForNullLocationInLimboPlayer() { + void shouldNotTeleportForNullLocationInLimboPlayer() { // given given(settings.getProperty(RestrictionSettings.SAVE_QUIT_LOCATION)).willReturn(false); given(settings.getProperty(RestrictionSettings.TELEPORT_UNAUTHED_TO_SPAWN)).willReturn(true); @@ -541,7 +541,7 @@ public void shouldNotTeleportForNullLocationInLimboPlayer() { teleportationService.teleportOnLogin(player, auth, limbo); // then - verify(player).getName(); + verifyNoInteractions(platformAdapter); verify(limbo).getLocation(); } @@ -563,7 +563,4 @@ private static PlayerAuth createAuthWithLocation() { .locX(123.45).locY(23.4).locZ(-4.567) .build(); } - } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java index 51e5d80565..45af82213a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/ValidationServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.service; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.base.Strings; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; @@ -18,11 +14,14 @@ import fr.xephi.authme.settings.properties.SecuritySettings; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetSocketAddress; import java.util.Collections; @@ -30,23 +29,24 @@ import static com.google.common.collect.Sets.newHashSet; import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Test for {@link ValidationService}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class ValidationServiceTest { +@ExtendWith(MockitoExtension.class) +class ValidationServiceTest { - @InjectDelayed + @InjectMocks private ValidationService validationService; @Mock private Settings settings; @@ -56,23 +56,17 @@ public class ValidationServiceTest { private PermissionsManager permissionsManager; @Mock private GeoIpService geoIpService; - @Captor - private ArgumentCaptor stringCaptor; - @BeforeInjecting - public void createService() { + @BeforeEach + void callReload() { given(settings.getProperty(RestrictionSettings.ALLOWED_PASSWORD_REGEX)).willReturn("[a-zA-Z]+"); - given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); - given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); - given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); - given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); - given(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES)).willReturn(newHashSet("name01", "npc")); given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(false); + validationService.reload(); } @Test - public void shouldRejectPasswordSameAsUsername() { - // given/when + void shouldRejectPasswordSameAsUsername() { + // given / when ValidationResult error = validationService.validatePassword("bobby", "Bobby"); // then @@ -80,8 +74,8 @@ public void shouldRejectPasswordSameAsUsername() { } @Test - public void shouldRejectPasswordNotMatchingPattern() { - // given/when + void shouldRejectPasswordNotMatchingPattern() { + // given / when // service mock returns pattern a-zA-Z -> numbers should not be accepted ValidationResult error = validationService.validatePassword("invalid1234", "myPlayer"); @@ -90,8 +84,11 @@ public void shouldRejectPasswordNotMatchingPattern() { } @Test - public void shouldRejectTooShortPassword() { - // given/when + void shouldRejectTooShortPassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + + // when ValidationResult error = validationService.validatePassword("ab", "tester"); // then @@ -99,8 +96,12 @@ public void shouldRejectTooShortPassword() { } @Test - public void shouldRejectTooLongPassword() { - // given/when + void shouldRejectTooLongPassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + + // when ValidationResult error = validationService.validatePassword(Strings.repeat("a", 30), "player"); // then @@ -108,8 +109,13 @@ public void shouldRejectTooLongPassword() { } @Test - public void shouldRejectUnsafePassword() { - // given/when + void shouldRejectUnsafePassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); + + // when ValidationResult error = validationService.validatePassword("unsafe", "playertest"); // then @@ -117,8 +123,13 @@ public void shouldRejectUnsafePassword() { } @Test - public void shouldAcceptValidPassword() { - // given/when + void shouldAcceptValidPassword() { + // given + given(settings.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(3); + given(settings.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(20); + given(settings.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).willReturn(newHashSet("unsafe", "other-unsafe")); + + // when ValidationResult error = validationService.validatePassword("safePass", "some_user"); // then @@ -126,7 +137,7 @@ public void shouldAcceptValidPassword() { } @Test - public void shouldAcceptEmailWithEmptyLists() { + void shouldAcceptEmailWithEmptyLists() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); @@ -139,11 +150,10 @@ public void shouldAcceptEmailWithEmptyLists() { } @Test - public void shouldAcceptEmailWithWhitelist() { + void shouldAcceptEmailWithWhitelist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)) .willReturn(asList("domain.tld", "example.com")); - given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); // when boolean result = validationService.validateEmail("TesT@Example.com"); @@ -153,11 +163,10 @@ public void shouldAcceptEmailWithWhitelist() { } @Test - public void shouldRejectEmailNotInWhitelist() { + void shouldRejectEmailNotInWhitelist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)) .willReturn(asList("domain.tld", "example.com")); - given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)).willReturn(Collections.emptyList()); // when boolean result = validationService.validateEmail("email@other-domain.abc"); @@ -167,7 +176,7 @@ public void shouldRejectEmailNotInWhitelist() { } @Test - public void shouldAcceptEmailNotInBlacklist() { + void shouldAcceptEmailNotInBlacklist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)) @@ -181,7 +190,7 @@ public void shouldAcceptEmailNotInBlacklist() { } @Test - public void shouldRejectEmailInBlacklist() { + void shouldRejectEmailInBlacklist() { // given given(settings.getProperty(EmailSettings.DOMAIN_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(EmailSettings.DOMAIN_BLACKLIST)) @@ -195,31 +204,32 @@ public void shouldRejectEmailInBlacklist() { } @Test - public void shouldRejectInvalidEmail() { - // given/when/then + void shouldRejectInvalidEmail() { + // given / when / then assertThat(validationService.validateEmail("invalidinput"), equalTo(false)); } @Test - public void shouldRejectInvalidEmailWithoutDomain() { - // given/when/then + void shouldRejectInvalidEmailWithoutDomain() { + // given / when / then assertThat(validationService.validateEmail("invalidinput@"), equalTo(false)); } @Test - public void shouldRejectDefaultEmail() { - // given/when/then + void shouldRejectDefaultEmail() { + // given / when / then assertThat(validationService.validateEmail("your@email.com"), equalTo(false)); } @Test - public void shouldAllowRegistration() { + void shouldAllowRegistration() { // given CommandSender sender = mock(CommandSender.class); String email = "my.address@example.org"; given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(false); given(dataSource.countAuthsByEmail(email)).willReturn(2); + given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); @@ -229,13 +239,14 @@ public void shouldAllowRegistration() { } @Test - public void shouldRejectEmailWithTooManyAccounts() { + void shouldRejectEmailWithTooManyAccounts() { // given CommandSender sender = mock(CommandSender.class); String email = "mail@example.org"; given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(false); given(dataSource.countAuthsByEmail(email)).willReturn(5); + given(settings.getProperty(EmailSettings.MAX_REG_PER_EMAIL)).willReturn(3); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); @@ -245,23 +256,27 @@ public void shouldRejectEmailWithTooManyAccounts() { } @Test - public void shouldAllowBypassForPresentPermission() { + void shouldAllowBypassForPresentPermission() { // given CommandSender sender = mock(CommandSender.class); String email = "mail-address@example.com"; given(permissionsManager.hasPermission(sender, PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS)) .willReturn(true); - given(dataSource.countAuthsByEmail(email)).willReturn(7); // when boolean result = validationService.isEmailFreeForRegistration(email, sender); // then + verifyNoInteractions(dataSource); assertThat(result, equalTo(true)); } @Test - public void shouldRecognizeUnrestrictedNames() { + void shouldRecognizeUnrestrictedNames() { + // given + given(settings.getProperty(RestrictionSettings.UNRESTRICTED_NAMES)).willReturn(newHashSet("name01", "npc")); + + // when / then assertThat(validationService.isUnrestricted("npc"), equalTo(true)); assertThat(validationService.isUnrestricted("someplayer"), equalTo(false)); assertThat(validationService.isUnrestricted("NAME01"), equalTo(true)); @@ -274,7 +289,7 @@ public void shouldRecognizeUnrestrictedNames() { } @Test - public void shouldNotInvokeGeoLiteApiIfCountryListsAreEmpty() { + void shouldNotInvokeGeoLiteApiIfCountryListsAreEmpty() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); @@ -288,10 +303,9 @@ public void shouldNotInvokeGeoLiteApiIfCountryListsAreEmpty() { } @Test - public void shouldAcceptCountryInWhitelist() { + void shouldAcceptCountryInWhitelist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(asList("ch", "it")); - given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); String ip = "127.0.0.1"; given(geoIpService.getCountryCode(ip)).willReturn("CH"); @@ -300,14 +314,12 @@ public void shouldAcceptCountryInWhitelist() { // then assertThat(result, equalTo(true)); - verify(geoIpService).getCountryCode(ip); } @Test - public void shouldRejectCountryMissingFromWhitelist() { + void shouldRejectCountryMissingFromWhitelist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(asList("ch", "it")); - given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(Collections.emptyList()); String ip = "123.45.67.89"; given(geoIpService.getCountryCode(ip)).willReturn("BR"); @@ -316,11 +328,10 @@ public void shouldRejectCountryMissingFromWhitelist() { // then assertThat(result, equalTo(false)); - verify(geoIpService).getCountryCode(ip); } @Test - public void shouldAcceptCountryAbsentFromBlacklist() { + void shouldAcceptCountryAbsentFromBlacklist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(asList("ch", "it")); @@ -336,7 +347,7 @@ public void shouldAcceptCountryAbsentFromBlacklist() { } @Test - public void shouldRejectCountryInBlacklist() { + void shouldRejectCountryInBlacklist() { // given given(settings.getProperty(ProtectionSettings.COUNTRIES_WHITELIST)).willReturn(Collections.emptyList()); given(settings.getProperty(ProtectionSettings.COUNTRIES_BLACKLIST)).willReturn(asList("ch", "it")); @@ -348,11 +359,10 @@ public void shouldRejectCountryInBlacklist() { // then assertThat(result, equalTo(false)); - verify(geoIpService).getCountryCode(ip); } @Test - public void shouldCheckNameRestrictions() { + void shouldCheckNameRestrictions() { // given given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(true); given(settings.getProperty(RestrictionSettings.RESTRICTED_USERS)) @@ -366,7 +376,8 @@ public void shouldCheckNameRestrictions() { Player emanuel = mockPlayer("emanuel", "94.65.24.10"); Player emanuel2 = mockPlayer("emanuel", "94.65.60.10"); Player imYourIsp = mockPlayer("imyourisp", "65.65.65.65"); - Player notRestricted = mockPlayer("notRestricted", "0.0.0.0"); + Player notRestricted = mock(Player.class); + given(notRestricted.getName()).willReturn("notRestricted"); ValidationService validationServiceSpy = Mockito.spy(validationService); willReturn("bogus.tld").given(validationServiceSpy).getHostName(any(InetSocketAddress.class)); @@ -392,10 +403,11 @@ public void shouldCheckNameRestrictions() { assertThat(isEmanuel2Admitted, equalTo(false)); assertThat(isImYourIspAdmitted, equalTo(true)); assertThat(isNotRestrictedAdmitted, equalTo(true)); + verify(notRestricted, only()).getName(); } @Test - public void shouldLogWarningForInvalidRestrictionRule() { + void shouldLogWarningForInvalidRestrictionRule() { // given Logger logger = TestHelper.setupLogger(); given(settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)).willReturn(true); @@ -406,6 +418,7 @@ public void shouldLogWarningForInvalidRestrictionRule() { validationService.reload(); // then + ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); verify(logger).warning(stringCaptor.capture()); assertThat(stringCaptor.getValue(), containsString("Tamara;")); } @@ -423,5 +436,3 @@ private static void assertErrorEquals(ValidationResult validationResult, Message assertThat(validationResult.getArgs(), equalTo(args)); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/service/bungeecord/BungeeReceiverTest.java b/authme-core/src/test/java/fr/xephi/authme/service/bungeecord/BungeeReceiverTest.java index aee27609b3..17a0256d67 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/bungeecord/BungeeReceiverTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/bungeecord/BungeeReceiverTest.java @@ -27,7 +27,7 @@ import java.util.UUID; import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously; -import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; @@ -182,7 +182,7 @@ void shouldFinalizePremiumLoginWhenValidateAcceptsVerifiedUuid() { given(settings.getProperty(HooksSettings.PROXY_SHARED_SECRET)).willReturn(sharedSecret); given(messenger.isIncomingChannelRegistered(plugin, "authme:main")).willReturn(false); setBukkitServiceToRunTaskAsynchronously(bukkitService); - setBukkitServiceToScheduleSyncTaskFromOptionallyAsyncTask(bukkitService); + setBukkitServiceToScheduleSyncEntityTaskFromOptionallyAsyncTask(bukkitService); Player player = mock(Player.class); given(player.isOnline()).willReturn(true); diff --git a/authme-core/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java b/authme-core/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java index ffc42baa55..78ad541c6b 100644 --- a/authme-core/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/service/yaml/YamlFileResourceProviderTest.java @@ -7,18 +7,18 @@ import java.io.File; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; /** * Test for {@link YamlFileResourceProvider}. */ -public class YamlFileResourceProviderTest { +class YamlFileResourceProviderTest { @Test - public void shouldLoadValidFile() { + void shouldLoadValidFile() { // given File yamlFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "service/yaml/validYaml.yml"); @@ -30,7 +30,7 @@ public void shouldLoadValidFile() { } @Test - public void shouldThrowForInvalidFile() { + void shouldThrowForInvalidFile() { // given File yamlFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "service/yaml/invalidYaml.yml"); @@ -46,4 +46,3 @@ public void shouldThrowForInvalidFile() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java index e6d26482a5..528d5b048c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsConsistencyTest.java @@ -23,7 +23,7 @@ /** * Tests the consistency of the settings configuration. */ -public class SettingsConsistencyTest { +class SettingsConsistencyTest { /** * Maximum characters one comment line may have (prevents horizontal scrolling). @@ -39,12 +39,12 @@ public class SettingsConsistencyTest { private static ConfigurationData configurationData; @BeforeAll - public static void buildConfigurationData() { + static void buildConfigurationData() { configurationData = AuthMeSettingsRetriever.buildConfigurationData(); } @Test - public void shouldHaveCommentOnEachProperty() { + void shouldHaveCommentOnEachProperty() { // given List> properties = configurationData.getProperties(); @@ -57,7 +57,7 @@ public void shouldHaveCommentOnEachProperty() { } @Test - public void shouldNotHaveVeryLongCommentLines() { + void shouldNotHaveVeryLongCommentLines() { // given Map> commentEntries = configurationData.getAllComments(); List badPaths = new ArrayList<>(0); @@ -86,7 +86,7 @@ public void shouldNotHaveVeryLongCommentLines() { * so the user knows which values are available. */ @Test - public void shouldMentionAllEnumValues() { + void shouldMentionAllEnumValues() { // given Map, Enum> invalidEnumProperties = new HashMap<>(); @@ -138,4 +138,3 @@ private static boolean isDeprecated(Enum enumValue) { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java index 760139ddbd..be401584ca 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsIntegrationTest.java @@ -11,10 +11,9 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.properties.TestConfiguration; import fr.xephi.authme.settings.properties.TestEnum; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -23,13 +22,13 @@ import java.util.Map; import static fr.xephi.authme.TestHelper.getJarFile; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Integration test for {@link Settings} (ConfigMe integration). */ -public class SettingsIntegrationTest { +class SettingsIntegrationTest { /** File name of the sample config including all {@link TestConfiguration} values. */ private static final String COMPLETE_FILE = TestHelper.PROJECT_ROOT + "settings/config-sample-values.yml"; @@ -38,26 +37,21 @@ public class SettingsIntegrationTest { private static ConfigurationData CONFIG_DATA = ConfigurationDataBuilder.createConfiguration(TestConfiguration.class); - public TempFolder temporaryFolder = new TempFolder(); - private File testPluginFolder; + @TempDir + File testPluginFolder; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } - @BeforeEach - public void setUpTestPluginFolder() throws IOException { - testPluginFolder = temporaryFolder.newFolder(); - } - @Test - public void shouldLoadAndReadAllProperties() throws IOException { + void shouldLoadAndReadAllProperties() throws IOException { // given PropertyResource resource = new YamlFileResource(copyFileFromResources(COMPLETE_FILE)); // Pass another, non-existent file to check if the settings had to be rewritten - File newFile = temporaryFolder.newFile(); + File newFile = TestHelper.createFile(testPluginFolder, "newfile"); // when / then Settings settings = new Settings(testPluginFolder, resource, @@ -82,7 +76,7 @@ public void shouldLoadAndReadAllProperties() throws IOException { } @Test - public void shouldWriteMissingProperties() { + void shouldWriteMissingProperties() { // given/when File file = copyFileFromResources(INCOMPLETE_FILE); PropertyResource resource = new YamlFileResource(file); @@ -114,9 +108,9 @@ public void shouldWriteMissingProperties() { } @Test - public void shouldReloadSettings() throws IOException { + void shouldReloadSettings() throws IOException { // given - File configFile = temporaryFolder.newFile(); + File configFile = TestHelper.createFile(testPluginFolder, "settings"); PropertyResource resource = new YamlFileResource(configFile); Settings settings = new Settings(testPluginFolder, resource, null, CONFIG_DATA); @@ -132,7 +126,7 @@ public void shouldReloadSettings() throws IOException { private File copyFileFromResources(String path) { try { File source = getJarFile(path); - File destination = temporaryFolder.newFile(); + File destination = TestHelper.createFile(testPluginFolder, "fileFromJar"); Files.copy(source, destination); return destination; } catch (IOException e) { @@ -141,5 +135,3 @@ private File copyFileFromResources(String path) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java index cd5b72e377..a2e2a6840c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsMigrationServiceTest.java @@ -14,7 +14,7 @@ import fr.xephi.authme.settings.properties.AuthMeSettingsRetriever; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -36,28 +36,29 @@ import static fr.xephi.authme.settings.properties.RestrictionSettings.FORCE_SPAWN_ON_WORLDS; import static fr.xephi.authme.settings.properties.SecuritySettings.LEGACY_HASHES; import static fr.xephi.authme.settings.properties.SecuritySettings.PASSWORD_HASH; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link SettingsMigrationService}. */ -public class SettingsMigrationServiceTest { +class SettingsMigrationServiceTest { private static final String OLD_CONFIG_FILE = TestHelper.PROJECT_ROOT + "settings/config-old.yml"; - public TempFolder temporaryFolder = new TempFolder(); + + @TempDir + File dataFolder; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } /* When settings are loaded, test that migrations are applied and immediately available in memory. */ @Test - public void shouldPerformMigrationsInMemory() throws IOException { + void shouldPerformMigrationsInMemory() throws IOException { // given - File dataFolder = temporaryFolder.newFolder(); File configFile = new File(dataFolder, "config.yml"); Files.copy(getJarFile(OLD_CONFIG_FILE), configFile); PropertyResource resource = new YamlFileResource(configFile); @@ -76,9 +77,8 @@ public void shouldPerformMigrationsInMemory() throws IOException { * i.e. when the settings are loaded again from the file, no migrations should be necessary. */ @Test - public void shouldPerformMigrationsAndPersistToDisk() throws IOException { + void shouldPerformMigrationsAndPersistToDisk() throws IOException { // given - File dataFolder = temporaryFolder.newFolder(); File configFile = new File(dataFolder, "config.yml"); Files.copy(getJarFile(OLD_CONFIG_FILE), configFile); PropertyResource resource = new YamlFileResource(configFile); @@ -96,9 +96,8 @@ public void shouldPerformMigrationsAndPersistToDisk() throws IOException { } @Test - public void shouldKeepOldOtherAccountsSettings() throws IOException { + void shouldKeepOldOtherAccountsSettings() throws IOException { // given - File dataFolder = temporaryFolder.newFolder(); File configFile = new File(dataFolder, "config.yml"); Files.copy(getJarFile(OLD_CONFIG_FILE), configFile); PropertyResource resource = new YamlFileResource(configFile); @@ -150,5 +149,3 @@ protected boolean performMigrations(PropertyReader reader, ConfigurationData con } } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsTest.java index 962f3b1ab3..c8cc12fb45 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsTest.java @@ -6,18 +6,17 @@ import ch.jalu.configme.resource.PropertyResource; import fr.xephi.authme.TestHelper; import fr.xephi.authme.settings.properties.TestConfiguration; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Collections; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; @@ -26,25 +25,21 @@ /** * Unit tests for {@link Settings}. */ -public class SettingsTest { +class SettingsTest { private static final ConfigurationData CONFIG_DATA = ConfigurationDataBuilder.createConfiguration(TestConfiguration.class); - public TempFolder temporaryFolder = new TempFolder(); - private File testPluginFolder; + + @TempDir + File testPluginFolder; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } - @BeforeEach - public void setUpTestPluginFolder() throws IOException { - testPluginFolder = temporaryFolder.newFolder(); - } - @Test - public void shouldLoadEmailMessage() throws IOException { + void shouldLoadEmailMessage() throws IOException { // given String emailMessage = "Sample email message\nThat's all!"; File emailFile = new File(testPluginFolder, "email.html"); @@ -62,7 +57,7 @@ public void shouldLoadEmailMessage() throws IOException { } @Test - public void shouldLoadRecoveryCodeMessage() throws IOException { + void shouldLoadRecoveryCodeMessage() throws IOException { // given String emailMessage = "Your recovery code is %code."; File emailFile = new File(testPluginFolder, "recovery_code_email.html"); @@ -80,7 +75,7 @@ public void shouldLoadRecoveryCodeMessage() throws IOException { } @Test - public void shouldLoadVerificationMessage() throws IOException { + void shouldLoadVerificationMessage() throws IOException { // given String emailMessage = "Please verify your identity with ."; File emailFile = new File(testPluginFolder, "verification_code_email.html"); @@ -115,5 +110,3 @@ private static void createFile(File file) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java index 61ff0b18ce..54621b2c67 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/SettingsWarnerTest.java @@ -1,19 +1,14 @@ package fr.xephi.authme.settings; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.AuthMe; import fr.xephi.authme.TestHelper; -import fr.xephi.authme.security.HashAlgorithm; import fr.xephi.authme.settings.properties.EmailSettings; import fr.xephi.authme.settings.properties.PluginSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; -import fr.xephi.authme.settings.properties.SecuritySettings; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.logging.Logger; @@ -21,14 +16,13 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.times; +import static org.mockito.internal.verification.VerificationModeFactory.times; /** * Test for {@link SettingsWarner}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class SettingsWarnerTest { +class SettingsWarnerTest { @InjectMocks private SettingsWarner settingsWarner; @@ -37,7 +31,7 @@ public class SettingsWarnerTest { private Settings settings; @Test - public void shouldLogWarnings() { + void shouldLogWarnings() { // given Logger logger = TestHelper.setupLogger(); given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(false); @@ -45,7 +39,6 @@ public void shouldLogWarnings() { given(settings.getProperty(EmailSettings.PORT25_USE_TLS)).willReturn(false); given(settings.getProperty(PluginSettings.SESSIONS_ENABLED)).willReturn(true); given(settings.getProperty(PluginSettings.SESSIONS_TIMEOUT)).willReturn(-5); - given(settings.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.BCRYPT); // when settingsWarner.logWarningsForMisconfigurations(); @@ -55,13 +48,13 @@ public void shouldLogWarnings() { } @Test - public void shouldNotLogAnyWarning() { + void shouldNotLogAnyWarning() { + // given Logger logger = TestHelper.setupLogger(); given(settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)).willReturn(true); given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(25); given(settings.getProperty(EmailSettings.PORT25_USE_TLS)).willReturn(false); given(settings.getProperty(PluginSettings.SESSIONS_ENABLED)).willReturn(false); - given(settings.getProperty(SecuritySettings.PASSWORD_HASH)).willReturn(HashAlgorithm.MD5); // when settingsWarner.logWarningsForMisconfigurations(); @@ -70,5 +63,3 @@ public void shouldNotLogAnyWarning() { verifyNoInteractions(logger); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java index f217c04758..c922c717ed 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/SpawnLoaderTest.java @@ -1,39 +1,38 @@ package fr.xephi.authme.settings; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.platform.TeleportAdapter; import fr.xephi.authme.service.PluginHookService; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.Bukkit; +import org.bukkit.GameRule; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.mockito.ArgumentMatchers; import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; import java.util.List; -import org.bukkit.GameRule; - +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; @@ -41,10 +40,9 @@ /** * Test for {@link SpawnLoader}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class SpawnLoaderTest { +@ExtendWith(MockitoExtension.class) +class SpawnLoaderTest { - @InjectDelayed private SpawnLoader spawnLoader; @Mock @@ -55,17 +53,18 @@ public class SpawnLoaderTest { @Mock private TeleportAdapter teleportAdapter; - public TempFolder temporaryFolder = new TempFolder(); - @DataFolder - private File testFolder; + @TempDir + File testFolder; - @BeforeInjecting - public void setup() throws IOException { + @BeforeAll + static void setUpLogger() { TestHelper.setupLogger(); + } + @BeforeEach + void setup() throws IOException { // Copy test config into a new temporary folder - testFolder = temporaryFolder.newFolder(); File source = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/spawn-firstspawn.yml"); File destination = new File(testFolder, "spawn.yml"); Files.copy(source, destination); @@ -73,10 +72,11 @@ public void setup() throws IOException { // Create a settings mock with default values given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)) .willReturn("authme, essentials, multiverse, default"); + spawnLoader = new SpawnLoader(testFolder, settings, pluginHookService, teleportAdapter); } @Test - public void shouldSetSpawn() { + void shouldSetSpawn() { // given World world = mock(World.class); given(world.getName()).willReturn("new_world"); @@ -95,7 +95,7 @@ public void shouldSetSpawn() { } @Test - public void shouldReturnBedSpawnLocationForDeadPlayer() { + void shouldReturnBedSpawnLocationForDeadPlayer() { // given Player player = mock(Player.class); given(player.getHealth()).willReturn(0.0); @@ -111,7 +111,7 @@ public void shouldReturnBedSpawnLocationForDeadPlayer() { } @Test - public void shouldFallbackToConfiguredSpawnIfDeadPlayerHasNoRespawnLocation() { + void shouldFallbackToConfiguredSpawnIfDeadPlayerHasNoRespawnLocation() { // given given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)).willReturn("default"); spawnLoader.reload(); @@ -132,7 +132,7 @@ public void shouldFallbackToConfiguredSpawnIfDeadPlayerHasNoRespawnLocation() { } @Test - public void shouldReturnExactWorldSpawnForServerPriorityWithZeroRadius() { + void shouldReturnExactWorldSpawnForServerPriorityWithZeroRadius() { // given given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)).willReturn("server"); spawnLoader.reload(); @@ -150,7 +150,7 @@ public void shouldReturnExactWorldSpawnForServerPriorityWithZeroRadius() { } @Test - public void shouldReturnExactYAndFaceTowardCenterWhenBaseYIsAlreadySafe() { + void shouldReturnExactYAndFaceTowardCenterWhenBaseYIsAlreadySafe() { // given given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)).willReturn("server"); spawnLoader.reload(); @@ -164,9 +164,9 @@ public void shouldReturnExactYAndFaceTowardCenterWhenBaseYIsAlreadySafe() { Block passable = mock(Block.class); given(passable.isPassable()).willReturn(true); - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(64), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(64), anyInt())) .willReturn(passable); - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(65), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(65), anyInt())) .willReturn(passable); // when @@ -183,7 +183,7 @@ public void shouldReturnExactYAndFaceTowardCenterWhenBaseYIsAlreadySafe() { } @Test - public void shouldSearchDownwardWhenBaseYIsInAVoid() { + void shouldSearchDownwardWhenBaseYIsInAVoid() { // given – foot at baseY is passable but head (baseY+1) is solid (1-block-high gap, e.g. near Nether ceiling) given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)).willReturn("server"); spawnLoader.reload(); @@ -199,12 +199,12 @@ public void shouldSearchDownwardWhenBaseYIsInAVoid() { given(solid.isPassable()).willReturn(false); // y=70 passable, y=71 solid → initial check fails; foot is passable → search downward - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(70), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(70), anyInt())) .willReturn(passable); - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(71), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(71), anyInt())) .willReturn(solid); // y=69 passable → isPassable(69) && isPassable(70) = true → safe at y=69 - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(69), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(69), anyInt())) .willReturn(passable); // when @@ -215,7 +215,7 @@ public void shouldSearchDownwardWhenBaseYIsInAVoid() { } @Test - public void shouldSearchUpwardWhenBaseYIsInsideASolidBlock() { + void shouldSearchUpwardWhenBaseYIsInsideASolidBlock() { // given – baseY is inside a solid block (e.g. underground) given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)).willReturn("server"); spawnLoader.reload(); @@ -231,16 +231,16 @@ public void shouldSearchUpwardWhenBaseYIsInsideASolidBlock() { given(solid.isPassable()).willReturn(false); // y=60 is solid → search upward - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(60), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(60), anyInt())) .willReturn(solid); // y=61 solid, y=62 solid, y=63 passable, y=64 passable → safe at y=63 - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(61), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(61), anyInt())) .willReturn(solid); - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(62), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(62), anyInt())) .willReturn(solid); - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(63), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(63), anyInt())) .willReturn(passable); - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.eq(64), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), eq(64), anyInt())) .willReturn(passable); // when @@ -251,7 +251,7 @@ public void shouldSearchUpwardWhenBaseYIsInsideASolidBlock() { } @Test - public void shouldFallbackToExactWorldSpawnWhenNoSafeSpotFoundWithinMargin() { + void shouldFallbackToExactWorldSpawnWhenNoSafeSpotFoundWithinMargin() { // given given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)).willReturn("server"); spawnLoader.reload(); @@ -263,7 +263,7 @@ public void shouldFallbackToExactWorldSpawnWhenNoSafeSpotFoundWithinMargin() { Block solid = mock(Block.class); given(solid.isPassable()).willReturn(false); - given(world.getBlockAt(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())) + given(world.getBlockAt(anyInt(), anyInt(), anyInt())) .willReturn(solid); // when @@ -274,7 +274,7 @@ public void shouldFallbackToExactWorldSpawnWhenNoSafeSpotFoundWithinMargin() { } @Test - public void shouldIgnoreNullCandidateWorldSpawnLocations() { + void shouldIgnoreNullCandidateWorldSpawnLocations() { // given given(settings.getProperty(RestrictionSettings.SPAWN_PRIORITY)).willReturn("default"); spawnLoader.reload(); @@ -298,5 +298,3 @@ public void shouldIgnoreNullCandidateWorldSpawnLocations() { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java index 558a198fc7..4e7496428c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/WelcomeMessageConfigurationTest.java @@ -1,12 +1,8 @@ package fr.xephi.authme.settings; -import org.junit.jupiter.api.extension.ExtendWith; -import fr.xephi.authme.DelayedInjectionExtension; -import ch.jalu.injector.testing.BeforeInjecting; -import ch.jalu.injector.testing.InjectDelayed; +import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; -import fr.xephi.authme.initialization.DataFolder; import fr.xephi.authme.service.BukkitService; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.service.GeoIpService; @@ -15,9 +11,13 @@ import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; @@ -25,10 +25,10 @@ import java.util.Arrays; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -36,10 +36,10 @@ /** * Test for {@link WelcomeMessageConfiguration}. */ -@ExtendWith(DelayedInjectionExtension.class) -public class WelcomeMessageConfigurationTest { +@ExtendWith(MockitoExtension.class) +class WelcomeMessageConfigurationTest { - @InjectDelayed + @InjectMocks private WelcomeMessageConfiguration welcomeMessageConfiguration; @Mock private Server server; @@ -51,22 +51,21 @@ public class WelcomeMessageConfigurationTest { private PlayerCache playerCache; @Mock private CommonService service; - @DataFolder - private File testPluginFolder; + @TempDir + File testPluginFolder; private File welcomeFile; - public TempFolder temporaryFolder = new TempFolder(); - @BeforeInjecting - public void createPluginFolder() throws IOException { - testPluginFolder = temporaryFolder.newFolder(); + @BeforeEach + void createWelcomeFileAndSetPluginFolder() throws IOException { welcomeFile = new File(testPluginFolder, "welcome.txt"); welcomeFile.createNewFile(); given(service.getProperty(RegistrationSettings.USE_WELCOME_MESSAGE)).willReturn(true); + ReflectionTestUtils.setField(welcomeMessageConfiguration, "pluginFolder", testPluginFolder); } @Test - public void shouldLoadWelcomeMessage() { + void shouldLoadWelcomeMessage() { // given String welcomeMessage = "This is my welcome message for testing\nBye!"; setWelcomeMessageAndReload(welcomeMessage); @@ -82,7 +81,7 @@ public void shouldLoadWelcomeMessage() { } @Test - public void shouldReplaceNameAndIpAndCountry() { + void shouldReplaceNameAndIpAndCountry() { // given String welcomeMessage = "Hello {PLAYER}, your IP is {IP}\nYour country is {COUNTRY}.\nWelcome to {SERVER}!"; setWelcomeMessageAndReload(welcomeMessage); @@ -105,7 +104,7 @@ public void shouldReplaceNameAndIpAndCountry() { } @Test - public void shouldApplyOtherReplacements() { + void shouldApplyOtherReplacements() { // given String welcomeMessage = "{ONLINE}/{MAXPLAYERS} online\n{LOGINS} logged in\nYour world is {WORLD}\nServer: {VERSION}"; setWelcomeMessageAndReload(welcomeMessage); @@ -139,5 +138,3 @@ private void setWelcomeMessageAndReload(String welcomeMessage) { welcomeMessageConfiguration.reload(); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java index 5ad1d4bac1..ef222576c2 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandManagerTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.settings.commandconfig; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import com.google.common.io.Files; import fr.xephi.authme.TestHelper; import fr.xephi.authme.service.BukkitService; @@ -13,19 +9,21 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; +import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.times; @@ -37,8 +35,7 @@ * Test for {@link CommandManager}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class CommandManagerTest { +class CommandManagerTest { private static final String TEST_FILES_FOLDER = "/fr/xephi/authme/settings/commandconfig/"; @@ -54,22 +51,23 @@ public class CommandManagerTest { private GeoIpService geoIpService; @Mock private SettingsMigrationService settingsMigrationService; - public TempFolder temporaryFolder = new TempFolder(); - private File testFolder; + @TempDir + File temporaryFolder; @BeforeEach - public void setup() throws IOException { - testFolder = temporaryFolder.newFolder(); - player = mockPlayer(); - BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + void setup() { + player = mock(Player.class); + given(player.getName()).willReturn("Bobby"); } @Test - public void shouldExecuteCommandsOnLogin() { + void shouldExecuteCommandsOnLogin() { // given + TestHelper.mockIpAddressToPlayer(player, "127.0.0.3"); copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); + setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); // when manager.runCommandsOnLogin(player, Collections.emptyList()); @@ -85,10 +83,12 @@ public void shouldExecuteCommandsOnLogin() { } @Test - public void shouldExecuteCommandsOnLoginWithTwoAlts() { + void shouldExecuteCommandsOnLoginWithTwoAlts() { // given + TestHelper.mockIpAddressToPlayer(player, "127.0.0.3"); copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); + setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); // when manager.runCommandsOnLogin(player, Arrays.asList("willy", "nilly", "billy", "silly")); @@ -106,10 +106,12 @@ public void shouldExecuteCommandsOnLoginWithTwoAlts() { } @Test - public void shouldExecuteCommandsOnLoginWithFifteenAlts() { + void shouldExecuteCommandsOnLoginWithFifteenAlts() { // given + TestHelper.mockIpAddressToPlayer(player, "127.0.0.3"); copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); + setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); // when manager.runCommandsOnLogin(player, Collections.nCopies(15, "swag")); @@ -129,10 +131,12 @@ public void shouldExecuteCommandsOnLoginWithFifteenAlts() { } @Test - public void shouldExecuteCommandsOnLoginWithTwentyFiveAlts() { + void shouldExecuteCommandsOnLoginWithTwentyFiveAlts() { // given + TestHelper.mockIpAddressToPlayer(player, "127.0.0.3"); copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); + setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); // when manager.runCommandsOnLogin(player, Collections.nCopies(25, "yolo")); @@ -150,11 +154,12 @@ public void shouldExecuteCommandsOnLoginWithTwentyFiveAlts() { } @Test - public void shouldExecuteCommandsOnLoginWithIncompleteConfig() { + void shouldExecuteCommandsOnLoginWithIncompleteConfig() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); - BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithDelay(bukkitService); + BukkitServiceTestHelper.setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); + given(player.getDisplayName()).willReturn("bob"); // when manager.runCommandsOnLogin(player, Collections.emptyList()); @@ -168,7 +173,7 @@ public void shouldExecuteCommandsOnLoginWithIncompleteConfig() { } @Test - public void shouldExecuteCommandsOnSessionLogin() { + void shouldExecuteCommandsOnSessionLogin() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); @@ -183,7 +188,7 @@ public void shouldExecuteCommandsOnSessionLogin() { } @Test - public void shouldExecuteCommandsOnFirstLogin() { + void shouldExecuteCommandsOnFirstLogin() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); @@ -198,7 +203,7 @@ public void shouldExecuteCommandsOnFirstLogin() { } @Test - public void shouldNotExecuteFirstLoginCommandWhoseThresholdIsNotMet() { + void shouldNotExecuteFirstLoginCommandWhoseThresholdIsNotMet() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); @@ -211,10 +216,12 @@ public void shouldNotExecuteFirstLoginCommandWhoseThresholdIsNotMet() { } @Test - public void shouldExecuteCommandsOnJoin() { + void shouldExecuteCommandsOnJoin() { // given + player.getName(); // Prevent UnnecessaryStubbingException as the name is not needed copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); + given(player.getDisplayName()).willReturn("bob"); // when manager.runCommandsOnJoin(player); @@ -225,7 +232,7 @@ public void shouldExecuteCommandsOnJoin() { } @Test - public void shouldExecuteCommandsOnJoinWithIncompleteConfig() { + void shouldExecuteCommandsOnJoinWithIncompleteConfig() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); @@ -239,10 +246,13 @@ public void shouldExecuteCommandsOnJoinWithIncompleteConfig() { } @Test - public void shouldExecuteCommandsOnRegister() { + void shouldExecuteCommandsOnRegister() { // given + TestHelper.mockIpAddressToPlayer(player, "127.0.0.3"); copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); + setBukkitServiceToScheduleSyncDelayedTaskWithEntityAndDelay(bukkitService); + given(geoIpService.getCountryName("127.0.0.3")).willReturn("Syldavia"); // when manager.runCommandsOnRegister(player); @@ -255,8 +265,9 @@ public void shouldExecuteCommandsOnRegister() { } @Test - public void shouldExecuteCommandOnLogout() { + void shouldExecuteCommandOnLogout() { // given + TestHelper.mockIpAddressToPlayer(player, "127.0.0.3"); copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.complete.yml"); initManager(); @@ -270,8 +281,9 @@ public void shouldExecuteCommandOnLogout() { } @Test - public void shouldExecuteCommandsOnRegisterWithIncompleteConfig() { + void shouldExecuteCommandsOnRegisterWithIncompleteConfig() { // given + player.getName(); // Prevent UnnecessaryStubbingException as the name is not needed copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); @@ -283,7 +295,7 @@ public void shouldExecuteCommandsOnRegisterWithIncompleteConfig() { } @Test - public void shouldExecuteCommandOnUnregister() { + void shouldExecuteCommandOnUnregister() { // given copyJarFileAsCommandsYml(TEST_FILES_FOLDER + "commands.incomplete.yml"); initManager(); @@ -296,28 +308,16 @@ public void shouldExecuteCommandOnUnregister() { } private void initManager() { - manager = new CommandManager(testFolder, bukkitService, geoIpService, commandMigrationService); + manager = new CommandManager(temporaryFolder, bukkitService, geoIpService, commandMigrationService); } private void copyJarFileAsCommandsYml(String path) { File source = TestHelper.getJarFile(path); - File destination = new File(testFolder, "commands.yml"); + File destination = new File(temporaryFolder, "commands.yml"); try { Files.copy(source, destination); } catch (IOException e) { throw new IllegalStateException(e); } } - - private Player mockPlayer() { - Player player = mock(Player.class); - lenient().when(player.getName()).thenReturn("Bobby"); - lenient().when(player.getDisplayName()).thenReturn("bob"); - String ip = "127.0.0.3"; - TestHelper.mockIpAddressToPlayer(player, ip); - lenient().when(geoIpService.getCountryName(ip)).thenReturn("Syldavia"); - return player; - } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java index a3816d0cdb..094b04983a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/settings/commandconfig/CommandMigrationServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.settings.commandconfig; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.configme.beanmapper.propertydescription.BeanDescriptionFactoryImpl; import ch.jalu.configme.beanmapper.propertydescription.BeanPropertyDescription; import ch.jalu.configme.configurationdata.ConfigurationData; @@ -14,8 +10,10 @@ import fr.xephi.authme.settings.SettingsMigrationService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.util.List; @@ -24,18 +22,17 @@ import java.util.stream.Collectors; import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.aMapWithSize; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; /** * Test for {@link CommandMigrationService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class CommandMigrationServiceTest { +class CommandMigrationServiceTest { @InjectMocks private CommandMigrationService commandMigrationService; @@ -44,12 +41,12 @@ public class CommandMigrationServiceTest { private SettingsMigrationService settingsMigrationService; @BeforeAll - public static void setUpLogger() { + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldRewriteForEmptyFile() { + void shouldRewriteForEmptyFile() { // given File commandFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/commandconfig/commands.empty.yml"); PropertyResource resource = new YamlFileResource(commandFile); @@ -63,7 +60,7 @@ public void shouldRewriteForEmptyFile() { } @Test - public void shouldRewriteIncompleteFile() { + void shouldRewriteIncompleteFile() { // given File commandFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/commandconfig/commands.incomplete.yml"); PropertyResource resource = new YamlFileResource(commandFile); @@ -77,7 +74,7 @@ public void shouldRewriteIncompleteFile() { } @Test - public void shouldNotChangeCompleteFile() { + void shouldNotChangeCompleteFile() { // given File commandFile = TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "settings/commandconfig/commands.complete.yml"); PropertyResource resource = new YamlFileResource(commandFile); @@ -95,7 +92,7 @@ public void shouldNotChangeCompleteFile() { * {@link CommandConfig} class. It is used to ensure that the commands.yml file is complete. */ @Test - public void shouldHaveAllPropertiesFromCommandConfig() { + void shouldHaveAllPropertiesFromCommandConfig() { // given String[] properties = new BeanDescriptionFactoryImpl() .getAllProperties(CommandConfig.class) @@ -108,7 +105,7 @@ public void shouldHaveAllPropertiesFromCommandConfig() { } @Test - public void shouldMigrateOldOtherAccountsCommand() { + void shouldMigrateOldOtherAccountsCommand() { // given given(settingsMigrationService.hasOldOtherAccountsCommand()).willReturn(true); given(settingsMigrationService.getOldOtherAccountsCommand()) @@ -147,5 +144,3 @@ private static OnLoginCommand getUnknownOnLoginCommand(Map> classes; @BeforeAll - public static void scanForSettingsClasses() { + static void scanForSettingsClasses() { ClassCollector collector = new ClassCollector(TestHelper.SOURCES_FOLDER, SETTINGS_FOLDER); classes = collector.collectClasses(SettingsHolder.class); @@ -44,7 +44,7 @@ public static void scanForSettingsClasses() { * Make sure that all {@link Property} instances we define are in public, static, final fields. */ @Test - public void shouldHavePublicStaticFinalFields() { + void shouldHavePublicStaticFinalFields() { for (Class clazz : classes) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { @@ -61,7 +61,7 @@ public void shouldHavePublicStaticFinalFields() { * Make sure that no properties use the same path. */ @Test - public void shouldHaveUniquePaths() { + void shouldHaveUniquePaths() { Set paths = new HashSet<>(); for (Class clazz : classes) { Field[] fields = clazz.getDeclaredFields(); @@ -82,7 +82,7 @@ public void shouldHaveUniquePaths() { * available SettingsHolder classes. */ @Test - public void shouldHaveAllClassesInConfigurationData() { + void shouldHaveAllClassesInConfigurationData() { // given long totalProperties = classes.stream() .map(Class::getDeclaredFields) @@ -103,4 +103,3 @@ private static boolean isValidConstantField(Field field) { return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java b/authme-core/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java index 6d61073c26..2ddb2e696f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/task/CleanupTaskTest.java @@ -1,14 +1,12 @@ package fr.xephi.authme.task; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import ch.jalu.injector.factory.SingletonStore; import fr.xephi.authme.initialization.HasCleanup; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; @@ -21,8 +19,7 @@ * Test for {@link CleanupTask}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class CleanupTaskTest { +class CleanupTaskTest { @InjectMocks private CleanupTask cleanupTask; @@ -31,7 +28,7 @@ public class CleanupTaskTest { private SingletonStore hasCleanupStore; @Test - public void shouldPerformCleanup() { + void shouldPerformCleanup() { // given List services = asList(mock(HasCleanup.class), mock(HasCleanup.class), mock(HasCleanup.class)); given(hasCleanupStore.retrieveAllOfType()).willReturn(services); @@ -45,5 +42,3 @@ public void shouldPerformCleanup() { verify(services.get(2)).performCleanup(); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java b/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java index 7920b9bb56..ea00b48934 100644 --- a/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeServiceTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.task.purge; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.datasource.DataSource; @@ -16,10 +12,11 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.Calendar; @@ -29,12 +26,12 @@ import java.util.UUID; import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; @@ -49,8 +46,7 @@ * Test for {@link PurgeService}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PurgeServiceTest { +class PurgeServiceTest { @InjectMocks private PurgeService purgeService; @@ -65,18 +61,14 @@ public class PurgeServiceTest { private PermissionsManager permissionsManager; @Mock private PurgeExecutor executor; - @Captor - private ArgumentCaptor longCaptor; - @Captor - private ArgumentCaptor purgeTaskCaptor; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldNotRunAutoPurge() { + void shouldNotRunAutoPurge() { // given given(settings.getProperty(PurgeSettings.USE_AUTO_PURGE)).willReturn(false); given(settings.getProperty(PurgeSettings.DAYS_BEFORE_REMOVE_PLAYER)).willReturn(60); @@ -89,7 +81,7 @@ public void shouldNotRunAutoPurge() { } @Test - public void shouldNotRunAutoPurgeForInvalidInterval() { + void shouldNotRunAutoPurgeForInvalidInterval() { // given given(settings.getProperty(PurgeSettings.USE_AUTO_PURGE)).willReturn(true); given(settings.getProperty(PurgeSettings.DAYS_BEFORE_REMOVE_PLAYER)).willReturn(0); @@ -102,7 +94,7 @@ public void shouldNotRunAutoPurgeForInvalidInterval() { } @Test - public void shouldRunAutoPurge() { + void shouldRunAutoPurge() { // given given(settings.getProperty(PurgeSettings.USE_AUTO_PURGE)).willReturn(true); given(settings.getProperty(PurgeSettings.DAYS_BEFORE_REMOVE_PLAYER)).willReturn(60); @@ -113,15 +105,16 @@ public void shouldRunAutoPurge() { purgeService.runAutoPurge(); // then - verify(dataSource).getRecordsToPurge(longCaptor.capture()); - assertCorrectPurgeTimestamp(longCaptor.getValue(), 60); + ArgumentCaptor captor = ArgumentCaptor.forClass(Long.class); + verify(dataSource).getRecordsToPurge(captor.capture()); + assertCorrectPurgeTimestamp(captor.getValue(), 60); assertThat(Boolean.TRUE, equalTo( ReflectionTestUtils.getFieldValue(PurgeService.class, purgeService, "isPurging"))); verifyScheduledPurgeTask(null, playerNames); } @Test - public void shouldRecognizeNoPlayersToPurge() { + void shouldRecognizeNoPlayersToPurge() { // given final long delay = 123012301L; given(dataSource.getRecordsToPurge(delay)).willReturn(Collections.emptySet()); @@ -138,7 +131,7 @@ public void shouldRecognizeNoPlayersToPurge() { } @Test - public void shouldRunPurge() { + void shouldRunPurge() { // given final long delay = 1809714L; Set playerNames = newHashSet("charlie", "delta", "echo", "foxtrot"); @@ -156,7 +149,7 @@ public void shouldRunPurge() { } @Test - public void shouldNotRunPurgeIfProcessIsAlreadyRunning() { + void shouldNotRunPurgeIfProcessIsAlreadyRunning() { // given purgeService.setPurging(true); CommandSender sender = mock(CommandSender.class); @@ -171,7 +164,7 @@ public void shouldNotRunPurgeIfProcessIsAlreadyRunning() { } @Test - public void shouldExecutePurgeActions() { + void shouldExecutePurgeActions() { // given List names = Arrays.asList("alpha", "bravo", "foxtrot"); List offlinePlayers = Arrays.asList( @@ -195,8 +188,9 @@ private void assertCorrectPurgeTimestamp(long timestamp, int configuredDays) { } private void verifyScheduledPurgeTask(UUID senderUuid, Set names) { - verify(bukkitService).runTaskTimerAsynchronously(purgeTaskCaptor.capture(), eq(0L), eq(1L)); - PurgeTask task = (PurgeTask) purgeTaskCaptor.getValue(); + ArgumentCaptor captor = ArgumentCaptor.forClass(PurgeTask.class); + verify(bukkitService).runTaskTimerAsynchronously(captor.capture(), eq(0L), eq(1L)); + PurgeTask task = captor.getValue(); Object senderInTask = ReflectionTestUtils.getFieldValue(PurgeTask.class, task, "sender"); Set namesInTask = ReflectionTestUtils.getFieldValue(PurgeTask.class, task, "toPurge"); @@ -204,5 +198,3 @@ private void verifyScheduledPurgeTask(UUID senderUuid, Set names) { assertThat(namesInTask, containsInAnyOrder(names.toArray())); } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java b/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java index 6e910071e7..a3d3b22606 100644 --- a/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/task/purge/PurgeTaskTest.java @@ -1,9 +1,5 @@ package fr.xephi.authme.task.purge; -import org.mockito.quality.Strictness; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.junit.jupiter.MockitoExtension; -import org.junit.jupiter.api.extension.ExtendWith; import fr.xephi.authme.ReflectionTestUtils; import fr.xephi.authme.TestHelper; import fr.xephi.authme.permission.PermissionNode; @@ -17,10 +13,11 @@ import org.bukkit.entity.Player; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import java.util.ArrayList; @@ -32,10 +29,10 @@ import java.util.UUID; import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; -import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -51,8 +48,7 @@ * Test for {@link PurgeTask}. */ @ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.WARN) -public class PurgeTaskTest { +class PurgeTaskTest { private static final PermissionNode BYPASS_NODE = PlayerStatePermission.BYPASS_PURGE; @@ -71,12 +67,12 @@ public class PurgeTaskTest { private ArgumentCaptor> namesCaptor; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldRunTask() { + void shouldRunTask() { // given Set names = newHashSet("alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india"); @@ -114,8 +110,9 @@ public void shouldRunTask() { // given (3) // Third round: no more OfflinePlayer objects, but some names remain reset(purgeService, permissionsManager); + // TODO LJ given(permissionsManager.hasPermissionOffline(anyString(), eq(BYPASS_NODE))).willReturn(false); given(permissionsManager.hasPermissionOffline("india", BYPASS_NODE)).willReturn(true); - given(permissionsManager.hasPermissionOffline("foxtrot", BYPASS_NODE)).willReturn(false); + given(permissionsManager.hasPermissionOffline("foxtrot", BYPASS_NODE)).willReturn(false); // TODO LJ ^ instead of above possible? // when (3) task.run(); @@ -131,7 +128,7 @@ public void shouldRunTask() { * #1008: OfflinePlayer#getName may return null. */ @Test - public void shouldHandleOfflinePlayerWithNullName() { + void shouldHandleOfflinePlayerWithNullName() { // given Set names = newHashSet("name1", "name2"); OfflinePlayer[] players = asArray( @@ -149,7 +146,7 @@ public void shouldHandleOfflinePlayerWithNullName() { } @Test - public void shouldStopTaskAndInformSenderUponCompletion() { + void shouldStopTaskAndInformSenderUponCompletion() { // given Set names = newHashSet("name1", "name2"); Player sender = mock(Player.class); @@ -174,7 +171,7 @@ public void shouldStopTaskAndInformSenderUponCompletion() { } @Test - public void shouldStopTaskAndInformConsoleUser() { + void shouldStopTaskAndInformConsoleUser() { // given Set names = newHashSet("name1", "name2"); PurgeTask task = new PurgeTask(purgeService, permissionsManager, null, names, new OfflinePlayer[0]); @@ -239,5 +236,3 @@ private void assertRanPurgeWithNames(String... names) { } } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java index 26022c2790..0a435f2700 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/ExceptionUtilsTest.java @@ -1,23 +1,22 @@ package fr.xephi.authme.util; -import fr.xephi.authme.ReflectionTestUtils; import org.junit.jupiter.api.Test; import java.net.MalformedURLException; import java.util.ConcurrentModificationException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link ExceptionUtils}. */ -public class ExceptionUtilsTest { +class ExceptionUtilsTest { @Test - public void shouldFindWantedThrowable() { + void shouldFindWantedThrowable() { // given ConcurrentModificationException initialCme = new ConcurrentModificationException(); Throwable th = new Throwable(initialCme); @@ -38,7 +37,7 @@ public void shouldFindWantedThrowable() { } @Test - public void shouldHandleCircularCausesGracefully() { + void shouldHandleCircularCausesGracefully() { // given ExceptionWithSettableCause exceptionWithSettableCause = new ExceptionWithSettableCause(); UnsupportedOperationException uoe = new UnsupportedOperationException(exceptionWithSettableCause); @@ -55,7 +54,7 @@ public void shouldHandleCircularCausesGracefully() { } @Test - public void shouldFormatException() { + void shouldFormatException() { // given MalformedURLException ex = new MalformedURLException("Unrecognized URL format"); @@ -76,4 +75,3 @@ public synchronized Throwable getCause() { } } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/FileUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/FileUtilsTest.java index d82b7c23a1..d8882b2e57 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/FileUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/FileUtilsTest.java @@ -4,36 +4,37 @@ import fr.xephi.authme.TestHelper; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import fr.xephi.authme.TempFolder; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link FileUtils}. */ -public class FileUtilsTest { +class FileUtilsTest { /** Regex that matches timestamps such as 20180211_1048. */ private static final String BACKUP_TIMESTAMP_PATTERN = "20\\d{6}_\\d{4}"; @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } - public TempFolder temporaryFolder = new TempFolder(); + + @TempDir + File temporaryFolder; @Test - public void shouldNotCopyFile() throws IOException { + void shouldNotCopyFile() throws IOException { // given - File folder = temporaryFolder.newFolder(); - File file = new File(folder, "config.yml"); + File file = new File(temporaryFolder, "config.yml"); // purposely don't copy config.yml to verify that config.yml isn't copied by the method File emailJarFile = TestHelper.getJarFile("/email.html"); Files.copy(emailJarFile, file); @@ -47,10 +48,9 @@ public void shouldNotCopyFile() throws IOException { } @Test - public void shouldCopyFileFromJar() throws IOException { + void shouldCopyFileFromJar() { // given - File folder = temporaryFolder.newFolder(); - File file = new File(folder, "some/folders/welcome.txt"); + File file = new File(temporaryFolder, "some/folders/welcome.txt"); // when boolean result = FileUtils.copyFileFromResource(file, "welcome.txt"); @@ -63,10 +63,9 @@ public void shouldCopyFileFromJar() throws IOException { } @Test - public void shouldReturnFalseForInvalidJarFile() throws IOException { + void shouldReturnFalseForInvalidJarFile() { // given - File folder = temporaryFolder.newFolder(); - File file = new File(folder, "bogus"); + File file = new File(temporaryFolder, "bogus"); // when boolean result = FileUtils.copyFileFromResource(file, "does-not-exist"); @@ -77,11 +76,10 @@ public void shouldReturnFalseForInvalidJarFile() throws IOException { } @Test - public void shouldReturnFalseForParentInvalidParentFolders() throws IOException { + void shouldReturnFalseForParentInvalidParentFolders() throws IOException { // given - File folder = temporaryFolder.newFolder(); - new File(folder, "hello").createNewFile(); - File fileToCreate = new File(folder, "hello/test"); + new File(temporaryFolder, "hello").createNewFile(); + File fileToCreate = new File(temporaryFolder, "hello/test"); // when boolean result = FileUtils.copyFileFromResource(fileToCreate, "welcome.txt"); @@ -91,30 +89,29 @@ public void shouldReturnFalseForParentInvalidParentFolders() throws IOException } @Test - public void shouldPurgeDirectory() throws IOException { + void shouldPurgeDirectory() throws IOException { // given - File root = temporaryFolder.newFolder(); - File file1 = new File(root, "a/b/c/test.html"); - File file2 = new File(root, "a/b/f/toast.txt"); - File file3 = new File(root, "a/g/rest.png"); - File file4 = new File(root, "j/l/roast.tiff"); + File file1 = new File(temporaryFolder, "a/b/c/test.html"); + File file2 = new File(temporaryFolder, "a/b/f/toast.txt"); + File file3 = new File(temporaryFolder, "a/g/rest.png"); + File file4 = new File(temporaryFolder, "j/l/roast.tiff"); createFiles(file1, file2, file3, file4); // when - FileUtils.purgeDirectory(new File(root, "a")); + FileUtils.purgeDirectory(new File(temporaryFolder, "a")); // then assertThat(file1.exists(), equalTo(false)); assertThat(file2.exists(), equalTo(false)); assertThat(file3.exists(), equalTo(false)); assertThat(file4.exists(), equalTo(true)); - assertThat(new File(root, "a").exists(), equalTo(true)); + assertThat(new File(temporaryFolder, "a").exists(), equalTo(true)); } @Test - public void shouldDeleteFile() throws IOException { + void shouldDeleteFile() throws IOException { // given - File file = temporaryFolder.newFile(); + File file = TestHelper.createFile(temporaryFolder, "tempFile"); assertThat(file.exists(), equalTo(true)); // when @@ -125,7 +122,7 @@ public void shouldDeleteFile() throws IOException { } @Test - public void shouldDoNothingForNullFile() { + void shouldDoNothingForNullFile() { // given File file = null; @@ -137,14 +134,14 @@ public void shouldDoNothingForNullFile() { } @Test - public void shouldGetResourceFromJar() { + void shouldGetResourceFromJar() { // given / when / then assertThat(FileUtils.getResourceFromJar("config.yml"), not(nullValue())); assertThat(FileUtils.getResourceFromJar("does-not-exist"), nullValue()); } @Test - public void shouldConstructPath() { + void shouldConstructPath() { // given/when String result = FileUtils.makePath("path", "to", "test-file.txt"); @@ -153,10 +150,9 @@ public void shouldConstructPath() { } @Test - public void shouldCreateDirectory() throws IOException { + void shouldCreateDirectory() { // given - File root = temporaryFolder.newFolder(); - File dir = new File(root, "folder/folder2/myFolder"); + File dir = new File(temporaryFolder, "folder/folder2/myFolder"); // when boolean result = FileUtils.createDirectory(dir); @@ -168,10 +164,9 @@ public void shouldCreateDirectory() throws IOException { } @Test - public void shouldReturnFalseOnDirectoryCreateFail() throws IOException { + void shouldReturnFalseOnDirectoryCreateFail() throws IOException { // given - File root = temporaryFolder.newFolder(); - File dirAsFile = new File(root, "file"); + File dirAsFile = new File(temporaryFolder, "file"); dirAsFile.createNewFile(); // when @@ -183,7 +178,7 @@ public void shouldReturnFalseOnDirectoryCreateFail() throws IOException { } @Test - public void shouldCreateCurrentTimestampString() { + void shouldCreateCurrentTimestampString() { // given / when String currentTimeString = FileUtils.createCurrentTimeString(); @@ -192,7 +187,7 @@ public void shouldCreateCurrentTimestampString() { } @Test - public void shouldCreateBackupFile() { + void shouldCreateBackupFile() { // given File file = new File("some/folders/config.yml"); @@ -212,7 +207,4 @@ private static void createFiles(File... files) throws IOException { } } } - } - - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java index 44e4246e18..e290406868 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java @@ -2,16 +2,16 @@ import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link InternetProtocolUtils} */ -public class InternetProtocolUtilsTest { +class InternetProtocolUtilsTest { @Test - public void shouldCheckLocalAddress() { + void shouldCheckLocalAddress() { // loopback assertThat(InternetProtocolUtils.isLocalAddress("localhost"), equalTo(true)); assertThat(InternetProtocolUtils.isLocalAddress("127.0.0.1"), equalTo(true)); @@ -43,11 +43,10 @@ public void shouldCheckLocalAddress() { } @Test - public void testIsLoopback() { + void shouldRecognizeLoopbackAddresses() { // loopback assertThat(InternetProtocolUtils.isLoopbackAddress("localhost"), equalTo(true)); assertThat(InternetProtocolUtils.isLoopbackAddress("127.0.0.1"), equalTo(true)); assertThat(InternetProtocolUtils.isLoopbackAddress("::1"), equalTo(true)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java index f8bf06e5bf..a76b35b951 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/PlayerUtilsTest.java @@ -5,23 +5,23 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test for {@link PlayerUtils}. */ -public class PlayerUtilsTest { +class PlayerUtilsTest { @BeforeAll - public static void setAuthmeInstance() { + static void setUpLogger() { TestHelper.setupLogger(); } @Test - public void shouldGetPlayerIp() { + void shouldGetPlayerIp() { // given Player player = mock(Player.class); String ip = "124.86.248.62"; @@ -35,7 +35,7 @@ public void shouldGetPlayerIp() { } @Test - public void shouldCheckIfIsNpc() { + void shouldCheckIfIsNpc() { // given Player player1 = mock(Player.class); given(player1.hasMetadata("NPC")).willReturn(false); @@ -51,4 +51,3 @@ public void shouldCheckIfIsNpc() { assertThat(result2, equalTo(true)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java index 05c24e9713..20eacb697a 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java @@ -4,17 +4,17 @@ import java.util.regex.Pattern; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test for {@link RandomStringUtils}. */ -public class RandomStringUtilsTest { +class RandomStringUtilsTest { @Test - public void shouldGenerateRandomStrings() { + void shouldGenerateRandomStrings() { // given int[] lengths = {0, 1, 19, 142, 1872}; Pattern badChars = Pattern.compile(".*[^0-9a-z].*"); @@ -30,7 +30,7 @@ public void shouldGenerateRandomStrings() { } @Test - public void shouldGenerateRandomHexString() { + void shouldGenerateRandomHexString() { // given int[] lengths = {0, 1, 21, 160, 1784}; Pattern badChars = Pattern.compile(".*[^0-9a-f].*"); @@ -46,7 +46,7 @@ public void shouldGenerateRandomHexString() { } @Test - public void shouldGenerateRandomLowerUpperString() { + void shouldGenerateRandomLowerUpperString() { // given int[] lengths = {0, 1, 17, 143, 1808}; Pattern badChars = Pattern.compile(".*[^0-9a-zA-Z].*"); @@ -62,7 +62,7 @@ public void shouldGenerateRandomLowerUpperString() { } @Test - public void shouldGenerateRandomNumberString() { + void shouldGenerateRandomNumberString() { // given int[] lengths = {0, 1, 18, 147, 1833}; Pattern badChars = Pattern.compile(".*[^0-9].*"); @@ -78,8 +78,9 @@ public void shouldGenerateRandomNumberString() { } @Test - public void shouldThrowForInvalidLength() { - assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.generate(-3)); + void shouldThrowForInvalidLength() { + // given / when / then + assertThrows(IllegalArgumentException.class, + () -> RandomStringUtils.generate(-3)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/StringUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/StringUtilsTest.java index 6451b09625..436bfc5454 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/StringUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/StringUtilsTest.java @@ -3,19 +3,19 @@ import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test for {@link StringUtils}. */ -public class StringUtilsTest { +class StringUtilsTest { @Test - public void shouldFindContainedItem() { + void shouldFindContainedItem() { // given String text = "This is a test of containsAny()"; String piece = "test"; @@ -28,7 +28,7 @@ public void shouldFindContainedItem() { } @Test - public void shouldReturnFalseIfNoneFound() { + void shouldReturnFalseIfNoneFound() { // given String text = "This is a test string"; @@ -40,7 +40,7 @@ public void shouldReturnFalseIfNoneFound() { } @Test - public void shouldReturnFalseForNullString() { + void shouldReturnFalseForNullString() { // given/when boolean result = StringUtils.containsAny(null, asList("some", "words", "to", "check")); @@ -49,7 +49,7 @@ public void shouldReturnFalseForNullString() { } @Test - public void shouldCheckIfIsBlankString() { + void shouldCheckIfIsBlankString() { // Should be true for null/empty/whitespace assertTrue(StringUtils.isBlank(null)); assertTrue(StringUtils.isBlank("")); @@ -61,7 +61,7 @@ public void shouldCheckIfIsBlankString() { } @Test - public void shouldGetDifferenceWithNullString() { + void shouldGetDifferenceWithNullString() { // given/when/then assertThat(StringUtils.getDifference(null, "test"), equalTo(1.0)); assertThat(StringUtils.getDifference("test", null), equalTo(1.0)); @@ -69,7 +69,7 @@ public void shouldGetDifferenceWithNullString() { } @Test - public void shouldGetDifferenceBetweenTwoString() { + void shouldGetDifferenceBetweenTwoString() { // given/when/then assertThat(StringUtils.getDifference("test", "taste"), equalTo(0.4)); assertThat(StringUtils.getDifference("test", "bear"), equalTo(0.75)); @@ -77,7 +77,7 @@ public void shouldGetDifferenceBetweenTwoString() { } @Test - public void shouldCheckIfHasNeedleInWord() { + void shouldCheckIfHasNeedleInWord() { // given/when/then assertThat(StringUtils.isInsideString('@', "@hello"), equalTo(false)); assertThat(StringUtils.isInsideString('?', "absent"), equalTo(false)); @@ -86,4 +86,3 @@ public void shouldCheckIfHasNeedleInWord() { assertThat(StringUtils.isInsideString('@', "D@Z"), equalTo(true)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/UtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/UtilsTest.java index 9b5077261a..83a6a95f78 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/UtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/UtilsTest.java @@ -15,8 +15,8 @@ import java.util.logging.Logger; import java.util.regex.Pattern; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -24,15 +24,15 @@ /** * Test for {@link Utils}. */ -public class UtilsTest { +class UtilsTest { @BeforeAll - public static void initLogger() { + static void initLogger() { TestHelper.setupLogger(); } @Test - public void shouldCompilePattern() { + void shouldCompilePattern() { // given String pattern = "gr(a|e)ys?"; @@ -44,7 +44,7 @@ public void shouldCompilePattern() { } @Test - public void shouldDefaultToAllAllowedPattern() { + void shouldDefaultToAllAllowedPattern() { // given String invalidPattern = "gr(a|eys?"; // missing closing ')' @@ -56,7 +56,7 @@ public void shouldDefaultToAllAllowedPattern() { } @Test - public void shouldLogAndSendMessage() { + void shouldLogAndSendMessage() { // given Logger logger = TestHelper.setupLogger(); Player player = mock(Player.class); @@ -71,7 +71,7 @@ public void shouldLogAndSendMessage() { } @Test - public void shouldHandleNullAsCommandSender() { + void shouldHandleNullAsCommandSender() { // given Logger logger = TestHelper.setupLogger(); String message = "Test test, test."; @@ -84,7 +84,7 @@ public void shouldHandleNullAsCommandSender() { } @Test - public void shouldNotSendToCommandSenderTwice() { + void shouldNotSendToCommandSenderTwice() { // given Logger logger = TestHelper.setupLogger(); CommandSender sender = mock(ConsoleCommandSender.class); @@ -99,7 +99,7 @@ public void shouldNotSendToCommandSenderTwice() { } @Test - public void shouldCheckIfCollectionIsEmpty() { + void shouldCheckIfCollectionIsEmpty() { // given List emptyList = Collections.emptyList(); Collection nonEmptyColl = Arrays.asList(3, 4, 5); @@ -111,7 +111,7 @@ public void shouldCheckIfCollectionIsEmpty() { } @Test - public void shouldLogAndSendWarning() { + void shouldLogAndSendWarning() { // given Logger logger = TestHelper.setupLogger(); String message = "Error while performing action"; @@ -126,7 +126,7 @@ public void shouldLogAndSendWarning() { } @Test - public void shouldLogWarningAndNotSendToConsoleSender() { + void shouldLogWarningAndNotSendToConsoleSender() { // given Logger logger = TestHelper.setupLogger(); String message = "Error while performing action"; @@ -141,7 +141,7 @@ public void shouldLogWarningAndNotSendToConsoleSender() { } @Test - public void shouldLogWarningAndHandleNullCommandSender() { + void shouldLogWarningAndHandleNullCommandSender() { // given Logger logger = TestHelper.setupLogger(); String message = "Error while performing action"; @@ -155,14 +155,14 @@ public void shouldLogWarningAndHandleNullCommandSender() { } @Test - public void shouldCheckIfClassIsLoaded() { + void shouldCheckIfClassIsLoaded() { // given / when / then assertThat(Utils.isClassLoaded("org.bukkit.event.player.PlayerFishEvent"), equalTo(true)); assertThat(Utils.isClassLoaded("com.someclass.doesnot.exist"), equalTo(false)); } @Test - public void shouldDetectIfEmailIsEmpty() { + void shouldDetectIfEmailIsEmpty() { // given / when / then assertThat(Utils.isEmailEmpty(""), equalTo(true)); assertThat(Utils.isEmailEmpty(null), equalTo(true)); @@ -173,4 +173,3 @@ public void shouldDetectIfEmailIsEmpty() { assertThat(Utils.isEmailEmpty("hey"), equalTo(false)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java b/authme-core/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java index 728c3c4c69..1040358bcc 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/UuidUtilsTest.java @@ -4,17 +4,17 @@ import java.util.UUID; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link UuidUtils}. */ -public class UuidUtilsTest { +class UuidUtilsTest { @Test - public void shouldParseUuidSafely() { + void shouldParseUuidSafely() { // given UUID correctUuid = UUID.fromString("8e0a9aaa-5eda-42ef-8daf-e6c6359f607e"); @@ -27,4 +27,3 @@ public void shouldParseUuidSafely() { assertThat(UuidUtils.parseUuidSafely("8e0a9aaa-5eda-42ef-InvalidEnding"), nullValue()); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java b/authme-core/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java index b852a9fe28..29c8970d0d 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/expiring/DurationTest.java @@ -4,16 +4,16 @@ import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link Duration}. */ -public class DurationTest { +class DurationTest { @Test - public void shouldConvertToAppropriateTimeUnit() { + void shouldConvertToAppropriateTimeUnit() { check(Duration.createWithSuitableUnit(0, TimeUnit.HOURS), 0, TimeUnit.SECONDS); @@ -41,4 +41,3 @@ private static void check(Duration duration, long expectedDuration, TimeUnit exp assertThat(duration.getDuration(), equalTo(expectedDuration)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java b/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java index 51b34cedf6..2e37c30b6c 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringMapTest.java @@ -5,18 +5,18 @@ import java.util.Map; import java.util.concurrent.TimeUnit; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link ExpiringMap}. */ -public class ExpiringMapTest { +class ExpiringMapTest { @Test - public void shouldAddAndRetrieveEntries() { + void shouldAddAndRetrieveEntries() { // given ExpiringMap map = new ExpiringMap<>(3, TimeUnit.MINUTES); @@ -29,7 +29,7 @@ public void shouldAddAndRetrieveEntries() { } @Test - public void shouldRemoveEntry() { + void shouldRemoveEntry() { // given ExpiringMap map = new ExpiringMap<>(1, TimeUnit.HOURS); map.put("hi", true); @@ -44,7 +44,7 @@ public void shouldRemoveEntry() { } @Test - public void shouldUpdateExpirationAndSupportNegativeValues() { + void shouldUpdateExpirationAndSupportNegativeValues() { // given ExpiringMap map = new ExpiringMap<>(2, TimeUnit.DAYS); map.put(2, 4); @@ -61,7 +61,7 @@ public void shouldUpdateExpirationAndSupportNegativeValues() { } @Test - public void shouldCleanUpExpiredEntries() throws InterruptedException { + void shouldCleanUpExpiredEntries() throws InterruptedException { // given ExpiringMap map = new ExpiringMap<>(200, TimeUnit.MILLISECONDS); map.put(144, 12); @@ -81,7 +81,7 @@ public void shouldCleanUpExpiredEntries() throws InterruptedException { } @Test - public void shouldReturnIfIsEmpty() { + void shouldReturnIfIsEmpty() { // given ExpiringMap map = new ExpiringMap<>(-8, TimeUnit.SECONDS); @@ -93,4 +93,3 @@ public void shouldReturnIfIsEmpty() { assertThat(map.isEmpty(), equalTo(true)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java b/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java index 4daea65794..7a877b6a7b 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/expiring/ExpiringSetTest.java @@ -4,16 +4,16 @@ import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link ExpiringSet}. */ -public class ExpiringSetTest { +class ExpiringSetTest { @Test - public void shouldAddEntry() { + void shouldAddEntry() { // given ExpiringSet set = new ExpiringSet<>(10, TimeUnit.MINUTES); @@ -26,7 +26,7 @@ public void shouldAddEntry() { } @Test - public void shouldRemoveEntries() { + void shouldRemoveEntries() { // given ExpiringSet set = new ExpiringSet<>(20, TimeUnit.SECONDS); set.add(20); @@ -43,7 +43,7 @@ public void shouldRemoveEntries() { } @Test - public void shouldHandleNewExpirationAndSupportNegativeValues() { + void shouldHandleNewExpirationAndSupportNegativeValues() { // given ExpiringSet set = new ExpiringSet<>(800, TimeUnit.MILLISECONDS); set.add('A'); @@ -58,7 +58,7 @@ public void shouldHandleNewExpirationAndSupportNegativeValues() { } @Test - public void shouldClearAllValues() { + void shouldClearAllValues() { // given ExpiringSet set = new ExpiringSet<>(1, TimeUnit.MINUTES); set.add("test"); @@ -71,7 +71,7 @@ public void shouldClearAllValues() { } @Test - public void shouldClearExpiredValues() { + void shouldClearExpiredValues() { // given ExpiringSet set = new ExpiringSet<>(2, TimeUnit.HOURS); set.add(2); @@ -90,7 +90,7 @@ public void shouldClearExpiredValues() { } @Test - public void shouldReturnExpiration() { + void shouldReturnExpiration() { // given ExpiringSet set = new ExpiringSet<>(123, TimeUnit.MINUTES); set.add("my entry"); @@ -105,7 +105,7 @@ public void shouldReturnExpiration() { } @Test - public void shouldReturnExpirationInSuitableUnits() { + void shouldReturnExpirationInSuitableUnits() { // given ExpiringSet set = new ExpiringSet<>(601, TimeUnit.SECONDS); set.add(12); @@ -124,7 +124,7 @@ public void shouldReturnExpirationInSuitableUnits() { } @Test - public void shouldReturnMinusOneForExpiredEntry() { + void shouldReturnMinusOneForExpiredEntry() { // given ExpiringSet set = new ExpiringSet<>(-100, TimeUnit.SECONDS); set.add(23); @@ -141,4 +141,3 @@ private static void assertIsDuration(Duration duration, long expectedDuration, T assertThat(duration.getDuration(), equalTo(expectedDuration)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java b/authme-core/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java index d3632f012c..7119bbdfc7 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/expiring/TimedCounterTest.java @@ -4,16 +4,16 @@ import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; /** * Test for {@link TimedCounter}. */ -public class TimedCounterTest { +class TimedCounterTest { @Test - public void shouldReturnZeroForAnyKey() { + void shouldReturnZeroForAnyKey() { // given TimedCounter counter = new TimedCounter<>(1, TimeUnit.DAYS); @@ -23,7 +23,7 @@ public void shouldReturnZeroForAnyKey() { } @Test - public void shouldIncrementCount() { + void shouldIncrementCount() { // given TimedCounter counter = new TimedCounter<>(10, TimeUnit.MINUTES); counter.put("moto", 12); @@ -38,7 +38,7 @@ public void shouldIncrementCount() { } @Test - public void shouldDecrementCount() { + void shouldDecrementCount() { // given TimedCounter counter = new TimedCounter<>(10, TimeUnit.MINUTES); counter.put("moto", 12); @@ -53,7 +53,7 @@ public void shouldDecrementCount() { } @Test - public void shouldSumUpEntries() { + void shouldSumUpEntries() { // given TimedCounter counter = new TimedCounter<>(90, TimeUnit.SECONDS); counter.getEntries().put("expired", new ExpiringMap.ExpiringEntry<>(800, 0)); @@ -68,4 +68,3 @@ public void shouldSumUpEntries() { assertThat(totals, equalTo(14)); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java b/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java index 6374b9abda..afa33b183f 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagBuilderTest.java @@ -5,17 +5,17 @@ import java.util.function.Function; import java.util.function.Supplier; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link TagBuilder}. */ -public class TagBuilderTest { +class TagBuilderTest { @Test - public void shouldCreateNoArgsTag() { + void shouldCreateNoArgsTag() { // given Supplier supplier = () -> "hello"; @@ -28,7 +28,7 @@ public void shouldCreateNoArgsTag() { } @Test - public void shouldCreateDependentTag() { + void shouldCreateDependentTag() { // given Function function = d -> Double.toString(d + d/10); @@ -40,4 +40,3 @@ public void shouldCreateDependentTag() { assertThat(tag.getValue(24d), equalTo("26.4")); } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java b/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java index bbaaffa69b..1b325f12e4 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/lazytags/TagReplacerTest.java @@ -6,17 +6,17 @@ import java.util.List; import static fr.xephi.authme.util.lazytags.TagBuilder.createTag; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link TagReplacer}. */ -public class TagReplacerTest { +class TagReplacerTest { @Test - public void shouldReplaceTags() { + void shouldReplaceTags() { // given TestTagService tagService = new TestTagService(); List> tags = tagService.getAvailableTags(); @@ -35,7 +35,7 @@ public void shouldReplaceTags() { } @Test - public void shouldNotCallUnusedTags() { + void shouldNotCallUnusedTags() { // given TestTagService tagService = new TestTagService(); List> tags = tagService.getAvailableTags(); @@ -88,4 +88,3 @@ List> getAvailableTags() { } } - diff --git a/authme-core/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java b/authme-core/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java index 9dffada697..e7ef379057 100644 --- a/authme-core/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java +++ b/authme-core/src/test/java/fr/xephi/authme/util/lazytags/WrappedTagReplacerTest.java @@ -9,17 +9,17 @@ import java.util.Arrays; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; /** * Test for {@link WrappedTagReplacer}. */ -public class WrappedTagReplacerTest { +class WrappedTagReplacerTest { @Test - public void shouldApplyTags() { + void shouldApplyTags() { // given TestTagService tagService = new TestTagService(); List> tags = tagService.getAvailableTags(); @@ -74,4 +74,3 @@ String getDescription() { } } } -