diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/generic/meta/MetaInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/generic/meta/MetaInfo.java index dae4da91b..f2cf7c2df 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/generic/meta/MetaInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/generic/meta/MetaInfo.java @@ -118,7 +118,7 @@ public class MetaInfo extends GenericChildCommand { if (result != 0) { return result; } - return NodeWithContextComparator.normal().compare(o1.getValue(), o2.getValue()); + return NodeWithContextComparator.ascending().compare(o1.getValue(), o2.getValue()); } } } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/generic/parent/ParentInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/generic/parent/ParentInfo.java index 59da06418..a6f3c6b86 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/generic/parent/ParentInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/generic/parent/ParentInfo.java @@ -115,6 +115,6 @@ public class ParentInfo extends GenericChildCommand { } // fallback to priority - return NodeWithContextComparator.reverse().compare(o1, o2); + return NodeWithContextComparator.descending().compare(o1, o2); }; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/generic/permission/PermissionInfo.java b/common/src/main/java/me/lucko/luckperms/common/commands/generic/permission/PermissionInfo.java index 84926fda5..291b92eb0 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/generic/permission/PermissionInfo.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/generic/permission/PermissionInfo.java @@ -115,6 +115,6 @@ public class PermissionInfo extends GenericChildCommand { } // fallback to priority - return NodeWithContextComparator.reverse().compare(o1, o2); + return NodeWithContextComparator.descending().compare(o1, o2); }; } diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/group/GroupListMembers.java b/common/src/main/java/me/lucko/luckperms/common/commands/group/GroupListMembers.java index 1cc50ddac..96ac218a6 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/group/GroupListMembers.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/group/GroupListMembers.java @@ -118,7 +118,7 @@ public class GroupListMembers extends ChildCommand { private static > void sendResult(Sender sender, List> results, Function lookupFunction, Message.Args3 headerMessage, HolderType holderType, String label, int page) { results = new ArrayList<>(results); - results.sort(NodeEntryComparator.normal()); + results.sort(NodeEntryComparator.ascending()); int pageIndex = page - 1; List>> pages = Iterators.divideIterable(results, 15); diff --git a/common/src/main/java/me/lucko/luckperms/common/commands/misc/SearchCommand.java b/common/src/main/java/me/lucko/luckperms/common/commands/misc/SearchCommand.java index ee003abf6..958ebbb07 100644 --- a/common/src/main/java/me/lucko/luckperms/common/commands/misc/SearchCommand.java +++ b/common/src/main/java/me/lucko/luckperms/common/commands/misc/SearchCommand.java @@ -98,7 +98,7 @@ public class SearchCommand extends SingleCommand { private static > void sendResult(Sender sender, List> results, Function lookupFunction, Message.Args3 headerMessage, HolderType holderType, String label, int page, Comparison comparison) { results = new ArrayList<>(results); - results.sort(NodeEntryComparator.normal()); + results.sort(NodeEntryComparator.ascending()); int pageIndex = page - 1; List>> pages = Iterators.divideIterable(results, 15); diff --git a/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextComparator.java b/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextComparator.java index ba56de8d1..bec4d7efc 100644 --- a/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextComparator.java +++ b/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextComparator.java @@ -32,7 +32,6 @@ import java.util.Comparator; public class ContextComparator implements Comparator { public static final ContextComparator INSTANCE = new ContextComparator(false); - public static final ContextComparator ONLY_KEY = new ContextComparator(true); private final boolean onlyKeys; diff --git a/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextSetComparator.java b/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextSetComparator.java index 9cbd51abe..29fe71f7c 100644 --- a/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextSetComparator.java +++ b/common/src/main/java/me/lucko/luckperms/common/context/comparator/ContextSetComparator.java @@ -34,16 +34,15 @@ import java.util.Arrays; import java.util.Comparator; public class ContextSetComparator implements Comparator { + private static final Comparator ASCENDING = new ContextSetComparator(); + private static final Comparator DESCENDING = ASCENDING.reversed(); - private static final Comparator INSTANCE = new ContextSetComparator(); - private static final Comparator REVERSE = INSTANCE.reversed(); - - public static Comparator normal() { - return INSTANCE; + public static Comparator ascending() { + return ASCENDING; } - public static Comparator reverse() { - return REVERSE; + public static Comparator descending() { + return DESCENDING; } @Override diff --git a/common/src/main/java/me/lucko/luckperms/common/model/PermissionHolder.java b/common/src/main/java/me/lucko/luckperms/common/model/PermissionHolder.java index 21af4b045..ca7b8b774 100644 --- a/common/src/main/java/me/lucko/luckperms/common/model/PermissionHolder.java +++ b/common/src/main/java/me/lucko/luckperms/common/model/PermissionHolder.java @@ -258,7 +258,7 @@ public abstract class PermissionHolder { } public SortedSet getOwnNodesSorted(QueryOptions queryOptions) { - SortedSet nodes = new TreeSet<>(NodeWithContextComparator.reverse()); + SortedSet nodes = new TreeSet<>(NodeWithContextComparator.descending()); for (DataType dataType : queryOrder(queryOptions)) { getData(dataType).copyTo(nodes, queryOptions); } @@ -301,7 +301,7 @@ public abstract class PermissionHolder { return getOwnNodesSorted(queryOptions); } - SortedSet nodes = new TreeSet<>(NodeWithContextComparator.reverse()); + SortedSet nodes = new TreeSet<>(NodeWithContextComparator.descending()); InheritanceGraph graph = this.plugin.getInheritanceGraphFactory().getGraph(queryOptions); for (PermissionHolder holder : graph.traverse(this)) { for (DataType dataType : holder.queryOrder(queryOptions)) { diff --git a/common/src/main/java/me/lucko/luckperms/common/model/Track.java b/common/src/main/java/me/lucko/luckperms/common/model/Track.java index fd2d0ac91..0eff019b7 100644 --- a/common/src/main/java/me/lucko/luckperms/common/model/Track.java +++ b/common/src/main/java/me/lucko/luckperms/common/model/Track.java @@ -250,7 +250,7 @@ public final class Track { } /** - * Clear all of the groups within this trackx + * Clear all of the groups within this track */ public void clearGroups() { List before = ImmutableList.copyOf(this.groups); diff --git a/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMap.java b/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMap.java index 4ade7a1f4..ca99cfbde 100644 --- a/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMap.java +++ b/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMap.java @@ -70,7 +70,7 @@ public interface NodeMap { } default SortedSet asSortedSet() { - SortedSet set = new TreeSet<>(NodeWithContextComparator.reverse()); + SortedSet set = new TreeSet<>(NodeWithContextComparator.descending()); copyTo(set); return set; } @@ -96,7 +96,7 @@ public interface NodeMap { } default SortedSet inheritanceAsSortedSet() { - SortedSet set = new TreeSet<>(NodeWithContextComparator.reverse()); + SortedSet set = new TreeSet<>(NodeWithContextComparator.descending()); copyInheritanceNodesTo(set); return set; } diff --git a/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMapMutable.java b/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMapMutable.java index 5bd83a371..9e047821b 100644 --- a/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMapMutable.java +++ b/common/src/main/java/me/lucko/luckperms/common/model/nodemap/NodeMapMutable.java @@ -57,12 +57,12 @@ public class NodeMapMutable extends NodeMapBase { // Used in calls to Map#computeIfAbsent to make them behave like a LoadingMap/Cache // The key (ImmutableContextSet) isn't actually used - these are more like suppliers than functions - private static final Function> VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.reverse()); - private static final Function> INHERITANCE_VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.reverse()); + private static final Function> VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.descending()); + private static final Function> INHERITANCE_VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.descending()); // Creates the Map instances used by this.map and this.inheritanceMap private static SortedMap> createMap() { - return new ConcurrentSkipListMap<>(ContextSetComparator.reverse()); + return new ConcurrentSkipListMap<>(ContextSetComparator.descending()); } /* diff --git a/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeComparator.java b/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeComparator.java index dc2e639a5..0aeafc3e2 100644 --- a/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeComparator.java +++ b/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeComparator.java @@ -31,15 +31,15 @@ import net.luckperms.api.node.types.PermissionNode; import java.util.Comparator; public class NodeComparator implements Comparator { - private static final Comparator INSTANCE = new NodeComparator(); - private static final Comparator REVERSE = INSTANCE.reversed(); + private static final Comparator ASCENDING = new NodeComparator(); + private static final Comparator DESCENDING = ASCENDING.reversed(); - public static Comparator normal() { - return INSTANCE; + public static Comparator ascending() { + return ASCENDING; } - public static Comparator reverse() { - return REVERSE; + public static Comparator descending() { + return DESCENDING; } @SuppressWarnings({"ConstantConditions", "OptionalGetWithoutIsPresent"}) @@ -49,13 +49,13 @@ public class NodeComparator implements Comparator { return 0; } - // compare whether nodes are temporary + // compare whether nodes are temporary - temporary has priority int result = Boolean.compare(o1.hasExpiry(), o2.hasExpiry()); if (result != 0) { return result; } - // compare whether nodes are wildcard nodes + // compare whether nodes are wildcard nodes - non-wildcard has priority result = Boolean.compare( o1 instanceof PermissionNode && ((PermissionNode) o1).isWildcard(), o2 instanceof PermissionNode && ((PermissionNode) o2).isWildcard() @@ -66,8 +66,9 @@ public class NodeComparator implements Comparator { // compare expiry times if both nodes are temporary // due to the comparison earlier, either both nodes are temporary or neither are. + // sooner expiry has priority if (o1.hasExpiry()) { - result = o1.getExpiry().compareTo(o2.getExpiry()); + result = -o1.getExpiry().compareTo(o2.getExpiry()); if (result != 0) { return result; } diff --git a/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeEntryComparator.java b/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeEntryComparator.java index 1165d098d..19cfc0ab4 100644 --- a/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeEntryComparator.java +++ b/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeEntryComparator.java @@ -31,17 +31,17 @@ import java.util.Comparator; public class NodeEntryComparator> implements Comparator> { - public static > Comparator> normal() { + public static > Comparator> ascending() { return new NodeEntryComparator<>(); } - public static > Comparator> reverse() { - return NodeEntryComparator.normal().reversed(); + public static > Comparator> descending() { + return NodeEntryComparator.ascending().reversed(); } @Override public int compare(NodeEntry o1, NodeEntry o2) { - int i = NodeWithContextComparator.normal().compare(o1.getNode(), o2.getNode()); + int i = NodeWithContextComparator.ascending().compare(o1.getNode(), o2.getNode()); if (i != 0) { return i; } diff --git a/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeWithContextComparator.java b/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeWithContextComparator.java index 222a1495c..2b59fc48e 100644 --- a/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeWithContextComparator.java +++ b/common/src/main/java/me/lucko/luckperms/common/node/comparator/NodeWithContextComparator.java @@ -32,18 +32,18 @@ import net.luckperms.api.node.Node; import java.util.Comparator; /** - * Compares permission nodes based upon their supposed "priority". + * Compares permission nodes based upon their "priority". */ public class NodeWithContextComparator implements Comparator { - private static final Comparator INSTANCE = new NodeWithContextComparator(ContextSetComparator.normal(), NodeComparator.normal()); - private static final Comparator REVERSE = new NodeWithContextComparator(ContextSetComparator.reverse(), NodeComparator.reverse()); + private static final Comparator ASCENDING = new NodeWithContextComparator(ContextSetComparator.ascending(), NodeComparator.ascending()); + private static final Comparator DESCENDING = new NodeWithContextComparator(ContextSetComparator.descending(), NodeComparator.descending()); - public static Comparator normal() { - return INSTANCE; + public static Comparator ascending() { + return ASCENDING; } - public static Comparator reverse() { - return REVERSE; + public static Comparator descending() { + return DESCENDING; } private final Comparator contextSetComparator; diff --git a/common/src/main/java/me/lucko/luckperms/common/util/Difference.java b/common/src/main/java/me/lucko/luckperms/common/util/Difference.java index d0a56fd29..070bd88ec 100644 --- a/common/src/main/java/me/lucko/luckperms/common/util/Difference.java +++ b/common/src/main/java/me/lucko/luckperms/common/util/Difference.java @@ -28,6 +28,7 @@ package me.lucko.luckperms.common.util; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; +import java.util.stream.Stream; /** * Records a log of the changes that occur as a result @@ -125,12 +126,22 @@ public class Difference { * @param type the type of change * @param values the changed values */ - public void recordChanges(ChangeType type, Iterable values) { + public void recordChanges(ChangeType type, Iterable values) { for (T value : values) { recordChange(new Change<>(type, value)); } } + /** + * Records some changes. + * + * @param type the type of change + * @param values the changed values + */ + public void recordChanges(ChangeType type, Stream values) { + values.forEach(value -> recordChange(new Change<>(type, value))); + } + /** * Merges the recorded differences in {@code other} into this. * diff --git a/common/src/test/java/me/lucko/luckperms/common/context/ContextSetComparatorTest.java b/common/src/test/java/me/lucko/luckperms/common/context/ContextSetComparatorTest.java index e8041f93e..2cd3ef489 100644 --- a/common/src/test/java/me/lucko/luckperms/common/context/ContextSetComparatorTest.java +++ b/common/src/test/java/me/lucko/luckperms/common/context/ContextSetComparatorTest.java @@ -54,6 +54,11 @@ public class ContextSetComparatorTest { .add("foo", "foo") .add("foo", "bar") .build(); + private static final ImmutableContextSet MISC_2 = new ImmutableContextSetImpl.BuilderImpl() + .add("foo", "foo") + .add("foo", "bar") + .add("bar", "foo") + .build(); private static final ImmutableContextSet SERVER_AND_MISC = new ImmutableContextSetImpl.BuilderImpl() .add("server", "foo") .add("foo", "foo") @@ -77,46 +82,46 @@ public class ContextSetComparatorTest { .build(); private static Stream all() { - return Stream.of(EMPTY, JUST_SERVER, JUST_WORLD, SERVER_AND_WORLD, MISC, SERVER_AND_MISC, WORLD_AND_MISC, SERVER_AND_WORLD_AND_MISC_1, SERVER_AND_WORLD_AND_MISC_2); + return Stream.of(EMPTY, JUST_SERVER, JUST_WORLD, SERVER_AND_WORLD, MISC, MISC_2, SERVER_AND_MISC, WORLD_AND_MISC, SERVER_AND_WORLD_AND_MISC_1, SERVER_AND_WORLD_AND_MISC_2); } - private static final Comparator INSTANCE = ContextSetComparator.normal(); + private static final Comparator ASCENDING = ContextSetComparator.ascending(); @ParameterizedTest @MethodSource("all") @SuppressWarnings("EqualsWithItself") public void testEquals(ImmutableContextSet set) { - assertEquals(0, INSTANCE.compare(set, set)); + assertEquals(0, ASCENDING.compare(set, set)); } @Test public void testEmpty() { - assertTrue(INSTANCE.compare(JUST_SERVER, EMPTY) > 0); - assertTrue(INSTANCE.compare(EMPTY, JUST_SERVER) < 0); + assertTrue(ASCENDING.compare(JUST_SERVER, EMPTY) > 0); + assertTrue(ASCENDING.compare(EMPTY, JUST_SERVER) < 0); } @Test public void testServerPresence() { - assertTrue(INSTANCE.compare(JUST_SERVER, MISC) > 0); - assertTrue(INSTANCE.compare(JUST_SERVER, WORLD_AND_MISC) > 0); + assertTrue(ASCENDING.compare(JUST_SERVER, MISC) > 0); + assertTrue(ASCENDING.compare(JUST_SERVER, WORLD_AND_MISC) > 0); } @Test public void testWorldPresence() { - assertTrue(INSTANCE.compare(JUST_WORLD, MISC) > 0); + assertTrue(ASCENDING.compare(JUST_WORLD, MISC) > 0); } @Test public void testOverallSize() { - assertTrue(INSTANCE.compare(SERVER_AND_MISC, JUST_SERVER) > 0); - assertTrue(INSTANCE.compare(WORLD_AND_MISC, JUST_WORLD) > 0); + assertTrue(ASCENDING.compare(SERVER_AND_MISC, JUST_SERVER) > 0); + assertTrue(ASCENDING.compare(WORLD_AND_MISC, JUST_WORLD) > 0); } @ParameterizedTest @MethodSource("all") public void testOverallSizeAll(ImmutableContextSet other) { if (other == SERVER_AND_WORLD_AND_MISC_2) return; - assertTrue(INSTANCE.compare(SERVER_AND_WORLD_AND_MISC_2, other) > 0); + assertTrue(ASCENDING.compare(SERVER_AND_WORLD_AND_MISC_2, other) > 0); } private static Stream testTransitivity() { @@ -141,12 +146,30 @@ public class ContextSetComparatorTest { list.add(a); list.add(b); list.add(c); - list.sort(INSTANCE); + list.sort(ASCENDING); List reversed = new ArrayList<>(list); - reversed.sort(INSTANCE.reversed()); + reversed.sort(ASCENDING.reversed()); assertEquals(Lists.reverse(list), reversed); } + @Test + public void testPriorityOrdering() { + List list = new ArrayList<>(); + list.add(EMPTY); + list.add(JUST_SERVER); + list.add(JUST_WORLD); + list.add(MISC); + list.add(MISC_2); + list.sort(ContextSetComparator.ascending()); + + assertEquals(List.of(EMPTY, MISC, MISC_2, JUST_WORLD, JUST_SERVER), list); + + // list sorted with the descending comparator should be exactly the reverse of the ascending list + List reversed = new ArrayList<>(list); + reversed.sort(ContextSetComparator.descending()); + assertEquals(Lists.reverse(list), reversed); + } + } diff --git a/common/src/test/java/me/lucko/luckperms/common/model/NodeMapTest.java b/common/src/test/java/me/lucko/luckperms/common/model/NodeMapTest.java index bd61748b1..08a0df534 100644 --- a/common/src/test/java/me/lucko/luckperms/common/model/NodeMapTest.java +++ b/common/src/test/java/me/lucko/luckperms/common/model/NodeMapTest.java @@ -52,13 +52,16 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.time.Duration; +import java.time.Instant; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @@ -178,54 +181,106 @@ public class NodeMapTest { assertEquals(4, map.size()); - map.remove(makeNode("test1").toBuilder().withContext("hello", "world").build()); - map.remove(makeNode("test3")); - map.remove(makeNode("test4")); - map.remove(makeNode("test4").toBuilder().withContext("hello", "world").withContext("aaa", "bbb").build()); - map.remove(makeNode("test5")); + for (Node node : List.of( + makeNode("test1").toBuilder().withContext("hello", "world").build(), + makeNode("test3"), + makeNode("test4"), + makeNode("test4").toBuilder().withContext("hello", "world").withContext("aaa", "bbb").build(), + makeNode("test5") + )) { + Difference diff = map.remove(node); + assertEquals(Set.of(), diff.getChanges()); + } assertEquals(4, map.size()); - map.remove(makeNode("test1")); - map.remove(makeNode("test2").toBuilder().value(true).build()); - map.remove(makeNode("test3").toBuilder().expiry(2, TimeUnit.HOURS).build()); - map.remove(makeNode("test4").toBuilder().withContext("hello", "world").build()); + for (Node node : List.of( + makeNode("test1"), + makeNode("test2").toBuilder().value(true).build(), + makeNode("test3").toBuilder().expiry(2, TimeUnit.HOURS).build(), + makeNode("test4").toBuilder().withContext("hello", "world").build() + )) { + Difference diff = map.remove(node); + assertEquals(0, diff.getAdded().size()); + assertEquals(1, diff.getRemoved().size()); + } assertEquals(0, map.size()); } @Test public void testRemoveExact() { + Instant expiry = Instant.now().plusSeconds(60); + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); map.add(makeNode("test1")); map.add(makeNode("test2").toBuilder().value(false).build()); - map.add(makeNode("test3").toBuilder().expiry(1, TimeUnit.HOURS).build()); + map.add(makeNode("test3").toBuilder().expiry(expiry).build()); map.add(makeNode("test4").toBuilder().withContext("hello", "world").build()); assertEquals(4, map.size()); - map.removeExact(makeNode("test1").toBuilder().withContext("hello", "world").build()); - map.removeExact(makeNode("test3")); - map.removeExact(makeNode("test4")); - map.removeExact(makeNode("test4").toBuilder().withContext("hello", "world").withContext("aaa", "bbb").build()); - map.removeExact(makeNode("test5")); + for (Node node : List.of( + makeNode("test1").toBuilder().withContext("hello", "world").build(), + makeNode("test3"), + makeNode("test4"), + makeNode("test4").toBuilder().withContext("hello", "world").withContext("aaa", "bbb").build(), + makeNode("test5"), + makeNode("test2").toBuilder().value(true).build(), + makeNode("test3").toBuilder().expiry(2, TimeUnit.HOURS).build(), + makeNode("test4").toBuilder().withContext("hello", "world").withContext("aaa", "bbb").build() + )) { + Difference diff = map.removeExact(node); + assertEquals(Set.of(), diff.getChanges()); + } assertEquals(4, map.size()); - map.removeExact(makeNode("test2").toBuilder().value(true).build()); - map.removeExact(makeNode("test3").toBuilder().expiry(2, TimeUnit.HOURS).build()); - map.removeExact(makeNode("test4").toBuilder().withContext("hello", "world").withContext("aaa", "bbb").build()); - - assertEquals(4, map.size()); - - map.removeExact(makeNode("test1")); - map.removeExact(makeNode("test2").toBuilder().value(false).build()); - map.removeExact(makeNode("test3").toBuilder().expiry(1, TimeUnit.HOURS).build()); - map.removeExact(makeNode("test4").toBuilder().withContext("hello", "world").build()); + for (Node node : List.of( + makeNode("test1"), + makeNode("test2").toBuilder().value(false).build(), + makeNode("test3").toBuilder().expiry(expiry).build(), + makeNode("test4").toBuilder().withContext("hello", "world").build() + )) { + Difference diff = map.removeExact(node); + assertEquals(0, diff.getAdded().size()); + assertEquals(1, diff.getRemoved().size()); + } assertEquals(0, map.size()); } + @Test + public void testClear() { + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + map.add(makeNode("a")); + map.add(makeNode("b")); + map.add(makeNode("c")); + + assertEquals(3, map.size()); + + Difference diff = map.clear(); + assertEquals(3, diff.getRemoved().size()); + assertEquals(0, map.size()); + } + + @Test + public void testSetContent() { + Node a = makeNode("a"); + Node b = makeNode("b"); + Node c = makeNode("c"); + + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + map.add(a); + map.add(b); + + Difference diff = map.setContent(List.of(b, c)); + assertEquals(Set.of(c), diff.getAdded()); + assertEquals(Set.of(a), diff.getRemoved()); + + assertEquals(Set.of(b, c), map.asSet()); + } + @ParameterizedTest(name = "s={0} w={1} is={2} iw={3}") @CsvSource({ "true, true, true, true, 8, 4", @@ -277,6 +332,130 @@ public class NodeMapTest { assertEquals(expectedInheritance, inheritanceOutput.size()); } + @Test + public void testRemoveIf() { + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + Node test1 = makeNode("test1"); + Node test2 = makeNode("test2").toBuilder().value(false).build(); + Node group1 = makeNode("group.test1"); + Node group2 = makeNode("group.test2").toBuilder().value(false).build(); + + map.add(test1); + map.add(test2); + map.add(group1); + map.add(group2); + assertEquals(4, map.size()); + + Difference diff = map.removeIf(node -> !node.getValue()); + assertEquals(Set.of(test2, group2), diff.getRemoved()); + assertEquals(Set.of(), diff.getAdded()); + assertEquals(2, map.size()); + assertEquals(Set.of(test1, group1), map.asSet()); + assertEquals(List.of(group1), map.inheritanceAsList()); + } + + @Test + public void testRemoveIfWithContext() { + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + Node inContext = makeNode("test1").toBuilder().withContext("server", "test").build(); + Node globalNode = makeNode("test2"); + Node otherInContext = makeNode("test3").toBuilder().withContext("server", "test").build(); + + map.add(inContext); + map.add(globalNode); + map.add(otherInContext); + assertEquals(3, map.size()); + + Difference diff = map.removeIf(inContext.getContexts(), node -> node.getKey().equals("test1")); + assertEquals(Set.of(inContext), diff.getRemoved()); + assertEquals(2, map.size()); + assertEquals(Set.of(globalNode, otherInContext), map.asSet()); + + // no-op if the context set isn't present in the map + Difference diff2 = map.removeIf(ImmutableContextSetImpl.of("world", "test"), node -> true); + assertTrue(diff2.isEmpty()); + assertEquals(2, map.size()); + } + + @ParameterizedTest + @CsvSource({ + "test1, test2, false", + "test1, test1, true" + }) + public void testRemoveThenAdd(String removeKey, String addKey, boolean sameNode) { + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + Node toRemove = makeNode(removeKey); + Node toAdd = makeNode(addKey); + map.add(toRemove); + + Difference diff = map.removeThenAdd(toRemove, toAdd); + + if (sameNode) { + // removeThenAdd is a no-op if the two nodes are equal + assertTrue(diff.isEmpty()); + assertEquals(1, map.size()); + assertEquals(Set.of(toRemove), map.asSet()); + } else { + assertEquals(Set.of(toAdd), diff.getAdded()); + assertEquals(Set.of(toRemove), diff.getRemoved()); + assertEquals(Set.of(toAdd), map.asSet()); + } + } + + @Test + public void testClearContext() { + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + Node global = makeNode("test1"); + Node scoped = makeNode("test2").toBuilder().withContext("server", "test").build(); + + map.add(global); + map.add(scoped); + assertEquals(2, map.size()); + + Difference diff = map.clear(scoped.getContexts()); + assertEquals(Set.of(scoped), diff.getRemoved()); + assertEquals(Set.of(global), map.asSet()); + + // clearing a context that's no longer present is a no-op + Difference diff2 = map.clear(scoped.getContexts()); + assertTrue(diff2.isEmpty()); + assertEquals(1, map.size()); + } + + @Test + public void testApplyChanges() { + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + Node existing = makeNode("test1"); + Node incoming = makeNode("test2"); + map.add(existing); + + Difference changes = new Difference<>(); + changes.recordChange(Difference.ChangeType.REMOVE, existing); + changes.recordChange(Difference.ChangeType.ADD, incoming); + + Difference result = map.applyChanges(changes); + assertEquals(Set.of(incoming), result.getAdded()); + assertEquals(Set.of(existing), result.getRemoved()); + assertEquals(Set.of(incoming), map.asSet()); + } + + @Test + public void testNodesInContext() { + NodeMapMutable map = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + Node global = makeNode("test1"); + Node scoped = makeNode("group.test2").toBuilder().withContext("server", "test").build(); + + map.add(global); + map.add(scoped); + + assertEquals(Set.of(global), Set.copyOf(map.nodesInContext(ImmutableContextSetImpl.EMPTY))); + assertEquals(Set.of(scoped), Set.copyOf(map.nodesInContext(scoped.getContexts()))); + assertEquals(Set.of(scoped), Set.copyOf(map.inheritanceNodesInContext(scoped.getContexts()))); + + // context not present in the map + assertEquals(Set.of(), map.nodesInContext(ImmutableContextSetImpl.of("world", "test"))); + } + @ParameterizedTest @CsvSource({ "'', 2, 1", @@ -324,5 +503,4 @@ public class NodeMapTest { assertEquals(expectedInheritance, inheritanceOutput.size()); } - } diff --git a/common/src/test/java/me/lucko/luckperms/common/model/RecordedNodeMapTest.java b/common/src/test/java/me/lucko/luckperms/common/model/RecordedNodeMapTest.java new file mode 100644 index 000000000..4b137f443 --- /dev/null +++ b/common/src/test/java/me/lucko/luckperms/common/model/RecordedNodeMapTest.java @@ -0,0 +1,147 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.common.model; + +import me.lucko.luckperms.common.model.nodemap.NodeMapMutable; +import me.lucko.luckperms.common.model.nodemap.RecordedNodeMap; +import me.lucko.luckperms.common.node.factory.NodeBuilders; +import me.lucko.luckperms.common.util.Difference; +import net.luckperms.api.model.data.DataType; +import net.luckperms.api.node.Node; +import net.luckperms.api.node.types.InheritanceNode; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class RecordedNodeMapTest { + + private static final PermissionHolderIdentifier ORIGIN = new PermissionHolderIdentifier(HolderType.GROUP, "test"); + + @Mock private PermissionHolder mockHolder; + + private NodeMapMutable delegate; + private RecordedNodeMap map; + + @BeforeEach + public void setup() { + when(this.mockHolder.getIdentifier()).thenReturn(ORIGIN); + this.delegate = new NodeMapMutable(this.mockHolder, DataType.NORMAL); + this.map = new RecordedNodeMap(this.delegate); + } + + private static Node makeNode(String key) { + return NodeBuilders.determineMostApplicable(key).build(); + } + + @Test + public void testMutationsAreRecorded() { + Node a = makeNode("a"); + Node b = makeNode("b"); + + this.map.add(a); + this.map.add(b); + this.map.remove(a); + + Difference exported = this.map.exportChanges(diff -> true); + assertEquals(Set.of(b), exported.getAdded()); + assertEquals(Set.of(), exported.getRemoved()); + } + + @Test + public void testExportChangesClearsTheLog() { + this.map.add(makeNode("a")); + + Difference first = this.map.exportChanges(diff -> true); + assertFalse(first.isEmpty()); + + // the log should have been reset, so a second export is empty + Difference second = this.map.exportChanges(diff -> true); + assertTrue(second.isEmpty()); + } + + @Test + public void testExportChangesRespectsPredicate() { + this.map.add(makeNode("a")); + + // predicate rejects the export, nothing should be returned and the log should be untouched + Difference rejected = this.map.exportChanges(diff -> false); + assertNull(rejected); + + Difference accepted = this.map.exportChanges(diff -> true); + assertFalse(accepted.isEmpty()); + } + + @Test + public void testDiscardChanges() { + this.map.add(makeNode("a")); + this.map.discardChanges(); + + Difference exported = this.map.exportChanges(diff -> true); + assertTrue(exported.isEmpty()); + + // the underlying delegate should be unaffected, only the change log is discarded + assertEquals(1, this.map.size()); + } + + @Test + public void testAddDefaultNodeToChangeSet() { + Difference result = this.map.addDefaultNodeToChangeSet(); + assertEquals(1, result.getAdded().size()); + Node added = result.getAdded().iterator().next(); + assertInstanceOf(InheritanceNode.class, added); + assertEquals("default", ((InheritanceNode) added).getGroupName()); + + // it should also have been recorded in the change log + Difference exported = this.map.exportChanges(diff -> true); + assertEquals(result.getAdded(), exported.getAdded()); + } + + @Test + public void testBypassMutatesWithoutRecording() { + assertSame(this.delegate, this.map.bypass()); + + this.map.bypass().add(makeNode("a")); + assertEquals(1, this.map.size()); + + // the mutation happened directly on the delegate, so it shouldn't show up in the change log + Difference exported = this.map.exportChanges(diff -> true); + assertTrue(exported == null || exported.isEmpty()); + } + +} diff --git a/common/src/test/java/me/lucko/luckperms/common/model/TrackTest.java b/common/src/test/java/me/lucko/luckperms/common/model/TrackTest.java index fc155521c..68c412ecc 100644 --- a/common/src/test/java/me/lucko/luckperms/common/model/TrackTest.java +++ b/common/src/test/java/me/lucko/luckperms/common/model/TrackTest.java @@ -25,13 +25,21 @@ package me.lucko.luckperms.common.model; +import me.lucko.luckperms.common.config.ConfigKeys; import me.lucko.luckperms.common.config.LuckPermsConfiguration; +import me.lucko.luckperms.common.context.ImmutableContextSetImpl; import me.lucko.luckperms.common.event.EventDispatcher; import me.lucko.luckperms.common.inheritance.InheritanceGraphFactory; import me.lucko.luckperms.common.model.manager.group.GroupManager; import me.lucko.luckperms.common.model.manager.group.StandardGroupManager; +import me.lucko.luckperms.common.node.types.Inheritance; import me.lucko.luckperms.common.plugin.LuckPermsPlugin; +import me.lucko.luckperms.common.util.Predicates; import net.luckperms.api.model.data.DataMutateResult; +import net.luckperms.api.model.data.DataType; +import net.luckperms.api.node.types.InheritanceNode; +import net.luckperms.api.track.DemotionResult; +import net.luckperms.api.track.PromotionResult; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -39,10 +47,13 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; +import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; @@ -63,6 +74,7 @@ public class TrackTest { lenient().when(this.plugin.getInheritanceGraphFactory()).thenReturn(new InheritanceGraphFactory(this.plugin)); lenient().when(this.plugin.getConfiguration()).thenReturn(this.configuration); lenient().when(this.plugin.getEventDispatcher()).thenReturn(mock(EventDispatcher.class)); + lenient().when(this.configuration.get(ConfigKeys.PRIMARY_GROUP_CALCULATION)).thenReturn(PrimaryGroupHolder.Stored::new); } @Test @@ -120,4 +132,238 @@ public class TrackTest { assertEquals(List.of("a", "d", "c"), track.getGroups()); } + @Test + public void testPromoteThrowsOnSmallTrack() { + Track track = new Track("test", this.plugin); + track.setGroups(List.of("a")); + + User user = new User(UUID.randomUUID(), this.plugin); + assertThrows(IllegalStateException.class, () -> + track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true) + ); + } + + @Test + public void testPromoteAddedToFirst() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + + // user isn't on the track at all, and addToFirst=false - no change made + PromotionResult result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, false); + assertEquals(PromotionResult.Status.ADDED_TO_FIRST_GROUP, result.getStatus()); + assertTrue(result.getGroupTo().isEmpty()); + assertTrue(user.normalData().inheritanceNodesInContext(ImmutableContextSetImpl.EMPTY).isEmpty()); + + // user isn't on the track at all, and addToFirst=true - added to first group + result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(PromotionResult.Status.ADDED_TO_FIRST_GROUP, result.getStatus()); + assertEquals("a", result.getGroupTo().orElse(null)); + assertTrue(userInheritsGroup(user, "a")); + } + + @Test + public void testPromoteSuccess() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + this.groupManager.getOrMake("c"); + track.setGroups(List.of("a", "b", "c")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("a").build(), false); + + PromotionResult result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(PromotionResult.Status.SUCCESS, result.getStatus()); + assertEquals("a", result.getGroupFrom().orElse(null)); + assertEquals("b", result.getGroupTo().orElse(null)); + assertFalse(userInheritsGroup(user, "a")); + assertTrue(userInheritsGroup(user, "b")); + + // promote again, to the end of the track + result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(PromotionResult.Status.SUCCESS, result.getStatus()); + assertEquals("b", result.getGroupFrom().orElse(null)); + assertEquals("c", result.getGroupTo().orElse(null)); + assertFalse(userInheritsGroup(user, "b")); + assertTrue(userInheritsGroup(user, "c")); + + // already at the end of the track + result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(PromotionResult.Status.END_OF_TRACK, result.getStatus()); + assertTrue(userInheritsGroup(user, "c")); + } + + @Test + public void testPromoteAmbiguousCall() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("a").build(), false); + user.setNode(DataType.NORMAL, Inheritance.builder("b").build(), false); + + PromotionResult result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(PromotionResult.Status.AMBIGUOUS_CALL, result.getStatus()); + } + + @Test + public void testPromoteMalformedTrack() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + // "b" is on the track but doesn't exist in the group manager + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("a").build(), false); + + PromotionResult result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(PromotionResult.Status.MALFORMED_TRACK, result.getStatus()); + assertEquals("b", result.getGroupTo().orElse(null)); + assertFalse(userInheritsGroup(user, "b")); + } + + @Test + public void testPromoteUndefinedFailure() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("a").build(), false); + + // permission checker denies the promotion + PromotionResult result = track.promote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysFalse(), null, true); + assertEquals(PromotionResult.Status.UNDEFINED_FAILURE, result.getStatus()); + assertTrue(userInheritsGroup(user, "a")); + assertFalse(userInheritsGroup(user, "b")); + } + + @Test + public void testDemoteThrowsOnSmallTrack() { + Track track = new Track("test", this.plugin); + track.setGroups(List.of("a")); + + User user = new User(UUID.randomUUID(), this.plugin); + assertThrows(IllegalStateException.class, () -> + track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true) + ); + } + + @Test + public void testDemoteNotOnTrack() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + + DemotionResult result = track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(DemotionResult.Status.NOT_ON_TRACK, result.getStatus()); + } + + @Test + public void testDemoteSuccess() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + this.groupManager.getOrMake("c"); + track.setGroups(List.of("a", "b", "c")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("c").build(), false); + + DemotionResult result = track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(DemotionResult.Status.SUCCESS, result.getStatus()); + assertEquals("c", result.getGroupFrom().orElse(null)); + assertEquals("b", result.getGroupTo().orElse(null)); + assertFalse(userInheritsGroup(user, "c")); + assertTrue(userInheritsGroup(user, "b")); + } + + @Test + public void testDemoteRemovedFromFirst() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("a").build(), false); + + // removeFromFirst=false - no change made, but reports as if removed + DemotionResult result = track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, false); + assertEquals(DemotionResult.Status.REMOVED_FROM_FIRST_GROUP, result.getStatus()); + assertNull(result.getGroupFrom().orElse(null)); + assertTrue(userInheritsGroup(user, "a")); + + // removeFromFirst=true - user is removed from the group entirely + result = track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(DemotionResult.Status.REMOVED_FROM_FIRST_GROUP, result.getStatus()); + assertEquals("a", result.getGroupFrom().orElse(null)); + assertFalse(userInheritsGroup(user, "a")); + } + + @Test + public void testDemoteAmbiguousCall() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("a").build(), false); + user.setNode(DataType.NORMAL, Inheritance.builder("b").build(), false); + + DemotionResult result = track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(DemotionResult.Status.AMBIGUOUS_CALL, result.getStatus()); + } + + @Test + public void testDemoteMalformedTrack() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("b"); + // "a" is on the track but doesn't exist in the group manager + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("b").build(), false); + + DemotionResult result = track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysTrue(), null, true); + assertEquals(DemotionResult.Status.MALFORMED_TRACK, result.getStatus()); + assertEquals("a", result.getGroupTo().orElse(null)); + } + + @Test + public void testDemoteUndefinedFailure() { + Track track = new Track("test", this.plugin); + this.groupManager.getOrMake("a"); + this.groupManager.getOrMake("b"); + track.setGroups(List.of("a", "b")); + + User user = new User(UUID.randomUUID(), this.plugin); + user.setNode(DataType.NORMAL, Inheritance.builder("b").build(), false); + + // permission checker denies the demotion + DemotionResult result = track.demote(user, ImmutableContextSetImpl.EMPTY, Predicates.alwaysFalse(), null, true); + assertEquals(DemotionResult.Status.UNDEFINED_FAILURE, result.getStatus()); + assertTrue(userInheritsGroup(user, "b")); + } + + private static boolean userInheritsGroup(User user, String group) { + for (InheritanceNode node : user.normalData().inheritanceNodesInContext(ImmutableContextSetImpl.EMPTY)) { + if (node.getGroupName().equalsIgnoreCase(group)) { + return true; + } + } + return false; + } + } diff --git a/common/src/test/java/me/lucko/luckperms/common/node/NodeComparatorTest.java b/common/src/test/java/me/lucko/luckperms/common/node/NodeComparatorTest.java new file mode 100644 index 000000000..0b1eccd7c --- /dev/null +++ b/common/src/test/java/me/lucko/luckperms/common/node/NodeComparatorTest.java @@ -0,0 +1,230 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.common.node; + +import com.google.common.collect.Lists; +import me.lucko.luckperms.common.context.ContextSetComparatorTest; +import me.lucko.luckperms.common.node.comparator.NodeComparator; +import me.lucko.luckperms.common.node.comparator.NodeWithContextComparator; +import me.lucko.luckperms.common.node.types.Permission; +import net.luckperms.api.node.Node; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for {@link NodeComparator} and {@link NodeWithContextComparator}. + * + *

Both comparators are used to order nodes by "priority" - the primary use case being the + * {@code SortedSet}/{@code SortedMap} instances backing {@code NodeMapMutable}, where the + * descending comparator is used so that the highest priority node appears first when the + * collection is iterated.

+ * + *

{@link ContextSetComparatorTest} already extensively covers the rules used to compare nodes + * based on their contexts (e.g. more specific contexts are higher priority) - this class instead + * focuses on the node-specific tie-breaking rules in {@link NodeComparator}, and how + * {@link NodeWithContextComparator} combines context specificity with those rules.

+ */ +public class NodeComparatorTest { + + @Nested + class NodeComparatorTests { + + @Test + @SuppressWarnings("EqualsWithItself") + public void testEquals() { + Node node = Permission.builder().permission("hello.world").build(); + assertEquals(0, NodeComparator.ascending().compare(node, node)); + assertEquals(0, NodeComparator.descending().compare(node, node)); + } + + @Test + public void testDescendingIsReverseOfAscending() { + Instant expiry = Instant.now().plusSeconds(60); + List nodes = new ArrayList<>(List.of( + Permission.builder().permission("a").build(), + Permission.builder().permission("z").build(), + Permission.builder().permission("a").expiry(expiry).build(), + Permission.builder().permission("foo.*").build(), + Permission.builder().permission("foo.bar.*").build() + )); + + List ascendingSorted = new ArrayList<>(nodes); + ascendingSorted.sort(NodeComparator.ascending()); + + List descendingSorted = new ArrayList<>(nodes); + descendingSorted.sort(NodeComparator.descending()); + + assertEquals(Lists.reverse(ascendingSorted), descendingSorted); + } + + @Test + public void testTemporaryNodesTakePriorityOverPermanent() { + Node permanentNode = Permission.builder().permission("hello.world").build(); + Instant expiry = Instant.now().plusSeconds(60); + Node temporaryNode = Permission.builder().permission("hello.world").expiry(expiry).build(); + + // the temporary node should sort first (higher priority) with the descending comparator + List list = new ArrayList<>(List.of(permanentNode, temporaryNode)); + list.sort(NodeComparator.descending()); + assertEquals(List.of(temporaryNode, permanentNode), list); + } + + @Test + public void testTemporaryNodesAreOrderedByExpiryTime() { + Instant expiry1 = Instant.now().plusSeconds(60); + Node temporaryNode1 = Permission.builder().permission("hello.world").expiry(expiry1).build(); + + Instant expiry2 = Instant.now().plusSeconds(120); + Node temporaryNode2 = Permission.builder().permission("hello.world").expiry(expiry2).build(); + + // the node with the sooner expiry time should sort first (higher priority) with the descending comparator + List list = new ArrayList<>(List.of(temporaryNode2, temporaryNode1)); + list.sort(NodeComparator.descending()); + assertEquals(List.of(temporaryNode1, temporaryNode2), list); + } + + @Test + public void testMoreSpecificWildcardsTakePriorityOverLessSpecific() { + Node rootWildcard = Permission.builder().permission("*").build(); + Node shallowWildcard = Permission.builder().permission("foo.*").build(); + Node deepWildcard = Permission.builder().permission("foo.bar.*").build(); + + List list = new ArrayList<>(List.of(rootWildcard, shallowWildcard, deepWildcard)); + list.sort(NodeComparator.descending()); + + // more specific (deeper) wildcards should be ordered first + assertEquals(List.of(deepWildcard, shallowWildcard, rootWildcard), list); + } + + @Test + public void testKeyOrderingIsAlphabeticalWhenOtherwiseEqual() { + Node a = Permission.builder().permission("a").build(); + Node m = Permission.builder().permission("m").build(); + Node z = Permission.builder().permission("z").build(); + + List list = new ArrayList<>(List.of(z, a, m)); + list.sort(NodeComparator.descending()); + + assertEquals(List.of(a, m, z), list); + } + + @Test + public void testFalseValuePriorityOverTrue() { + Node trueNode = Permission.builder().permission("hello.world").value(true).build(); + Node falseNode = Permission.builder().permission("hello.world").value(false).build(); + + List list = new ArrayList<>(List.of(trueNode, falseNode)); + list.sort(NodeComparator.descending()); + + assertEquals(List.of(falseNode, trueNode), list); + } + } + + @Nested + class NodeWithContextComparatorTests { + + @Test + @SuppressWarnings("EqualsWithItself") + public void testEquals() { + Node node = Permission.builder().permission("hello.world").withContext("server", "foo").build(); + assertEquals(0, NodeWithContextComparator.ascending().compare(node, node)); + assertEquals(0, NodeWithContextComparator.descending().compare(node, node)); + } + + @Test + public void testDescendingIsReverseOfAscending() { + Instant expiry = Instant.now().plusSeconds(60); + List nodes = new ArrayList<>(List.of( + Permission.builder().permission("a").build(), + Permission.builder().permission("a").withContext("server", "foo").build(), + Permission.builder().permission("a").withContext("world", "foo").build(), + Permission.builder().permission("a").expiry(expiry).build() + )); + + List ascendingSorted = new ArrayList<>(nodes); + ascendingSorted.sort(NodeWithContextComparator.ascending()); + + List descendingSorted = new ArrayList<>(nodes); + descendingSorted.sort(NodeWithContextComparator.descending()); + + assertEquals(Lists.reverse(ascendingSorted), descendingSorted); + } + + @Test + public void testContextSpecificityTakesPriorityOverNodeProperties() { + // this node has a more specific context set, but would otherwise be considered + // lower priority than the other node if only NodeComparator rules were applied + // (it's permanent, whereas the other is temporary) + Node moreSpecificContext = Permission.builder().permission("hello.world").withContext("server", "foo").build(); + Instant expiry = Instant.now().plusSeconds(60); + Node lessSpecificContext = Permission.builder().permission("hello.world").expiry(expiry).build(); + + // context specificity should win out regardless of the temporary/permanent difference + assertTrue(NodeWithContextComparator.descending().compare(moreSpecificContext, lessSpecificContext) < 0); + + List list = new ArrayList<>(List.of(lessSpecificContext, moreSpecificContext)); + list.sort(NodeWithContextComparator.descending()); + assertEquals(List.of(moreSpecificContext, lessSpecificContext), list); + } + + @Test + public void testFallsBackToNodeComparatorWhenContextsAreEqual() { + // both nodes share the same (empty) context set, so the comparator should + // fall back to NodeComparator's rules - temporary nodes take priority + Node permanentNode = Permission.builder().permission("hello.world").build(); + Instant expiry = Instant.now().plusSeconds(60); + Node temporaryNode = Permission.builder().permission("hello.world").expiry(expiry).build(); + + List list = new ArrayList<>(List.of(permanentNode, temporaryNode)); + list.sort(NodeWithContextComparator.descending()); + assertEquals(List.of(temporaryNode, permanentNode), list); + } + + @Test + public void testPriorityOrderingAcrossContextsAndNodeProperties() { + Node empty = Permission.builder().permission("hello.world").build(); + Node withServerContext = Permission.builder().permission("hello.world").withContext("server", "foo").build(); + Instant expiry = Instant.now().plusSeconds(60); + Node withServerContextTemporary = (Permission.builder().permission("hello.world").expiry(expiry).build()).toBuilder() + .withContext("server", "foo") + .build(); + + List list = new ArrayList<>(List.of(empty, withServerContext, withServerContextTemporary)); + list.sort(NodeWithContextComparator.descending()); + + // most specific context wins first; within the same context, temporary beats permanent + assertEquals(List.of(withServerContextTemporary, withServerContext, empty), list); + } + } + +} diff --git a/common/src/test/java/me/lucko/luckperms/common/node/NodeEqualityTest.java b/common/src/test/java/me/lucko/luckperms/common/node/NodeEqualityTest.java new file mode 100644 index 000000000..3de8ffc8d --- /dev/null +++ b/common/src/test/java/me/lucko/luckperms/common/node/NodeEqualityTest.java @@ -0,0 +1,224 @@ +/* + * This file is part of LuckPerms, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.common.node; + +import me.lucko.luckperms.common.node.types.Permission; +import net.luckperms.api.node.Node; +import net.luckperms.api.node.NodeEqualityPredicate; +import net.luckperms.api.node.types.PermissionNode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class NodeEqualityTest { + + private static Node node(String permission, boolean value, Instant expiry, String contextKey, String contextValue) { + PermissionNode.Builder builder = Permission.builder().permission(permission).value(value); + if (expiry != null) { + builder.expiry(expiry); + } + if (contextKey != null) { + builder.withContext(contextKey, contextValue); + } + return builder.build(); + } + + @Test + public void testExact() { + Instant expiry = Instant.now().plusSeconds(60).truncatedTo(ChronoUnit.SECONDS); + + Node base = node("hello.world", true, expiry, "server", "one"); + Node same = node("hello.world", true, expiry, "server", "one"); + Node differentKey = node("hello.other", true, expiry, "server", "one"); + Node differentValue = node("hello.world", false, expiry, "server", "one"); + Node differentExpiry = node("hello.world", true, expiry.plusSeconds(60), "server", "one"); + Node differentContext = node("hello.world", true, expiry, "server", "two"); + + NodeEqualityPredicate predicate = NodeEqualityPredicate.EXACT; + assertTrue(predicate.areEqual(base, same)); + assertFalse(predicate.areEqual(base, differentKey)); + assertFalse(predicate.areEqual(base, differentValue)); + assertFalse(predicate.areEqual(base, differentExpiry)); + assertFalse(predicate.areEqual(base, differentContext)); + } + + @Test + public void testIgnoreValue() { + Instant expiry = Instant.now().plusSeconds(60).truncatedTo(ChronoUnit.SECONDS); + + Node base = node("hello.world", true, expiry, "server", "one"); + Node differentValue = node("hello.world", false, expiry, "server", "one"); + Node differentKey = node("hello.other", true, expiry, "server", "one"); + Node differentExpiry = node("hello.world", true, expiry.plusSeconds(60), "server", "one"); + Node differentContext = node("hello.world", true, expiry, "server", "two"); + + NodeEqualityPredicate predicate = NodeEqualityPredicate.IGNORE_VALUE; + // value is ignored + assertTrue(predicate.areEqual(base, differentValue)); + assertFalse(predicate.areEqual(base, differentKey)); + assertFalse(predicate.areEqual(base, differentExpiry)); + assertFalse(predicate.areEqual(base, differentContext)); + } + + @Test + public void testIgnoreExpiryTime() { + Instant expiryA = Instant.now().plusSeconds(60).truncatedTo(ChronoUnit.SECONDS); + Instant expiryB = Instant.now().plusSeconds(120).truncatedTo(ChronoUnit.SECONDS); + + Node base = node("hello.world", true, expiryA, "server", "one"); + Node differentExpiryTime = node("hello.world", true, expiryB, "server", "one"); + Node permanent = node("hello.world", true, null, "server", "one"); + Node differentValue = node("hello.world", false, expiryA, "server", "one"); + Node differentContext = node("hello.world", true, expiryA, "server", "two"); + + NodeEqualityPredicate predicate = NodeEqualityPredicate.IGNORE_EXPIRY_TIME; + // exact expiry time is ignored, but whether it has an expiry still matters + assertTrue(predicate.areEqual(base, differentExpiryTime)); + assertFalse(predicate.areEqual(base, permanent)); + assertFalse(predicate.areEqual(base, differentValue)); + assertFalse(predicate.areEqual(base, differentContext)); + } + + @Test + public void testIgnoreExpiryTimeAndValue() { + Instant expiryA = Instant.now().plusSeconds(60).truncatedTo(ChronoUnit.SECONDS); + Instant expiryB = Instant.now().plusSeconds(120).truncatedTo(ChronoUnit.SECONDS); + + Node base = node("hello.world", true, expiryA, "server", "one"); + Node differentValue = node("hello.world", false, expiryA, "server", "one"); + Node differentExpiryTime = node("hello.world", true, expiryB, "server", "one"); + Node permanent = node("hello.world", true, null, "server", "one"); + Node differentContext = node("hello.world", true, expiryA, "server", "two"); + + NodeEqualityPredicate predicate = NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE; + // value and exact expiry time are ignored, but whether it has an expiry still matters + assertTrue(predicate.areEqual(base, differentValue)); + assertTrue(predicate.areEqual(base, differentExpiryTime)); + assertFalse(predicate.areEqual(base, permanent)); + assertFalse(predicate.areEqual(base, differentContext)); + } + + @Test + public void testIgnoreValueOrIfTemporary() { + Instant expiry = Instant.now().plusSeconds(60).truncatedTo(ChronoUnit.SECONDS); + + Node base = node("hello.world", true, expiry, "server", "one"); + Node differentValue = node("hello.world", false, expiry, "server", "one"); + Node permanent = node("hello.world", true, null, "server", "one"); + Node differentContext = node("hello.world", true, expiry, "server", "two"); + Node differentKey = node("hello.other", true, expiry, "server", "one"); + + NodeEqualityPredicate predicate = NodeEqualityPredicate.IGNORE_VALUE_OR_IF_TEMPORARY; + // value and expiry (whether temporary or not) are entirely ignored + assertTrue(predicate.areEqual(base, differentValue)); + assertTrue(predicate.areEqual(base, permanent)); + assertFalse(predicate.areEqual(base, differentContext)); + assertFalse(predicate.areEqual(base, differentKey)); + } + + @Test + public void testOnlyKey() { + Node base = node("hello.world", true, null, "server", "one"); + Node differentValue = node("hello.world", false, null, "server", "two"); + Node differentKey = node("hello.other", true, null, "server", "one"); + + NodeEqualityPredicate predicate = NodeEqualityPredicate.ONLY_KEY; + assertTrue(predicate.areEqual(base, differentValue)); + assertFalse(predicate.areEqual(base, differentKey)); + } + + private static Stream testSameInstanceAlwaysEqual() { + return Stream.of( + Arguments.of(NodeEqualityPredicate.EXACT), + Arguments.of(NodeEqualityPredicate.ONLY_KEY), + Arguments.of(NodeEqualityPredicate.IGNORE_VALUE), + Arguments.of(NodeEqualityPredicate.IGNORE_EXPIRY_TIME), + Arguments.of(NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE), + Arguments.of(NodeEqualityPredicate.IGNORE_VALUE_OR_IF_TEMPORARY) + ); + } + + @ParameterizedTest + @MethodSource + public void testSameInstanceAlwaysEqual(NodeEqualityPredicate predicate) { + Instant expiry = Instant.now().plusSeconds(60).truncatedTo(ChronoUnit.SECONDS); + Node node = node("hello.world", true, expiry, "server", "one"); + + assertTrue(predicate.areEqual(node, node)); + } + + @ParameterizedTest + @EnumSource + public void testComparesContexts(NodeEquality nodeEquality) { + if (nodeEquality.name().contains("CONTEXTS")) { + assertTrue(nodeEquality.comparesContexts()); + } else { + assertFalse(nodeEquality.comparesContexts()); + } + } + + private static Stream testMappingToNodeEquality() { + return Stream.of( + Arguments.of(NodeEqualityPredicate.EXACT, NodeEquality.KEY_VALUE_EXPIRY_CONTEXTS), + Arguments.of(NodeEqualityPredicate.IGNORE_VALUE, NodeEquality.KEY_EXPIRY_CONTEXTS), + Arguments.of(NodeEqualityPredicate.IGNORE_EXPIRY_TIME, NodeEquality.KEY_VALUE_HASEXPIRY_CONTEXTS), + Arguments.of(NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE, NodeEquality.KEY_HASEXPIRY_CONTEXTS), + Arguments.of(NodeEqualityPredicate.IGNORE_VALUE_OR_IF_TEMPORARY, NodeEquality.KEY_CONTEXTS), + Arguments.of(NodeEqualityPredicate.ONLY_KEY, NodeEquality.KEY) + ); + } + + @ParameterizedTest + @MethodSource + public void testMappingToNodeEquality(NodeEqualityPredicate predicate, NodeEquality expected) { + assertEquals(expected, NodeEquality.of(predicate)); + } + + @Test + public void testMappingToNodeEqualityNull() { + assertNull(NodeEquality.of((o1, o2) -> true)); + } + + @Test + public void testComparesContextsHelper() { + assertTrue(NodeEquality.comparesContexts(NodeEqualityPredicate.EXACT)); + assertFalse(NodeEquality.comparesContexts(NodeEqualityPredicate.ONLY_KEY)); + // an unrecognised predicate maps to null, and should be reported as not comparing contexts + assertFalse(NodeEquality.comparesContexts((o1, o2) -> true)); + } + +} diff --git a/common/src/test/java/me/lucko/luckperms/common/node/NodeMatcherTest.java b/common/src/test/java/me/lucko/luckperms/common/node/NodeMatcherTest.java index 51c27eb18..0db4e39af 100644 --- a/common/src/test/java/me/lucko/luckperms/common/node/NodeMatcherTest.java +++ b/common/src/test/java/me/lucko/luckperms/common/node/NodeMatcherTest.java @@ -29,9 +29,15 @@ import me.lucko.luckperms.common.filter.Comparison; import me.lucko.luckperms.common.filter.Constraint; import me.lucko.luckperms.common.node.matcher.ConstraintNodeMatcher; import me.lucko.luckperms.common.node.matcher.StandardNodeMatchers; +import me.lucko.luckperms.common.node.types.Inheritance; +import me.lucko.luckperms.common.node.types.Meta; import me.lucko.luckperms.common.node.types.Permission; +import me.lucko.luckperms.common.node.types.Prefix; +import me.lucko.luckperms.common.node.types.Weight; import net.luckperms.api.node.Node; +import net.luckperms.api.node.NodeEqualityPredicate; import net.luckperms.api.node.NodeType; +import net.luckperms.api.node.types.InheritanceNode; import net.luckperms.api.node.types.MetaNode; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -42,6 +48,10 @@ import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; public class NodeMatcherTest { @@ -108,4 +118,152 @@ public class NodeMatcherTest { } + @ParameterizedTest + @CsvSource({ + "foo, true", + "bar, false", + "FOO, true", // case-insensitive + }) + public void testKeyMatch(String permission, boolean expectedMatch) { + ConstraintNodeMatcher matcher = StandardNodeMatchers.key("foo"); + Node node = Permission.builder().permission(permission).build(); + + assertEquals(expectedMatch, matcher.test(node)); + if (expectedMatch) { + assertSame(node, matcher.match(node)); + } else { + assertNull(matcher.match(node)); + } + } + + @ParameterizedTest + @CsvSource({ + "foo.bar, true", + "foo.baz, true", + "foo, false", + "bar.foo, false", + }) + public void testKeyStartsWithMatch(String permission, boolean expectedMatch) { + ConstraintNodeMatcher matcher = StandardNodeMatchers.keyStartsWith("foo."); + Node node = Permission.builder().permission(permission).build(); + assertEquals(expectedMatch, matcher.test(node)); + } + + private static Stream testNodeEqualsMatch() { + return Stream.of( + // same key & value -> matches + Arguments.of( + Permission.builder().permission("foo").value(true).build(), + Permission.builder().permission("foo").value(true).build(), + NodeEqualityPredicate.EXACT, + true + ), + // different value, EXACT equality -> doesn't match + Arguments.of( + Permission.builder().permission("foo").value(true).build(), + Permission.builder().permission("foo").value(false).build(), + NodeEqualityPredicate.EXACT, + false + ), + // different value, but IGNORE_VALUE equality -> matches + Arguments.of( + Permission.builder().permission("foo").value(true).build(), + Permission.builder().permission("foo").value(false).build(), + NodeEqualityPredicate.IGNORE_VALUE, + true + ), + // different key -> never matches, regardless of equality predicate + Arguments.of( + Permission.builder().permission("foo").build(), + Permission.builder().permission("bar").build(), + NodeEqualityPredicate.IGNORE_VALUE, + false + ), + // ONLY_KEY equality -> value/context/expiry differences are ignored + Arguments.of( + Permission.builder().permission("foo").value(true).withContext("server", "foo").build(), + Permission.builder().permission("foo").value(false).build(), + NodeEqualityPredicate.ONLY_KEY, + true + ) + ); + } + + @ParameterizedTest + @MethodSource + public void testNodeEqualsMatch(Node matcherNode, Node candidateNode, NodeEqualityPredicate equalityPredicate, boolean expectedMatch) { + ConstraintNodeMatcher matcher = StandardNodeMatchers.equals(matcherNode, equalityPredicate); + + assertEquals(expectedMatch, matcher.test(candidateNode)); + assertEquals(expectedMatch, matcher.match(candidateNode) != null); + } + + @Test + public void testNodeEqualsMatchFailsConstraintBeforeReachingFilter() { + // the key comparison constraint is checked before filterConstraintMatch is invoked + // if the keys don't match, filterConstraintMatch should never even be considered + ConstraintNodeMatcher matcher = StandardNodeMatchers.equals( + Permission.builder().permission("foo").build(), + (o1, o2) -> { + throw new RuntimeException("should never be called"); + } + ); + + Node differentKeyNode = Permission.builder().permission("bar").build(); + assertNull(matcher.match(differentKeyNode)); + assertFalse(matcher.test(differentKeyNode)); + } + + @ParameterizedTest + @CsvSource({ + "foo, true", + "bar, false", + }) + public void testMetaKeyMatch(String metaKey, boolean expectedMatch) { + ConstraintNodeMatcher matcher = StandardNodeMatchers.metaKey("foo"); + Node node = Meta.builder(metaKey, "100").build(); + + assertEquals(expectedMatch, matcher.test(node)); + + MetaNode result = matcher.match(node); + if (expectedMatch) { + assertNotNull(result); + assertSame(node, result); + assertEquals(metaKey, result.getMetaKey()); + } else { + assertNull(result); + } + } + + private static Stream testTypeMatch() { + return Stream.of( + Arguments.of(NodeType.INHERITANCE, Inheritance.builder("admin").build(), true), + Arguments.of(NodeType.INHERITANCE, Permission.builder().permission("foo").build(), false), + Arguments.of(NodeType.META, Meta.builder("foo", "bar").build(), true), + Arguments.of(NodeType.META, Prefix.builder("foo", 100).build(), false), + Arguments.of(NodeType.PREFIX, Prefix.builder("foo", 100).build(), true), + Arguments.of(NodeType.PREFIX, Meta.builder("foo", "bar").build(), false), + Arguments.of(NodeType.WEIGHT, Weight.builder(100).build(), true), + Arguments.of(NodeType.WEIGHT, Permission.builder().permission("some.permission").build(), false) + ); + } + + @ParameterizedTest + @MethodSource + public void testTypeMatch(NodeType type, Node node, boolean expectedMatch) { + ConstraintNodeMatcher matcher = StandardNodeMatchers.type(type); + + assertEquals(expectedMatch, matcher.test(node)); + assertEquals(expectedMatch, matcher.match(node) != null); + } + + @Test + public void testTypeMatchCastsToRequestedType() { + ConstraintNodeMatcher matcher = StandardNodeMatchers.type(NodeType.INHERITANCE); + Node node = Inheritance.builder("admin").build(); + + InheritanceNode result = matcher.match(node); + assertNotNull(result); + assertSame(node, result); + } } diff --git a/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/calculated/CalculatedSubjectData.java b/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/calculated/CalculatedSubjectData.java index 20d0a31ae..c15f77e51 100644 --- a/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/calculated/CalculatedSubjectData.java +++ b/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/calculated/CalculatedSubjectData.java @@ -142,7 +142,7 @@ public class CalculatedSubjectData implements LPSubjectData { public Map resolvePermissions(QueryOptions filter) { // get relevant entries - SortedMap> sorted = new TreeMap<>(ContextSetComparator.reverse()); + SortedMap> sorted = new TreeMap<>(ContextSetComparator.descending()); for (Map.Entry> entry : this.permissions.entrySet()) { if (!filter.satisfies(entry.getKey(), defaultSatisfyMode())) { continue; @@ -231,7 +231,7 @@ public class CalculatedSubjectData implements LPSubjectData { public Set resolveParents(QueryOptions filter) { // get relevant entries - SortedMap> sorted = new TreeMap<>(ContextSetComparator.reverse()); + SortedMap> sorted = new TreeMap<>(ContextSetComparator.descending()); for (Map.Entry> entry : this.parents.entrySet()) { if (!filter.satisfies(entry.getKey(), defaultSatisfyMode())) { continue; @@ -307,7 +307,7 @@ public class CalculatedSubjectData implements LPSubjectData { public Map resolveOptions(QueryOptions filter) { // get relevant entries - SortedMap> sorted = new TreeMap<>(ContextSetComparator.reverse()); + SortedMap> sorted = new TreeMap<>(ContextSetComparator.descending()); for (Map.Entry> entry : this.options.entrySet()) { if (!filter.satisfies(entry.getKey(), defaultSatisfyMode())) { continue; diff --git a/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/persisted/SubjectDataContainer.java b/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/persisted/SubjectDataContainer.java index 4b402dcf1..360ef4975 100644 --- a/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/persisted/SubjectDataContainer.java +++ b/sponge/src/main/java/me/lucko/luckperms/sponge/service/model/persisted/SubjectDataContainer.java @@ -281,7 +281,7 @@ public class SubjectDataContainer { private static List> sortContextMap(Map map) { List> entries = new ArrayList<>(map.entrySet()); - entries.sort((o1, o2) -> ContextSetComparator.reverse().compare(o1.getKey(), o2.getKey())); + entries.sort((o1, o2) -> ContextSetComparator.descending().compare(o1.getKey(), o2.getKey())); return entries; }