Get player via BukkitService; add unit tests for commands

This commit is contained in:
ljacqu 2016-04-08 19:56:44 +02:00
parent 0cda9a7698
commit e2b50b72a5
14 changed files with 525 additions and 44 deletions

View File

@ -138,6 +138,7 @@ public class AuthMe extends JavaPlugin {
private SpawnLoader spawnLoader; private SpawnLoader spawnLoader;
private AntiBot antiBot; private AntiBot antiBot;
private boolean autoPurging; private boolean autoPurging;
private BukkitService bukkitService;
/** /**
* Get the plugin's instance. * Get the plugin's instance.
@ -257,13 +258,13 @@ public class AuthMe extends JavaPlugin {
// Set up the permissions manager and command handler // Set up the permissions manager and command handler
bukkitService = new BukkitService(this);
permsMan = initializePermissionsManager(); permsMan = initializePermissionsManager();
ValidationService validationService = new ValidationService(newSettings, database, permsMan); ValidationService validationService = new ValidationService(newSettings, database, permsMan);
commandHandler = initializeCommandHandler(permsMan, messages, passwordSecurity, newSettings, commandHandler = initializeCommandHandler(permsMan, messages, passwordSecurity, newSettings,
pluginHooks, spawnLoader, antiBot, validationService); pluginHooks, spawnLoader, antiBot, validationService, bukkitService);
// AntiBot delay // AntiBot delay
BukkitService bukkitService = new BukkitService(this);
antiBot = new AntiBot(newSettings, messages, permsMan, bukkitService); antiBot = new AntiBot(newSettings, messages, permsMan, bukkitService);
// Set up Metrics // Set up Metrics
@ -291,7 +292,7 @@ public class AuthMe extends JavaPlugin {
playerBackup = new JsonCache(); playerBackup = new JsonCache();
// Set the DataManager // Set the DataManager
dataManager = new DataManager(this, pluginHooks); dataManager = new DataManager(this, pluginHooks, bukkitService);
// Set up the new API // Set up the new API
setupApi(); setupApi();
@ -378,7 +379,8 @@ public class AuthMe extends JavaPlugin {
PluginManager pluginManager = server.getPluginManager(); PluginManager pluginManager = server.getPluginManager();
// Register event listeners // Register event listeners
pluginManager.registerEvents(new AuthMePlayerListener(this, messages, dataSource, antiBot, management), this); pluginManager.registerEvents(new AuthMePlayerListener(
this, messages, dataSource, antiBot, management, bukkitService), this);
pluginManager.registerEvents(new AuthMeBlockListener(), this); pluginManager.registerEvents(new AuthMeBlockListener(), this);
pluginManager.registerEvents(new AuthMeEntityListener(), this); pluginManager.registerEvents(new AuthMeEntityListener(), this);
pluginManager.registerEvents(new AuthMeServerListener(this, messages, pluginHooks, spawnLoader), this); pluginManager.registerEvents(new AuthMeServerListener(this, messages, pluginHooks, spawnLoader), this);
@ -429,13 +431,13 @@ public class AuthMe extends JavaPlugin {
private CommandHandler initializeCommandHandler(PermissionsManager permissionsManager, Messages messages, private CommandHandler initializeCommandHandler(PermissionsManager permissionsManager, Messages messages,
PasswordSecurity passwordSecurity, NewSetting settings, PasswordSecurity passwordSecurity, NewSetting settings,
PluginHooks pluginHooks, SpawnLoader spawnLoader, PluginHooks pluginHooks, SpawnLoader spawnLoader, AntiBot antiBot,
AntiBot antiBot, ValidationService validationService) { ValidationService validationService, BukkitService bukkitService) {
HelpProvider helpProvider = new HelpProvider(permissionsManager, settings.getProperty(HELP_HEADER)); HelpProvider helpProvider = new HelpProvider(permissionsManager, settings.getProperty(HELP_HEADER));
Set<CommandDescription> baseCommands = CommandInitializer.buildCommands(); Set<CommandDescription> baseCommands = CommandInitializer.buildCommands();
CommandMapper mapper = new CommandMapper(baseCommands, permissionsManager); CommandMapper mapper = new CommandMapper(baseCommands, permissionsManager);
CommandService commandService = new CommandService(this, mapper, helpProvider, messages, passwordSecurity, CommandService commandService = new CommandService(this, mapper, helpProvider, messages, passwordSecurity,
permissionsManager, settings, pluginHooks, spawnLoader, antiBot, validationService); permissionsManager, settings, pluginHooks, spawnLoader, antiBot, validationService, bukkitService);
return new CommandHandler(commandService); return new CommandHandler(commandService);
} }
@ -757,8 +759,8 @@ public class AuthMe extends JavaPlugin {
public void run() { public void run() {
for (PlayerAuth auth : database.getLoggedPlayers()) { for (PlayerAuth auth : database.getLoggedPlayers()) {
String email = auth.getEmail(); String email = auth.getEmail();
if (StringUtils.isEmpty(email) || email.equalsIgnoreCase("your@email.com")) { if (StringUtils.isEmpty(email) || "your@email.com".equalsIgnoreCase(email)) {
Player player = Utils.getPlayer(auth.getRealName()); Player player = bukkitService.getPlayerExact(auth.getRealName());
if (player != null) { if (player != null) {
messages.send(player, MessageKey.ADD_EMAIL_MESSAGE); messages.send(player, MessageKey.ADD_EMAIL_MESSAGE);
} }

View File

@ -3,6 +3,7 @@ package fr.xephi.authme;
import fr.xephi.authme.hooks.PluginHooks; import fr.xephi.authme.hooks.PluginHooks;
import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.settings.properties.PurgeSettings; import fr.xephi.authme.settings.properties.PurgeSettings;
import fr.xephi.authme.util.BukkitService;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -17,6 +18,7 @@ public class DataManager {
private final AuthMe plugin; private final AuthMe plugin;
private final PluginHooks pluginHooks; private final PluginHooks pluginHooks;
private final BukkitService bukkitService;
/** /**
* Constructor for DataManager. * Constructor for DataManager.
@ -24,9 +26,10 @@ public class DataManager {
* @param plugin The plugin instance * @param plugin The plugin instance
* @param pluginHooks Plugin hooks instance * @param pluginHooks Plugin hooks instance
*/ */
public DataManager(AuthMe plugin, PluginHooks pluginHooks) { public DataManager(AuthMe plugin, PluginHooks pluginHooks, BukkitService bukkitService) {
this.plugin = plugin; this.plugin = plugin;
this.pluginHooks = pluginHooks; this.pluginHooks = pluginHooks;
this.bukkitService = bukkitService;
} }
private List<OfflinePlayer> getOfflinePlayers(List<String> names) { private List<OfflinePlayer> getOfflinePlayers(List<String> names) {
@ -148,11 +151,9 @@ public class DataManager {
ConsoleLogger.showError("Unable to access permissions manager instance!"); ConsoleLogger.showError("Unable to access permissions manager instance!");
return; return;
} }
int i = 0;
for (String name : cleared) { for (String name : cleared) {
permsMan.removeAllGroups(Utils.getPlayer(name)); permsMan.removeAllGroups(bukkitService.getPlayerExact(name));
i++;
} }
ConsoleLogger.info("AutoPurge: Removed permissions from " + i + " player(s)."); ConsoleLogger.info("AutoPurge: Removed permissions from " + cleared.size() + " player(s).");
} }
} }

View File

@ -14,8 +14,10 @@ import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.NewSetting; import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.util.BukkitService;
import fr.xephi.authme.util.ValidationService; import fr.xephi.authme.util.ValidationService;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List; import java.util.List;
@ -36,13 +38,15 @@ public class CommandService {
private final SpawnLoader spawnLoader; private final SpawnLoader spawnLoader;
private final AntiBot antiBot; private final AntiBot antiBot;
private final ValidationService validationService; private final ValidationService validationService;
private final BukkitService bukkitService;
/* /*
* Constructor. * Constructor.
*/ */
public CommandService(AuthMe authMe, CommandMapper commandMapper, HelpProvider helpProvider, Messages messages, public CommandService(AuthMe authMe, CommandMapper commandMapper, HelpProvider helpProvider, Messages messages,
PasswordSecurity passwordSecurity, PermissionsManager permissionsManager, NewSetting settings, PasswordSecurity passwordSecurity, PermissionsManager permissionsManager, NewSetting settings,
PluginHooks pluginHooks, SpawnLoader spawnLoader, AntiBot antiBot, ValidationService validationService) { PluginHooks pluginHooks, SpawnLoader spawnLoader, AntiBot antiBot,
ValidationService validationService, BukkitService bukkitService) {
this.authMe = authMe; this.authMe = authMe;
this.messages = messages; this.messages = messages;
this.helpProvider = helpProvider; this.helpProvider = helpProvider;
@ -54,6 +58,7 @@ public class CommandService {
this.spawnLoader = spawnLoader; this.spawnLoader = spawnLoader;
this.antiBot = antiBot; this.antiBot = antiBot;
this.validationService = validationService; this.validationService = validationService;
this.bukkitService = bukkitService;
} }
/** /**
@ -222,4 +227,8 @@ public class CommandService {
return validationService.isEmailFreeForRegistration(email, sender); return validationService.isEmailFreeForRegistration(email, sender);
} }
public Player getPlayer(String name) {
return bukkitService.getPlayerExact(name);
}
} }

View File

@ -2,13 +2,13 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.util.Utils;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.List; import java.util.List;
import static fr.xephi.authme.permission.PlayerPermission.CAN_LOGIN_BE_FORCED;
/** /**
* Forces the login of a player, i.e. logs the player in without the need of a (correct) password. * Forces the login of a player, i.e. logs the player in without the need of a (correct) password.
*/ */
@ -19,15 +19,14 @@ public class ForceLoginCommand implements ExecutableCommand {
// Get the player query // Get the player query
String playerName = arguments.isEmpty() ? sender.getName() : arguments.get(0); String playerName = arguments.isEmpty() ? sender.getName() : arguments.get(0);
Player player = Utils.getPlayer(playerName); Player player = commandService.getPlayer(playerName);
if (player == null || !player.isOnline()) { if (player == null || !player.isOnline()) {
sender.sendMessage("Player needs to be online!"); sender.sendMessage("Player needs to be online!");
} else if (!commandService.getPermissionsManager() } else if (!commandService.getPermissionsManager().hasPermission(player, CAN_LOGIN_BE_FORCED)) {
.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)) { sender.sendMessage("You cannot force login the player " + playerName + "!");
sender.sendMessage("You cannot force login for the player " + playerName + "!");
} else { } else {
commandService.getManagement().performLogin(player, "dontneed", true); commandService.getManagement().performLogin(player, "dontneed", true);
sender.sendMessage("Force Login for " + playerName + " performed!"); sender.sendMessage("Force login for " + playerName + " performed!");
} }
} }
} }

View File

@ -2,8 +2,6 @@ package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService; import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.settings.properties.HooksSettings;
import fr.xephi.authme.util.Utils;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -14,9 +12,9 @@ public class GetIpCommand implements ExecutableCommand {
@Override @Override
public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) { public void executeCommand(CommandSender sender, List<String> arguments, CommandService commandService) {
// Get the player query // Get the player query
String playerName = (arguments.size() >= 1) ? arguments.get(0) : sender.getName(); String playerName = arguments.get(0);
Player player = Utils.getPlayer(playerName); Player player = commandService.getPlayer(playerName);
if (player == null) { if (player == null) {
sender.sendMessage("The player is not online"); sender.sendMessage("The player is not online");
return; return;
@ -24,6 +22,5 @@ public class GetIpCommand implements ExecutableCommand {
sender.sendMessage(player.getName() + "'s IP is: " + player.getAddress().getAddress().getHostAddress() sender.sendMessage(player.getName() + "'s IP is: " + player.getAddress().getAddress().getHostAddress()
+ ":" + player.getAddress().getPort()); + ":" + player.getAddress().getPort());
} }
} }

View File

@ -6,8 +6,8 @@ import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.output.MessageKey; import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.security.crypts.HashedPassword; import fr.xephi.authme.security.crypts.HashedPassword;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List; import java.util.List;
@ -52,11 +52,12 @@ public class RegisterAdminCommand implements ExecutableCommand {
return; return;
} }
commandService.getDataSource().setUnlogged(playerNameLowerCase); commandService.getDataSource().setUnlogged(playerNameLowerCase);
if (Bukkit.getPlayerExact(playerName) != null) {
Bukkit.getPlayerExact(playerName).kickPlayer("An admin just registered you, please log again"); commandService.send(sender, MessageKey.REGISTER_SUCCESS);
} else { ConsoleLogger.info(sender.getName() + " registered " + playerName);
commandService.send(sender, MessageKey.REGISTER_SUCCESS); Player player = commandService.getPlayer(playerName);
ConsoleLogger.info(playerName + " registered"); if (player != null) {
player.kickPlayer("An admin just registered you, please log in again");
} }
} }
}); });

View File

@ -49,7 +49,7 @@ public class UnregisterAdminCommand implements ExecutableCommand {
} }
// Unregister the player // Unregister the player
Player target = Utils.getPlayer(playerNameLowerCase); Player target = commandService.getPlayer(playerNameLowerCase);
PlayerCache.getInstance().removePlayer(playerNameLowerCase); PlayerCache.getInstance().removePlayer(playerNameLowerCase);
Utils.setGroup(target, Utils.GroupType.UNREGISTERED); Utils.setGroup(target, Utils.GroupType.UNREGISTERED);
if (target != null && target.isOnline()) { if (target != null && target.isOnline()) {

View File

@ -17,6 +17,7 @@ import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerStatePermission; import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.process.Management; import fr.xephi.authme.process.Management;
import fr.xephi.authme.settings.Settings; import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.util.BukkitService;
import fr.xephi.authme.util.GeoLiteAPI; import fr.xephi.authme.util.GeoLiteAPI;
import fr.xephi.authme.util.Utils; import fr.xephi.authme.util.Utils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -53,7 +54,7 @@ import java.util.concurrent.ConcurrentHashMap;
import static fr.xephi.authme.listener.ListenerService.shouldCancelEvent; import static fr.xephi.authme.listener.ListenerService.shouldCancelEvent;
/** /**
* Listener class for player's events * Listener class for player events.
*/ */
public class AuthMePlayerListener implements Listener { public class AuthMePlayerListener implements Listener {
@ -64,14 +65,16 @@ public class AuthMePlayerListener implements Listener {
private final DataSource dataSource; private final DataSource dataSource;
private final AntiBot antiBot; private final AntiBot antiBot;
private final Management management; private final Management management;
private final BukkitService bukkitService;
public AuthMePlayerListener(AuthMe plugin, Messages messages, DataSource dataSource, AntiBot antiBot, public AuthMePlayerListener(AuthMe plugin, Messages messages, DataSource dataSource, AntiBot antiBot,
Management management) { Management management, BukkitService bukkitService) {
this.plugin = plugin; this.plugin = plugin;
this.m = messages; this.m = messages;
this.dataSource = dataSource; this.dataSource = dataSource;
this.antiBot = antiBot; this.antiBot = antiBot;
this.management = management; this.management = management;
this.bukkitService = bukkitService;
} }
private void handleChat(AsyncPlayerChatEvent event) { private void handleChat(AsyncPlayerChatEvent event) {
@ -94,7 +97,7 @@ public class AuthMePlayerListener implements Listener {
} }
private void sendLoginOrRegisterMessage(final Player player) { private void sendLoginOrRegisterMessage(final Player player) {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { bukkitService.runTaskAsynchronously(new Runnable() {
@Override @Override
public void run() { public void run() {
if (dataSource.isAuthAvailable(player.getName().toLowerCase())) { if (dataSource.isAuthAvailable(player.getName().toLowerCase())) {
@ -236,7 +239,7 @@ public class AuthMePlayerListener implements Listener {
// Shedule login task so works after the prelogin // Shedule login task so works after the prelogin
// (Fix found by Koolaid5000) // (Fix found by Koolaid5000)
Bukkit.getScheduler().runTask(plugin, new Runnable() { bukkitService.runTask(new Runnable() {
@Override @Override
public void run() { public void run() {
management.performJoin(player); management.performJoin(player);
@ -277,7 +280,7 @@ public class AuthMePlayerListener implements Listener {
} }
final String name = event.getName().toLowerCase(); final String name = event.getName().toLowerCase();
final Player player = Utils.getPlayer(name); final Player player = bukkitService.getPlayerExact(name);
// Check if forceSingleSession is set to true, so kick player that has // Check if forceSingleSession is set to true, so kick player that has
// joined with same nick of online player // joined with same nick of online player
if (player != null && Settings.isForceSingleSessionEnabled) { if (player != null && Settings.isForceSingleSessionEnabled) {

View File

@ -2,6 +2,11 @@ package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe; import fr.xephi.authme.AuthMe;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import java.util.Set;
/** /**
* Service for operations requiring server entities, such as for scheduling. * Service for operations requiring server entities, such as for scheduling.
@ -44,6 +49,33 @@ public class BukkitService {
return Bukkit.getScheduler().scheduleSyncDelayedTask(authMe, task, delay); return Bukkit.getScheduler().scheduleSyncDelayedTask(authMe, task, delay);
} }
/**
* Returns a task that will run on the next server tick.
*
* @param task the task to be run
* @return a BukkitTask that contains the id number
* @throws IllegalArgumentException if plugin is null
* @throws IllegalArgumentException if task is null
*/
public BukkitTask runTask(Runnable task) {
return Bukkit.getScheduler().runTask(authMe, task);
}
/**
* <b>Asynchronous tasks should never access any API in Bukkit. Great care
* should be taken to assure the thread-safety of asynchronous tasks.</b>
* <p>
* Returns a task that will run asynchronously.
*
* @param task the task to be run
* @return a BukkitTask that contains the id number
* @throws IllegalArgumentException if plugin is null
* @throws IllegalArgumentException if task is null
*/
public BukkitTask runTaskAsynchronously(Runnable task) {
return Bukkit.getScheduler().runTaskAsynchronously(authMe, task);
}
/** /**
* Broadcast a message to all players. * Broadcast a message to all players.
* *
@ -54,4 +86,24 @@ public class BukkitService {
return Bukkit.broadcastMessage(message); return Bukkit.broadcastMessage(message);
} }
/**
* Gets the player with the exact given name, case insensitive.
*
* @param name Exact name of the player to retrieve
* @return a player object if one was found, null otherwise
*/
public Player getPlayerExact(String name) {
return authMe.getServer().getPlayerExact(name);
}
/**
* Gets a set containing all banned players.
*
* @return a set containing banned players
*/
public Set<OfflinePlayer> getBannedPlayers() {
Bukkit.getBannedPlayers();
return authMe.getServer().getBannedPlayers();
}
} }

View File

@ -232,10 +232,6 @@ public final class Utils {
} }
} }
public static Player getPlayer(String name) {
return wrapper.getServer().getPlayerExact(name); // bukkit will lowercase the input
}
public static boolean isNPC(Player player) { public static boolean isNPC(Player player) {
return player.hasMetadata("NPC") || plugin.getPluginHooks().isNpcInCombatTagPlus(player); return player.hasMetadata("NPC") || plugin.getPluginHooks().isNpcInCombatTagPlus(player);
} }

View File

@ -14,6 +14,7 @@ import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.SpawnLoader; import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.domain.Property; import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.settings.properties.SecuritySettings; import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.util.BukkitService;
import fr.xephi.authme.util.ValidationService; import fr.xephi.authme.util.ValidationService;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -63,11 +64,13 @@ public class CommandServiceTest {
private AntiBot antiBot; private AntiBot antiBot;
@Mock @Mock
private ValidationService validationService; private ValidationService validationService;
@Mock
private BukkitService bukkitService;
@Before @Before
public void setUpService() { public void setUpService() {
commandService = new CommandService(authMe, commandMapper, helpProvider, messages, passwordSecurity, commandService = new CommandService(authMe, commandMapper, helpProvider, messages, passwordSecurity,
permissionsManager, settings, pluginHooks, spawnLoader, antiBot, validationService); permissionsManager, settings, pluginHooks, spawnLoader, antiBot, validationService, bukkitService);
} }
@Test @Test
@ -265,4 +268,19 @@ public class CommandServiceTest {
verify(validationService).isEmailFreeForRegistration(email, sender); verify(validationService).isEmailFreeForRegistration(email, sender);
} }
@Test
public void shouldGetPlayer() {
// given
String playerName = "_tester";
Player player = mock(Player.class);
given(bukkitService.getPlayerExact(playerName)).willReturn(player);
// when
Player result = commandService.getPlayer(playerName);
// then
assertThat(result, equalTo(player));
verify(bukkitService).getPlayerExact(playerName);
}
} }

View File

@ -0,0 +1,146 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.process.Management;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collections;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Test for {@link ForceLoginCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class ForceLoginCommandTest {
@Mock
private CommandService commandService;
@Test
public void shouldRejectOfflinePlayer() {
// given
String playerName = "Bobby";
Player player = mockPlayer(false, playerName);
given(commandService.getPlayer(playerName)).willReturn(player);
CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ForceLoginCommand();
// when
command.executeCommand(sender, Collections.singletonList(playerName), commandService);
// then
verify(commandService).getPlayer(playerName);
verify(sender).sendMessage(argThat(equalTo("Player needs to be online!")));
verify(commandService, never()).getManagement();
}
@Test
public void shouldRejectInexistentPlayer() {
// given
String playerName = "us3rname01";
given(commandService.getPlayer(playerName)).willReturn(null);
CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ForceLoginCommand();
// when
command.executeCommand(sender, Collections.singletonList(playerName), commandService);
// then
verify(commandService).getPlayer(playerName);
verify(sender).sendMessage(argThat(equalTo("Player needs to be online!")));
verify(commandService, never()).getManagement();
}
@Test
public void shouldRejectPlayerWithMissingPermission() {
// given
String playerName = "testTest";
Player player = mockPlayer(true, playerName);
given(commandService.getPlayer(playerName)).willReturn(player);
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(false);
given(commandService.getPermissionsManager()).willReturn(permissionsManager);
CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ForceLoginCommand();
// when
command.executeCommand(sender, Collections.singletonList(playerName), commandService);
// then
verify(commandService).getPlayer(playerName);
verify(sender).sendMessage(argThat(containsString("You cannot force login the player")));
verify(commandService, never()).getManagement();
}
@Test
public void shouldForceLoginPlayer() {
// given
String playerName = "tester23";
Player player = mockPlayer(true, playerName);
given(commandService.getPlayer(playerName)).willReturn(player);
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true);
given(commandService.getPermissionsManager()).willReturn(permissionsManager);
Management management = mock(Management.class);
given(commandService.getManagement()).willReturn(management);
CommandSender sender = mock(CommandSender.class);
ExecutableCommand command = new ForceLoginCommand();
// when
command.executeCommand(sender, Collections.singletonList(playerName), commandService);
// then
verify(commandService).getPlayer(playerName);
verify(management).performLogin(eq(player), anyString(), eq(true));
}
@Test
public void shouldForceLoginSenderSelf() {
// given
String senderName = "tester23";
Player player = mockPlayer(true, senderName);
given(commandService.getPlayer(senderName)).willReturn(player);
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true);
given(commandService.getPermissionsManager()).willReturn(permissionsManager);
Management management = mock(Management.class);
given(commandService.getManagement()).willReturn(management);
CommandSender sender = mock(CommandSender.class);
given(sender.getName()).willReturn(senderName);
ExecutableCommand command = new ForceLoginCommand();
// when
command.executeCommand(sender, Collections.<String>emptyList(), commandService);
// then
verify(commandService).getPlayer(senderName);
verify(management).performLogin(eq(player), anyString(), eq(true));
}
private static Player mockPlayer(boolean isOnline, String name) {
Player player = mock(Player.class);
given(player.isOnline()).willReturn(isOnline);
given(player.getName()).willReturn(name);
return player;
}
}

View File

@ -0,0 +1,75 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Collections;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Test for {@link GetIpCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class GetIpCommandTest {
@Mock
private CommandService commandService;
@Mock
private CommandSender sender;
@Test
public void shouldGetIpOfPlayer() {
// given
given(commandService.getPlayer(anyString())).willReturn(null);
ExecutableCommand command = new GetIpCommand();
// when
command.executeCommand(sender, Collections.singletonList("Testt"), commandService);
// then
verify(commandService).getPlayer("Testt");
verify(sender).sendMessage(argThat(containsString("not online")));
}
@Test
public void shouldReturnIpAddressOfPlayer() {
// given
String playerName = "charlie";
String ip = "123.34.56.88";
Player player = mockPlayer(playerName, ip);
given(commandService.getPlayer(playerName)).willReturn(player);
ExecutableCommand command = new GetIpCommand();
// when
command.executeCommand(sender, Collections.singletonList(playerName), commandService);
// then
verify(commandService).getPlayer(playerName);
verify(sender).sendMessage(argThat(allOf(containsString(playerName), containsString(ip))));
}
private static Player mockPlayer(String name, String ip) {
Player player = mock(Player.class);
given(player.getName()).willReturn(name);
InetAddress inetAddress = mock(InetAddress.class);
given(inetAddress.getHostAddress()).willReturn(ip);
InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 8093);
given(player.getAddress()).willReturn(inetSocketAddress);
return player;
}
}

View File

@ -0,0 +1,182 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.ConsoleLoggerTestInitializer;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Arrays;
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.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Test for {@link RegisterAdminCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class RegisterAdminCommandTest {
@Mock
private CommandSender sender;
@Mock
private CommandService commandService;
@BeforeClass
public static void setUpLogger() {
ConsoleLoggerTestInitializer.setupLogger();
}
@Test
public void shouldRejectInvalidPassword() {
// given
String user = "tester";
String password = "myPassword";
given(commandService.validatePassword(password, user)).willReturn(MessageKey.INVALID_PASSWORD_LENGTH);
ExecutableCommand command = new RegisterAdminCommand();
// when
command.executeCommand(sender, Arrays.asList(user, password), commandService);
// then
verify(commandService).validatePassword(password, user);
verify(commandService).send(sender, MessageKey.INVALID_PASSWORD_LENGTH);
verify(commandService, never()).runTaskAsynchronously(any(Runnable.class));
}
@Test
public void shouldRejectAlreadyRegisteredAccount() {
// given
String user = "my_name55";
String password = "@some-pass@";
given(commandService.validatePassword(password, user)).willReturn(null);
DataSource dataSource = mock(DataSource.class);
given(dataSource.isAuthAvailable(user)).willReturn(true);
given(commandService.getDataSource()).willReturn(dataSource);
ExecutableCommand command = new RegisterAdminCommand();
// when
command.executeCommand(sender, Arrays.asList(user, password), commandService);
TestHelper.runInnerRunnable(commandService);
// then
verify(commandService).validatePassword(password, user);
verify(commandService).send(sender, MessageKey.NAME_ALREADY_REGISTERED);
verify(dataSource, never()).saveAuth(any(PlayerAuth.class));
}
@Test
public void shouldHandleSavingError() {
// given
String user = "test-test";
String password = "afdjhfkt";
given(commandService.validatePassword(password, user)).willReturn(null);
DataSource dataSource = mock(DataSource.class);
given(dataSource.isAuthAvailable(user)).willReturn(false);
given(dataSource.saveAuth(any(PlayerAuth.class))).willReturn(false);
given(commandService.getDataSource()).willReturn(dataSource);
PasswordSecurity passwordSecurity = mock(PasswordSecurity.class);
HashedPassword hashedPassword = new HashedPassword("235sdf4w5udsgf");
given(passwordSecurity.computeHash(password, user)).willReturn(hashedPassword);
given(commandService.getPasswordSecurity()).willReturn(passwordSecurity);
ExecutableCommand command = new RegisterAdminCommand();
// when
command.executeCommand(sender, Arrays.asList(user, password), commandService);
TestHelper.runInnerRunnable(commandService);
// then
verify(commandService).validatePassword(password, user);
verify(commandService).send(sender, MessageKey.ERROR);
ArgumentCaptor<PlayerAuth> captor = ArgumentCaptor.forClass(PlayerAuth.class);
verify(dataSource).saveAuth(captor.capture());
assertAuthHasInfo(captor.getValue(), user, hashedPassword);
}
@Test
public void shouldRegisterOfflinePlayer() {
// given
String user = "someone";
String password = "Al1O3P49S5%";
given(commandService.validatePassword(password, user)).willReturn(null);
DataSource dataSource = mock(DataSource.class);
given(dataSource.isAuthAvailable(user)).willReturn(false);
given(dataSource.saveAuth(any(PlayerAuth.class))).willReturn(true);
given(commandService.getDataSource()).willReturn(dataSource);
PasswordSecurity passwordSecurity = mock(PasswordSecurity.class);
HashedPassword hashedPassword = new HashedPassword("$aea2345EW235dfsa@#R%987048");
given(passwordSecurity.computeHash(password, user)).willReturn(hashedPassword);
given(commandService.getPasswordSecurity()).willReturn(passwordSecurity);
given(commandService.getPlayer(user)).willReturn(null);
ExecutableCommand command = new RegisterAdminCommand();
// when
command.executeCommand(sender, Arrays.asList(user, password), commandService);
TestHelper.runInnerRunnable(commandService);
// then
verify(commandService).validatePassword(password, user);
verify(commandService).send(sender, MessageKey.REGISTER_SUCCESS);
ArgumentCaptor<PlayerAuth> captor = ArgumentCaptor.forClass(PlayerAuth.class);
verify(dataSource).saveAuth(captor.capture());
assertAuthHasInfo(captor.getValue(), user, hashedPassword);
verify(dataSource).setUnlogged(user);
}
@Test
public void shouldRegisterOnlinePlayer() {
// given
String user = "someone";
String password = "Al1O3P49S5%";
given(commandService.validatePassword(password, user)).willReturn(null);
DataSource dataSource = mock(DataSource.class);
given(dataSource.isAuthAvailable(user)).willReturn(false);
given(dataSource.saveAuth(any(PlayerAuth.class))).willReturn(true);
given(commandService.getDataSource()).willReturn(dataSource);
PasswordSecurity passwordSecurity = mock(PasswordSecurity.class);
HashedPassword hashedPassword = new HashedPassword("$aea2345EW235dfsa@#R%987048");
given(passwordSecurity.computeHash(password, user)).willReturn(hashedPassword);
given(commandService.getPasswordSecurity()).willReturn(passwordSecurity);
Player player = mock(Player.class);
given(commandService.getPlayer(user)).willReturn(player);
ExecutableCommand command = new RegisterAdminCommand();
// when
command.executeCommand(sender, Arrays.asList(user, password), commandService);
TestHelper.runInnerRunnable(commandService);
// then
verify(commandService).validatePassword(password, user);
verify(commandService).send(sender, MessageKey.REGISTER_SUCCESS);
ArgumentCaptor<PlayerAuth> captor = ArgumentCaptor.forClass(PlayerAuth.class);
verify(dataSource).saveAuth(captor.capture());
assertAuthHasInfo(captor.getValue(), user, hashedPassword);
verify(dataSource).setUnlogged(user);
verify(player).kickPlayer(argThat(containsString("please log in again")));
}
private void assertAuthHasInfo(PlayerAuth auth, String name, HashedPassword hashedPassword) {
assertThat(auth.getRealName(), equalTo(name));
assertThat(auth.getNickname(), equalTo(name.toLowerCase()));
assertThat(auth.getPassword(), equalTo(hashedPassword));
}
}