Merge origin/enum into local branch

This commit is contained in:
ljacqu
2015-11-25 22:18:21 +01:00
185 changed files with 10883 additions and 9491 deletions
@@ -0,0 +1,36 @@
package fr.xephi.authme;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.util.Wrapper;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Test for {@link AntiBot}.
*/
public class AntiBotTest {
private Wrapper wrapper;
@Before
public void setUpMocks() {
AuthMeMockUtil.mockAuthMeInstance();
wrapper = AuthMeMockUtil.insertMockWrapperInstance(AntiBot.class, "wrapper");
}
@Test
public void shouldNotEnableAntiBot() {
// given
Settings.enableAntiBot = false;
// when
AntiBot.setupAntiBotService();
// then
verify(wrapper.getScheduler(), never()).scheduleSyncDelayedTask(any(AuthMe.class), any(Runnable.class));
}
}
@@ -2,6 +2,7 @@ package fr.xephi.authme;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.settings.Messages;
import fr.xephi.authme.util.Wrapper;
import org.mockito.Mockito;
import java.lang.reflect.Field;
@@ -16,15 +17,18 @@ public final class AuthMeMockUtil {
}
/**
* Sets the AuthMe plugin instance to a mock object. Use {@link AuthMe#getInstance()} to retrieve the mock.
* Set the AuthMe plugin instance to a mock object. Use {@link AuthMe#getInstance()} to retrieve the mock.
*
* @return The generated mock for the AuthMe instance
*/
public static void mockAuthMeInstance() {
public static AuthMe mockAuthMeInstance() {
AuthMe mock = Mockito.mock(AuthMe.class);
mockSingletonForClass(AuthMe.class, "plugin", mock);
return mock;
}
/**
* Creates a mock Messages object for the instance returned from {@link Messages#getInstance()}.
* Create a mock Messages object for the instance returned from {@link Messages#getInstance()}.
*/
public static void mockMessagesInstance() {
Messages mock = Mockito.mock(Messages.class);
@@ -40,11 +44,39 @@ public final class AuthMeMockUtil {
}
/**
* Sets a field of a class to the given mock.
* Set the given class' {@link Wrapper} field to a mock implementation.
*
* @param clazz the class to modify
* @param fieldName the field name
* @param mock the mock to set for the given field
* @param clazz The class to modify
* @param fieldName The name of the field containing the Wrapper in the class
*
* @return The generated Wrapper mock
* @see WrapperMock
*/
public static Wrapper insertMockWrapperInstance(Class<?> clazz, String fieldName) {
Wrapper wrapperMock = new WrapperMock();
mockSingletonForClass(clazz, fieldName, wrapperMock);
return wrapperMock;
}
public static Wrapper insertMockWrapperInstance(Class<?> clazz, String fieldName, AuthMe authMe) {
Wrapper wrapperMock = new WrapperMock(authMe);
mockSingletonForClass(clazz, fieldName, wrapperMock);
return wrapperMock;
}
// TODO ljacqu 20151123: Find the use cases for the WrapperMock and remove any of these
// methods that will end up unused
public static Wrapper insertMockWrapperInstance(Class<?> clazz, String fieldName, WrapperMock wrapperMock) {
mockSingletonForClass(clazz, fieldName, wrapperMock);
return wrapperMock;
}
/**
* Set a field of a class to the given mock.
*
* @param clazz The class to modify
* @param fieldName The field name
* @param mock The mock to set for the given field
*/
private static void mockSingletonForClass(Class<?> clazz, String fieldName, Object mock) {
try {
@@ -97,7 +97,7 @@ public class Log4JFilterTest {
@Test
public void shouldFilterSensitiveStringMessage() {
// given / when
Result result = log4JFilter.filter(null, null, null, SENSITIVE_COMMAND, new Object[0]);
Result result = log4JFilter.filter(null, null, null, SENSITIVE_COMMAND);
// then
assertThat(result, equalTo(Result.DENY));
@@ -106,7 +106,7 @@ public class Log4JFilterTest {
@Test
public void shouldNotFilterNormalStringMessage() {
// given / when
Result result = log4JFilter.filter(null, null, null, NORMAL_COMMAND, new Object[0]);
Result result = log4JFilter.filter(null, null, null, NORMAL_COMMAND);
// then
assertThat(result, equalTo(Result.NEUTRAL));
@@ -115,7 +115,7 @@ public class Log4JFilterTest {
@Test
public void shouldNotFilterNonCommandStringMessage() {
// given / when
Result result = log4JFilter.filter(null, null, null, OTHER_COMMAND, new Object[0]);
Result result = log4JFilter.filter(null, null, null, OTHER_COMMAND);
// then
assertThat(result, equalTo(Result.NEUTRAL));
@@ -124,7 +124,7 @@ public class Log4JFilterTest {
@Test
public void shouldReturnNeutralForNullMessage() {
// given / when
Result result = log4JFilter.filter(null, null, null, null, new Object[0]);
Result result = log4JFilter.filter(null, null, null, null);
// then
assertThat(result, equalTo(Result.NEUTRAL));
@@ -211,7 +211,7 @@ public class Log4JFilterTest {
@Test
public void shouldNotFilterNullMessage() {
// given / when
Result result = log4JFilter.filter(null, null, null, (Message) null, new Exception());
Result result = log4JFilter.filter(null, null, null, null, new Exception());
// then
assertThat(result, equalTo(Result.NEUTRAL));
@@ -0,0 +1,60 @@
package fr.xephi.authme;
import fr.xephi.authme.util.Wrapper;
import org.bukkit.Server;
import org.bukkit.scheduler.BukkitScheduler;
import org.mockito.Mockito;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Class returning mocks for all calls in {@link Wrapper}.
* This class keeps track of its mocks and will always return
* the same one for each type.
*/
public class WrapperMock extends Wrapper {
private static Map<Class<?>, Object> mocks = new HashMap<>();
public WrapperMock() {
this((AuthMe) getMock(AuthMe.class));
}
public WrapperMock(AuthMe authMe) {
super(authMe);
}
@Override
public Logger getLogger() {
return getMock(Logger.class);
}
@Override
public Server getServer() {
return getMock(Server.class);
}
@Override
public AuthMe getAuthMe() {
return getMock(AuthMe.class);
}
@Override
public BukkitScheduler getScheduler() {
return getMock(BukkitScheduler.class);
}
@SuppressWarnings("unchecked")
private static <T> T getMock(Class<?> clazz) {
Object o = mocks.get(clazz);
if (o == null) {
o = Mockito.mock(clazz);
mocks.put(clazz, o);
}
return (T) o;
}
}
@@ -0,0 +1,33 @@
package fr.xephi.authme.settings;
import fr.xephi.authme.util.StringUtils;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.fail;
/**
* Test for {@link MessageKey}.
*/
public class MessageKeyTest {
@Test
public void shouldHaveUniqueMessageKeys() {
// given
MessageKey[] messageKeys = MessageKey.values();
Set<String> keys = new HashSet<>();
// when / then
for (MessageKey messageKey : messageKeys) {
String key = messageKey.getKey();
if (keys.contains(key)) {
fail("Found key '" + messageKey.getKey() + "' twice!");
} else if (StringUtils.isEmpty(key)) {
fail("Key for message key '" + messageKey + "' is empty");
}
keys.add(key);
}
}
}
@@ -0,0 +1,129 @@
package fr.xephi.authme.settings;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.AuthMeMockUtil;
import fr.xephi.authme.ConsoleLogger;
import org.bukkit.entity.Player;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.File;
import java.net.URL;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
/**
* Test for {@link Messages}.
*/
public class MessagesTest {
private static final String YML_TEST_FILE = "messages_test.yml";
private Messages messages;
/**
* Loads the messages in the file {@code messages_test.yml} in the test resources folder.
* The file does not contain all messages defined in {@link MessageKey} and its contents
* reflect various test cases -- not what the keys stand for.
*/
@Before
public void setUpMessages() {
AuthMe authMe = AuthMeMockUtil.mockAuthMeInstance();
AuthMeMockUtil.insertMockWrapperInstance(ConsoleLogger.class, "wrapper", authMe);
Settings.messagesLanguage = "en";
URL url = getClass().getClassLoader().getResource(YML_TEST_FILE);
if (url == null) {
throw new RuntimeException("File '" + YML_TEST_FILE + "' could not be loaded");
}
File file = new File(url.getFile());
messages = new Messages(file, "en");
}
@Test
public void shouldLoadMessageAndSplitAtNewLines() {
// given
MessageKey key = MessageKey.UNKNOWN_USER;
// when
String[] send = messages.retrieve(key);
// then
String[] lines = new String[]{"This test message", "includes", "some new lines"};
assertThat(send, equalTo(lines));
}
@Test
public void shouldFormatColorCodes() {
// given
MessageKey key = MessageKey.UNSAFE_QUIT_LOCATION;
// when
String[] message = messages.retrieve(key);
// then
assertThat(message, arrayWithSize(1));
assertThat(message[0], equalTo("§cHere we have§bdefined some colors §dand some other §lthings"));
}
@Test
public void shouldRetainApostrophes() {
// given
MessageKey key = MessageKey.NOT_LOGGED_IN;
// when
String[] message = messages.retrieve(key);
// then
assertThat(message, arrayWithSize(1));
assertThat(message[0], equalTo("Apostrophes ' should be loaded correctly, don't you think?"));
}
@Test
public void shouldReturnErrorForUnknownCode() {
// given
// The following is a key that is not defined in the test file
MessageKey key = MessageKey.UNREGISTERED_SUCCESS;
// when
String[] message = messages.retrieve(key);
// then
assertThat(message, arrayWithSize(1));
assertThat(message[0], startsWith("Error getting message with key '"));
}
@Test
public void shouldSendMessageToPlayer() {
// given
MessageKey key = MessageKey.UNSAFE_QUIT_LOCATION;
Player player = Mockito.mock(Player.class);
// when
messages.send(player, key);
// then
verify(player).sendMessage("§cHere we have§bdefined some colors §dand some other §lthings");
}
@Test
public void shouldSendMultiLineMessageToPlayer() {
// given
MessageKey key = MessageKey.UNKNOWN_USER;
Player player = Mockito.mock(Player.class);
// when
messages.send(player, key);
// then
String[] lines = new String[]{"This test message", "includes", "some new lines"};
for (String line : lines) {
verify(player).sendMessage(line);
}
}
}
@@ -0,0 +1,123 @@
package fr.xephi.authme.util;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.AuthMeMockUtil;
import fr.xephi.authme.WrapperMock;
import fr.xephi.authme.permission.PermissionsManager;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Collection;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test for the {@link Utils} class.
*/
@Ignore
// TODO ljacqu 20151123: Fix test setup
public class UtilsTest {
private AuthMe authMeMock;
private PermissionsManager permissionsManagerMock;
private Wrapper wrapperMock;
@Before
public void setUpMocks() {
authMeMock = AuthMeMockUtil.mockAuthMeInstance();
// We need to create the Wrapper mock before injecting it into Utils because it runs a lot of code in
// a static block which needs the proper mocks to be set up.
wrapperMock = new WrapperMock(authMeMock);
Server serverMock = wrapperMock.getServer();
BukkitScheduler schedulerMock = mock(BukkitScheduler.class);
when(serverMock.getScheduler()).thenReturn(schedulerMock);
when(schedulerMock.runTaskAsynchronously(any(Plugin.class), any(Runnable.class)))
.thenReturn(mock(BukkitTask.class));
System.out.println("Initialized scheduler mock for server mock");
AuthMeMockUtil.insertMockWrapperInstance(Utils.class, "wrapper", (WrapperMock) wrapperMock);
System.out.println("Iniadfk");
permissionsManagerMock = mock(PermissionsManager.class);
when(authMeMock.getPermissionsManager()).thenReturn(permissionsManagerMock);
}
// TODO ljacques 20151122: The tests for Utils.forceGM somehow can't be set up with the mocks correctly
/*@Test
public void shouldForceSurvivalGameMode() {
// given
Player player = mock(Player.class);
given(permissionsManagerMock.hasPermission(player, "authme.bypassforcesurvival")).willReturn(false);
// when
Utils.forceGM(player);
// then
verify(player).setGameMode(GameMode.SURVIVAL);
}
@Test
public void shouldNotForceGameModeForUserWithBypassPermission() {
// given
Player player = mock(Player.class);
given(permissionsManagerMock.hasPermission(player, "authme.bypassforcesurvival")).willReturn(true);
// when
Utils.forceGM(player);
// then
verify(authMeMock).getPermissionsManager();
verify(permissionsManagerMock).hasPermission(player, "authme.bypassforcesurvival");
verify(player, never()).setGameMode(any(GameMode.class));
}*/
@Test
// Note ljacqu 20151122: This is a heavy test setup with Reflections... If it causes trouble, skip it with @Ignore
public void shouldRetrieveListOfOnlinePlayersFromReflectedMethod() {
// given
setField("getOnlinePlayersIsCollection", false);
try {
setField("getOnlinePlayers", UtilsTest.class.getDeclaredMethod("onlinePlayersImpl"));
} catch (NoSuchMethodException e) {
throw new RuntimeException("Cannot initialize test with custom test method", e);
}
// when
Collection<? extends Player> players = Utils.getOnlinePlayers();
// then
assertThat(players, hasSize(2));
}
private static void setField(String name, Object value) {
try {
Field field = Utils.class.getDeclaredField(name);
field.setAccessible(true);
field.set(null, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Could not set field '" + name + "'", e);
}
}
public static Player[] onlinePlayersImpl() {
return new Player[]{
mock(Player.class), mock(Player.class)
};
}
}
+6
View File
@@ -0,0 +1,6 @@
unknown_user: 'This test message&nincludes&nsome new lines'
unsafe_spawn: '&cHere we have&bdefined some colors &dand some other &lthings'
not_logged_in: 'Apostrophes '' should be loaded correctly, don''t you think?'
reg_voluntarily: 'You can register yourself to the server with the command "/register <password> <ConfirmPassword>"'
usage_log: '&cUsage: /login <password>'
wrong_pwd: '&cWrong password!'