Add more unit/integration tests

This commit is contained in:
Luck committed 2023-06-25 22:25:42 +01:00
1 parent 77a5a7b41f
commit 9f4082ca0b
29 files changed
+523 -191

No files matched your search

@@ -86,6 +86,17 @@ public abstract class BufferedRequest<T> {
}
}
/**
* Gets if the request buffer has been enqueued
*
* @return if the buffer is enqueued
*/
public boolean isEnqueued() {
synchronized (this.mutex) {
return this.processor != null;
}
}
/**
* Requests the value, bypassing the buffer
*
@@ -84,7 +84,7 @@ public class HolderEditor<T extends PermissionHolder> extends ChildCommand<T> {
Message.EDITOR_START.send(sender);
WebEditorSession.createAndOpen(holders, Collections.emptyList(), sender, label, plugin);
WebEditorSession.create(holders, Collections.emptyList(), sender, label, plugin).open();
}
}
@@ -107,7 +107,7 @@ public class EditorCommand extends SingleCommand {
Message.EDITOR_START.send(sender);
WebEditorSession.createAndOpen(holders, tracks, sender, label, plugin);
WebEditorSession.create(holders, tracks, sender, label, plugin).open();
}
private enum Type {
@@ -97,7 +97,7 @@ public class TrackEditor extends ChildCommand<Track> {
Message.EDITOR_START.send(sender);
WebEditorSession.createAndOpen(holders, Collections.singletonList(target), sender, label, plugin);
WebEditorSession.create(holders, Collections.singletonList(target), sender, label, plugin).open();
}
}
@@ -725,6 +725,11 @@ public final class ConfigKeys {
*/
public static final ConfigKey<String> BYTESOCKS_HOST = stringKey("bytesocks-host", "usersockets.luckperms.net");
/**
* If TLS (https/wss) should be used when connecting to bytesocks
*/
public static final ConfigKey<Boolean> BYTESOCKS_USE_TLS = booleanKey("bytesocks-use-tls", true);
/**
* The URL of the web editor
*/
@@ -49,11 +49,11 @@ public class BytesocksClient extends AbstractHttpClient {
* @param host the bytesocks host
* @param userAgent the client user agent string
*/
public BytesocksClient(OkHttpClient okHttpClient, String host, String userAgent) {
public BytesocksClient(OkHttpClient okHttpClient, String host, boolean tls, String userAgent) {
super(okHttpClient);
this.httpUrl = "https://" + host + "/";
this.wsUrl = "wss://" + host + "/";
this.httpUrl = (tls ? "https://" : "http://") + host + "/";
this.wsUrl = (tls ? "wss://" : "ws://") + host + "/";
this.userAgent = userAgent;
}
@@ -148,8 +148,17 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
.callTimeout(15, TimeUnit.SECONDS)
.build();
this.bytebin = new BytebinClient(this.httpClient, getConfiguration().get(ConfigKeys.BYTEBIN_URL), "luckperms");
this.bytesocks = new BytesocksClient(this.httpClient, getConfiguration().get(ConfigKeys.BYTESOCKS_HOST), "luckperms/editor");
this.bytebin = new BytebinClient(
this.httpClient,
getConfiguration().get(ConfigKeys.BYTEBIN_URL),
"luckperms"
);
this.bytesocks = new BytesocksClient(
this.httpClient,
getConfiguration().get(ConfigKeys.BYTESOCKS_HOST),
getConfiguration().get(ConfigKeys.BYTESOCKS_USE_TLS),
"luckperms/editor"
);
this.webEditorStore = new WebEditorStore(this);
// init translation repo and update bundle files
@@ -451,6 +460,10 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
return this.configuration;
}
public OkHttpClient getHttpClient() {
return this.httpClient;
}
@Override
public BytebinClient getBytebin() {
return this.bytebin;
@@ -131,6 +131,11 @@ public class FileActionLogger {
}
public Log getLog() throws IOException {
// if there is log content waiting to be written, flush immediately before trying to read
if (this.saveBuffer.isEnqueued()) {
this.saveBuffer.requestDirectly();
}
if (!Files.exists(this.contentFile)) {
return Log.empty();
}
@@ -54,6 +54,11 @@ public final class NodeEntry<H extends Comparable<H>, N extends Node> implements
return this.node;
}
@Override
public String toString() {
return "NodeEntry(holder=" + this.holder + ", node=" + this.node + ')';
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
@@ -56,10 +56,9 @@ import java.util.stream.Collectors;
*/
public class WebEditorSession {
public static void createAndOpen(List<PermissionHolder> holders, List<Track> tracks, Sender sender, String cmdLabel, LuckPermsPlugin plugin) {
public static WebEditorSession create(List<PermissionHolder> holders, List<Track> tracks, Sender sender, String cmdLabel, LuckPermsPlugin plugin) {
WebEditorRequest initialRequest = WebEditorRequest.generate(holders, tracks, sender, cmdLabel, plugin);
WebEditorSession session = new WebEditorSession(initialRequest, plugin, sender, cmdLabel);
session.open();
return new WebEditorSession(initialRequest, plugin, sender, cmdLabel);
}
private WebEditorRequest initialRequest;
@@ -83,9 +82,9 @@ public class WebEditorSession {
this.tracks = new LinkedHashSet<>(initialRequest.getTracks().keySet());
}
public void open() {
public String open() {
createSocket();
createInitialSession();
return createInitialSession();
}
private void createSocket() {
@@ -117,7 +116,7 @@ public class WebEditorSession {
return false;
}
private void createInitialSession() {
private String createInitialSession() {
Objects.requireNonNull(this.initialRequest);
WebEditorRequest request = this.initialRequest;
@@ -129,7 +128,7 @@ public class WebEditorSession {
String id = uploadRequestData(request);
if (id == null) {
return;
return null;
}
// form a url for the editor
@@ -140,6 +139,12 @@ public class WebEditorSession {
if (this.socket != null) {
this.socket.scheduleCleanupIfUnused();
}
return id;
}
public WebEditorSocket getSocket() {
return this.socket;
}
public void includeCreatedGroup(Group group) {
@@ -76,9 +76,6 @@ public class WebEditorStore {
}
public KeyPair keyPair() {
if (!this.keyPair.get().isDone()) {
throw new IllegalStateException("Web editor keypair has not been generated yet! Has the server just started?");
}
return this.keyPair.get().join();
}
@@ -0,0 +1,105 @@
/*
* 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.command.utils;
import com.google.common.collect.ImmutableList;
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
import net.luckperms.api.context.ContextSet;
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.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class ArgumentListTest {
@Test
public void testGetString() {
ArgumentList list = new ArgumentList(ImmutableList.of("hello", "world{SPACE}"));
assertEquals("hello", list.getOrDefault(0, "def"));
assertEquals("world ", list.getOrDefault(1, "def"));
assertEquals("def", list.getOrDefault(2, "def"));
assertEquals("def", list.getOrDefault(-1, "def"));
assertNull(list.getOrDefault(2, null));
assertNull(list.getOrDefault(-1, null));
}
@Test
public void testGetInt() {
ArgumentList list = new ArgumentList(ImmutableList.of("5", "-50"));
assertEquals(5, list.getIntOrDefault(0, -1));
assertEquals(-50, list.getIntOrDefault(1, -1));
assertEquals(-1, list.getIntOrDefault(2, -1));
assertEquals(-1, list.getIntOrDefault(-1, -1));
}
private static Stream<Arguments> testParseContext() {
return Stream.of(
Arguments.of(new String[]{}, ImmutableContextSetImpl.EMPTY),
Arguments.of(new String[]{"test"}, ImmutableContextSetImpl.of("server", "test")),
Arguments.of(
new String[]{"a", "b", "c"},
new ImmutableContextSetImpl.BuilderImpl()
.add("server", "a")
.add("world", "b")
.add("server", "c")
.build()
),
Arguments.of(
new String[]{"a", "thing=b", "c"},
new ImmutableContextSetImpl.BuilderImpl()
.add("server", "a")
.add("thing", "b")
.add("server", "c")
.build()
),
Arguments.of(
new String[]{"thing=a", "thing=b", "c"},
new ImmutableContextSetImpl.BuilderImpl()
.add("thing", "a")
.add("thing", "b")
.add("server", "c")
.build()
),
Arguments.of(new String[]{"="}, ImmutableContextSetImpl.EMPTY)
);
}
@ParameterizedTest
@MethodSource
public void testParseContext(String[] arguments, ContextSet expected) {
ArgumentList list = new ArgumentList(ImmutableList.copyOf(arguments));
assertEquals(expected, list.getContextOrEmpty(0));
}
}
@@ -0,0 +1,92 @@
/*
* 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.command.utils;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArgumentTokenizerTest {
private static Stream<Arguments> testBasicTokenize() {
return Stream.of(
Arguments.of("", new String[]{}),
Arguments.of("hello world", new String[]{"hello", "world"}),
Arguments.of("hello world", new String[]{"hello", "", "world"}),
Arguments.of("hello world", new String[]{"hello", "", "", "world"}),
Arguments.of("\"hello world\"", new String[]{"hello world"}),
Arguments.of("\"hello world\"", new String[]{"hello world"}),
Arguments.of("\" hello world\"", new String[]{" hello world"}),
Arguments.of("\"hello world \"", new String[]{"hello world "}),
Arguments.of("\"hello\"\"world\"", new String[]{"hello", "world"}),
Arguments.of("\"hello\" \"world\"", new String[]{"hello", "world"})
);
}
@ParameterizedTest
@MethodSource
public void testBasicTokenize(String input, String[] expectedTokens) {
for (ArgumentTokenizer tokenizer : ArgumentTokenizer.values()) {
List<String> tokens = tokenizer.tokenizeInput(input);
assertEquals(ImmutableList.copyOf(expectedTokens), ImmutableList.copyOf(tokens), "tokenizer " + tokenizer + " produced tokens " + tokens);
}
}
private static Stream<Arguments> testExecuteTokenize() {
return Stream.of(
Arguments.of("hello world ", new String[]{"hello", "world"}),
Arguments.of("hello world ", new String[]{"hello", "world", ""})
);
}
@ParameterizedTest
@MethodSource
public void testExecuteTokenize(String input, String[] expectedTokens) {
List<String> tokens = ArgumentTokenizer.EXECUTE.tokenizeInput(input);
assertEquals(ImmutableList.copyOf(expectedTokens), ImmutableList.copyOf(tokens));
}
private static Stream<Arguments> testTabCompleteTokenize() {
return Stream.of(
Arguments.of("hello world ", new String[]{"hello", "world", ""}),
Arguments.of("hello world ", new String[]{"hello", "world", "", ""})
);
}
@ParameterizedTest
@MethodSource
public void testTabCompleteTokenize(String input, String[] expectedTokens) {
List<String> tokens = ArgumentTokenizer.TAB_COMPLETE.tokenizeInput(input);
assertEquals(ImmutableList.copyOf(expectedTokens), ImmutableList.copyOf(tokens));
}
}
+2 -1
View File
@@ -23,7 +23,7 @@ dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.1'
testImplementation "org.testcontainers:junit-jupiter:1.17.6"
testImplementation "org.testcontainers:junit-jupiter:1.18.3"
testImplementation 'org.mockito:mockito-core:4.11.0'
testImplementation 'org.mockito:mockito-junit-jupiter:4.11.0'
testImplementation 'org.awaitility:awaitility:4.2.0'
@@ -34,6 +34,7 @@ dependencies {
testImplementation 'com.rabbitmq:amqp-client:5.12.0'
testImplementation 'org.postgresql:postgresql:42.6.0'
testImplementation 'com.h2database:h2:2.1.214'
testImplementation 'org.xerial:sqlite-jdbc:3.42.0.0'
testImplementation 'mysql:mysql-connector-java:8.0.23'
testImplementation 'org.mariadb.jdbc:mariadb-java-client:3.1.3'
testImplementation 'org.mongodb:mongodb-driver-legacy:4.5.0'
@@ -25,22 +25,31 @@
package me.lucko.luckperms.standalone;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.model.Group;
import me.lucko.luckperms.common.model.Track;
import me.lucko.luckperms.common.model.User;
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.storage.misc.NodeEntry;
import me.lucko.luckperms.standalone.app.LuckPermsApplication;
import me.lucko.luckperms.standalone.app.integration.HealthReporter;
import me.lucko.luckperms.standalone.utils.TestPluginBootstrap;
import me.lucko.luckperms.standalone.utils.TestPluginBootstrap.TestPlugin;
import me.lucko.luckperms.standalone.utils.TestPluginProvider;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.event.cause.CreationCause;
import net.luckperms.api.model.data.DataType;
import net.luckperms.api.node.Node;
import net.luckperms.api.node.NodeType;
import net.luckperms.api.node.types.PrefixNode;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@@ -59,6 +68,7 @@ import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -121,10 +131,14 @@ public class StorageIntegrationTest {
group.setNode(DataType.NORMAL, TEST_META, true);
plugin.getStorage().saveGroup(group).join();
// try to create / save a track
Track track = plugin.getStorage().createAndLoadTrack("example", CreationCause.INTERNAL).join();
track.setGroups(ImmutableList.of("default", "test"));
plugin.getStorage().saveTrack(track);
// try to create / save a user
UUID exampleUniqueId = UUID.fromString("c1d60c50-70b5-4722-8057-87767557e50d");
String exampleUsername = "Luck";
plugin.getStorage().savePlayerData(exampleUniqueId, exampleUsername).join();
User user = plugin.getStorage().loadUser(exampleUniqueId, exampleUsername).join();
user.setNode(DataType.NORMAL, TEST_PERMISSION_1, true);
@@ -134,7 +148,19 @@ public class StorageIntegrationTest {
user.setNode(DataType.NORMAL, TEST_META, true);
plugin.getStorage().saveUser(user).join();
plugin.getStorage().loadAllGroups().join();
// add something to the action log
LoggedAction exampleLogEntry = LoggedAction.build()
.source(UUID.randomUUID())
.sourceName("Test Source")
.targetType(Action.Target.Type.USER)
.target(UUID.randomUUID())
.targetName("Test Target")
.description("hello 123 hello 123")
.build();
plugin.getStorage().logAction(exampleLogEntry).join();
// read back the data we just saved to ensure it is as expected
plugin.getSyncTaskBuffer().requestDirectly();
Group testGroup = plugin.getGroupManager().getIfLoaded("test");
assertNotNull(testGroup);
@@ -145,8 +171,27 @@ public class StorageIntegrationTest {
assertEquals(ImmutableSet.of(Inheritance.builder("default").build(), TEST_PERMISSION_1, TEST_PERMISSION_2, TEST_GROUP, TEST_PREFIX, TEST_META), testUser.normalData().asSet());
assertTrue(exampleUsername.equalsIgnoreCase(testUser.getUsername().orElse("unknown")));
Track testTrack = plugin.getTrackManager().getIfLoaded("example");
assertNotNull(testTrack);
assertEquals(ImmutableList.of("default", "test"), track.getGroups());
// create another user
Log actionLog = plugin.getStorage().getLog().join();
assertTrue(actionLog.getContent().contains(exampleLogEntry));
List<NodeEntry<String, Node>> groupSearchResult = plugin.getStorage().searchGroupNodes(StandardNodeMatchers.key(TEST_PERMISSION_1)).join();
assertEquals(1, groupSearchResult.size());
assertTrue(groupSearchResult.contains(NodeEntry.of("test", TEST_PERMISSION_1)));
List<NodeEntry<UUID, Node>> userSearchResult = plugin.getStorage().searchUserNodes(StandardNodeMatchers.key(TEST_PERMISSION_1)).join();
assertEquals(1, userSearchResult.size());
assertTrue(userSearchResult.contains(NodeEntry.of(exampleUniqueId, TEST_PERMISSION_1)));
List<NodeEntry<UUID, PrefixNode>> userWildcardSearchResult = plugin.getStorage().searchUserNodes(StandardNodeMatchers.type(NodeType.PREFIX)).join();
assertEquals(1, userWildcardSearchResult.size());
assertTrue(userWildcardSearchResult.contains(NodeEntry.of(exampleUniqueId, TEST_PREFIX)));
// create another user and test getUniqueUsers method
UUID otherExampleUniqueId = UUID.fromString("069a79f4-44e9-4726-a5be-fca90e38aaf5");
String otherExampleUsername = "Notch";
@@ -289,6 +334,21 @@ public class StorageIntegrationTest {
}
}
@Nested
class FlatFileDatabase {
@Test
public void testH2(@TempDir Path tempDir) {
TestPluginProvider.use(tempDir, ImmutableMap.of("storage-method", "h2"), StorageIntegrationTest::testStorage);
}
@Test
public void testSqlite(@TempDir Path tempDir) {
TestPluginProvider.use(tempDir, ImmutableMap.of("storage-method", "sqlite"), StorageIntegrationTest::testStorage);
}
}
@Nested
class FlatFile {
@@ -299,6 +359,7 @@ public class StorageIntegrationTest {
Path storageDir = tempDir.resolve("yaml-storage");
compareFiles(storageDir, "example/yaml", "groups/default.yml");
compareFiles(storageDir, "example/yaml", "groups/test.yml");
compareFiles(storageDir, "example/yaml", "tracks/example.yml");
compareFiles(storageDir, "example/yaml", "users/c1d60c50-70b5-4722-8057-87767557e50d.yml");
}
@@ -309,6 +370,7 @@ public class StorageIntegrationTest {
Path storageDir = tempDir.resolve("json-storage");
compareFiles(storageDir, "example/json", "groups/default.json");
compareFiles(storageDir, "example/json", "groups/test.json");
compareFiles(storageDir, "example/json", "tracks/example.json");
compareFiles(storageDir, "example/json", "users/c1d60c50-70b5-4722-8057-87767557e50d.json");
}
@@ -319,17 +381,13 @@ public class StorageIntegrationTest {
Path storageDir = tempDir.resolve("hocon-storage");
compareFiles(storageDir, "example/hocon", "groups/default.conf");
compareFiles(storageDir, "example/hocon", "groups/test.conf");
compareFiles(storageDir, "example/hocon", "tracks/example.conf");
compareFiles(storageDir, "example/hocon", "users/c1d60c50-70b5-4722-8057-87767557e50d.conf");
}
@Test
public void testToml(@TempDir Path tempDir) throws IOException {
TestPluginProvider.use(tempDir, ImmutableMap.of("storage-method", "toml"), StorageIntegrationTest::testStorage);
Path storageDir = tempDir.resolve("toml-storage");
compareFiles(storageDir, "example/toml", "groups/default.toml");
compareFiles(storageDir, "example/toml", "groups/test.toml");
compareFiles(storageDir, "example/toml", "users/c1d60c50-70b5-4722-8057-87767557e50d.toml");
}
@Test
@@ -365,11 +423,6 @@ public class StorageIntegrationTest {
@Test
public void testTomlCombined(@TempDir Path tempDir) throws IOException {
TestPluginProvider.use(tempDir, ImmutableMap.of("storage-method", "toml-combined"), StorageIntegrationTest::testStorage);
Path storageDir = tempDir.resolve("toml-storage");
compareFiles(storageDir, "example/toml-combined", "groups.toml");
compareFiles(storageDir, "example/toml-combined", "tracks.toml");
compareFiles(storageDir, "example/toml-combined", "users.toml");
}
private static void compareFiles(Path dir, String examplePath, String file) throws IOException {
@@ -0,0 +1,164 @@
/*
* 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.standalone;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonObject;
import me.lucko.luckperms.common.model.Group;
import me.lucko.luckperms.common.model.PermissionHolder;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.node.types.Permission;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.util.Predicates;
import me.lucko.luckperms.common.util.gson.GsonProvider;
import me.lucko.luckperms.common.webeditor.WebEditorRequest;
import me.lucko.luckperms.common.webeditor.WebEditorSession;
import me.lucko.luckperms.standalone.app.integration.SingletonPlayer;
import me.lucko.luckperms.standalone.utils.TestPluginProvider;
import net.luckperms.api.model.data.DataType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
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.assertTrue;
@Testcontainers(parallel = true)
@Tag("docker")
public class WebEditorIntegrationTest {
@Container
private final GenericContainer<?> bytebin = new GenericContainer<>(DockerImageName.parse("ghcr.io/lucko/bytebin"))
.withExposedPorts(8080);
@Container
private final GenericContainer<?> bytesocks = new GenericContainer<>(DockerImageName.parse("ghcr.io/lucko/bytesocks"))
.withExposedPorts(8080);
@Test
public void testWebEditor(@TempDir Path tempDir) throws Exception {
assertTrue(this.bytebin.isRunning());
assertTrue(this.bytesocks.isRunning());
String bytebinUrl = "http://" + this.bytebin.getHost() + ":" + this.bytebin.getFirstMappedPort() + "/";
String bytesocksHost = this.bytesocks.getHost() + ":" + this.bytesocks.getFirstMappedPort();
Map<String, String> config = ImmutableMap.<String, String>builder()
.put("bytebin-url", bytebinUrl)
.put("bytesocks-host", bytesocksHost)
.put("bytesocks-use-tls", "false")
.build();
TestPluginProvider.use(tempDir, config, (app, bootstrap, plugin) -> {
// setup some example data
UUID exampleUniqueId = UUID.fromString("c1d60c50-70b5-4722-8057-87767557e50d");
plugin.getStorage().savePlayerData(exampleUniqueId, "Luck").join();
User user = plugin.getStorage().loadUser(exampleUniqueId, null).join();
user.setNode(DataType.NORMAL, Permission.builder().permission("test.node").build(), false);
plugin.getStorage().saveUser(user).join();
Group group = plugin.getGroupManager().getOrMake("default");
group.setNode(DataType.NORMAL, Permission.builder().permission("other.test.node").build(), false);
plugin.getStorage().saveGroup(group).join();
// collect holders
List<PermissionHolder> holders = new ArrayList<>();
WebEditorRequest.includeMatchingGroups(holders, Predicates.alwaysTrue(), plugin);
WebEditorRequest.includeMatchingUsers(holders, Collections.emptyList(), true, plugin);
assertFalse(holders.isEmpty());
// create a new editor session
Sender sender = plugin.getSenderFactory().wrap(SingletonPlayer.INSTANCE);
WebEditorSession session = WebEditorSession.create(holders, Collections.emptyList(), sender, "lp", plugin);
String bytebinKey = session.open();
String bytesocksKey = session.getSocket().getSocket().channelId();
assertNotNull(bytebinKey);
assertNotNull(bytesocksKey);
// check bytebin payload
OkHttpClient httpClient = plugin.getHttpClient();
Response resp = httpClient.newCall(new Request.Builder()
.url(bytebinUrl + bytebinKey)
.build()).execute();
assertTrue(resp.isSuccessful());
assertEquals(200, resp.code());
JsonObject respObject = GsonProvider.normal().fromJson(resp.body().string(), JsonObject.class);
assertEquals(2, respObject.getAsJsonArray("permissionHolders").size());
// check bytesocks channel is open
CountDownLatch socketRespLatch = new CountDownLatch(1);
AtomicReference<Response> socketResp = new AtomicReference<>();
httpClient.newWebSocket(
new Request.Builder()
.url("ws://" + bytesocksHost + "/" + bytesocksKey)
.build(),
new WebSocketListener() {
@Override
public void onOpen(WebSocket ws, Response resp) {
socketResp.set(resp);
socketRespLatch.countDown();
}
@Override
public void onFailure(WebSocket ws, Throwable err, @Nullable Response resp) {
socketResp.set(resp);
socketRespLatch.countDown();
}
});
assertTrue(socketRespLatch.await(5, TimeUnit.SECONDS));
assertEquals(101, socketResp.get().code());
});
}
}
@@ -126,7 +126,7 @@ public final class TestPluginBootstrap extends LPStandaloneBootstrap {
}
}
static final class TestSenderFactory extends StandaloneSenderFactory {
public static final class TestSenderFactory extends StandaloneSenderFactory {
private Function<String, Tristate> permissionChecker;
@@ -1 +1,6 @@
example {
groups=[
default,
test
]
}
@@ -0,0 +1,5 @@
groups=[
default,
test
]
name=example
@@ -1 +1,8 @@
{}
{
"example": {
"groups": [
"default",
"test"
]
}
}
@@ -0,0 +1,7 @@
{
"name": "example",
"groups": [
"default",
"test"
]
}
@@ -1,33 +0,0 @@
[[test.prefixes]]
prefix = "TEST"
priority = 100
[test.prefixes.context]
server = "foo"
world = "bar"
[[test.permissions]]
permission = "group.default"
expiry = 2532384000
value = false
[test.permissions.context]
server = "foo"
world = "bar"
test = "test"
[[test.permissions]]
permission = "test"
expiry = 2532384000
value = false
[test.permissions.context]
server = "foo"
world = "bar"
test = "test"
[[test.permissions]]
permission = "example.permission"
value = true
[[test.meta]]
value = "bar"
key = "foo"
Whitespace-only changes.
@@ -1,42 +0,0 @@
[c1d60c50-70b5-4722-8057-87767557e50d]
name = "Luck"
primary-group = "default"
[[c1d60c50-70b5-4722-8057-87767557e50d.permissions]]
permission = "group.default"
value = false
expiry = 2532384000
[c1d60c50-70b5-4722-8057-87767557e50d.permissions.context]
server = "foo"
test = "test"
world = "bar"
[[c1d60c50-70b5-4722-8057-87767557e50d.permissions]]
permission = "test"
value = false
expiry = 2532384000
[c1d60c50-70b5-4722-8057-87767557e50d.permissions.context]
server = "foo"
test = "test"
world = "bar"
[[c1d60c50-70b5-4722-8057-87767557e50d.permissions]]
permission = "example.permission"
value = true
[[c1d60c50-70b5-4722-8057-87767557e50d.parents]]
group = "default"
[[c1d60c50-70b5-4722-8057-87767557e50d.prefixes]]
prefix = "TEST"
priority = 100
[c1d60c50-70b5-4722-8057-87767557e50d.prefixes.context]
server = "foo"
world = "bar"
[[c1d60c50-70b5-4722-8057-87767557e50d.meta]]
key = "foo"
value = "bar"
@@ -1 +0,0 @@
name = "default"
@@ -1,37 +0,0 @@
name = "test"
[[permissions]]
permission = "group.default"
value = false
expiry = 2532384000
[permissions.context]
server = "foo"
test = "test"
world = "bar"
[[permissions]]
permission = "test"
value = false
expiry = 2532384000
[permissions.context]
server = "foo"
test = "test"
world = "bar"
[[permissions]]
permission = "example.permission"
value = true
[[prefixes]]
prefix = "TEST"
priority = 100
[prefixes.context]
server = "foo"
world = "bar"
[[meta]]
key = "foo"
value = "bar"
@@ -1,42 +0,0 @@
uuid = "c1d60c50-70b5-4722-8057-87767557e50d"
name = "Luck"
primary-group = "default"
[[permissions]]
permission = "group.default"
value = false
expiry = 2532384000
[permissions.context]
server = "foo"
test = "test"
world = "bar"
[[permissions]]
permission = "test"
value = false
expiry = 2532384000
[permissions.context]
server = "foo"
test = "test"
world = "bar"
[[permissions]]
permission = "example.permission"
value = true
[[parents]]
group = "default"
[[prefixes]]
prefix = "TEST"
priority = 100
[prefixes.context]
server = "foo"
world = "bar"
[[meta]]
key = "foo"
value = "bar"
@@ -1 +1,4 @@
null
example:
groups:
- default
- test
@@ -0,0 +1,4 @@
name: example
groups:
- default
- test