Merge branch 'master' of https://github.com/AuthMe/AuthMeReloaded into explicit-getters-from-db

This commit is contained in:
ljacqu
2017-04-29 08:19:30 +02:00
47 changed files with 786 additions and 306 deletions
@@ -0,0 +1,84 @@
package fr.xephi.authme;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.fail;
/**
* Matcher which checks with reflection that all fields have the same value.
* This matcher considers all non-static fields until the Object parent.
*/
public final class IsEqualByReflectionMatcher<T> extends TypeSafeMatcher<T> {
private final T expected;
private IsEqualByReflectionMatcher(T expected) {
this.expected = expected;
}
/**
* Creates a matcher that checks if all fields are the same as on the {@code expected} object.
*
* @param expected the object to match
* @param <T> the object's type
* @return the matcher for the expected object
*/
public static <T> Matcher<T> isEqualTo(T expected) {
return new IsEqualByReflectionMatcher<>(expected);
}
@Override
protected boolean matchesSafely(T item) {
return assertAreFieldsEqual(item);
}
@Override
public void describeTo(Description description) {
description.appendText("parameters " + expected);
}
private boolean assertAreFieldsEqual(T item) {
if (expected.getClass() != item.getClass()) {
fail("Classes don't match, got " + expected.getClass().getSimpleName()
+ " and " + item.getClass().getSimpleName());
return false;
}
List<Field> fieldsToCheck = getAllFields(expected);
for (Field field : fieldsToCheck) {
Object lhsValue = ReflectionTestUtils.getFieldValue(field, expected);
Object rhsValue = ReflectionTestUtils.getFieldValue(field, item);
if (!Objects.equals(lhsValue, rhsValue)) {
fail("Field '" + field.getName() + "' does not have same value: '"
+ lhsValue + "' vs. '" + rhsValue + "'");
return false;
}
}
return true;
}
private static List<Field> getAllFields(Object object) {
List<Field> fields = new ArrayList<>();
Class<?> currentClass = object.getClass();
while (currentClass != null) {
for (Field f : currentClass.getDeclaredFields()) {
if (!Modifier.isStatic(f.getModifiers())) {
fields.add(f);
}
}
if (currentClass == Object.class) {
break;
}
currentClass = currentClass.getSuperclass();
}
return fields;
}
}
@@ -0,0 +1,154 @@
package fr.xephi.authme.command.executable.authme.debug;
import fr.xephi.authme.initialization.factory.Factory;
import fr.xephi.authme.permission.DebugSectionPermissions;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsManager;
import org.bukkit.command.CommandSender;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Collections.emptyList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link DebugCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class DebugCommandTest {
/**
* Number we test against if we expect an action to have been performed for each debug section.
* This is a minimum number so tests don't fail each time a new debug section is added; however,
* it should be close to the total.
*/
private static final int MIN_DEBUG_SECTIONS = 9;
@InjectMocks
private DebugCommand command;
@Mock
private Factory<DebugSection> debugSectionFactory;
@Mock
private PermissionsManager permissionsManager;
@Before
@SuppressWarnings("unchecked")
public void initFactory() {
given(debugSectionFactory.newInstance(any(Class.class))).willAnswer(
invocation -> {
Class<?> classArgument = invocation.getArgument(0);
checkArgument(DebugSection.class.isAssignableFrom(classArgument));
return spy(classArgument);
});
}
@Test
public void shouldListAllAvailableDebugSections() {
// given
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(false);
given(permissionsManager.hasPermission(sender, DebugSectionPermissions.INPUT_VALIDATOR)).willReturn(true);
given(permissionsManager.hasPermission(sender, DebugSectionPermissions.DATA_STATISTICS)).willReturn(true);
// when
command.executeCommand(sender, emptyList());
// then
verify(debugSectionFactory, atLeast(MIN_DEBUG_SECTIONS)).newInstance(any(Class.class));
verify(permissionsManager, atLeast(MIN_DEBUG_SECTIONS)).hasPermission(eq(sender), any(DebugSectionPermissions.class));
ArgumentCaptor<String> strCaptor = ArgumentCaptor.forClass(String.class);
verify(sender, times(3)).sendMessage(strCaptor.capture());
assertThat(strCaptor.getAllValues(), contains(
containsString("Sections available to you"),
containsString("stats: Outputs general data statistics"),
containsString("valid: Check if email / password is valid")));
}
@Test
public void shouldNotListAnyDebugSection() {
// given
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(false);
// when
command.executeCommand(sender, emptyList());
// then
verify(debugSectionFactory, atLeast(MIN_DEBUG_SECTIONS)).newInstance(any(Class.class));
verify(permissionsManager, atLeast(MIN_DEBUG_SECTIONS)).hasPermission(eq(sender), any(DebugSectionPermissions.class));
ArgumentCaptor<String> strCaptor = ArgumentCaptor.forClass(String.class);
verify(sender, times(2)).sendMessage(strCaptor.capture());
assertThat(strCaptor.getAllValues(), contains(
equalTo("Sections available to you:"),
containsString("You don't have permission to view any debug section")));
}
@Test
public void shouldRunSection() {
// given
DebugSection section = spy(InputValidator.class);
doNothing().when(section).execute(any(CommandSender.class), anyList());
// Mockito throws a runtime error if below we use the usual "given(factory.newInstance(...)).willReturn(...)"
doReturn(section).when(debugSectionFactory).newInstance(InputValidator.class);
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(sender, section.getRequiredPermission())).willReturn(true);
List<String> arguments = Arrays.asList(section.getName().toUpperCase(), "test", "toast");
// when
command.executeCommand(sender, arguments);
// then
verify(permissionsManager).hasPermission(sender, section.getRequiredPermission());
verify(section).execute(sender, Arrays.asList("test", "toast"));
}
@Test
public void shouldNotRunSectionForMissingPermission() {
// given
DebugSection section = spy(InputValidator.class);
// Mockito throws a runtime error if below we use the usual "given(factory.newInstance(...)).willReturn(...)"
doReturn(section).when(debugSectionFactory).newInstance(InputValidator.class);
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(sender, section.getRequiredPermission())).willReturn(false);
List<String> arguments = Arrays.asList(section.getName().toUpperCase(), "test");
// when
command.executeCommand(sender, arguments);
// then
verify(permissionsManager).hasPermission(sender, section.getRequiredPermission());
verify(section, never()).execute(any(CommandSender.class), anyList());
verify(sender).sendMessage(argThat(containsString("You don't have permission")));
}
}
@@ -20,9 +20,9 @@ import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeast;
@@ -55,8 +55,7 @@ public class HasPermissionCheckerTest {
.collect(Collectors.toList());
// when / then
assertThat(HasPermissionChecker.PERMISSION_NODE_CLASSES.containsAll(permissionClasses), equalTo(true));
assertThat(HasPermissionChecker.PERMISSION_NODE_CLASSES, hasSize(permissionClasses.size()));
assertThat(HasPermissionChecker.PERMISSION_NODE_CLASSES, containsInAnyOrder(permissionClasses.toArray()));
}
@Test
@@ -1,6 +1,5 @@
package fr.xephi.authme.command.executable.register;
import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey;
@@ -10,7 +9,6 @@ import fr.xephi.authme.process.register.RegistrationType;
import fr.xephi.authme.process.register.executors.EmailRegisterParams;
import fr.xephi.authme.process.register.executors.PasswordRegisterParams;
import fr.xephi.authme.process.register.executors.RegistrationMethod;
import fr.xephi.authme.process.register.executors.RegistrationParameters;
import fr.xephi.authme.process.register.executors.TwoFactorRegisterParams;
import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.service.CommonService;
@@ -20,9 +18,6 @@ import fr.xephi.authme.settings.properties.SecuritySettings;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -31,16 +26,11 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static fr.xephi.authme.IsEqualByReflectionMatcher.isEqualTo;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -306,56 +296,4 @@ public class RegisterCommandTest {
verify(management).performRegister(eq(RegistrationMethod.PASSWORD_REGISTRATION),
argThat(isEqualTo(PasswordRegisterParams.of(player, "myPass", null))));
}
// TODO ljacqu 20170317: Document and extract as util
private static <P extends RegistrationParameters> Matcher<P> isEqualTo(P expected) {
return new TypeSafeMatcher<P>() {
@Override
protected boolean matchesSafely(RegistrationParameters item) {
assertAreParamsEqual(expected, item);
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("parameters " + expected);
}
};
}
private static void assertAreParamsEqual(RegistrationParameters lhs, RegistrationParameters rhs) {
if (lhs.getClass() != rhs.getClass()) {
fail("Params classes don't match, got " + lhs.getClass().getSimpleName()
+ " and " + rhs.getClass().getSimpleName());
}
List<Field> fieldsToCheck = getFields(lhs);
for (Field field : fieldsToCheck) {
Object lhsValue = ReflectionTestUtils.getFieldValue(field, lhs);
Object rhsValue = ReflectionTestUtils.getFieldValue(field, rhs);
if (!Objects.equals(lhsValue, rhsValue)) {
fail("Field '" + field.getName() + "' does not have same value: '"
+ lhsValue + "' vs. '" + rhsValue + "'");
}
}
}
private static List<Field> getFields(RegistrationParameters params) {
List<Field> fields = new ArrayList<>();
Class<?> currentClass = params.getClass();
while (currentClass != null) {
for (Field f : currentClass.getDeclaredFields()) {
if (!Modifier.isStatic(f.getModifiers())) {
fields.add(f);
}
}
if (currentClass == RegistrationParameters.class) {
break;
}
currentClass = currentClass.getSuperclass();
}
return fields;
}
}
@@ -0,0 +1,52 @@
package fr.xephi.authme.permission;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.fail;
/**
* Has common tests for enums implementing {@link PermissionNode}.
*/
public abstract class AbstractPermissionsEnumTest {
@Test
public void shouldAllStartWitRequiredPrefix() {
// given
String requiredPrefix = getRequiredPrefix();
// when/then
for (PermissionNode permission : getPermissionNodes()) {
if (!permission.getNode().startsWith(requiredPrefix)) {
fail("The permission '" + permission + "' does not start with the required prefix '"
+ requiredPrefix + "'");
}
}
}
@Test
public void shouldHaveUniqueNodes() {
// given
Set<String> nodes = new HashSet<>();
// when/then
for (PermissionNode permission : getPermissionNodes()) {
if (!nodes.add(permission.getNode())) {
fail("More than one enum value defines the node '" + permission.getNode() + "'");
}
}
}
/**
* @return the permission nodes to test
*/
protected abstract PermissionNode[] getPermissionNodes();
/**
* @return text with which all permission nodes must start with
*/
protected abstract String getRequiredPrefix();
}
@@ -1,42 +1,18 @@
package fr.xephi.authme.permission;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.fail;
/**
* Test for {@link AdminPermission}.
*/
public class AdminPermissionTest {
public class AdminPermissionTest extends AbstractPermissionsEnumTest {
@Test
public void shouldStartWithAuthMeAdminPrefix() {
// given
String requiredPrefix = "authme.admin.";
// when/then
for (AdminPermission permission : AdminPermission.values()) {
if (!permission.getNode().startsWith(requiredPrefix)) {
fail("The permission '" + permission + "' does not start with the required prefix '"
+ requiredPrefix + "'");
}
}
@Override
protected PermissionNode[] getPermissionNodes() {
return AdminPermission.values();
}
@Test
public void shouldHaveUniqueNodes() {
// given
Set<String> nodes = new HashSet<>();
// when/then
for (AdminPermission permission : AdminPermission.values()) {
if (!nodes.add(permission.getNode())) {
fail("More than one enum value defines the node '" + permission.getNode() + "'");
}
}
@Override
protected String getRequiredPrefix() {
return "authme.admin.";
}
}
@@ -0,0 +1,17 @@
package fr.xephi.authme.permission;
/**
* Test for {@link DebugSectionPermissions}.
*/
public class DebugSectionPermissionsTest extends AbstractPermissionsEnumTest {
@Override
protected PermissionNode[] getPermissionNodes() {
return DebugSectionPermissions.values();
}
@Override
protected String getRequiredPrefix() {
return "authme.debug.";
}
}
@@ -31,7 +31,7 @@ public class PermissionConsistencyTest {
/** Wildcard permissions (present in plugin.yml but not in the codebase). */
private static final Set<String> PLUGIN_YML_PERMISSIONS_WILDCARDS =
ImmutableSet.of("authme.admin.*", "authme.player.*", "authme.player.email");
ImmutableSet.of("authme.admin.*", "authme.player.*", "authme.player.email", "authme.debug");
/** Name of the fields that make up a permission entry in plugin.yml. */
private static final Set<String> PERMISSION_FIELDS = ImmutableSet.of("description", "default", "children");
@@ -1,41 +1,17 @@
package fr.xephi.authme.permission;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.fail;
/**
* Test for {@link PlayerPermission}.
*/
public class PlayerPermissionTest {
public class PlayerPermissionTest extends AbstractPermissionsEnumTest {
@Test
public void shouldStartWithPlayerPrefix() {
// given
String playerBranch = "authme.player.";
// when/then
for (PlayerPermission permission : PlayerPermission.values()) {
if (!permission.getNode().startsWith(playerBranch)) {
fail("The permission '" + permission + "' should use a node with the player-specific branch '"
+ playerBranch + "'");
}
}
@Override
protected PermissionNode[] getPermissionNodes() {
return PlayerPermission.values();
}
@Test
public void shouldHaveUniqueNodes() {
// given
Set<String> nodes = new HashSet<>();
// when/then
for (PlayerPermission permission : PlayerPermission.values()) {
if (!nodes.add(permission.getNode())) {
fail("More than one enum value defines the node '" + permission.getNode() + "'");
}
}
@Override
protected String getRequiredPrefix() {
return "authme.player.";
}
}
@@ -2,7 +2,7 @@ package fr.xephi.authme.permission;
import org.junit.Test;
import java.util.HashSet;
import java.util.Collection;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
@@ -11,39 +11,32 @@ import static org.junit.Assert.fail;
/**
* Test for {@link PlayerStatePermission}.
*/
public class PlayerStatePermissionTest {
public class PlayerStatePermissionTest extends AbstractPermissionsEnumTest {
@Test
public void shouldStartWithAuthMeAdminPrefix() {
public void shouldNotStartWithOtherPrefixes() {
// given
String requiredPrefix = "authme.";
Set<String> forbiddenPrefixes = newHashSet("authme.player", "authme.admin");
Set<String> forbiddenPrefixes = newHashSet("authme.player", "authme.admin", "authme.debug");
// when/then
for (PlayerStatePermission permission : PlayerStatePermission.values()) {
if (!permission.getNode().startsWith(requiredPrefix)) {
fail("The permission '" + permission + "' does not start with the required prefix '"
+ requiredPrefix + "'");
} else if (hasAnyPrefix(permission.getNode(), forbiddenPrefixes)) {
if (startsWithAny(permission.getNode(), forbiddenPrefixes)) {
fail("The permission '" + permission + "' should not start with any of " + forbiddenPrefixes);
}
}
}
@Test
public void shouldHaveUniqueNodes() {
// given
Set<String> nodes = new HashSet<>();
// when/then
for (PlayerStatePermission permission : PlayerStatePermission.values()) {
if (!nodes.add(permission.getNode())) {
fail("More than one enum value defines the node '" + permission.getNode() + "'");
}
}
@Override
protected PermissionNode[] getPermissionNodes() {
return PlayerStatePermission.values();
}
private static boolean hasAnyPrefix(String node, Set<String> prefixes) {
@Override
protected String getRequiredPrefix() {
return "authme.";
}
private static boolean startsWithAny(String node, Collection<String> prefixes) {
for (String prefix : prefixes) {
if (node.startsWith(prefix)) {
return true;
@@ -51,5 +44,4 @@ public class PlayerStatePermissionTest {
}
return false;
}
}
@@ -11,7 +11,6 @@ import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.ProtectionSettings;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -82,7 +81,6 @@ public class AntiBotServiceTest {
}
@Test
@Ignore // TODO ljacqu 20161030: Fix test
public void shouldActivateAntibot() {
// given - listening antibot
runSyncDelayedTaskWithDelay(bukkitService);