Add some more unit tests

This commit is contained in:
Luck committed 2026-07-17 21:49:30 +01:00
1 parent cd61d05b53
commit f19f605650
24 files changed
+1301 -85

No files matched your search

@@ -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());
}
}
}
@@ -115,6 +115,6 @@ public class ParentInfo extends GenericChildCommand {
}
// fallback to priority
return NodeWithContextComparator.reverse().compare(o1, o2);
return NodeWithContextComparator.descending().compare(o1, o2);
};
}
@@ -115,6 +115,6 @@ public class PermissionInfo extends GenericChildCommand {
}
// fallback to priority
return NodeWithContextComparator.reverse().compare(o1, o2);
return NodeWithContextComparator.descending().compare(o1, o2);
};
}
@@ -118,7 +118,7 @@ public class GroupListMembers extends ChildCommand<Group> {
private static <T extends Comparable<T>> void sendResult(Sender sender, List<NodeEntry<T, InheritanceNode>> results, Function<T, String> lookupFunction, Message.Args3<Integer, Integer, Integer> headerMessage, HolderType holderType, String label, int page) {
results = new ArrayList<>(results);
results.sort(NodeEntryComparator.normal());
results.sort(NodeEntryComparator.ascending());
int pageIndex = page - 1;
List<List<NodeEntry<T, InheritanceNode>>> pages = Iterators.divideIterable(results, 15);
@@ -98,7 +98,7 @@ public class SearchCommand extends SingleCommand {
private static <T extends Comparable<T>> void sendResult(Sender sender, List<NodeEntry<T, Node>> results, Function<T, String> lookupFunction, Message.Args3<Integer, Integer, Integer> 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<List<NodeEntry<T, Node>>> pages = Iterators.divideIterable(results, 15);
@@ -32,7 +32,6 @@ import java.util.Comparator;
public class ContextComparator implements Comparator<Context> {
public static final ContextComparator INSTANCE = new ContextComparator(false);
public static final ContextComparator ONLY_KEY = new ContextComparator(true);
private final boolean onlyKeys;
@@ -34,16 +34,15 @@ import java.util.Arrays;
import java.util.Comparator;
public class ContextSetComparator implements Comparator<ImmutableContextSet> {
private static final Comparator<ImmutableContextSet> ASCENDING = new ContextSetComparator();
private static final Comparator<ImmutableContextSet> DESCENDING = ASCENDING.reversed();
private static final Comparator<ImmutableContextSet> INSTANCE = new ContextSetComparator();
private static final Comparator<ImmutableContextSet> REVERSE = INSTANCE.reversed();
public static Comparator<ImmutableContextSet> normal() {
return INSTANCE;
public static Comparator<ImmutableContextSet> ascending() {
return ASCENDING;
}
public static Comparator<ImmutableContextSet> reverse() {
return REVERSE;
public static Comparator<ImmutableContextSet> descending() {
return DESCENDING;
}
@Override
@@ -258,7 +258,7 @@ public abstract class PermissionHolder {
}
public SortedSet<Node> getOwnNodesSorted(QueryOptions queryOptions) {
SortedSet<Node> nodes = new TreeSet<>(NodeWithContextComparator.reverse());
SortedSet<Node> 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<Node> nodes = new TreeSet<>(NodeWithContextComparator.reverse());
SortedSet<Node> nodes = new TreeSet<>(NodeWithContextComparator.descending());
InheritanceGraph graph = this.plugin.getInheritanceGraphFactory().getGraph(queryOptions);
for (PermissionHolder holder : graph.traverse(this)) {
for (DataType dataType : holder.queryOrder(queryOptions)) {
@@ -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<String> before = ImmutableList.copyOf(this.groups);
@@ -70,7 +70,7 @@ public interface NodeMap {
}
default SortedSet<Node> asSortedSet() {
SortedSet<Node> set = new TreeSet<>(NodeWithContextComparator.reverse());
SortedSet<Node> set = new TreeSet<>(NodeWithContextComparator.descending());
copyTo(set);
return set;
}
@@ -96,7 +96,7 @@ public interface NodeMap {
}
default SortedSet<InheritanceNode> inheritanceAsSortedSet() {
SortedSet<InheritanceNode> set = new TreeSet<>(NodeWithContextComparator.reverse());
SortedSet<InheritanceNode> set = new TreeSet<>(NodeWithContextComparator.descending());
copyInheritanceNodesTo(set);
return set;
}
@@ -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<ImmutableContextSet, SortedSet<Node>> VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.reverse());
private static final Function<ImmutableContextSet, SortedSet<InheritanceNode>> INHERITANCE_VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.reverse());
private static final Function<ImmutableContextSet, SortedSet<Node>> VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.descending());
private static final Function<ImmutableContextSet, SortedSet<InheritanceNode>> INHERITANCE_VALUE_SET_SUPPLIER = k -> new ConcurrentSkipListSet<>(NodeComparator.descending());
// Creates the Map instances used by this.map and this.inheritanceMap
private static <N extends Node> SortedMap<ImmutableContextSet, SortedSet<N>> createMap() {
return new ConcurrentSkipListMap<>(ContextSetComparator.reverse());
return new ConcurrentSkipListMap<>(ContextSetComparator.descending());
}
/*
@@ -31,15 +31,15 @@ import net.luckperms.api.node.types.PermissionNode;
import java.util.Comparator;
public class NodeComparator implements Comparator<Node> {
private static final Comparator<? super Node> INSTANCE = new NodeComparator();
private static final Comparator<? super Node> REVERSE = INSTANCE.reversed();
private static final Comparator<? super Node> ASCENDING = new NodeComparator();
private static final Comparator<? super Node> DESCENDING = ASCENDING.reversed();
public static Comparator<? super Node> normal() {
return INSTANCE;
public static Comparator<? super Node> ascending() {
return ASCENDING;
}
public static Comparator<? super Node> reverse() {
return REVERSE;
public static Comparator<? super Node> descending() {
return DESCENDING;
}
@SuppressWarnings({"ConstantConditions", "OptionalGetWithoutIsPresent"})
@@ -49,13 +49,13 @@ public class NodeComparator implements Comparator<Node> {
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<Node> {
// 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;
}
@@ -31,17 +31,17 @@ import java.util.Comparator;
public class NodeEntryComparator<T extends Comparable<T>> implements Comparator<NodeEntry<T, ?>> {
public static <T extends Comparable<T>> Comparator<? super NodeEntry<T, ?>> normal() {
public static <T extends Comparable<T>> Comparator<? super NodeEntry<T, ?>> ascending() {
return new NodeEntryComparator<>();
}
public static <T extends Comparable<T>> Comparator<? super NodeEntry<T, ?>> reverse() {
return NodeEntryComparator.<T>normal().reversed();
public static <T extends Comparable<T>> Comparator<? super NodeEntry<T, ?>> descending() {
return NodeEntryComparator.<T>ascending().reversed();
}
@Override
public int compare(NodeEntry<T, ?> o1, NodeEntry<T, ?> o2) {
int i = NodeWithContextComparator.normal().compare(o1.getNode(), o2.getNode());
int i = NodeWithContextComparator.ascending().compare(o1.getNode(), o2.getNode());
if (i != 0) {
return i;
}
@@ -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<Node> {
private static final Comparator<? super Node> INSTANCE = new NodeWithContextComparator(ContextSetComparator.normal(), NodeComparator.normal());
private static final Comparator<? super Node> REVERSE = new NodeWithContextComparator(ContextSetComparator.reverse(), NodeComparator.reverse());
private static final Comparator<? super Node> ASCENDING = new NodeWithContextComparator(ContextSetComparator.ascending(), NodeComparator.ascending());
private static final Comparator<? super Node> DESCENDING = new NodeWithContextComparator(ContextSetComparator.descending(), NodeComparator.descending());
public static Comparator<? super Node> normal() {
return INSTANCE;
public static Comparator<? super Node> ascending() {
return ASCENDING;
}
public static Comparator<? super Node> reverse() {
return REVERSE;
public static Comparator<? super Node> descending() {
return DESCENDING;
}
private final Comparator<? super ImmutableContextSet> contextSetComparator;
@@ -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<T> {
* @param type the type of change
* @param values the changed values
*/
public void recordChanges(ChangeType type, Iterable<T> values) {
public void recordChanges(ChangeType type, Iterable<? extends T> 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<? extends T> values) {
values.forEach(value -> recordChange(new Change<>(type, value)));
}
/**
* Merges the recorded differences in {@code other} into this.
*
@@ -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<ImmutableContextSet> 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<ImmutableContextSet> INSTANCE = ContextSetComparator.normal();
private static final Comparator<ImmutableContextSet> 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<Arguments> testTransitivity() {
@@ -141,12 +146,30 @@ public class ContextSetComparatorTest {
list.add(a);
list.add(b);
list.add(c);
list.sort(INSTANCE);
list.sort(ASCENDING);
List<ImmutableContextSet> reversed = new ArrayList<>(list);
reversed.sort(INSTANCE.reversed());
reversed.sort(ASCENDING.reversed());
assertEquals(Lists.reverse(list), reversed);
}
@Test
public void testPriorityOrdering() {
List<ImmutableContextSet> 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<ImmutableContextSet> reversed = new ArrayList<>(list);
reversed.sort(ContextSetComparator.descending());
assertEquals(Lists.reverse(list), reversed);
}
}
@@ -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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> changes = new Difference<>();
changes.recordChange(Difference.ChangeType.REMOVE, existing);
changes.recordChange(Difference.ChangeType.ADD, incoming);
Difference<Node> 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());
}
}
@@ -0,0 +1,147 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* 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<Node> 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<Node> first = this.map.exportChanges(diff -> true);
assertFalse(first.isEmpty());
// the log should have been reset, so a second export is empty
Difference<Node> 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<Node> rejected = this.map.exportChanges(diff -> false);
assertNull(rejected);
Difference<Node> accepted = this.map.exportChanges(diff -> true);
assertFalse(accepted.isEmpty());
}
@Test
public void testDiscardChanges() {
this.map.add(makeNode("a"));
this.map.discardChanges();
Difference<Node> 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<Node> 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<Node> 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<Node> exported = this.map.exportChanges(diff -> true);
assertTrue(exported == null || exported.isEmpty());
}
}
@@ -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;
}
}
@@ -0,0 +1,230 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* 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}.
*
* <p>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
* <b>descending</b> comparator is used so that the highest priority node appears first when the
* collection is iterated.</p>
*
* <p>{@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.</p>
*/
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<Node> 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<Node> ascendingSorted = new ArrayList<>(nodes);
ascendingSorted.sort(NodeComparator.ascending());
List<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> 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<Node> ascendingSorted = new ArrayList<>(nodes);
ascendingSorted.sort(NodeWithContextComparator.ascending());
List<Node> 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<Node> 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<Node> 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<Node> 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);
}
}
}
@@ -0,0 +1,224 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <[email protected]>
* 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<Arguments> 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<Arguments> 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));
}
}
@@ -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<Node> 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<Node> matcher = StandardNodeMatchers.keyStartsWith("foo.");
Node node = Permission.builder().permission(permission).build();
assertEquals(expectedMatch, matcher.test(node));
}
private static Stream<Arguments> 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<Node> 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<Node> 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<MetaNode> 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<Arguments> 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<InheritanceNode> matcher = StandardNodeMatchers.type(NodeType.INHERITANCE);
Node node = Inheritance.builder("admin").build();
InheritanceNode result = matcher.match(node);
assertNotNull(result);
assertSame(node, result);
}
}
@@ -142,7 +142,7 @@ public class CalculatedSubjectData implements LPSubjectData {
public Map<String, Node> resolvePermissions(QueryOptions filter) {
// get relevant entries
SortedMap<ImmutableContextSet, Map<String, Node>> sorted = new TreeMap<>(ContextSetComparator.reverse());
SortedMap<ImmutableContextSet, Map<String, Node>> sorted = new TreeMap<>(ContextSetComparator.descending());
for (Map.Entry<ImmutableContextSet, Map<String, Boolean>> entry : this.permissions.entrySet()) {
if (!filter.satisfies(entry.getKey(), defaultSatisfyMode())) {
continue;
@@ -231,7 +231,7 @@ public class CalculatedSubjectData implements LPSubjectData {
public Set<LPSubjectReference> resolveParents(QueryOptions filter) {
// get relevant entries
SortedMap<ImmutableContextSet, Set<LPSubjectReference>> sorted = new TreeMap<>(ContextSetComparator.reverse());
SortedMap<ImmutableContextSet, Set<LPSubjectReference>> sorted = new TreeMap<>(ContextSetComparator.descending());
for (Map.Entry<ImmutableContextSet, Set<LPSubjectReference>> entry : this.parents.entrySet()) {
if (!filter.satisfies(entry.getKey(), defaultSatisfyMode())) {
continue;
@@ -307,7 +307,7 @@ public class CalculatedSubjectData implements LPSubjectData {
public Map<String, MetaNode> resolveOptions(QueryOptions filter) {
// get relevant entries
SortedMap<ImmutableContextSet, Map<String, MetaNode>> sorted = new TreeMap<>(ContextSetComparator.reverse());
SortedMap<ImmutableContextSet, Map<String, MetaNode>> sorted = new TreeMap<>(ContextSetComparator.descending());
for (Map.Entry<ImmutableContextSet, Map<String, String>> entry : this.options.entrySet()) {
if (!filter.satisfies(entry.getKey(), defaultSatisfyMode())) {
continue;
@@ -281,7 +281,7 @@ public class SubjectDataContainer {
private static <T> List<Map.Entry<ImmutableContextSet, T>> sortContextMap(Map<ImmutableContextSet, T> map) {
List<Map.Entry<ImmutableContextSet, T>> 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;
}