Add some tests, minor Checkstyle fixes

This commit is contained in:
ljacqu 2017-07-16 12:59:33 +02:00
parent 7c48cf59c7
commit 4ac980111d
22 changed files with 435 additions and 34 deletions

View File

@ -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 <days> [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<String> 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() + "]";
}

View File

@ -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?

View File

@ -61,7 +61,7 @@ public final class FileUtils {
ConsoleLogger.warning("Could not create directory '" + dir + "'");
return false;
}
return true;
return dir.isDirectory();
}
/**

View File

@ -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() {

View File

@ -55,7 +55,7 @@ public class ClassesConsistencyTest {
/** Classes excluded from the field visibility test. */
private static final Set<Class<?>> 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
);
/**

View File

@ -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

View File

@ -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);
}
}

View File

@ -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<Object> singletonStore;
@Before
public void setUpLimboCacheMap() {
Map<String, LimboPlayer> 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<String> 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<String, Optional<PlayerAuth>> 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<String> stringCaptor = ArgumentCaptor.forClass(String.class);
verify(sender, atLeastOnce()).sendMessage(stringCaptor.capture());
assertThat(stringCaptor.getAllValues(), hasItem("Cached PlayerAuth objects: 11"));
}
private static <T> List<T> mockListOfSize(Class<T> mockClass, int size) {
T mock = mock(mockClass);
List<T> mocks = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
mocks.add(mock);
}
return mocks;
}
}

View File

@ -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<String, LimboPlayer> limboMap = new HashMap<>();
ReflectionTestUtils.setField(LimboService.class, limboService, "entries", limboMap);
// when
Object result = DebugSectionUtils.applyToLimboPlayersMap(limboService, map -> {
throw new IllegalStateException();
});
// then
assertThat(result, nullValue());
}
}

View File

@ -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;
}
}

View File

@ -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));
}
}

View File

@ -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<String>());
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));
}
}

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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));
}
}

View File

@ -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 <player>")));
}
@Test
public void shouldDefineArgumentMismatchMessage() {
// given / when / then
assertThat(command.getArgumentsMismatchMessage(), equalTo(MessageKey.USAGE_UNREGISTER));
}
}

View File

@ -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<Function<String, String>> functionCaptor = ArgumentCaptor.forClass(Function.class);
verify(messageFileHandlerProvider).initializeHandler(functionCaptor.capture());
Function<String, String> helpFilePathBuilder = functionCaptor.getValue();
String defaultFilePath = helpFilePathBuilder.apply("en");
assertThat(getClass().getClassLoader().getResource(defaultFilePath), not(nullValue()));
}
@Test
public void shouldReturnLocalizedCommand() {
// given

View File

@ -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);

View File

@ -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);
}
}

View File

@ -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",

View File

@ -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<String> emptyList = Collections.emptyList();
Collection<Integer> 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

View File

@ -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 <password> <confirmPass>
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"))