Merge branch 'master' of https://github.com/AuthMe-Team/AuthMeReloaded into 437-add-email

This commit is contained in:
ljacqu
2016-01-19 17:16:05 +01:00
60 changed files with 4380 additions and 752 deletions
@@ -1,5 +1,6 @@
package fr.xephi.authme.command;
import fr.xephi.authme.permission.PermissionsManager;
import org.bukkit.command.CommandSender;
import org.junit.Before;
import org.junit.Test;
@@ -7,20 +8,27 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import java.util.Collections;
import java.util.List;
import static fr.xephi.authme.command.FoundResultStatus.INCORRECT_ARGUMENTS;
import static fr.xephi.authme.command.FoundResultStatus.MISSING_BASE_COMMAND;
import static fr.xephi.authme.command.FoundResultStatus.NO_PERMISSION;
import static fr.xephi.authme.command.FoundResultStatus.SUCCESS;
import static fr.xephi.authme.command.FoundResultStatus.UNKNOWN_LABEL;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
@@ -89,7 +97,138 @@ public class CommandHandlerTest {
assertThat(captor.getValue(), contains("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
verify(serviceMock).outputMappingError(eq(sender), any(FoundCommandResult.class));
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender).sendMessage(captor.capture());
assertThat(captor.getValue(), containsString("don't have permission"));
}
@Test
public void shouldNotCallExecutableForWrongArguments() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS));
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(sender, command)).willReturn(true);
given(serviceMock.getPermissionsManager()).willReturn(permissionsManager);
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(serviceMock).mapPartsToCommand(eq(sender), captor.capture());
assertThat(captor.getValue(), contains("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender, atLeastOnce()).sendMessage(captor.capture());
assertThat(captor.getAllValues().get(0), containsString("Incorrect command arguments"));
}
@Test
public void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS));
PermissionsManager permissionsManager = mock(PermissionsManager.class);
given(permissionsManager.hasPermission(sender, command)).willReturn(false);
given(serviceMock.getPermissionsManager()).willReturn(permissionsManager);
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(serviceMock).mapPartsToCommand(eq(sender), captor.capture());
assertThat(captor.getValue(), contains("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender).sendMessage(captor.capture());
assertThat(captor.getValue(), containsString("You don't have permission"));
}
@Test
public void shouldNotCallExecutableForFailedParsing() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, MISSING_BASE_COMMAND));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(serviceMock).mapPartsToCommand(eq(sender), captor.capture());
assertThat(captor.getValue(), contains("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender).sendMessage(captor.capture());
assertThat(captor.getValue(), containsString("Failed to parse"));
}
@Test
public void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(command.getLabels()).willReturn(Collections.singletonList("test_cmd"));
given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.01, UNKNOWN_LABEL));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(serviceMock).mapPartsToCommand(eq(sender), captor.capture());
assertThat(captor.getValue(), contains("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender, times(3)).sendMessage(captor.capture());
assertThat(captor.getAllValues().get(0), containsString("Unknown command"));
assertThat(captor.getAllValues().get(1), containsString("Did you mean"));
assertThat(captor.getAllValues().get(1), containsString("/test_cmd"));
assertThat(captor.getAllValues().get(2), containsString("Use the command"));
assertThat(captor.getAllValues().get(2), containsString("to view help"));
}
@Test
public void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(command.getLabels()).willReturn(Collections.singletonList("test_cmd"));
given(serviceMock.mapPartsToCommand(any(CommandSender.class), anyListOf(String.class))).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 1.0, UNKNOWN_LABEL));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(serviceMock).mapPartsToCommand(eq(sender), captor.capture());
assertThat(captor.getValue(), contains("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender, times(2)).sendMessage(captor.capture());
assertThat(captor.getAllValues().get(0), containsString("Unknown command"));
assertThat(captor.getAllValues().get(1), containsString("Use the command"));
assertThat(captor.getAllValues().get(1), containsString("to view help"));
}
@Test
@@ -1,7 +1,5 @@
package fr.xephi.authme.command;
import fr.xephi.authme.command.help.HelpProvider;
import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PermissionsManager;
import org.bukkit.command.CommandSender;
import org.junit.Before;
@@ -43,7 +41,7 @@ public class CommandMapperTest {
@Before
public void setUpMocks() {
permissionsManagerMock = mock(PermissionsManager.class);
mapper = new CommandMapper(commands, mock(Messages.class), permissionsManagerMock, mock(HelpProvider.class));
mapper = new CommandMapper(commands, permissionsManagerMock);
}
// -----------
@@ -256,4 +254,23 @@ public class CommandMapperTest {
assertThat(result.getDifference(), equalTo(0.0));
}
@Test
public void shouldRecognizeMissingPermissionForCommand() {
// given
List<String> parts = Arrays.asList("authme", "login", "test1");
CommandSender sender = mock(CommandSender.class);
given(permissionsManagerMock.hasPermission(eq(sender), any(CommandDescription.class))).willReturn(false);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "login")));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.NO_PERMISSION));
assertThat(result.getArguments(), contains("test1"));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getLabels(), equalTo(parts.subList(0, 2)));
assertThat(result.getArguments(), contains(parts.get(2)));
}
}
@@ -8,6 +8,9 @@ import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.custom.NewSetting;
import fr.xephi.authme.settings.custom.SecuritySettings;
import fr.xephi.authme.settings.domain.Property;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Before;
@@ -36,6 +39,8 @@ public class CommandServiceTest {
private Messages messages;
private PasswordSecurity passwordSecurity;
private CommandService commandService;
private PermissionsManager permissionsManager;
private NewSetting settings;
@Before
public void setUpService() {
@@ -44,7 +49,10 @@ public class CommandServiceTest {
helpProvider = mock(HelpProvider.class);
messages = mock(Messages.class);
passwordSecurity = mock(PasswordSecurity.class);
commandService = new CommandService(authMe, commandMapper, helpProvider, messages, passwordSecurity);
permissionsManager = mock(PermissionsManager.class);
settings = mock(NewSetting.class);
commandService = new CommandService(
authMe, commandMapper, helpProvider, messages, passwordSecurity, permissionsManager, settings);
}
@Test
@@ -87,19 +95,6 @@ public class CommandServiceTest {
verify(commandMapper).mapPartsToCommand(sender, commandParts);
}
@Test
public void shouldOutputMappingError() {
// given
CommandSender sender = mock(CommandSender.class);
FoundCommandResult result = mock(FoundCommandResult.class);
// when
commandService.outputMappingError(sender, result);
// then
verify(commandMapper).outputStandardError(sender, result);
}
@Test
@Ignore
public void shouldRunTaskInAsync() {
@@ -169,16 +164,11 @@ public class CommandServiceTest {
@Test
public void shouldReturnPermissionsManager() {
// given
PermissionsManager manager = mock(PermissionsManager.class);
given(authMe.getPermissionsManager()).willReturn(manager);
// when
// given / when
PermissionsManager result = commandService.getPermissionsManager();
// then
assertThat(result, equalTo(manager));
verify(authMe).getPermissionsManager();
assertThat(result, equalTo(permissionsManager));
}
@Test
@@ -195,4 +185,18 @@ public class CommandServiceTest {
assertThat(result, equalTo(givenMessages));
verify(messages).retrieve(key);
}
@Test
public void shouldRetrieveProperty() {
// given
Property<Integer> property = SecuritySettings.CAPTCHA_LENGTH;
given(settings.getProperty(property)).willReturn(7);
// when
int result = settings.getProperty(property);
// then
assertThat(result, equalTo(7));
verify(settings).getProperty(property);
}
}
@@ -5,13 +5,12 @@ import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.custom.SecuritySettings;
import fr.xephi.authme.util.WrapperMock;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
@@ -20,6 +19,7 @@ import java.util.Collections;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -35,8 +35,8 @@ public class CaptchaCommandTest {
@Before
public void setUpWrapperMock() {
wrapperMock = WrapperMock.createInstance();
Settings.useCaptcha = true;
commandService = mock(CommandService.class);
given(commandService.getProperty(SecuritySettings.USE_CAPTCHA)).willReturn(true);
}
@Test
@@ -46,7 +46,7 @@ public class CaptchaCommandTest {
ExecutableCommand command = new CaptchaCommand();
// when
command.executeCommand(sender, new ArrayList<String>(), mock(CommandService.class));
command.executeCommand(sender, new ArrayList<String>(), commandService);
// then
assertThat(wrapperMock.wasMockCalled(AuthMe.class), equalTo(false));
@@ -54,14 +54,14 @@ public class CaptchaCommandTest {
}
@Test
@Ignore
public void shouldRejectIfCaptchaIsNotUsed() {
// given
Player player = mockPlayerWithName("testplayer");
ExecutableCommand command = new CaptchaCommand();
given(commandService.getProperty(SecuritySettings.USE_CAPTCHA)).willReturn(false);
// when
command.executeCommand(player, Collections.singletonList("1234"), mock(CommandService.class));
command.executeCommand(player, Collections.singletonList("1234"), commandService);
// then
verify(commandService).send(player, MessageKey.USAGE_LOGIN);
@@ -4,7 +4,8 @@ import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.command.CommandService;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.custom.RestrictionSettings;
import fr.xephi.authme.settings.custom.SecuritySettings;
import fr.xephi.authme.task.ChangePasswordTask;
import fr.xephi.authme.util.WrapperMock;
import org.bukkit.Server;
@@ -19,9 +20,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
@@ -44,11 +45,11 @@ public class ChangePasswordCommandTest {
cacheMock = wrapperMock.getPlayerCache();
commandService = mock(CommandService.class);
when(commandService.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).thenReturn(2);
when(commandService.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).thenReturn(50);
// Only allow passwords with alphanumerical characters for the test
Settings.getPassRegex = "[a-zA-Z0-9]+";
Settings.getPasswordMinLen = 2;
Settings.passwordMaxLength = 50;
Settings.unsafePasswords = Collections.EMPTY_LIST;
when(commandService.getProperty(RestrictionSettings.ALLOWED_PASSWORD_REGEX)).thenReturn("[a-zA-Z0-9]+");
when(commandService.getProperty(SecuritySettings.UNSAFE_PASSWORDS)).thenReturn(Collections.EMPTY_LIST);
}
@Test
@@ -112,7 +113,7 @@ public class ChangePasswordCommandTest {
// given
CommandSender sender = initPlayerWithName("abc12", true);
ChangePasswordCommand command = new ChangePasswordCommand();
Settings.passwordMaxLength = 3;
given(commandService.getProperty(SecuritySettings.MAX_PASSWORD_LENGTH)).willReturn(3);
// when
command.executeCommand(sender, Arrays.asList("12", "test"), commandService);
@@ -127,7 +128,7 @@ public class ChangePasswordCommandTest {
// given
CommandSender sender = initPlayerWithName("abc12", true);
ChangePasswordCommand command = new ChangePasswordCommand();
Settings.getPasswordMinLen = 7;
given(commandService.getProperty(SecuritySettings.MIN_PASSWORD_LENGTH)).willReturn(7);
// when
command.executeCommand(sender, Arrays.asList("oldverylongpassword", "tester"), commandService);
@@ -142,7 +143,8 @@ public class ChangePasswordCommandTest {
// given
CommandSender sender = initPlayerWithName("player", true);
ChangePasswordCommand command = new ChangePasswordCommand();
Settings.unsafePasswords = asList("test", "abc123");
given(commandService.getProperty(SecuritySettings.UNSAFE_PASSWORDS))
.willReturn(Arrays.asList("test", "abc123"));
// when
command.executeCommand(sender, Arrays.asList("oldpw", "abc123"), commandService);
@@ -7,6 +7,7 @@ import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.security.crypts.EncryptionMethod;
import fr.xephi.authme.security.crypts.JOOMLA;
import fr.xephi.authme.security.crypts.PHPBB;
import fr.xephi.authme.util.WrapperMock;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginManager;
import org.junit.Before;
@@ -42,6 +43,7 @@ public class PasswordSecurityTest {
@Before
public void setUpMocks() {
WrapperMock.createInstance();
pluginManager = mock(PluginManager.class);
dataSource = mock(DataSource.class);
method = mock(EncryptionMethod.class);
@@ -209,7 +211,7 @@ public class PasswordSecurityTest {
HashedPassword hashedPassword = new HashedPassword("~T!est#Hash");
given(method.computeHash(password, username)).willReturn(hashedPassword);
given(method.hasSeparateSalt()).willReturn(true);
PasswordSecurity security = new PasswordSecurity(dataSource, HashAlgorithm.XAUTH, pluginManager, true);
PasswordSecurity security = new PasswordSecurity(dataSource, HashAlgorithm.XAUTH, pluginManager, false);
// when
boolean result = security.comparePassword(password, hashedPassword, username);
@@ -26,8 +26,8 @@ public abstract class AbstractEncryptionMethodTest {
*/
public static final String[] GIVEN_PASSWORDS = {"password", "PassWord1", "&^%te$t?Pw@_", "âË_3(íù*"};
/**
* List of passwords that are hashed at runtime and then tested against; this verifies that hashes that are
* generated are valid.
* List of passwords that are hashed at runtime and then tested against; this verifies that newly generated hashes
* are valid.
*/
private static final List<String> INTERNAL_PASSWORDS =
ImmutableList.of("test1234", "Ab_C73", "(!#&$~`_-Aa0", "Ûïé1&?+A");
@@ -1,20 +1,16 @@
package fr.xephi.authme.security.crypts;
import org.junit.Ignore;
/**
* Test for {@link WBB4}.
*/
@Ignore
// TODO #369: Fix WBB4 hash and un-ignore this test
public class WBB4Test extends AbstractEncryptionMethodTest {
public WBB4Test() {
super(new WBB4(),
"$2a$08$GktrHRoOk0EHrl3ONsFmieIbjq7EIzBx8dhsWiCmn6sWwO3b3DoRO", // password
"$2a$08$ouvtovnHgPWz6YHuOhyct.I2/j1xTOLG8OTuEn1/YqtkiRJYUV7lq", // PassWord1
"$2a$08$z.qWFh7k0qvIu5.qiq/Wuu2HDCNH7LNlMDNhN61F1ISsV8wZRKD0.", // &^%te$t?Pw@_
"$2a$08$OU8e9dncXyz8UP5Z.gWP8Os1IK89pspCS4FPzj8hBjgCWmjbLVcO2"); // âË_3(íù*
"$2a$08$7DGr.wROqEPe0Z3XJS7n5.k.QWehovLHbpI.UkdfRb4ns268WsR6C", // password
"$2a$08$yWWVUA4PB4mqW.0wyIvV3OdoH492HuLk5L3iaqUrpRK2.2zn08d/K", // PassWord1
"$2a$08$EHXUFt7bTT9Fnsu22KWvF.QDssiosV8YzH8CyWqulB/ckOA7qioJG", // &^%te$t?Pw@_
"$2a$08$ZZu5YH4zwpk0cr2dOYZpF.CkTKMvCBOAtTbAH7AwnOiL.n0mWkgDC"); // âË_3(íù*
}
}
@@ -0,0 +1,92 @@
package fr.xephi.authme.settings.custom;
import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.settings.propertymap.PropertyMap;
import fr.xephi.authme.util.StringUtils;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.fail;
/**
* Test for {@link NewSetting} and the project's config.yml,
* verifying that no settings are missing from the file.
*/
public class ConfigFileConsistencyTest {
/** The file name of the project's sample config file. */
private static final String CONFIG_FILE = "/config.yml";
@Test
public void shouldHaveAllConfigs() throws IOException {
// given
URL url = this.getClass().getResource(CONFIG_FILE);
File configFile = new File(url.getFile());
NewSetting settings = new NewSetting(YamlConfiguration.loadConfiguration(configFile), new File("bogus"), null);
// when
boolean result = settings.containsAllSettings(SettingsFieldRetriever.getAllPropertyFields());
// then
if (!result) {
FileConfiguration configuration =
(FileConfiguration) ReflectionTestUtils.getFieldValue(NewSetting.class, settings, "configuration");
Set<String> knownProperties = getAllKnownPropertyPaths();
List<String> missingProperties = new ArrayList<>();
for (String path : knownProperties) {
if (!configuration.contains(path)) {
missingProperties.add(path);
}
}
fail("Found missing properties!\n-" + StringUtils.join("\n-", missingProperties));
}
}
@Test
public void shouldNotHaveUnknownConfigs() {
// given
URL url = this.getClass().getResource(CONFIG_FILE);
File configFile = new File(url.getFile());
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(configFile);
Map<String, Object> allReadProperties = configuration.getValues(true);
Set<String> knownKeys = getAllKnownPropertyPaths();
// when
List<String> unknownPaths = new ArrayList<>();
for (Map.Entry<String, Object> entry : allReadProperties.entrySet()) {
// The value being a MemorySection means it's a parent node
if (!(entry.getValue() instanceof MemorySection) && !knownKeys.contains(entry.getKey())) {
unknownPaths.add(entry.getKey());
}
}
// then
if (!unknownPaths.isEmpty()) {
fail("Found " + unknownPaths.size() + " unknown property paths in the project's config.yml: \n- "
+ StringUtils.join("\n- ", unknownPaths));
}
}
private static Set<String> getAllKnownPropertyPaths() {
PropertyMap propertyMap = SettingsFieldRetriever.getAllPropertyFields();
Set<String> paths = new HashSet<>(propertyMap.size());
for (Property<?> property : propertyMap.keySet()) {
paths.add(property.getPath());
}
return paths;
}
}
@@ -0,0 +1,115 @@
package fr.xephi.authme.settings.custom;
import com.google.common.collect.ImmutableMap;
import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.settings.propertymap.PropertyMap;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
/**
* Integration test for {@link NewSetting}.
*/
public class NewSettingIntegrationTest {
/** File name of the sample config including all {@link TestConfiguration} values. */
private static final String COMPLETE_FILE = "config-sample-values.yml";
/** File name of the sample config missing certain {@link TestConfiguration} values. */
private static final String INCOMPLETE_FILE = "config-incomplete-sample.yml";
private static PropertyMap propertyMap;
@BeforeClass
public static void generatePropertyMap() {
propertyMap = new PropertyMap();
for (Field field : TestConfiguration.class.getDeclaredFields()) {
Object fieldValue = ReflectionTestUtils.getFieldValue(TestConfiguration.class, null, field.getName());
if (fieldValue instanceof Property<?>) {
Property<?> property = (Property<?>) fieldValue;
String[] comments = new String[]{"Comment for '" + property.getPath() + "'"};
propertyMap.put(property, comments);
}
}
}
@Test
public void shouldLoadAndReadAllProperties() {
// given
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(getConfigFile(COMPLETE_FILE));
File file = new File("unused");
assumeThat(file.exists(), equalTo(false));
// when / then
NewSetting settings = new NewSetting(configuration, file, propertyMap);
Map<Property<?>, Object> expectedValues = ImmutableMap.<Property<?>, Object>builder()
.put(TestConfiguration.DURATION_IN_SECONDS, 22)
.put(TestConfiguration.SYSTEM_NAME, "Custom sys name")
.put(TestConfiguration.RATIO_LIMIT, -4.1)
.put(TestConfiguration.RATIO_FIELDS, Arrays.asList("Australia", "Burundi", "Colombia"))
.put(TestConfiguration.VERSION_NUMBER, 2492)
.put(TestConfiguration.SKIP_BORING_FEATURES, false)
.put(TestConfiguration.BORING_COLORS, Arrays.asList("beige", "gray"))
.put(TestConfiguration.DUST_LEVEL, 0.81)
.put(TestConfiguration.USE_COOL_FEATURES, true)
.put(TestConfiguration.COOL_OPTIONS, Arrays.asList("Dinosaurs", "Explosions", "Big trucks"))
.build();
for (Map.Entry<Property<?>, Object> entry : expectedValues.entrySet()) {
assertThat("Property '" + entry.getKey().getPath() + "' has expected value",
settings.getProperty(entry.getKey()), equalTo(entry.getValue()));
}
assertThat(file.exists(), equalTo(false));
}
@Test
public void shouldWriteMissingProperties() {
// given/when
File file = getConfigFile(INCOMPLETE_FILE);
YamlConfiguration configuration = YamlConfiguration.loadConfiguration(file);
assumeThat(configuration.contains(TestConfiguration.BORING_COLORS.getPath()), equalTo(false));
// Expectation: File is rewritten to since it does not have all configurations
new NewSetting(configuration, file, propertyMap);
// Load the settings again -> checks that what we wrote can be loaded again
configuration = YamlConfiguration.loadConfiguration(file);
// then
NewSetting settings = new NewSetting(configuration, file, propertyMap);
Map<Property<?>, Object> expectedValues = ImmutableMap.<Property<?>, Object>builder()
.put(TestConfiguration.DURATION_IN_SECONDS, 22)
.put(TestConfiguration.SYSTEM_NAME, "[TestDefaultValue]")
.put(TestConfiguration.RATIO_LIMIT, 3.0)
.put(TestConfiguration.RATIO_FIELDS, Arrays.asList("Australia", "Burundi", "Colombia"))
.put(TestConfiguration.VERSION_NUMBER, 32046)
.put(TestConfiguration.SKIP_BORING_FEATURES, false)
.put(TestConfiguration.BORING_COLORS, Collections.EMPTY_LIST)
.put(TestConfiguration.DUST_LEVEL, 0.2)
.put(TestConfiguration.USE_COOL_FEATURES, false)
.put(TestConfiguration.COOL_OPTIONS, Arrays.asList("Dinosaurs", "Explosions", "Big trucks"))
.build();
for (Map.Entry<Property<?>, Object> entry : expectedValues.entrySet()) {
assertThat("Property '" + entry.getKey().getPath() + "' has expected value",
settings.getProperty(entry.getKey()), equalTo(entry.getValue()));
}
}
private File getConfigFile(String file) {
URL url = getClass().getClassLoader().getResource(file);
if (url == null) {
throw new IllegalStateException("File '" + file + "' could not be loaded");
}
return new File(url.getFile());
}
}
@@ -0,0 +1,84 @@
package fr.xephi.authme.settings.custom;
import fr.xephi.authme.settings.domain.Property;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.File;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyDouble;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test for {@link NewSetting}.
*/
public class NewSettingTest {
@Test
public void shouldLoadAllConfigs() {
// given
YamlConfiguration file = mock(YamlConfiguration.class);
given(file.getString(anyString(), anyString())).willAnswer(withDefaultArgument());
given(file.getBoolean(anyString(), anyBoolean())).willAnswer(withDefaultArgument());
given(file.getDouble(anyString(), anyDouble())).willAnswer(withDefaultArgument());
given(file.getInt(anyString(), anyInt())).willAnswer(withDefaultArgument());
setReturnValue(file, TestConfiguration.VERSION_NUMBER, 20);
setReturnValue(file, TestConfiguration.SKIP_BORING_FEATURES, true);
setReturnValue(file, TestConfiguration.RATIO_LIMIT, 4.25);
setReturnValue(file, TestConfiguration.SYSTEM_NAME, "myTestSys");
// when / then
NewSetting settings = new NewSetting(file, new File("conf.txt"), null);
assertThat(settings.getProperty(TestConfiguration.VERSION_NUMBER), equalTo(20));
assertThat(settings.getProperty(TestConfiguration.SKIP_BORING_FEATURES), equalTo(true));
assertThat(settings.getProperty(TestConfiguration.RATIO_LIMIT), equalTo(4.25));
assertThat(settings.getProperty(TestConfiguration.SYSTEM_NAME), equalTo("myTestSys"));
assertDefaultValue(TestConfiguration.DURATION_IN_SECONDS, settings);
assertDefaultValue(TestConfiguration.DUST_LEVEL, settings);
assertDefaultValue(TestConfiguration.COOL_OPTIONS, settings);
}
private static <T> void setReturnValue(YamlConfiguration config, Property<T> property, T value) {
if (value instanceof String) {
when(config.getString(eq(property.getPath()), anyString())).thenReturn((String) value);
} else if (value instanceof Integer) {
when(config.getInt(eq(property.getPath()), anyInt())).thenReturn((Integer) value);
} else if (value instanceof Boolean) {
when(config.getBoolean(eq(property.getPath()), anyBoolean())).thenReturn((Boolean) value);
} else if (value instanceof Double) {
when(config.getDouble(eq(property.getPath()), anyDouble())).thenReturn((Double) value);
} else {
throw new UnsupportedOperationException("Value has unsupported type '"
+ (value == null ? "null" : value.getClass().getSimpleName()) + "'");
}
}
private static void assertDefaultValue(Property<?> property, NewSetting setting) {
assertThat(property.getPath() + " has default value",
setting.getProperty(property).equals(property.getDefaultValue()), equalTo(true));
}
private static <T> Answer<T> withDefaultArgument() {
return new Answer<T>() {
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
// Return the second parameter -> the default
return (T) invocation.getArguments()[1];
}
};
}
}
@@ -0,0 +1,119 @@
package fr.xephi.authme.settings.custom;
import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.settings.domain.SettingsClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Test for {@link SettingsClass} implementations.
*/
public class SettingsClassConsistencyTest {
private static final String SETTINGS_FOLDER = "src/main/java/fr/xephi/authme/settings/custom";
private static List<Class<? extends SettingsClass>> classes;
@BeforeClass
public static void scanForSettingsClasses() {
File settingsFolder = new File(SETTINGS_FOLDER);
File[] filesInFolder = settingsFolder.listFiles();
if (filesInFolder == null || filesInFolder.length == 0) {
throw new IllegalStateException("Could not read folder '" + SETTINGS_FOLDER + "'. Is it correct?");
}
classes = new ArrayList<>();
for (File file : filesInFolder) {
Class<? extends SettingsClass> clazz = getSettingsClassFromFile(file);
if (clazz != null) {
classes.add(clazz);
}
}
System.out.println("Found " + classes.size() + " SettingsClass implementations");
}
/**
* Make sure that all {@link Property} instances we define are in public, static, final fields.
*/
@Test
public void shouldHavePublicStaticFinalFields() {
for (Class<?> clazz : classes) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (Property.class.isAssignableFrom(field.getType())) {
String fieldName = "Field " + clazz.getSimpleName() + "#" + field.getName();
assertThat(fieldName + " should be public, static, and final",
isValidConstantField(field), equalTo(true));
}
}
}
}
/**
* Make sure that no properties use the same path.
*/
@Test
public void shouldHaveUniquePaths() {
Set<String> paths = new HashSet<>();
for (Class<?> clazz : classes) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (Property.class.isAssignableFrom(field.getType())) {
Property<?> property =
(Property<?>) ReflectionTestUtils.getFieldValue(clazz, null, field.getName());
if (paths.contains(property.getPath())) {
fail("Path '" + property.getPath() + "' should be used by only one constant");
}
paths.add(property.getPath());
}
}
}
}
@Test
public void shouldHaveHiddenDefaultConstructorOnly() {
for (Class<?> clazz : classes) {
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
assertThat(clazz + " should only have one constructor",
constructors, arrayWithSize(1));
assertThat("Constructor of " + clazz + " is private",
Modifier.isPrivate(constructors[0].getModifiers()), equalTo(true));
}
}
private static boolean isValidConstantField(Field field) {
int modifiers = field.getModifiers();
return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers);
}
private static Class<? extends SettingsClass> getSettingsClassFromFile(File file) {
String fileName = file.getPath();
String className = fileName
.substring("src/main/java/".length(), fileName.length() - ".java".length())
.replace(File.separator, ".");
try {
Class<?> clazz = SettingsClassConsistencyTest.class.getClassLoader().loadClass(className);
if (SettingsClass.class.isAssignableFrom(clazz)) {
return (Class<? extends SettingsClass>) clazz;
}
return null;
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Could not load class '" + className + "'", e);
}
}
}
@@ -0,0 +1,46 @@
package fr.xephi.authme.settings.custom;
import fr.xephi.authme.settings.domain.Property;
import fr.xephi.authme.settings.domain.PropertyType;
import fr.xephi.authme.settings.domain.SettingsClass;
import java.util.List;
import static fr.xephi.authme.settings.domain.Property.newProperty;
/**
* Sample properties for testing purposes.
*/
class TestConfiguration implements SettingsClass {
public static final Property<Integer> DURATION_IN_SECONDS =
newProperty("test.duration", 4);
public static final Property<String> SYSTEM_NAME =
newProperty("test.systemName", "[TestDefaultValue]");
public static final Property<Double> RATIO_LIMIT =
newProperty(PropertyType.DOUBLE, "sample.ratio.limit", 3.0);
public static final Property<List<String>> RATIO_FIELDS =
newProperty(PropertyType.STRING_LIST, "sample.ratio.fields", "a", "b", "c");
public static final Property<Integer> VERSION_NUMBER =
newProperty("version", 32046);
public static final Property<Boolean> SKIP_BORING_FEATURES =
newProperty("features.boring.skip", false);
public static final Property<List<String>> BORING_COLORS =
newProperty(PropertyType.STRING_LIST, "features.boring.colors");
public static final Property<Double> DUST_LEVEL =
newProperty(PropertyType.DOUBLE, "features.boring.dustLevel", 0.2);
public static final Property<Boolean> USE_COOL_FEATURES =
newProperty("features.cool.enabled", false);
public static final Property<List<String>> COOL_OPTIONS =
newProperty(PropertyType.STRING_LIST, "features.cool.options", "Sparks", "Sprinkles");
}
@@ -0,0 +1,118 @@
package fr.xephi.authme.settings.domain;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Test for {@link EnumPropertyType}.
*/
public class EnumPropertyTypeTest {
@Test
public void shouldReturnCorrectEnumValue() {
// given
PropertyType<TestEnum> propertyType = new EnumPropertyType<>(TestEnum.class);
Property<TestEnum> property = Property.newProperty(TestEnum.class, "enum.path", TestEnum.ENTRY_C);
YamlConfiguration configuration = mock(YamlConfiguration.class);
given(configuration.getString(property.getPath())).willReturn("Entry_B");
// when
TestEnum result = propertyType.getFromFile(property, configuration);
// then
assertThat(result, equalTo(TestEnum.ENTRY_B));
}
@Test
public void shouldFallBackToDefaultForInvalidValue() {
// given
PropertyType<TestEnum> propertyType = new EnumPropertyType<>(TestEnum.class);
Property<TestEnum> property = Property.newProperty(TestEnum.class, "enum.path", TestEnum.ENTRY_C);
YamlConfiguration configuration = mock(YamlConfiguration.class);
given(configuration.getString(property.getPath())).willReturn("Bogus");
// when
TestEnum result = propertyType.getFromFile(property, configuration);
// then
assertThat(result, equalTo(TestEnum.ENTRY_C));
}
@Test
public void shouldFallBackToDefaultForNonExistentValue() {
// given
PropertyType<TestEnum> propertyType = new EnumPropertyType<>(TestEnum.class);
Property<TestEnum> property = Property.newProperty(TestEnum.class, "enum.path", TestEnum.ENTRY_C);
YamlConfiguration configuration = mock(YamlConfiguration.class);
given(configuration.getString(property.getPath())).willReturn(null);
// when
TestEnum result = propertyType.getFromFile(property, configuration);
// then
assertThat(result, equalTo(TestEnum.ENTRY_C));
}
@Test
public void shouldReturnTrueForContainsCheck() {
// given
PropertyType<TestEnum> propertyType = new EnumPropertyType<>(TestEnum.class);
Property<TestEnum> property = Property.newProperty(TestEnum.class, "my.test.path", TestEnum.ENTRY_C);
YamlConfiguration configuration = mock(YamlConfiguration.class);
given(configuration.contains(property.getPath())).willReturn(true);
given(configuration.getString(property.getPath())).willReturn("ENTRY_B");
// when
boolean result = propertyType.contains(property, configuration);
// then
assertThat(result, equalTo(true));
}
@Test
public void shouldReturnFalseForFileWithoutConfig() {
// given
PropertyType<TestEnum> propertyType = new EnumPropertyType<>(TestEnum.class);
Property<TestEnum> property = Property.newProperty(TestEnum.class, "my.test.path", TestEnum.ENTRY_C);
YamlConfiguration configuration = mock(YamlConfiguration.class);
given(configuration.contains(property.getPath())).willReturn(false);
// when
boolean result = propertyType.contains(property, configuration);
// then
assertThat(result, equalTo(false));
}
@Test
public void shouldReturnFalseForUnknownValue() {
// given
PropertyType<TestEnum> propertyType = new EnumPropertyType<>(TestEnum.class);
Property<TestEnum> property = Property.newProperty(TestEnum.class, "my.test.path", TestEnum.ENTRY_C);
YamlConfiguration configuration = mock(YamlConfiguration.class);
given(configuration.contains(property.getPath())).willReturn(true);
given(configuration.getString(property.getPath())).willReturn("wrong value");
// when
boolean result = propertyType.contains(property, configuration);
// then
assertThat(result, equalTo(false));
}
private enum TestEnum {
ENTRY_A,
ENTRY_B,
ENTRY_C
}
}
@@ -0,0 +1,182 @@
package fr.xephi.authme.settings.domain;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyDouble;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test for {@link PropertyType} and the contained subtypes.
*/
public class PropertyTypeTest {
private static YamlConfiguration configuration;
@BeforeClass
public static void setUpYamlConfigurationMock() {
configuration = mock(YamlConfiguration.class);
when(configuration.getBoolean(eq("bool.path.test"), anyBoolean())).thenReturn(true);
when(configuration.getBoolean(eq("bool.path.wrong"), anyBoolean())).thenAnswer(secondParameter());
when(configuration.getDouble(eq("double.path.test"), anyDouble())).thenReturn(-6.4);
when(configuration.getDouble(eq("double.path.wrong"), anyDouble())).thenAnswer(secondParameter());
when(configuration.getInt(eq("int.path.test"), anyInt())).thenReturn(27);
when(configuration.getInt(eq("int.path.wrong"), anyInt())).thenAnswer(secondParameter());
when(configuration.getString(eq("str.path.test"), anyString())).thenReturn("Test value");
when(configuration.getString(eq("str.path.wrong"), anyString())).thenAnswer(secondParameter());
when(configuration.isList("list.path.test")).thenReturn(true);
when(configuration.getStringList("list.path.test")).thenReturn(Arrays.asList("test1", "Test2", "3rd test"));
when(configuration.isList("list.path.wrong")).thenReturn(false);
}
/* Boolean */
@Test
public void shouldGetBoolValue() {
// given
Property<Boolean> property = Property.newProperty("bool.path.test", false);
// when
boolean result = property.getFromFile(configuration);
// then
assertThat(result, equalTo(true));
}
@Test
public void shouldGetBoolDefault() {
// given
Property<Boolean> property = Property.newProperty("bool.path.wrong", true);
// when
boolean result = property.getFromFile(configuration);
// then
assertThat(result, equalTo(true));
}
/* Double */
@Test
public void shouldGetDoubleValue() {
// given
Property<Double> property = Property.newProperty(PropertyType.DOUBLE, "double.path.test", 3.8);
// when
double result = property.getFromFile(configuration);
// then
assertThat(result, equalTo(-6.4));
}
@Test
public void shouldGetDoubleDefault() {
// given
Property<Double> property = Property.newProperty(PropertyType.DOUBLE, "double.path.wrong", 12.0);
// when
double result = property.getFromFile(configuration);
// then
assertThat(result, equalTo(12.0));
}
/* Integer */
@Test
public void shouldGetIntValue() {
// given
Property<Integer> property = Property.newProperty("int.path.test", 3);
// when
int result = property.getFromFile(configuration);
// then
assertThat(result, equalTo(27));
}
@Test
public void shouldGetIntDefault() {
// given
Property<Integer> property = Property.newProperty("int.path.wrong", -10);
// when
int result = property.getFromFile(configuration);
// then
assertThat(result, equalTo(-10));
}
/* String */
@Test
public void shouldGetStringValue() {
// given
Property<String> property = Property.newProperty("str.path.test", "unused default");
// when
String result = property.getFromFile(configuration);
// then
assertThat(result, equalTo("Test value"));
}
@Test
public void shouldGetStringDefault() {
// given
Property<String> property = Property.newProperty("str.path.wrong", "given default value");
// when
String result = property.getFromFile(configuration);
// then
assertThat(result, equalTo("given default value"));
}
/* String list */
@Test
public void shouldGetStringListValue() {
// given
Property<List<String>> property = Property.newProperty(PropertyType.STRING_LIST, "list.path.test", "1", "b");
// when
List<String> result = property.getFromFile(configuration);
// then
assertThat(result, contains("test1", "Test2", "3rd test"));
}
@Test
public void shouldGetStringListDefault() {
// given
Property<List<String>> property =
Property.newProperty(PropertyType.STRING_LIST, "list.path.wrong", "default", "list", "elements");
// when
List<String> result = property.getFromFile(configuration);
// then
assertThat(result, contains("default", "list", "elements"));
}
private static <T> Answer<T> secondParameter() {
return new Answer<T>() {
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
// Return the second parameter -> the default
return (T) invocation.getArguments()[1];
}
};
}
}
@@ -0,0 +1,53 @@
package fr.xephi.authme.settings.propertymap;
import fr.xephi.authme.settings.domain.Property;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.Matchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test for {@link PropertyMap}.
*/
public class PropertyMapTest {
@Test
public void shouldKeepEntriesByInsertionAndGroup() {
// given
List<String> paths = Arrays.asList("japan", "indonesia.jakarta", "japan.tokyo", "china.shanghai", "egypt.cairo",
"china.shenzhen", "china", "indonesia.jakarta.tugu", "egypt", "japan.nagoya", "japan.tokyo.taito");
PropertyMap map = new PropertyMap();
// when
for (String path : paths) {
Property<?> property = createPropertyWithPath(path);
map.put(property, new String[0]);
}
// then
Set<Map.Entry<Property<?>, String[]>> entrySet = map.entrySet();
List<String> resultPaths = new ArrayList<>(entrySet.size());
for (Map.Entry<Property<?>, String[]> entry : entrySet) {
resultPaths.add(entry.getKey().getPath());
}
Assert.assertThat(resultPaths, contains("japan", "japan.tokyo", "japan.tokyo.taito", "japan.nagoya",
"indonesia.jakarta", "indonesia.jakarta.tugu", "china", "china.shanghai", "china.shenzhen",
"egypt", "egypt.cairo"));
}
private static Property<?> createPropertyWithPath(String path) {
Property<?> property = mock(Property.class);
when(property.getPath()).thenReturn(path);
return property;
}
}