diff --git a/src/main/java/fr/xephi/authme/command/CommandUtils.java b/src/main/java/fr/xephi/authme/command/CommandUtils.java index 90d0138ab..391a14631 100644 --- a/src/main/java/fr/xephi/authme/command/CommandUtils.java +++ b/src/main/java/fr/xephi/authme/command/CommandUtils.java @@ -5,7 +5,6 @@ import org.bukkit.ChatColor; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * Utility functions for {@link CommandDescription} objects. @@ -76,19 +75,14 @@ public final class CommandUtils { } /** - * Returns a textual representation of the command, including its arguments. - * For example: {@code /authme purge [includeZero]}. + * Constructs a command path with color formatting, based on the supplied labels. This includes + * the command's arguments, as defined in the provided command description. The list of labels + * must contain all labels to be used. * - * @param command the command to create a usage string for - * @return the command's path and arguments + * @param command the command to read arguments from + * @param correctLabels the labels to use (must be complete) + * @return formatted command syntax incl. arguments */ - public static String buildSyntax(CommandDescription command) { - String arguments = command.getArguments().stream() - .map(arg -> formatArgument(arg)) - .collect(Collectors.joining(" ")); - return (constructCommandPath(command) + " " + arguments).trim(); - } - public static String buildSyntax(CommandDescription command, List correctLabels) { String commandSyntax = ChatColor.WHITE + "/" + correctLabels.get(0) + ChatColor.YELLOW; for (int i = 1; i < correctLabels.size(); ++i) { @@ -106,7 +100,7 @@ public final class CommandUtils { * @param argument the argument to format * @return the formatted argument */ - private static String formatArgument(CommandArgumentDescription argument) { + public static String formatArgument(CommandArgumentDescription argument) { if (argument.isOptional()) { return "[" + argument.getName() + "]"; } diff --git a/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java b/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java index 13bd29233..16fd154d7 100644 --- a/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java +++ b/src/main/java/fr/xephi/authme/task/purge/PurgeExecutor.java @@ -169,7 +169,6 @@ public class PurgeExecutor { return; } - int i = 0; File essentialsDataFolder = pluginHookService.getEssentialsDataFolder(); if (essentialsDataFolder == null) { ConsoleLogger.info("Cannot purge Essentials: plugin is not loaded"); @@ -181,14 +180,15 @@ public class PurgeExecutor { return; } + int deletedFiles = 0; for (OfflinePlayer offlinePlayer : cleared) { File playerFile = new File(userDataFolder, PlayerUtils.getUuidOrName(offlinePlayer) + ".yml"); if (playerFile.exists() && playerFile.delete()) { - i++; + deletedFiles++; } } - ConsoleLogger.info("AutoPurge: Removed " + i + " EssentialsFiles"); + ConsoleLogger.info("AutoPurge: Removed " + deletedFiles + " EssentialsFiles"); } // TODO #676: What is this method for? Is it correct? diff --git a/src/main/java/fr/xephi/authme/util/FileUtils.java b/src/main/java/fr/xephi/authme/util/FileUtils.java index fa8c858ad..759f55811 100644 --- a/src/main/java/fr/xephi/authme/util/FileUtils.java +++ b/src/main/java/fr/xephi/authme/util/FileUtils.java @@ -61,7 +61,7 @@ public final class FileUtils { ConsoleLogger.warning("Could not create directory '" + dir + "'"); return false; } - return true; + return dir.isDirectory(); } /** diff --git a/src/main/java/fr/xephi/authme/util/InternetProtocolUtils.java b/src/main/java/fr/xephi/authme/util/InternetProtocolUtils.java index 33ab451e3..548e1e913 100644 --- a/src/main/java/fr/xephi/authme/util/InternetProtocolUtils.java +++ b/src/main/java/fr/xephi/authme/util/InternetProtocolUtils.java @@ -5,11 +5,11 @@ import java.util.regex.Pattern; /** * Utility class about the InternetProtocol */ -public class InternetProtocolUtils { +public final class InternetProtocolUtils { - private final static Pattern LOCAL_ADDRESS_PATTERN = - Pattern.compile("(^127\\.)|(^(0)?10\\.)|(^172\\.(0)?1[6-9]\\.)|(^172\\.(0)?2[0-9]\\.)" + - "|(^172\\.(0)?3[0-1]\\.)|(^169\\.254\\.)|(^192\\.168\\.)"); + private static final Pattern LOCAL_ADDRESS_PATTERN = + Pattern.compile("(^127\\.)|(^(0)?10\\.)|(^172\\.(0)?1[6-9]\\.)|(^172\\.(0)?2[0-9]\\.)" + + "|(^172\\.(0)?3[0-1]\\.)|(^169\\.254\\.)|(^192\\.168\\.)"); // Utility class private InternetProtocolUtils() { diff --git a/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java b/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java index 7f26cef57..a8b3a0fa6 100644 --- a/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java +++ b/src/test/java/fr/xephi/authme/ClassesConsistencyTest.java @@ -55,7 +55,7 @@ public class ClassesConsistencyTest { /** Classes excluded from the field visibility test. */ private static final Set> CLASSES_EXCLUDED_FROM_VISIBILITY_TEST = ImmutableSet.of( Whirlpool.class, // not our implementation, so we don't touch it - Columns.class // uses non-final String constants, which is safe + Columns.class // uses non-static String constants, which is safe ); /** diff --git a/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java b/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java index c0b4771cd..9d1f757e0 100644 --- a/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java +++ b/src/test/java/fr/xephi/authme/command/CommandUtilsTest.java @@ -22,7 +22,7 @@ public class CommandUtilsTest { @BeforeClass public static void setUpTestCommands() { - commands = TestCommandsUtil.generateCommands(); + commands = Collections.unmodifiableCollection(TestCommandsUtil.generateCommands()); } @Test @@ -49,10 +49,6 @@ public class CommandUtilsTest { assertThat(commandPath, equalTo("/authme help")); } - - // ------ - // min / max arguments - // ------ @Test public void shouldComputeMinAndMaxOnEmptyCommand() { // given diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java new file mode 100644 index 000000000..2e1e0b5e8 --- /dev/null +++ b/src/test/java/fr/xephi/authme/command/executable/authme/BackupCommandTest.java @@ -0,0 +1,39 @@ +package fr.xephi.authme.command.executable.authme; + +import fr.xephi.authme.service.BackupService; +import org.bukkit.command.CommandSender; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Collections; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Test for {@link BackupCommand}. + */ +@RunWith(MockitoJUnitRunner.class) +public class BackupCommandTest { + + @InjectMocks + private BackupCommand command; + + @Mock + private BackupService backupService; + + @Test + public void shouldStartBackup() { + // given + CommandSender sender = mock(CommandSender.class); + + // when + command.executeCommand(sender, Collections.emptyList()); + + // then + verify(backupService).doBackup(BackupService.BackupCause.COMMAND, sender); + } +} diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DataStatisticsTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DataStatisticsTest.java new file mode 100644 index 000000000..dee5bdb7b --- /dev/null +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DataStatisticsTest.java @@ -0,0 +1,116 @@ +package fr.xephi.authme.command.executable.authme.debug; + +import com.google.common.cache.LoadingCache; +import fr.xephi.authme.ReflectionTestUtils; +import fr.xephi.authme.data.auth.PlayerAuth; +import fr.xephi.authme.data.auth.PlayerCache; +import fr.xephi.authme.data.limbo.LimboPlayer; +import fr.xephi.authme.data.limbo.LimboService; +import fr.xephi.authme.datasource.CacheDataSource; +import fr.xephi.authme.datasource.DataSource; +import fr.xephi.authme.initialization.HasCleanup; +import fr.xephi.authme.initialization.Reloadable; +import fr.xephi.authme.initialization.SettingsDependent; +import fr.xephi.authme.initialization.factory.SingletonStore; +import org.bukkit.command.CommandSender; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Test for {@link DataStatistics}. + */ +@RunWith(MockitoJUnitRunner.class) +public class DataStatisticsTest { + + @InjectMocks + private DataStatistics dataStatistics; + + @Mock + private DataSource dataSource; + @Mock + private PlayerCache playerCache; + @Mock + private LimboService limboService; + @Mock + private SingletonStore singletonStore; + + @Before + public void setUpLimboCacheMap() { + Map limboMap = new HashMap<>(); + limboMap.put("test", mock(LimboPlayer.class)); + ReflectionTestUtils.setField(LimboService.class, limboService, "entries", limboMap); + } + + @Test + public void shouldOutputStatistics() { + // given + CommandSender sender = mock(CommandSender.class); + given(singletonStore.retrieveAllOfType()).willReturn(mockListOfSize(Object.class, 7)); + given(singletonStore.retrieveAllOfType(Reloadable.class)).willReturn(mockListOfSize(Reloadable.class, 4)); + given(singletonStore.retrieveAllOfType(SettingsDependent.class)).willReturn(mockListOfSize(SettingsDependent.class, 3)); + given(singletonStore.retrieveAllOfType(HasCleanup.class)).willReturn(mockListOfSize(HasCleanup.class, 2)); + given(dataSource.getAccountsRegistered()).willReturn(219); + given(playerCache.getLogged()).willReturn(12); + + + // when + dataStatistics.execute(sender, Collections.emptyList()); + + // then + ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); + verify(sender, atLeastOnce()).sendMessage(stringCaptor.capture()); + assertThat(stringCaptor.getAllValues(), containsInAnyOrder( + "Singleton Java classes: 7 (Reloadable: 4 / SettingsDependent: 3 / HasCleanup: 2)", + "LimboPlayers in memory: 1", + "Total players in DB: 219", + "PlayerCache size: 12 (= logged in players)")); + } + + @Test + public void shouldOutputCachedDataSourceStatistics() { + // given + CacheDataSource cacheDataSource = mock(CacheDataSource.class); + LoadingCache> cache = mock(LoadingCache.class); + given(cache.size()).willReturn(11L); + given(cacheDataSource.getCachedAuths()).willReturn(cache); + ReflectionTestUtils.setField(DataStatistics.class, dataStatistics, "dataSource", cacheDataSource); + CommandSender sender = mock(CommandSender.class); + + // when + dataStatistics.execute(sender, Collections.emptyList()); + + // then + ArgumentCaptor stringCaptor = ArgumentCaptor.forClass(String.class); + verify(sender, atLeastOnce()).sendMessage(stringCaptor.capture()); + assertThat(stringCaptor.getAllValues(), hasItem("Cached PlayerAuth objects: 11")); + } + + private static List mockListOfSize(Class mockClass, int size) { + T mock = mock(mockClass); + List mocks = new ArrayList<>(size); + for (int i = 0; i < size; ++i) { + mocks.add(mock); + } + return mocks; + } +} diff --git a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java index e8443260d..bd4b42e0c 100644 --- a/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/authme/debug/DebugSectionUtilsTest.java @@ -5,6 +5,7 @@ import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.limbo.LimboPlayer; import fr.xephi.authme.data.limbo.LimboService; import org.bukkit.Location; +import org.junit.Before; import org.junit.Test; import java.util.HashMap; @@ -12,6 +13,7 @@ import java.util.Map; import java.util.function.Function; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; @@ -21,6 +23,11 @@ import static org.mockito.Mockito.mock; */ public class DebugSectionUtilsTest { + @Before + public void initMockLogger() { + TestHelper.setupLogger(); + } + @Test public void shouldFormatLocation() { // given / when @@ -66,4 +73,20 @@ public class DebugSectionUtilsTest { // then assertThat(map, sameInstance(limboMap)); } + + @Test + public void shouldHandleErrorGracefully() { + // given + LimboService limboService = mock(LimboService.class); + Map limboMap = new HashMap<>(); + ReflectionTestUtils.setField(LimboService.class, limboService, "entries", limboMap); + + // when + Object result = DebugSectionUtils.applyToLimboPlayersMap(limboService, map -> { + throw new IllegalStateException(); + }); + + // then + assertThat(result, nullValue()); + } } diff --git a/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java index e43566f2d..cee384041 100644 --- a/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommandTest.java @@ -19,6 +19,8 @@ import java.util.Arrays; import java.util.Collections; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; @@ -106,11 +108,16 @@ public class ChangePasswordCommandTest { verify(management).performPasswordChange(player, oldPass, newPass); } + @Test + public void shouldDefineArgumentMismatchMessage() { + // given / when / then + assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_CHANGE_PASSWORD)); + } + private Player initPlayerWithName(String name, boolean loggedIn) { Player player = mock(Player.class); when(player.getName()).thenReturn(name); when(playerCache.isAuthenticated(name)).thenReturn(loggedIn); return player; } - } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java index 75c10e7a4..9a039b50e 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/AddEmailCommandTest.java @@ -15,6 +15,8 @@ import org.mockito.junit.MockitoJUnitRunner; import java.util.Arrays; import java.util.Collections; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -73,4 +75,9 @@ public class AddEmailCommandTest { verify(commandService).send(sender, MessageKey.CONFIRM_EMAIL_MESSAGE); } + @Test + public void shouldDefineArgumentMismatchMessage() { + // given / when / then + assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_ADD_EMAIL)); + } } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java index 8876abbfe..b4cb80a96 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/ChangeEmailCommandTest.java @@ -1,5 +1,6 @@ package fr.xephi.authme.command.executable.email; +import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.Management; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; @@ -10,9 +11,11 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -36,7 +39,7 @@ public class ChangeEmailCommandTest { CommandSender sender = mock(BlockCommandSender.class); // when - command.executeCommand(sender, new ArrayList()); + command.executeCommand(sender, Collections.emptyList()); // then verifyZeroInteractions(management); @@ -54,4 +57,9 @@ public class ChangeEmailCommandTest { verify(management).performChangeEmail(sender, "new.mail@example.org", "old_mail@example.org"); } + @Test + public void shouldDefineArgumentMismatchMessage() { + // given / when / then + assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_CHANGE_EMAIL)); + } } diff --git a/src/test/java/fr/xephi/authme/command/executable/email/EmailBaseCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/EmailBaseCommandTest.java new file mode 100644 index 000000000..7ca0aff9c --- /dev/null +++ b/src/test/java/fr/xephi/authme/command/executable/email/EmailBaseCommandTest.java @@ -0,0 +1,49 @@ +package fr.xephi.authme.command.executable.email; + +import fr.xephi.authme.command.CommandMapper; +import fr.xephi.authme.command.FoundCommandResult; +import fr.xephi.authme.command.help.HelpProvider; +import org.bukkit.command.CommandSender; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Collections; + +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Test for {@link EmailBaseCommand}. + */ +@RunWith(MockitoJUnitRunner.class) +public class EmailBaseCommandTest { + + @InjectMocks + private EmailBaseCommand command; + + @Mock + private HelpProvider helpProvider; + @Mock + private CommandMapper commandMapper; + + @Test + public void shouldDisplayHelp() { + // given + CommandSender sender = mock(CommandSender.class); + FoundCommandResult result = mock(FoundCommandResult.class); + given(commandMapper.mapPartsToCommand(eq(sender), anyList())).willReturn(result); + + // when + command.executeCommand(sender, Collections.emptyList()); + + // then + verify(commandMapper).mapPartsToCommand(sender, Collections.singletonList("email")); + verify(helpProvider).outputHelp(sender, result, HelpProvider.SHOW_CHILDREN); + } +} diff --git a/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java index b6c08eaa7..9ca0bc090 100644 --- a/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/email/RecoverEmailCommandTest.java @@ -22,6 +22,8 @@ import org.mockito.Mock; import java.util.Collections; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -208,4 +210,10 @@ public class RecoverEmailCommandTest { verify(dataSource).getEmail(name); verify(recoveryService).generateAndSendNewPassword(sender, email); } + + @Test + public void shouldDefineArgumentMismatchMessage() { + // given / when / then + assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_RECOVER_EMAIL)); + } } diff --git a/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java index df6eb7d86..38307f93d 100644 --- a/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/login/LoginCommandTest.java @@ -1,5 +1,6 @@ package fr.xephi.authme.command.executable.login; +import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.Management; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; @@ -13,6 +14,8 @@ import org.mockito.junit.MockitoJUnitRunner; import java.util.Collections; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -57,4 +60,9 @@ public class LoginCommandTest { verify(management).performLogin(eq(sender), eq("password")); } + @Test + public void shouldDefineArgumentMismatchMessage() { + // given / when / then + assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_LOGIN)); + } } diff --git a/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java b/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java index d4560640b..2adc66d51 100644 --- a/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java +++ b/src/test/java/fr/xephi/authme/command/executable/unregister/UnregisterCommandTest.java @@ -15,6 +15,8 @@ import org.mockito.junit.MockitoJUnitRunner; import java.util.Collections; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; import static org.mockito.hamcrest.MockitoHamcrest.argThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -87,4 +89,9 @@ public class UnregisterCommandTest { verify(sender).sendMessage(argThat(containsString("/authme unregister "))); } + @Test + public void shouldDefineArgumentMismatchMessage() { + // given / when / then + assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_UNREGISTER)); + } } diff --git a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java index ea0f372a2..bef86fca4 100644 --- a/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java +++ b/src/test/java/fr/xephi/authme/command/help/HelpMessagesServiceTest.java @@ -10,6 +10,7 @@ import fr.xephi.authme.message.MessageFileHandlerProvider; import fr.xephi.authme.permission.DefaultPermission; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import java.util.Collection; @@ -19,10 +20,13 @@ import static fr.xephi.authme.TestHelper.getJarFile; import static fr.xephi.authme.command.TestCommandsUtil.getCommandWithLabel; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; /** * Test for {@link HelpMessagesService}. @@ -46,6 +50,17 @@ public class HelpMessagesServiceTest { given(messageFileHandlerProvider.initializeHandler(any(Function.class))).willReturn(handler); } + @Test + @SuppressWarnings("unchecked") + public void shouldUseExistingFileAsTextFile() { + // given / when / then + ArgumentCaptor> functionCaptor = ArgumentCaptor.forClass(Function.class); + verify(messageFileHandlerProvider).initializeHandler(functionCaptor.capture()); + Function helpFilePathBuilder = functionCaptor.getValue(); + String defaultFilePath = helpFilePathBuilder.apply("en"); + assertThat(getClass().getClassLoader().getResource(defaultFilePath), not(nullValue())); + } + @Test public void shouldReturnLocalizedCommand() { // given diff --git a/src/test/java/fr/xephi/authme/util/FileUtilsTest.java b/src/test/java/fr/xephi/authme/util/FileUtilsTest.java index 9d65047c5..a20210bb9 100644 --- a/src/test/java/fr/xephi/authme/util/FileUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/FileUtilsTest.java @@ -75,6 +75,20 @@ public class FileUtilsTest { assertThat(file.exists(), equalTo(false)); } + @Test + public void shouldReturnFalseForParentInvalidParentFolders() throws IOException { + // given + File folder = temporaryFolder.newFolder(); + new File(folder, "hello").createNewFile(); + File fileToCreate = new File(folder, "hello/test"); + + // when + boolean result = FileUtils.copyFileFromResource(fileToCreate, "welcome.txt"); + + // then + assertThat(result, equalTo(false)); + } + @Test public void shouldPurgeDirectory() throws IOException { // given @@ -137,6 +151,36 @@ public class FileUtilsTest { assertThat(result, equalTo("path" + File.separator + "to" + File.separator + "test-file.txt")); } + @Test + public void shouldCreateDirectory() throws IOException { + // given + File root = temporaryFolder.newFolder(); + File dir = new File(root, "folder/folder2/myFolder"); + + // when + boolean result = FileUtils.createDirectory(dir); + + // then + assertThat(result, equalTo(true)); + assertThat(dir.exists(), equalTo(true)); + assertThat(dir.isDirectory(), equalTo(true)); + } + + @Test + public void shouldReturnFalseOnDirectoryCreateFail() throws IOException { + // given + File root = temporaryFolder.newFolder(); + File dirAsFile = new File(root, "file"); + dirAsFile.createNewFile(); + + // when + boolean result = FileUtils.createDirectory(dirAsFile); + + // then + assertThat(result, equalTo(false)); + assertThat(dirAsFile.isFile(), equalTo(true)); + } + @Test public void shouldHaveHiddenConstructor() { TestHelper.validateHasOnlyPrivateEmptyConstructor(FileUtils.class); diff --git a/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java b/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java index e71f69c16..d45c0a578 100644 --- a/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/InternetProtocolUtilsTest.java @@ -1,5 +1,6 @@ package fr.xephi.authme.util; +import fr.xephi.authme.TestHelper; import org.junit.Test; import static org.junit.Assert.assertThat; @@ -19,4 +20,10 @@ public class InternetProtocolUtilsTest { assertThat(InternetProtocolUtils.isLocalAddress("192.168.0.1"), equalTo(true)); assertThat(InternetProtocolUtils.isLocalAddress("94.32.34.5"), equalTo(false)); } + + @Test + public void shouldHavePrivateConstructor() { + // given / when / then + TestHelper.validateHasOnlyPrivateEmptyConstructor(InternetProtocolUtils.class); + } } diff --git a/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java b/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java index b5200b01d..556a604c3 100644 --- a/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/RandomStringUtilsTest.java @@ -53,7 +53,7 @@ public class RandomStringUtilsTest { // when / then for (int length : lengths) { - String result = RandomStringUtils.generateHex(length); + String result = RandomStringUtils.generateLowerUpper(length); assertThat("Result '" + result + "' should have length " + length, result.length(), equalTo(length)); assertThat("Result '" + result + "' should only have characters a-z, A-Z, 0-9", diff --git a/src/test/java/fr/xephi/authme/util/UtilsTest.java b/src/test/java/fr/xephi/authme/util/UtilsTest.java index ce8675f43..87fc308c1 100644 --- a/src/test/java/fr/xephi/authme/util/UtilsTest.java +++ b/src/test/java/fr/xephi/authme/util/UtilsTest.java @@ -1,16 +1,22 @@ package fr.xephi.authme.util; import fr.xephi.authme.TestHelper; +import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.junit.BeforeClass; import org.junit.Test; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import java.util.logging.Logger; import java.util.regex.Pattern; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -99,6 +105,68 @@ public class UtilsTest { verifyZeroInteractions(sender); } + @Test + public void shouldCheckIfCollectionIsEmpty() { + // given + List emptyList = Collections.emptyList(); + Collection nonEmptyColl = Arrays.asList(3, 4, 5); + + // when / then + assertThat(Utils.isCollectionEmpty(emptyList), equalTo(true)); + assertThat(Utils.isCollectionEmpty(nonEmptyColl), equalTo(false)); + assertThat(Utils.isCollectionEmpty(null), equalTo(true)); + } + + @Test + public void shouldReturnCoreCount() { + // given / when / then + assertThat(Utils.getCoreCount(), greaterThan(0)); + } + + @Test + public void shouldLogAndSendWarning() { + // given + Logger logger = TestHelper.setupLogger(); + String message = "Error while performing action"; + CommandSender sender = mock(CommandSender.class); + + // when + Utils.logAndSendWarning(sender, message); + + // then + verify(logger).warning(message); + verify(sender).sendMessage(ChatColor.RED + message); + } + + @Test + public void shouldLogWarningAndNotSendToConsoleSender() { + // given + Logger logger = TestHelper.setupLogger(); + String message = "Error while performing action"; + CommandSender sender = mock(ConsoleCommandSender.class); + + // when + Utils.logAndSendWarning(sender, message); + + // then + verify(logger).warning(message); + verifyZeroInteractions(sender); + } + + @Test + public void shouldLogWarningAndHandleNullCommandSender() { + // given + Logger logger = TestHelper.setupLogger(); + String message = "Error while performing action"; + CommandSender sender = null; + + // when + Utils.logAndSendWarning(sender, message); + + // then + verify(logger).warning(message); + } + @Test public void shouldCheckIfClassIsLoaded() { // given / when / then diff --git a/src/test/java/tools/filegeneration/GeneratePluginYml.java b/src/test/java/tools/filegeneration/GeneratePluginYml.java index 8fdc779d7..04dba91ef 100644 --- a/src/test/java/tools/filegeneration/GeneratePluginYml.java +++ b/src/test/java/tools/filegeneration/GeneratePluginYml.java @@ -140,10 +140,15 @@ public class GeneratePluginYml implements AutoToolTask { } private static String buildUsage(CommandDescription command) { - if (!command.getArguments().isEmpty()) { - return CommandUtils.buildSyntax(command); - } final String commandStart = "/" + command.getLabels().get(0); + if (!command.getArguments().isEmpty()) { + // Command has arguments, so generate something like /authme register + final String arguments = command.getArguments().stream() + .map(CommandUtils::formatArgument) + .collect(Collectors.joining(" ")); + return commandStart + " " + arguments; + } + // Argument-less command, list all children: /authme register|login|firstspawn|spawn|... String usage = commandStart + " " + command.getChildren() .stream() .filter(cmd -> !cmd.getLabels().contains("help"))