From 55f7b67f9d1b9930f771bb552833d30cf92fe039 Mon Sep 17 00:00:00 2001 From: derklaro Date: Sun, 20 Feb 2022 12:16:11 +0100 Subject: [PATCH] Update to junit 5, remove powermock --- pom.xml | 112 +++++--- .../protocol/SimpleCraftBukkitITCase.java | 107 ++++--- .../protocol/SimpleMinecraftClient.java | 231 +++++++-------- .../integration/protocol/TestPingPacket.java | 40 +-- .../protocol/BukkitInitialization.java | 41 +-- .../protocol/MinecraftVersionTest.java | 32 +-- .../comphenix/protocol/PacketTypeTest.java | 89 +++--- .../concurrency/BlockingHashMapTest.java | 34 +-- .../protocol/events/PacketContainerTest.java | 267 ++++++++++-------- .../events/SerializedOfflinePlayerTest.java | 106 ++++--- .../injector/EntityUtilitiesTest.java | 34 +-- .../protocol/injector/PluginVerifierTest.java | 53 ++-- .../injector/SortedCopyOnWriteArrayTest.java | 53 ++-- .../protocol/injector/WirePacketTest.java | 28 +- .../server/TemporaryPlayerFactoryTest.java | 52 ++-- .../reflect/accessors/AccessorsTest.java | 72 ++--- .../reflect/cloning/AggregateClonerTest.java | 26 +- .../protocol/updater/UpdaterTest.java | 42 +-- .../utility/MinecraftMethodsTest.java | 16 +- .../utility/MinecraftReflectionTest.java | 60 ++-- .../protocol/utility/SnapshotVersionTest.java | 29 +- .../utility/StreamSerializerTest.java | 32 +-- .../comphenix/protocol/utility/TestUtils.java | 20 +- .../protocol/wrappers/AutoWrapperTest.java | 14 +- .../wrappers/BukkitConvertersTest.java | 17 +- .../wrappers/ChunkCoordIntPairTest.java | 15 +- .../protocol/wrappers/CloningTest.java | 17 +- .../protocol/wrappers/EnumWrappersTest.java | 60 ++-- .../wrappers/MultiBlockChangeTest.java | 45 ++- .../protocol/wrappers/PlayerInfoDataTest.java | 41 ++- .../wrappers/WrappedAttributeTest.java | 85 +++--- .../wrappers/WrappedBlockDataTest.java | 40 ++- .../wrappers/WrappedChatComponentTest.java | 15 +- .../wrappers/WrappedDataWatcherTest.java | 48 ++-- .../wrappers/WrappedGameProfileTest.java | 35 +-- .../wrappers/WrappedIntHashMapTest.java | 26 -- .../wrappers/WrappedParticleTest.java | 16 +- .../wrappers/WrappedServerPingTest.java | 20 +- .../wrappers/nbt/NbtCompoundTest.java | 52 ++-- .../protocol/wrappers/nbt/NbtFactoryTest.java | 48 ++-- .../protocol/wrappers/nbt/TileEntityTest.java | 37 ++- .../io/NbtConfigurationSerializerTest.java | 25 +- .../org.mockito.plugins.MockMaker | 1 + 43 files changed, 1076 insertions(+), 1157 deletions(-) delete mode 100644 src/test/java/com/comphenix/protocol/wrappers/WrappedIntHashMapTest.java create mode 100644 src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker diff --git a/pom.xml b/pom.xml index 26917520..fe40c5d3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - com.comphenix.protocol + com.comphenix.protocol ProtocolLib ProtocolLib 4.8.0-SNAPSHOT @@ -16,7 +16,9 @@ ${project.version} - 2.0.9 + 5.8.2 + 4.3.1 + 4.1.74.Final 1.18.1-R0.1-SNAPSHOT @@ -71,7 +73,7 @@ maven-compiler-plugin - 3.8.1 + 3.10.0 1.8 1.8 @@ -81,7 +83,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.2.0 + 3.2.2 @@ -99,6 +101,14 @@ org.apache.maven.plugins maven-surefire-plugin 3.0.0-M5 + + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + + false false @@ -108,22 +118,22 @@ ${project.version} - - - --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.util.regex=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED + + --add-opens java.base/java.util=ALL-UNNAMED maven-javadoc-plugin - 3.3.1 + 3.3.2 false ISO-8859-1 ProtocolLib JavaDocs ProtocolLib JavaDocs Copyright © {inceptionYear}–{currentYear} - Comphenix and dmulloy2. Licensed under the GNU GPL v2. + Comphenix and dmulloy2. Licensed under the GNU GPL v2. + -Xdoclint:none @@ -185,7 +195,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.2.0 + 3.3.2 attach-javadocs @@ -227,7 +237,7 @@ GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - http://www.gnu.org/licenses/gpl-2.0.txt + https://www.gnu.org/licenses/gpl-2.0.txt repo @@ -236,7 +246,7 @@ dmulloy2 Dan Mulloy - http://dmulloy2.net/ + https://dmulloy2.net/ developer maintainer @@ -246,7 +256,7 @@ aadnk Kristian S. Stangeland kr_stang@hotmail.com - http://comphenix.net/ + https://comphenix.net/ former author @@ -277,38 +287,41 @@ - - - io.netty - netty-all - 4.0.23.Final - provided - - - - io.netty - netty-common - 4.1.70.Final - test - - - io.netty - netty-transport - 4.1.70.Final - test - + org.spigotmc spigot-api ${spigot.version} provided + + + junit + * + + org.spigotmc spigot ${spigot.version} provided + + + junit + * + + + + + + + io.netty + netty-all + 4.0.23.Final + provided + + net.kyori adventure-text-serializer-gson @@ -319,32 +332,43 @@ net.bytebuddy byte-buddy - 1.12.3 + 1.12.8 + - junit - junit - 4.13.2 + org.junit.jupiter + junit-jupiter-api + ${junit.version} test + org.mockito mockito-core - 3.12.4 + ${mockito.version} test + - org.powermock - powermock-module-junit4 - ${powermock.version} + org.mockito + mockito-inline + ${mockito.version} test + - org.powermock - powermock-api-mockito2 - ${powermock.version} + io.netty + netty-common + ${netty.version} + test + + + + io.netty + netty-transport + ${netty.version} test diff --git a/src/test/java/com/comphenix/integration/protocol/SimpleCraftBukkitITCase.java b/src/test/java/com/comphenix/integration/protocol/SimpleCraftBukkitITCase.java index d7ab0f83..6c00297d 100644 --- a/src/test/java/com/comphenix/integration/protocol/SimpleCraftBukkitITCase.java +++ b/src/test/java/com/comphenix/integration/protocol/SimpleCraftBukkitITCase.java @@ -3,6 +3,10 @@ package com.comphenix.integration.protocol; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.reflect.FieldUtils; +import com.google.common.collect.Lists; +import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.util.Collections; @@ -10,7 +14,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; - import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.simple.SimpleLogger; import org.bukkit.Bukkit; @@ -18,41 +21,25 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginLoadOrder; import org.bukkit.plugin.PluginManager; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.reflect.FieldUtils; -import com.google.common.collect.Lists; -import com.google.common.io.Files; - -// TODO Migrate this to Gradle if necessary -// Damn final classes ... -@RunWith(org.powermock.modules.junit4.PowerMockRunner.class) -@PowerMockIgnore({ "org.apache.logging.log4j.core.config.xml.*", "javax.management.*" }) -@PrepareForTest(PluginDescriptionFile.class) public class SimpleCraftBukkitITCase { - // The fake plugin - private static volatile Plugin FAKE_PLUGIN = null; - + /** * The maximum amount of time to wait before a server has started. *

- * We have to give it the ample time of 60 seconds, as a server may have to - * generate the spawn area in three worlds. + * We have to give it the ample time of 60 seconds, as a server may have to generate the spawn area in three worlds. */ private static final int TIMEOUT_MS = 60000; - + // The fake plugin + private static volatile Plugin FAKE_PLUGIN = null; + /** * Setup the CraftBukkit server for all the tests. - * @throws IOException Unable to setup server. + * + * @throws IOException Unable to setup server. * @throws InterruptedException Thread interrupted. */ - //@BeforeClass + //@BeforeAll public static void setupCraftBukkit() throws Exception { setupPlugins(); @@ -63,17 +50,18 @@ public class SimpleCraftBukkitITCase { System.out.println("Loader of SimpleLogger: " + SimpleLogger.class.getClassLoader()); System.out.println("Loader of Logger: " + Logger.class.getClassLoader()); } - + // We need to wait until the server object is ready - while (Bukkit.getServer() == null) + while (Bukkit.getServer() == null) { Thread.sleep(1); - + } + // Make it clear this plugin doesn't exist FAKE_PLUGIN = createPlugin("FakeTestPluginIntegration"); - + // No need to look for updates FieldUtils.writeStaticField(ProtocolLibrary.class, "UPDATES_DISABLED", Boolean.TRUE, true); - + // Wait until the server and all the plugins have loaded Bukkit.getScheduler().callSyncMethod(FAKE_PLUGIN, new Callable() { @Override @@ -82,26 +70,22 @@ public class SimpleCraftBukkitITCase { return null; } }).get(TIMEOUT_MS, TimeUnit.MILLISECONDS); - + // Plugins are now ready ProtocolLibrary.getConfig().setDebug(true); } - + /** * Close the CraftBukkit server when they're done. */ - //@AfterClass + //@AfterAll public static void shutdownCraftBukkit() { Bukkit.shutdown(); } - - //@Test - public void testPingPacket() throws Throwable { - TestPingPacket.newTest().startTest(FAKE_PLUGIN); - } - + /** * Copy ProtocolLib into the plugins folder. + * * @throws IOException If anything went wrong. */ private static void setupPlugins() throws IOException { @@ -109,27 +93,27 @@ public class SimpleCraftBukkitITCase { File srcDirectory = new File("../"); File bestFile = null; int bestLength = Integer.MAX_VALUE; - + for (File file : srcDirectory.listFiles()) { String name = file.getName(); - + if (file.isFile() && name.startsWith("ProtocolLib") && name.length() < bestLength) { bestLength = name.length(); bestFile = file; } } - + if (bestFile == null) { throw new IllegalStateException("Cannot find ProtocolLib in " + srcDirectory); } - + // Copy the ProtocolLib plugin to the server if (pluginDirectory.exists()) { deleteFolder(pluginDirectory); } - + pluginDirectory.mkdirs(); - + File destination = new File(pluginDirectory, bestFile.getName()).getAbsoluteFile(); Files.copy(bestFile, destination); } @@ -148,46 +132,53 @@ public class SimpleCraftBukkitITCase { } } } - + /** * Load a specific fake plugin. + * * @param plugin - the plugin to load. */ @SuppressWarnings("unchecked") private static void initializePlugin(Plugin plugin) { PluginManager manager = Bukkit.getPluginManager(); - + try { List plugins = (List) FieldUtils.readField(manager, "plugins", true); - Map lookupNames = (Map) FieldUtils.readField(manager, "lookupNames", true); - - /// Associate this plugin - plugins.add(plugin); - lookupNames.put(plugin.getName(), plugin); - + Map lookupNames = (Map) FieldUtils.readField(manager, "lookupNames", true); + + /// Associate this plugin + plugins.add(plugin); + lookupNames.put(plugin.getName(), plugin); + } catch (Exception e) { throw new RuntimeException("Unable to access the fields of " + manager, e); } } - + /** * Create a mockable plugin for all the tests. + * * @param fakePluginName - the fake plugin name. * @return The plugin. */ private static Plugin createPlugin(String fakePluginName) { Plugin plugin = mock(Plugin.class); PluginDescriptionFile description = mock(PluginDescriptionFile.class); - + when(description.getDepend()).thenReturn(Lists.newArrayList("ProtocolLib")); - when(description.getSoftDepend()).thenReturn(Collections.emptyList()); - when(description.getLoadBefore()).thenReturn(Collections.emptyList()); + when(description.getSoftDepend()).thenReturn(Collections.emptyList()); + when(description.getLoadBefore()).thenReturn(Collections.emptyList()); when(description.getLoad()).thenReturn(PluginLoadOrder.POSTWORLD); - + when(plugin.getName()).thenReturn(fakePluginName); when(plugin.getServer()).thenReturn(Bukkit.getServer()); when(plugin.isEnabled()).thenReturn(true); when(plugin.getDescription()).thenReturn(description); return plugin; } + + //@Test + public void testPingPacket() throws Throwable { + TestPingPacket.newTest().startTest(FAKE_PLUGIN); + } } diff --git a/src/test/java/com/comphenix/integration/protocol/SimpleMinecraftClient.java b/src/test/java/com/comphenix/integration/protocol/SimpleMinecraftClient.java index c187fcdc..2eb7d3fd 100644 --- a/src/test/java/com/comphenix/integration/protocol/SimpleMinecraftClient.java +++ b/src/test/java/com/comphenix/integration/protocol/SimpleMinecraftClient.java @@ -1,5 +1,10 @@ package com.comphenix.integration.protocol; +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.PacketType.Protocol; +import com.comphenix.protocol.PacketType.Sender; +import com.comphenix.protocol.utility.StreamSerializer; +import com.google.common.io.ByteStreams; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; @@ -10,84 +15,110 @@ import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.PacketType.Protocol; -import com.comphenix.protocol.PacketType.Sender; -import com.comphenix.protocol.utility.StreamSerializer; -import com.google.common.io.ByteStreams; - public class SimpleMinecraftClient { - private static final int CONNECT_TIMEOUT = 2500; - private static final int READ_TIMEOUT = 15000; - // Current Minecraft version - private final int protocolVersion; + private static final int CONNECT_TIMEOUT = 2500; + private static final int READ_TIMEOUT = 15000; + // Typical Minecraft serializer + private static final StreamSerializer serializer = StreamSerializer.getDefault(); + // Current Minecraft version + private final int protocolVersion; - // Typical Minecraft serializer - private static StreamSerializer serializer = StreamSerializer.getDefault(); - - public SimpleMinecraftClient(int protocolVersion) { + public SimpleMinecraftClient(int protocolVersion) { this.protocolVersion = protocolVersion; } - - /** - * Query the local server for ping information. - * @return The server information. - * @throws IOException - */ - public String queryLocalPing() throws IOException { - return queryServerPing(new InetSocketAddress("localhost", 25565)); + + /** + * Write a byte array to the output stream, prefixed by a length. + * + * @param output - the stream. + * @param data - the data to write. + */ + private static void writeByteArray(DataOutputStream output, byte[] data) throws IOException { + StreamSerializer.getDefault().serializeVarInt(output, data.length); + + if (data.length > 0) { + output.write(data); + } } - + + /** + * Read a byte array from an input stream, prefixed by length. + * + * @param input - the input stream. + * @return The read byte array. + */ + private static byte[] readByteArray(DataInputStream input) throws IOException { + int length = serializer.deserializeVarInt(input); + byte[] data = new byte[length]; + + ByteStreams.readFully(input, data); + return data; + } + + /** + * Query the local server for ping information. + * + * @return The server information. + * @throws IOException + */ + public String queryLocalPing() throws IOException { + return this.queryServerPing(new InetSocketAddress("localhost", 25565)); + } + /** * Query the given server for its list ping information. + * * @param address - the server hostname and port. * @return The server information. * @throws IOException */ public String queryServerPing(InetSocketAddress address) throws IOException { - Socket socket = null; - OutputStream output = null; - InputStream input = null; - - try { - socket = new Socket(); - socket.connect(address, CONNECT_TIMEOUT); + Socket socket = null; + OutputStream output = null; + InputStream input = null; - // Shouldn't take that long - socket.setSoTimeout(READ_TIMEOUT); - - // Retrieve sockets - output = socket.getOutputStream(); - input = socket.getInputStream(); + try { + socket = new Socket(); + socket.connect(address, CONNECT_TIMEOUT); - // The output writer - DataOutputStream data = new DataOutputStream(output); + // Shouldn't take that long + socket.setSoTimeout(READ_TIMEOUT); - // Request a server information packet - writePacket(data, new HandshakePacket(protocolVersion, address.getHostName(), address.getPort(), 1)); - writePacket(data, new RequestPacket()); - data.flush(); - - // Read a single packet, and close the connection - SimplePacket packet = readPacket(new DataInputStream(input), Protocol.STATUS); - - socket.close(); - return ((ResponsePacket) packet).getPingJson(); - } finally { - if (input != null) - input.close(); - if (output != null) - output.close(); - if (socket != null) - socket.close(); - } + // Retrieve sockets + output = socket.getOutputStream(); + input = socket.getInputStream(); + + // The output writer + DataOutputStream data = new DataOutputStream(output); + + // Request a server information packet + this.writePacket(data, new HandshakePacket(this.protocolVersion, address.getHostName(), address.getPort(), 1)); + this.writePacket(data, new RequestPacket()); + data.flush(); + + // Read a single packet, and close the connection + SimplePacket packet = this.readPacket(new DataInputStream(input), Protocol.STATUS); + + socket.close(); + return ((ResponsePacket) packet).getPingJson(); + } finally { + if (input != null) { + input.close(); + } + if (output != null) { + output.close(); + } + if (socket != null) { + socket.close(); + } + } } - + private void writePacket(DataOutputStream output, SimplePacket packet) throws IOException { ByteArrayOutputStream packetBuffer = new ByteArrayOutputStream(); DataOutputStream packetOutput = new DataOutputStream(packetBuffer); - + // Prefix the packet with a length field packet.write(packetOutput); writeByteArray(output, packetBuffer.toByteArray()); @@ -96,14 +127,15 @@ public class SimpleMinecraftClient { private SimplePacket readPacket(DataInputStream input, Protocol protocol) throws IOException { while (true) { byte[] buffer = readByteArray(input); - + // Skip empty packets - if (buffer.length == 0) + if (buffer.length == 0) { continue; - - DataInputStream data = getDataInput(buffer); + } + + DataInputStream data = this.getDataInput(buffer); PacketType type = PacketType.findCurrent(protocol, Sender.SERVER, serializer.deserializeVarInt(data)); - + if (type == PacketType.Status.Server.SERVER_INFO) { ResponsePacket response = new ResponsePacket(); response.read(type, data); @@ -116,69 +148,47 @@ public class SimpleMinecraftClient { /** * Wrap an input stream around a byte array. + * * @param bytes - the array. * @return The wrapped input stream. */ private DataInputStream getDataInput(byte[] bytes) { return new DataInputStream(new ByteArrayInputStream(bytes)); } - - /** - * Write a byte array to the output stream, prefixed by a length. - * @param output - the stream. - * @param data - the data to write. - */ - private static void writeByteArray(DataOutputStream output, byte[] data) throws IOException { - StreamSerializer.getDefault().serializeVarInt(output, data.length); - - if (data.length > 0) { - output.write(data); - } - } - - /** - * Read a byte array from an input stream, prefixed by length. - * @param input - the input stream. - * @return The read byte array. - */ - private static byte[] readByteArray(DataInputStream input) throws IOException { - int length = serializer.deserializeVarInt(input); - byte[] data = new byte[length]; - - ByteStreams.readFully(input, data); - return data; - } private static class RequestPacket extends SimplePacket { + public RequestPacket() { super(PacketType.Status.Client.START); } } - + private static class ResponsePacket extends SimplePacket { + private String ping; - + public ResponsePacket() { super(PacketType.Status.Server.SERVER_INFO); } - + @Override public void read(PacketType type, DataInputStream input) throws IOException { super.read(type, input); - ping = serializer.deserializeString(input, 32000); + this.ping = this.serializer.deserializeString(input, 32000); } - + public String getPingJson() { - return ping; + return this.ping; } } - + private static class HandshakePacket extends SimplePacket { - private int protocol; - private String host; - private int port; - private int nextState; - + + private final int protocol; + private final String host; + private final int port; + private final int nextState; + public HandshakePacket(int protocol, String host, int port, int nextState) { super(PacketType.Handshake.Client.SET_PROTOCOL); this.protocol = protocol; @@ -190,25 +200,26 @@ public class SimpleMinecraftClient { @Override public void write(DataOutputStream output) throws IOException { super.write(output); - serializer.serializeVarInt(output, protocol); - serializer.serializeString(output, host); - output.writeShort(port); - serializer.serializeVarInt(output, nextState); + this.serializer.serializeVarInt(output, this.protocol); + this.serializer.serializeString(output, this.host); + output.writeShort(this.port); + this.serializer.serializeVarInt(output, this.nextState); } } - + private static class SimplePacket { + protected final PacketType type; protected final StreamSerializer serializer = StreamSerializer.getDefault(); - + public SimplePacket(PacketType type) { this.type = type; } - + public void write(DataOutputStream output) throws IOException { - serializer.serializeVarInt(output, type.getCurrentId()); + this.serializer.serializeVarInt(output, this.type.getCurrentId()); } - + @SuppressWarnings("unused") public void read(PacketType type, DataInputStream input) throws IOException { // Note - we don't read the packet id diff --git a/src/test/java/com/comphenix/integration/protocol/TestPingPacket.java b/src/test/java/com/comphenix/integration/protocol/TestPingPacket.java index ef392aa8..10534bde 100644 --- a/src/test/java/com/comphenix/integration/protocol/TestPingPacket.java +++ b/src/test/java/com/comphenix/integration/protocol/TestPingPacket.java @@ -1,21 +1,20 @@ package com.comphenix.integration.protocol; -import static org.junit.Assert.assertEquals; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import org.bukkit.plugin.Plugin; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketEvent; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.bukkit.plugin.Plugin; public class TestPingPacket { + // Current versions private static final int PROTOCOL_VERSION = 4; @@ -30,6 +29,7 @@ public class TestPingPacket { /** * Create a new test ping packet test. + * * @return The new test. */ public static TestPingPacket newTest() { @@ -38,17 +38,18 @@ public class TestPingPacket { /** * Invoked when the test should be started. + * * @param plugin - the current plugin. * @throws Throwable Anything went wrong. */ public void startTest(Plugin plugin) throws Throwable { try { - String transmitted = testInterception(plugin). - get(TIMEOUT_PING_MS, TimeUnit.MILLISECONDS); + String transmitted = this.testInterception(plugin). + get(TIMEOUT_PING_MS, TimeUnit.MILLISECONDS); // Make sure it's the same System.out.println("Server string: " + transmitted); - assertEquals(source, transmitted); + assertEquals(this.source, transmitted); } catch (ExecutionException e) { throw e.getCause(); } @@ -56,12 +57,12 @@ public class TestPingPacket { private Future testInterception(Plugin test) { ProtocolLibrary.getProtocolManager().addPacketListener( - new PacketAdapter(test, PacketType.Status.Server.SERVER_INFO) { - @Override - public void onPacketSending(PacketEvent event) { - source = event.getPacket().getServerPings().read(0).toJson(); - } - }); + new PacketAdapter(test, PacketType.Status.Server.SERVER_INFO) { + @Override + public void onPacketSending(PacketEvent event) { + TestPingPacket.this.source = event.getPacket().getServerPings().read(0).toJson(); + } + }); // Invoke the client on a separate thread return Executors.newSingleThreadExecutor().submit(new Callable() { @@ -71,8 +72,9 @@ public class TestPingPacket { String information = client.queryLocalPing(); // Wait for the listener to catch up - for (int i = 0; i < 1000 && (source == null); i++) + for (int i = 0; i < 1000 && (TestPingPacket.this.source == null); i++) { Thread.sleep(1); + } return information; } diff --git a/src/test/java/com/comphenix/protocol/BukkitInitialization.java b/src/test/java/com/comphenix/protocol/BukkitInitialization.java index 9a25e1df..f9d48d32 100644 --- a/src/test/java/com/comphenix/protocol/BukkitInitialization.java +++ b/src/test/java/com/comphenix/protocol/BukkitInitialization.java @@ -1,16 +1,16 @@ package com.comphenix.protocol; -import java.util.Collections; -import java.util.List; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.comphenix.protocol.reflect.FieldUtils; import com.comphenix.protocol.utility.Constants; - +import java.util.Collections; +import java.util.List; import net.minecraft.SharedConstants; import net.minecraft.core.IRegistry; import net.minecraft.server.DispenserRegistry; import net.minecraft.server.level.WorldServer; - import org.apache.logging.log4j.LogManager; import org.bukkit.Bukkit; import org.bukkit.Server; @@ -21,24 +21,21 @@ import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemFactory; import org.bukkit.craftbukkit.v1_18_R1.util.Versioning; import org.spigotmc.SpigotWorldConfig; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - /** * Used to ensure that ProtocolLib and Bukkit is prepared to be tested. * * @author Kristian */ public class BukkitInitialization { + private static final BukkitInitialization instance = new BukkitInitialization(); + private boolean initialized; + private boolean packaged; private BukkitInitialization() { System.out.println("Created new BukkitInitialization on " + Thread.currentThread().getName()); } - private boolean initialized; - private boolean packaged; - /** * Statically initializes the mock server for unit testing */ @@ -46,29 +43,13 @@ public class BukkitInitialization { instance.initialize(); } - /** - * @deprecated - Replaced with initializeAll() - */ - @Deprecated - public static synchronized void initializePackage() { - initializeAll(); - } - - /** - * @deprecated - Replaced with initializeAll() - */ - @Deprecated - public static synchronized void initializeItemMeta() { - initializeAll(); - } - /** * Initialize Bukkit and ProtocolLib such that we can perfrom unit testing */ private void initialize() { - if (!initialized) { + if (!this.initialized) { // Denote that we're done - initialized = true; + this.initialized = true; try { LogManager.getLogger(); @@ -127,8 +108,8 @@ public class BukkitInitialization { * Ensure that package names are correctly set up. */ private void setPackage() { - if (!packaged) { - packaged = true; + if (!this.packaged) { + this.packaged = true; try { LogManager.getLogger(); diff --git a/src/test/java/com/comphenix/protocol/MinecraftVersionTest.java b/src/test/java/com/comphenix/protocol/MinecraftVersionTest.java index 4b48a56c..754f810e 100644 --- a/src/test/java/com/comphenix/protocol/MinecraftVersionTest.java +++ b/src/test/java/com/comphenix/protocol/MinecraftVersionTest.java @@ -2,39 +2,38 @@ * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * You should have received a copy of the GNU General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ package com.comphenix.protocol; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; - -import com.comphenix.protocol.utility.MinecraftProtocolVersion; import com.comphenix.protocol.utility.MinecraftVersion; +import org.junit.jupiter.api.Test; public class MinecraftVersionTest { + @Test public void testComparision() { MinecraftVersion within = new MinecraftVersion(1, 2, 5); MinecraftVersion outside = new MinecraftVersion(1, 7, 0); - + MinecraftVersion lower = new MinecraftVersion(1, 0, 0); MinecraftVersion highest = new MinecraftVersion(1, 4, 5); - + MinecraftVersion atLeast = new MinecraftVersion(1, 8, 8); // Make sure this is valid @@ -54,8 +53,9 @@ public class MinecraftVersionTest { assertEquals(MinecraftVersion.extractVersion("CraftBukkit R3.0 (MC: 1.4.3)"), "1.4.3"); assertEquals(MinecraftVersion.extractVersion("CraftBukkit Test Beta 1 (MC: 1.10.01 )"), "1.10.01"); assertEquals(MinecraftVersion.extractVersion("Hello (MC: 2.3.4)"), "2.3.4"); - - assertEquals(MinecraftVersion.fromServerVersion("git-Cauldron-Reloaded-1.7.10-1.1388.1.0 (MC: 1.7.10)"), new MinecraftVersion(1, 7, 10)); + + assertEquals(MinecraftVersion.fromServerVersion("git-Cauldron-Reloaded-1.7.10-1.1388.1.0 (MC: 1.7.10)"), + new MinecraftVersion(1, 7, 10)); assertEquals(MinecraftVersion.fromServerVersion("git-Bukkit-18fbb24 (MC: 1.8.8)"), new MinecraftVersion(1, 8, 8)); } } diff --git a/src/test/java/com/comphenix/protocol/PacketTypeTest.java b/src/test/java/com/comphenix/protocol/PacketTypeTest.java index 01058cb5..4c4078f3 100644 --- a/src/test/java/com/comphenix/protocol/PacketTypeTest.java +++ b/src/test/java/com/comphenix/protocol/PacketTypeTest.java @@ -1,62 +1,63 @@ /** - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2016 dmulloy2 + * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. Copyright (C) 2016 dmulloy2 *

- * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later + * version. *

- * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. *

- * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA + * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.comphenix.protocol; -import java.lang.reflect.Field; -import java.util.*; -import java.util.Map.Entry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.comphenix.protocol.PacketType.Protocol; import com.comphenix.protocol.PacketType.Sender; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.injector.packet.PacketRegistry; import com.comphenix.protocol.utility.Constants; -import com.comphenix.protocol.utility.MinecraftReflection; -import com.comphenix.protocol.utility.MinecraftVersion; - +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; import net.minecraft.network.EnumProtocol; import net.minecraft.network.protocol.EnumProtocolDirection; import net.minecraft.network.protocol.login.PacketLoginInStart; - import org.apache.commons.lang.WordUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author dmulloy2 */ public class PacketTypeTest { - @BeforeClass + @BeforeAll public static void beforeClass() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); // I'm well aware this is jank, but it does in fact work correctly and give the desired result PacketType.onDynamicCreate = className -> { - throw new RuntimeException("Dynamically generated packet " + className); + throw new RuntimeException("Dynamically generated packet " + className); }; } - @AfterClass + @AfterAll public static void afterClass() { - PacketType.onDynamicCreate = __ -> {}; + PacketType.onDynamicCreate = __ -> { + }; } @SuppressWarnings("unchecked") @@ -229,7 +230,8 @@ public class PacketTypeTest { names.add(alias); } } - } catch (Exception ignored) { } + } catch (Exception ignored) { + } return names; } @@ -246,14 +248,15 @@ public class PacketTypeTest { return builder.toString(); } - @BeforeClass + @BeforeAll public static void initializeReflection() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } @Test public void testFindCurrent() { - assertEquals(PacketType.Play.Client.STEER_VEHICLE, PacketType.findCurrent(Protocol.PLAY, Sender.CLIENT, "SteerVehicle")); + assertEquals(PacketType.Play.Client.STEER_VEHICLE, + PacketType.findCurrent(Protocol.PLAY, Sender.CLIENT, "SteerVehicle")); } @Test @@ -264,12 +267,12 @@ public class PacketTypeTest { @Test public void testDeprecation() { - assertTrue("Packet isn't properly deprecated", PacketType.Status.Server.OUT_SERVER_INFO.isDeprecated()); - assertTrue("Deprecated packet isn't properly included", - PacketRegistry.getServerPacketTypes().contains(PacketType.Status.Server.OUT_SERVER_INFO)); - assertFalse("Packet isn't properly deprecated", PacketType.Play.Server.CHAT.isDeprecated()); - assertEquals("Deprecated packets aren't equal", PacketType.Status.Server.OUT_SERVER_INFO, - PacketType.Status.Server.SERVER_INFO); + assertTrue(PacketType.Status.Server.OUT_SERVER_INFO.isDeprecated(), "Packet isn't properly deprecated"); + assertTrue(PacketRegistry.getServerPacketTypes().contains(PacketType.Status.Server.OUT_SERVER_INFO), + "Deprecated packet isn't properly included"); + assertFalse(PacketType.Play.Server.CHAT.isDeprecated(), "Packet isn't properly deprecated"); + assertEquals(PacketType.Status.Server.OUT_SERVER_INFO, PacketType.Status.Server.SERVER_INFO, + "Deprecated packets aren't equal"); } @Test @@ -297,9 +300,11 @@ public class PacketTypeTest { for (Entry> entry1 : treeMap.entrySet()) { try { PacketType type = PacketType.fromClass(entry1.getValue()); - if (type.getCurrentId() != entry1.getKey()) + if (type.getCurrentId() != entry1.getKey()) { throw new IllegalStateException( - "Packet ID for " + type + " is incorrect. Expected " + entry1.getKey() + ", but got " + type.getCurrentId()); + "Packet ID for " + type + " is incorrect. Expected " + entry1.getKey() + ", but got " + + type.getCurrentId()); + } } catch (Throwable ex) { ex.printStackTrace(); fail = true; @@ -308,7 +313,7 @@ public class PacketTypeTest { } } - assertTrue("Packet type(s) were incorrect!", !fail); + assertFalse(fail, "Packet type(s) were incorrect!"); } @Test @@ -324,6 +329,6 @@ public class PacketTypeTest { } } } - assertFalse("Packet type(s) failed to instantiate", fail); + assertFalse(fail, "Packet type(s) failed to instantiate"); } } diff --git a/src/test/java/com/comphenix/protocol/concurrency/BlockingHashMapTest.java b/src/test/java/com/comphenix/protocol/concurrency/BlockingHashMapTest.java index f73e91ca..b0edd260 100644 --- a/src/test/java/com/comphenix/protocol/concurrency/BlockingHashMapTest.java +++ b/src/test/java/com/comphenix/protocol/concurrency/BlockingHashMapTest.java @@ -2,30 +2,28 @@ * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * You should have received a copy of the GNU General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ package com.comphenix.protocol.concurrency; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; - -import org.junit.Test; +import org.junit.jupiter.api.Test; public class BlockingHashMapTest { @@ -35,25 +33,21 @@ public class BlockingHashMapTest { final BlockingHashMap map = BlockingHashMap.create(); ExecutorService service = Executors.newSingleThreadExecutor(); - + // Create a reader - Future future = service.submit(new Callable() { - @Override - public String call() throws Exception { - // Combine for easy reading - return map.get(0) + map.get(1); - } + Future future = service.submit(() -> { + // Combine for easy reading + return map.get(0) + map.get(1); }); // Wait a bit Thread.sleep(50); - + // Insert values map.put(0, "hello "); map.put(1, "world"); - + // Wait for the other thread to complete assertEquals(future.get(), "hello world"); } - } diff --git a/src/test/java/com/comphenix/protocol/events/PacketContainerTest.java b/src/test/java/com/comphenix/protocol/events/PacketContainerTest.java index 91ab697b..50b1a771 100644 --- a/src/test/java/com/comphenix/protocol/events/PacketContainerTest.java +++ b/src/test/java/com/comphenix/protocol/events/PacketContainerTest.java @@ -1,26 +1,31 @@ /** - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2012 Kristian S. Stangeland - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA + * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. Copyright (C) 2012 Kristian S. + * Stangeland + *

+ * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later + * version. + *

+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + *

+ * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.comphenix.protocol.events; -import com.comphenix.protocol.wrappers.EnumWrappers.EntityUseAction; -import com.comphenix.protocol.wrappers.EnumWrappers.Hand; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.util.*; +import static com.comphenix.protocol.utility.TestUtils.assertItemCollectionsEqual; +import static com.comphenix.protocol.utility.TestUtils.assertItemsEqual; +import static com.comphenix.protocol.utility.TestUtils.equivalentItem; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.PacketType; @@ -30,30 +35,48 @@ import com.comphenix.protocol.reflect.StructureModifier; import com.comphenix.protocol.utility.MinecraftReflection; import com.comphenix.protocol.utility.Util; import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.*; +import com.comphenix.protocol.wrappers.BukkitConverters; +import com.comphenix.protocol.wrappers.ComponentConverter; +import com.comphenix.protocol.wrappers.EnumWrappers; +import com.comphenix.protocol.wrappers.EnumWrappers.EntityUseAction; +import com.comphenix.protocol.wrappers.EnumWrappers.Hand; import com.comphenix.protocol.wrappers.EnumWrappers.SoundCategory; import com.comphenix.protocol.wrappers.MovingObjectPositionBlock; +import com.comphenix.protocol.wrappers.Pair; +import com.comphenix.protocol.wrappers.WrappedBlockData; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry; import com.comphenix.protocol.wrappers.WrappedDataWatcher.WrappedDataWatcherObject; +import com.comphenix.protocol.wrappers.WrappedEnumEntityUseAction; +import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.comphenix.protocol.wrappers.WrappedWatchableObject; import com.comphenix.protocol.wrappers.nbt.NbtCompound; import com.comphenix.protocol.wrappers.nbt.NbtFactory; import com.google.common.collect.Lists; - -import net.md_5.bungee.api.chat.*; - +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.hover.content.Text; import net.minecraft.core.IRegistry; import net.minecraft.network.protocol.game.PacketPlayOutUpdateAttributes; import net.minecraft.network.protocol.game.PacketPlayOutUpdateAttributes.AttributeSnapshot; +import net.minecraft.resources.MinecraftKey; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectList; import net.minecraft.world.entity.ai.attributes.AttributeBase; import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import net.minecraft.resources.MinecraftKey; import net.minecraft.world.entity.npc.VillagerData; import net.minecraft.world.entity.npc.VillagerProfession; import net.minecraft.world.entity.npc.VillagerType; - -import net.minecraft.world.level.dimension.DimensionManager; import org.apache.commons.lang.SerializationUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.bukkit.ChatColor; @@ -66,34 +89,26 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; - -import static com.comphenix.protocol.utility.TestUtils.*; -import static org.junit.Assert.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; // Ensure that the CraftItemFactory is mockable -@RunWith(org.powermock.modules.junit4.PowerMockRunner.class) -@PowerMockIgnore({ "org.apache.logging.log4j.core.config.xml.*", "javax.management.*" }) -//@PrepareForTest(CraftItemFactory.class) public class PacketContainerTest { - // Helper converters - private EquivalentConverter watchConvert = BukkitConverters.getDataWatcherConverter(); - private EquivalentConverter itemConvert = BukkitConverters.getItemStackConverter(); + private static BaseComponent[] TEST_COMPONENT; + // Helper converters + private final EquivalentConverter watchConvert = BukkitConverters.getDataWatcherConverter(); + private final EquivalentConverter itemConvert = BukkitConverters.getItemStackConverter(); - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); - TEST_COMPONENT = - new ComponentBuilder("Hit or miss?") - .event(new ClickEvent(ClickEvent.Action.OPEN_URL, "http://reddit.com")) - .event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[] { new TextComponent("The \"front page\" of the internet") })) - .append("I guess they never miss, huh?").create(); + TEST_COMPONENT = new ComponentBuilder("Hit or miss?") + .event(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://reddit.com")) + .event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text("The \"front page\" of the internet"))) + .append("I guess they never miss, huh?") + .create(); } private void testPrimitive(StructureModifier modifier, int index, T initialValue, T testValue) { @@ -123,7 +138,7 @@ public class PacketContainerTest { // Contains a byte array we will test PacketContainer customPayload = new PacketContainer(PacketType.Login.Client.ENCRYPTION_BEGIN); StructureModifier bytes = customPayload.getByteArrays(); - byte[] testArray = new byte[] { 1, 2, 3 }; + byte[] testArray = new byte[]{1, 2, 3}; // It's NULL at first // assertEquals(null, bytes.read(0)); @@ -140,51 +155,51 @@ public class PacketContainerTest { @Test public void testGetBytes() { PacketContainer spawnMob = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY_LIVING); - testPrimitive(spawnMob.getBytes(), 0, (byte)0, (byte)1); + this.testPrimitive(spawnMob.getBytes(), 0, (byte) 0, (byte) 1); } @Test public void testGetShorts() { PacketContainer itemData = new PacketContainer(PacketType.Play.Server.REL_ENTITY_MOVE); - testPrimitive(itemData.getShorts(), 0, (short)0, (short)1); + this.testPrimitive(itemData.getShorts(), 0, (short) 0, (short) 1); } @Test public void testGetIntegers() { PacketContainer updateSign = new PacketContainer(PacketType.Play.Client.CLOSE_WINDOW); - testPrimitive(updateSign.getIntegers(), 0, 0, 1); + this.testPrimitive(updateSign.getIntegers(), 0, 0, 1); } @Test public void testGetLongs() { PacketContainer updateTime = new PacketContainer(PacketType.Play.Server.UPDATE_TIME); - testPrimitive(updateTime.getLongs(), 0, (long)0, (long)1); + this.testPrimitive(updateTime.getLongs(), 0, (long) 0, (long) 1); } @Test public void testGetFloat() { PacketContainer explosion = new PacketContainer(PacketType.Play.Server.EXPLOSION); - testPrimitive(explosion.getFloat(), 0, (float)0, (float)0.8); + this.testPrimitive(explosion.getFloat(), 0, (float) 0, (float) 0.8); } @Test public void testGetDoubles() { PacketContainer explosion = new PacketContainer(PacketType.Play.Server.EXPLOSION); - testPrimitive(explosion.getDoubles(), 0, (double)0, 0.8); + this.testPrimitive(explosion.getDoubles(), 0, (double) 0, 0.8); } @Test public void testGetStrings() { PacketContainer explosion = new PacketContainer(PacketType.Play.Client.CHAT); - testPrimitive(explosion.getStrings(), 0, "", "hello"); + this.testPrimitive(explosion.getStrings(), 0, "", "hello"); } @Test public void testGetStringArrays() { PacketContainer packet = new PacketContainer(PacketType.Play.Client.UPDATE_SIGN); - testObjectArray(packet.getStringArrays(), 0, - new String[] { "", "", "", "" }, - new String[] { "hello", "world" } + this.testObjectArray(packet.getStringArrays(), 0, + new String[]{"", "", "", ""}, + new String[]{"hello", "world"} ); } @@ -193,7 +208,7 @@ public class PacketContainerTest { // Contains a byte array we will test PacketContainer packet = new PacketContainer(PacketType.Play.Server.MOUNT); StructureModifier integers = packet.getIntegerArrays(); - int[] testArray = new int[] { 1, 2, 3 }; + int[] testArray = new int[]{1, 2, 3}; assertArrayEquals(new int[0], integers.read(0)); @@ -205,14 +220,14 @@ public class PacketContainerTest { public void testGetItemModifier() { PacketContainer windowClick = new PacketContainer(PacketType.Play.Client.WINDOW_CLICK); - ItemStack item = itemWithData(); + ItemStack item = this.itemWithData(); StructureModifier items = windowClick.getItemModifier(); // assertNull(items.read(0)); // Insert the item and check if it's there items.write(0, item); - assertTrue("Item " + item + " != " + items.read(0), equivalentItem(item, items.read(0))); + assertTrue(equivalentItem(item, items.read(0)), "Item " + item + " != " + items.read(0)); } private ItemStack itemWithData() { @@ -230,7 +245,7 @@ public class PacketContainerTest { StructureModifier> itemAccess = windowItems.getItemListModifier(); List items = new ArrayList<>(); - items.add(itemWithData()); + items.add(this.itemWithData()); items.add(new ItemStack(Material.DIAMOND_AXE)); assertEquals(itemAccess.read(0).size(), 0); @@ -246,8 +261,9 @@ public class PacketContainerTest { @Test public void testGetWorldTypeModifier() { // Not used in Netty - if (MinecraftReflection.isUsingNetty()) + if (MinecraftReflection.isUsingNetty()) { return; + } PacketContainer loginPacket = new PacketContainer(PacketType.Play.Server.LOGIN); StructureModifier worldAccess = loginPacket.getWorldTypeModifier(); @@ -358,7 +374,8 @@ public class PacketContainerTest { @Test public void testGameProfiles() { PacketContainer spawnEntity = new PacketContainer(PacketType.Login.Server.SUCCESS); - WrappedGameProfile profile = new WrappedGameProfile(UUID.fromString("d7047a08-3150-4aa8-a2f2-7c1e2b17e298"), "name"); + WrappedGameProfile profile = new WrappedGameProfile(UUID.fromString("d7047a08-3150-4aa8-a2f2-7c1e2b17e298"), + "name"); spawnEntity.getGameProfiles().write(0, profile); assertEquals(profile, spawnEntity.getGameProfiles().read(0)); @@ -371,7 +388,7 @@ public class PacketContainerTest { WrappedChatComponent.fromChatMessage("You shall not " + ChatColor.ITALIC + "pass!")[0]); assertEquals("{\"extra\":[{\"text\":\"You shall not \"},{\"italic\":true,\"text\":\"pass!\"}],\"text\":\"\"}", - chatPacket.getChatComponents().read(0).getJson()); + chatPacket.getChatComponents().read(0).getJson()); } @Test @@ -389,8 +406,8 @@ public class PacketContainerTest { public void testIntList() { PacketContainer destroy = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY); destroy.getIntLists().write(0, new ArrayList() {{ - add(420); - add(69); + this.add(420); + this.add(69); }}); List back = destroy.getIntLists().read(0); assertEquals(back.size(), 2); @@ -405,7 +422,8 @@ public class PacketContainerTest { // Initialize some test data List modifiers = Lists.newArrayList( - new AttributeModifier(UUID.randomUUID(), "Unknown synced attribute modifier", 10, AttributeModifier.Operation.a)); + new AttributeModifier(UUID.randomUUID(), "Unknown synced attribute modifier", 10, + AttributeModifier.Operation.a)); // Obtain an AttributeSnapshot instance. This is complicated by the fact that AttributeSnapshots // are inner classes (which is ultimately pointless because AttributeSnapshots don't access any @@ -428,7 +446,7 @@ public class PacketContainerTest { } field.setAccessible(true); - testEquality(field.get(snapshot), field.get(clonedSnapshot)); + this.testEquality(field.get(snapshot), field.get(clonedSnapshot)); } catch (AssertionError e) { throw e; } catch (Throwable ex) { @@ -461,13 +479,14 @@ public class PacketContainerTest { @SuppressWarnings("deprecation") public void testPotionEffect() { PotionEffect effect = new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 20 * 60, 1); - MobEffect mobEffect = new MobEffect(MobEffectList.a(effect.getType().getId()), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), + MobEffect mobEffect = new MobEffect(MobEffectList.a(effect.getType().getId()), effect.getDuration(), + effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()); int entityId = 42; - + // The constructor we want to call PacketConstructor creator = PacketConstructor.DEFAULT.withPacket( - PacketType.Play.Server.ENTITY_EFFECT, new Class[] { int.class, MobEffect.class }); + PacketType.Play.Server.ENTITY_EFFECT, new Class[]{int.class, MobEffect.class}); PacketContainer packet = creator.createPacket(entityId, mobEffect); assertEquals(entityId, (int) packet.getIntegers().read(0)); @@ -476,9 +495,15 @@ public class PacketContainerTest { assertEquals(effect.getDuration(), (int) packet.getIntegers().read(1)); int e = 0; - if (effect.isAmbient()) e |= 1; - if (effect.hasParticles()) e |= 2; - if (effect.hasIcon()) e |= 4; + if (effect.isAmbient()) { + e |= 1; + } + if (effect.hasParticles()) { + e |= 2; + } + if (effect.hasIcon()) { + e |= 4; + } assertEquals(e, (byte) packet.getBytes().read(2)); } @@ -540,7 +565,7 @@ public class PacketContainerTest { optStruct = container.getOptionalStructures().read(0); assertTrue(optStruct.isPresent()); struct = optStruct.get(); - testEquality( + this.testEquality( struct.getChatComponents().read(0), WrappedChatComponent.fromText("hi there") ); @@ -591,14 +616,14 @@ public class PacketContainerTest { public void testMultiBlockChange() { PacketContainer packet = new PacketContainer(PacketType.Play.Server.MULTI_BLOCK_CHANGE); - packet.getShortArrays().writeSafely(0, new short[] { 420, 69 }); - assertArrayEquals(new short[] { 420, 69}, packet.getShortArrays().readSafely(0)); + packet.getShortArrays().writeSafely(0, new short[]{420, 69}); + assertArrayEquals(new short[]{420, 69}, packet.getShortArrays().readSafely(0)); - packet.getBlockDataArrays().writeSafely(0, new WrappedBlockData[] { + packet.getBlockDataArrays().writeSafely(0, new WrappedBlockData[]{ WrappedBlockData.createData(Material.IRON_BARS), WrappedBlockData.createData(Material.IRON_BLOCK) }); - assertArrayEquals(new WrappedBlockData[] { + assertArrayEquals(new WrappedBlockData[]{ WrappedBlockData.createData(Material.IRON_BARS), WrappedBlockData.createData(Material.IRON_BLOCK) }, packet.getBlockDataArrays().readSafely(0)); @@ -613,9 +638,10 @@ public class PacketContainerTest { @Test public void testGameStateChange() { PacketContainer packet = new PacketContainer(PacketType.Play.Server.GAME_STATE_CHANGE); - assertTrue(packet.getGameStateIDs().read(0) == 0); + assertEquals(0, (int) packet.getGameStateIDs().read(0)); + packet.getGameStateIDs().write(0, 2); - assertTrue(packet.getGameStateIDs().read(0) == 2); + assertEquals(2, (int) packet.getGameStateIDs().read(0)); } @Test @@ -679,23 +705,10 @@ public class PacketContainerTest { assertTrue(container.getStructures().read(0).getNbtModifier().optionRead(0).isPresent()); } - /** - * Actions from the outbound Boss packet. Used for testing generic enums. - * @author dmulloy2 - */ - public enum Action { - ADD, - REMOVE, - UPDATE_PCT, - UPDATE_NAME, - UPDATE_STYLE, - UPDATE_PROPERTIES - } - @Test public void testComponentArrays() { PacketContainer signChange = new PacketContainer(PacketType.Play.Server.TILE_ENTITY_DATA); - WrappedChatComponent[] components = new WrappedChatComponent[] { + WrappedChatComponent[] components = new WrappedChatComponent[]{ WrappedChatComponent.fromText("hello world"), WrappedChatComponent.fromText(""), WrappedChatComponent.fromText(""), WrappedChatComponent.fromText("") }; @@ -714,10 +727,11 @@ public class PacketContainerTest { } else { // Make sure all the fields are equivalent for (int i = 0; i < firstMod.size(); i++) { - if (firstMod.getField(i).getType().isArray()) - assertArrayEquals(getArray(firstMod.read(i)), getArray(secondMod.read(i))); - else - testEquality(firstMod.read(i), secondMod.read(i)); + if (firstMod.getField(i).getType().isArray()) { + assertArrayEquals(this.getArray(firstMod.read(i)), this.getArray(secondMod.read(i))); + } else { + this.testEquality(firstMod.read(i), secondMod.read(i)); + } } } } @@ -728,8 +742,9 @@ public class PacketContainerTest { // Try constructing all the packets for (PacketType type : PacketType.values()) { - if (type.isDeprecated() || type.name().contains("CUSTOM_PAYLOAD") || type.name().contains("TAGS") || !type.isSupported() - || type == PacketType.Play.Server.RECIPES) { + if (type.isDeprecated() || type.name().contains("CUSTOM_PAYLOAD") || type.name().contains("TAGS") + || !type.isSupported() + || type == PacketType.Play.Server.RECIPES) { continue; } @@ -748,9 +763,9 @@ public class PacketContainerTest { "String"), new WrappedWatchableObject(new WrappedDataWatcherObject(0, Registry.get(Float.class)), 1.0F), new WrappedWatchableObject(new WrappedDataWatcherObject(0, Registry.getChatComponentSerializer(true)), - Optional.of(ComponentConverter.fromBaseComponent(TEST_COMPONENT).getHandle())), + Optional.of(ComponentConverter.fromBaseComponent(TEST_COMPONENT).getHandle())), new WrappedWatchableObject(new WrappedDataWatcherObject(0, Registry.get(VillagerData.class)), - new VillagerData(VillagerType.b, VillagerProfession.c, 69)) + new VillagerData(VillagerType.b, VillagerProfession.c, 69)) )); } else if (type == PacketType.Play.Server.CHAT) { constructed.getChatComponents().write(0, ComponentConverter.fromBaseComponent(TEST_COMPONENT)); @@ -759,17 +774,17 @@ public class PacketContainerTest { // Clone the packet both ways PacketContainer shallowCloned = constructed.shallowClone(); - assertPacketsEqual(constructed, shallowCloned); + this.assertPacketsEqual(constructed, shallowCloned); PacketContainer deepCloned = constructed.deepClone(); - assertPacketsEqual(constructed, deepCloned); + this.assertPacketsEqual(constructed, deepCloned); } catch (Exception ex) { ex.printStackTrace(); failed = true; } } - assertFalse("Packet(s) failed to clone", failed); + assertFalse(failed, "Packet(s) failed to clone"); } // Convert to objects that support equals() @@ -786,26 +801,26 @@ public class PacketContainerTest { if (a instanceof Optional) { if (b instanceof Optional) { - testEquality(((Optional) a).orElse(null), ((Optional) b).orElse(null)); + this.testEquality(((Optional) a).orElse(null), ((Optional) b).orElse(null)); return; } else { throw new AssertionError("a was optional, but b was not"); } } - if (a.equals(b) || Objects.equals(a, b) || stringEquality(a, b)) { + if (a.equals(b) || Objects.equals(a, b) || this.stringEquality(a, b)) { return; } if (MinecraftReflection.isDataWatcher(a)) { - a = watchConvert.getSpecific(a); - b = watchConvert.getSpecific(b); + a = this.watchConvert.getSpecific(a); + b = this.watchConvert.getSpecific(b); } else if (MinecraftReflection.isItemStack(a)) { - a = itemConvert.getSpecific(a); - b = itemConvert.getSpecific(b); + a = this.itemConvert.getSpecific(a); + b = this.itemConvert.getSpecific(b); } - if (a instanceof ItemStack || b instanceof ItemStack) { + if (a instanceof ItemStack && b instanceof ItemStack) { assertItemsEqual((ItemStack) a, (ItemStack) b); return; } @@ -828,20 +843,38 @@ public class PacketContainerTest { /** * Get the underlying array as an object array. + * * @param val - array wrapped as an Object. * @return An object array. */ private Object[] getArray(Object val) { - if (val instanceof Object[]) + if (val instanceof Object[]) { return (Object[]) val; - if (val == null) + } + if (val == null) { return null; + } int arrlength = Array.getLength(val); Object[] outputArray = new Object[arrlength]; - for (int i = 0; i < arrlength; ++i) + for (int i = 0; i < arrlength; ++i) { outputArray[i] = Array.get(val, i); + } return outputArray; } + + /** + * Actions from the outbound Boss packet. Used for testing generic enums. + * + * @author dmulloy2 + */ + public enum Action { + ADD, + REMOVE, + UPDATE_PCT, + UPDATE_NAME, + UPDATE_STYLE, + UPDATE_PROPERTIES + } } diff --git a/src/test/java/com/comphenix/protocol/events/SerializedOfflinePlayerTest.java b/src/test/java/com/comphenix/protocol/events/SerializedOfflinePlayerTest.java index eabf8383..ff75e102 100644 --- a/src/test/java/com/comphenix/protocol/events/SerializedOfflinePlayerTest.java +++ b/src/test/java/com/comphenix/protocol/events/SerializedOfflinePlayerTest.java @@ -1,72 +1,70 @@ package com.comphenix.protocol.events; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +import java.util.UUID; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.UUID; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.when; - public class SerializedOfflinePlayerTest { - @Mock - static OfflinePlayer offlinePlayer; + private static final String name = "playerName"; + private static final long firstPlayed = 1000L; + private static final long lastPlayed = firstPlayed + 100L; + private static final boolean isOp = false; + private static final boolean playedBefore = true; + private static final boolean whitelisted = true; + @Mock + static OfflinePlayer offlinePlayer; + private static UUID uuid; + private static SerializedOfflinePlayer serializedOfflinePlayer; - private static final String name = "playerName"; - private static UUID uuid; - private static final long firstPlayed = 1000L; - private static final long lastPlayed = firstPlayed + 100L; - private static final boolean isOp = false; - private static final boolean playedBefore = true; - private static final boolean whitelisted = true; + @BeforeEach + public void initMocks() { + MockitoAnnotations.openMocks(this); - private static SerializedOfflinePlayer serializedOfflinePlayer; + uuid = UUID.randomUUID(); + when(offlinePlayer.getName()).thenReturn(name); + when(offlinePlayer.getUniqueId()).thenReturn(uuid); + when(offlinePlayer.getFirstPlayed()).thenReturn(firstPlayed); + when(offlinePlayer.getLastPlayed()).thenReturn(lastPlayed); + when(offlinePlayer.isOp()).thenReturn(isOp); + when(offlinePlayer.hasPlayedBefore()).thenReturn(playedBefore); + when(offlinePlayer.isWhitelisted()).thenReturn(whitelisted); - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); + serializedOfflinePlayer = new SerializedOfflinePlayer(offlinePlayer); + } - uuid = UUID.randomUUID(); - when(offlinePlayer.getName()).thenReturn(name); - when(offlinePlayer.getUniqueId()).thenReturn(uuid); - when(offlinePlayer.getFirstPlayed()).thenReturn(firstPlayed); - when(offlinePlayer.getLastPlayed()).thenReturn(lastPlayed); - when(offlinePlayer.isOp()).thenReturn(isOp); - when(offlinePlayer.hasPlayedBefore()).thenReturn(playedBefore); - when(offlinePlayer.isWhitelisted()).thenReturn(whitelisted); + @Test + public void getProxyPlayer() { + Player player = serializedOfflinePlayer.getProxyPlayer(); + assertNotNull(player); - serializedOfflinePlayer = new SerializedOfflinePlayer(offlinePlayer); - } + // getDisplayName only works for online players. + assertThrows(UnsupportedOperationException.class, player::getDisplayName); - @Test - public void getProxyPlayer() { - Player player = serializedOfflinePlayer.getProxyPlayer(); - Assert.assertNotNull(player); + assertEquals(uuid, player.getUniqueId()); + assertEquals(name, player.getName()); + assertEquals(firstPlayed, player.getFirstPlayed()); + assertEquals(lastPlayed, player.getLastPlayed()); + assertEquals(isOp, player.isOp()); + assertEquals(playedBefore, player.hasPlayedBefore()); + assertEquals(whitelisted, player.isWhitelisted()); + } - // getDisplayName only works for online players. - assertThrows(UnsupportedOperationException.class, player::getDisplayName); + @Test + public void getSecondProxyPlayer() { + // Make sure that the proxyPlayer generation doesn't work only once. + Player player = serializedOfflinePlayer.getProxyPlayer(); + assertNotNull(player); - assertEquals(uuid, player.getUniqueId()); - assertEquals(name, player.getName()); - assertEquals(firstPlayed, player.getFirstPlayed()); - assertEquals(lastPlayed, player.getLastPlayed()); - assertEquals(isOp, player.isOp()); - assertEquals(playedBefore, player.hasPlayedBefore()); - assertEquals(whitelisted, player.isWhitelisted()); - } - - @Test - public void getSecondProxyPlayer() { - // Make sure that the proxyPlayer generation doesn't work only once. - Player player = serializedOfflinePlayer.getProxyPlayer(); - Assert.assertNotNull(player); - - assertEquals(uuid, player.getUniqueId()); - } + assertEquals(uuid, player.getUniqueId()); + } } diff --git a/src/test/java/com/comphenix/protocol/injector/EntityUtilitiesTest.java b/src/test/java/com/comphenix/protocol/injector/EntityUtilitiesTest.java index 495f4995..e5d48e80 100644 --- a/src/test/java/com/comphenix/protocol/injector/EntityUtilitiesTest.java +++ b/src/test/java/com/comphenix/protocol/injector/EntityUtilitiesTest.java @@ -1,45 +1,35 @@ package com.comphenix.protocol.injector; -import com.comphenix.protocol.BukkitInitialization; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.reflect.FieldUtils; -import com.comphenix.protocol.reflect.FuzzyReflection; -import com.comphenix.protocol.reflect.StructureModifier; -import com.comphenix.protocol.reflect.accessors.Accessors; +import static com.comphenix.protocol.utility.TestUtils.setFinalField; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import com.comphenix.protocol.reflect.accessors.FieldAccessor; +import com.comphenix.protocol.BukkitInitialization; +import com.comphenix.protocol.reflect.FuzzyReflection; import com.comphenix.protocol.reflect.fuzzy.FuzzyFieldContract; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import java.lang.reflect.Field; import net.minecraft.server.level.ChunkProviderServer; -import net.minecraft.server.level.EntityTrackerEntry; import net.minecraft.server.level.PlayerChunkMap; import net.minecraft.server.level.PlayerChunkMap.EntityTracker; import net.minecraft.server.level.WorldServer; import net.minecraft.world.entity.Entity; - import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R1.entity.CraftEntity; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.lang.reflect.Field; - -import static com.comphenix.protocol.utility.TestUtils.setFinalField; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class EntityUtilitiesTest { - @BeforeClass + @BeforeAll public static void beforeClass() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } @Test - public void testReflection() throws ReflectiveOperationException { + public void testReflection() { CraftWorld bukkit = mock(CraftWorld.class); WorldServer world = mock(WorldServer.class); when(bukkit.getHandle()).thenReturn(world); diff --git a/src/test/java/com/comphenix/protocol/injector/PluginVerifierTest.java b/src/test/java/com/comphenix/protocol/injector/PluginVerifierTest.java index b730cb8e..652df338 100644 --- a/src/test/java/com/comphenix/protocol/injector/PluginVerifierTest.java +++ b/src/test/java/com/comphenix/protocol/injector/PluginVerifierTest.java @@ -1,53 +1,46 @@ package com.comphenix.protocol.injector; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.comphenix.protocol.injector.PluginVerifier.VerificationResult; +import com.google.common.base.Objects; +import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; - import org.bukkit.Server; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginLoadOrder; import org.bukkit.plugin.PluginManager; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; - -import com.comphenix.protocol.injector.PluginVerifier.VerificationResult; -import com.google.common.base.Objects; -import com.google.common.collect.Lists; // Damn final classes -@RunWith(org.powermock.modules.junit4.PowerMockRunner.class) -@PowerMockIgnore({ "org.apache.logging.log4j.core.config.xml.*", "javax.management.*" }) -@PrepareForTest(PluginDescriptionFile.class) public class PluginVerifierTest { + @Test public void testDependecies() { List plugins = Lists.newArrayList(); - Server server = mockServer(plugins); - - Plugin library = mockPlugin(server, "ProtocolLib", PluginLoadOrder.POSTWORLD); - Plugin skillPlugin = mockPlugin(server, "SkillPlugin", "RaidCraft-API", "RCPermissions", "RCConversations"); - Plugin raidCraftAPI = mockPlugin(server, "RaidCraft-API", "WorldGuard", "WorldEdit"); - Plugin conversations = mockPlugin(server, "RCConversations", "RaidCraft-API"); - Plugin permissions = mockPlugin(server, "RCPermissions", "RaidCraft-API"); - + Server server = this.mockServer(plugins); + + Plugin library = this.mockPlugin(server, "ProtocolLib", PluginLoadOrder.POSTWORLD); + Plugin skillPlugin = this.mockPlugin(server, "SkillPlugin", "RaidCraft-API", "RCPermissions", "RCConversations"); + Plugin raidCraftAPI = this.mockPlugin(server, "RaidCraft-API", "WorldGuard", "WorldEdit"); + Plugin conversations = this.mockPlugin(server, "RCConversations", "RaidCraft-API"); + Plugin permissions = this.mockPlugin(server, "RCPermissions", "RaidCraft-API"); + // Add the plugins plugins.addAll(Arrays.asList(library, skillPlugin, raidCraftAPI, conversations, permissions)); PluginVerifier verifier = new PluginVerifier(library); - + // Verify the root - it should have no dependencies on ProtocolLib assertEquals(VerificationResult.NO_DEPEND, verifier.verify(skillPlugin)); } - + private Server mockServer(final List plugins) { Server mockServer = mock(Server.class); PluginManager manager = mock(PluginManager.class); @@ -57,7 +50,7 @@ public class PluginVerifierTest { @Override public Plugin answer(InvocationOnMock invocation) throws Throwable { String name = (String) invocation.getArguments()[0]; - + for (Plugin plugin : plugins) { if (Objects.equal(name, plugin.getName())) { return plugin; @@ -68,20 +61,20 @@ public class PluginVerifierTest { }); return mockServer; } - - private Plugin mockPlugin(Server server, String name,String... depend) { - return mockPlugin(server, name, PluginLoadOrder.POSTWORLD, depend); + + private Plugin mockPlugin(Server server, String name, String... depend) { + return this.mockPlugin(server, name, PluginLoadOrder.POSTWORLD, depend); } - + private Plugin mockPlugin(Server server, String name, PluginLoadOrder order, String... depend) { Plugin plugin = mock(Plugin.class); PluginDescriptionFile file = mock(PluginDescriptionFile.class); - + when(plugin.getServer()).thenReturn(server); when(plugin.getName()).thenReturn(name); when(plugin.toString()).thenReturn(name); when(plugin.getDescription()).thenReturn(file); - + // This is the difficult part when(file.getLoad()).thenReturn(order); when(file.getDepend()).thenReturn(Arrays.asList(depend)); diff --git a/src/test/java/com/comphenix/protocol/injector/SortedCopyOnWriteArrayTest.java b/src/test/java/com/comphenix/protocol/injector/SortedCopyOnWriteArrayTest.java index 783f4008..ee66680e 100644 --- a/src/test/java/com/comphenix/protocol/injector/SortedCopyOnWriteArrayTest.java +++ b/src/test/java/com/comphenix/protocol/injector/SortedCopyOnWriteArrayTest.java @@ -2,85 +2,84 @@ * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * You should have received a copy of the GNU General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ package com.comphenix.protocol.injector; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import com.comphenix.protocol.concurrency.SortedCopyOnWriteArray; import com.comphenix.protocol.events.ListenerPriority; import com.google.common.primitives.Ints; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; public class SortedCopyOnWriteArrayTest { + @Test public void testInsertion() { - final int MAX_NUMBER = 50; SortedCopyOnWriteArray test = new SortedCopyOnWriteArray(); - + // Generate some numbers List numbers = new ArrayList(); - + for (int i = 0; i < MAX_NUMBER; i++) { numbers.add(i); } - + // Random insertion to test it all Collections.shuffle(numbers); - + // O(n^2) of course, so don't use too large numbers for (int i = 0; i < MAX_NUMBER; i++) { test.add(numbers.get(i)); } - + // Check that everything is correct for (int i = 0; i < MAX_NUMBER; i++) { assertEquals((Integer) i, test.get(i)); } } - + @Test public void testOrder() { PriorityStuff a = new PriorityStuff(ListenerPriority.HIGH, 1); PriorityStuff b = new PriorityStuff(ListenerPriority.NORMAL, 2); PriorityStuff c = new PriorityStuff(ListenerPriority.NORMAL, 3); SortedCopyOnWriteArray test = new SortedCopyOnWriteArray(); - + test.add(a); test.add(b); test.add(c); - + // Make sure the normal's are in the right order assertEquals(2, test.get(0).id); assertEquals(3, test.get(1).id); - + // Test remove test.remove(b); assertEquals(2, test.size()); assertFalse(test.contains(b)); } - + private static class PriorityStuff implements Comparable { + public ListenerPriority priority; public int id; @@ -92,8 +91,8 @@ public class SortedCopyOnWriteArrayTest { @Override public int compareTo(PriorityStuff other) { // This ensures that lower priority listeners are executed first - return Ints.compare(priority.getSlot(), - other.priority.getSlot()); + return Ints.compare(this.priority.getSlot(), + other.priority.getSlot()); } } } diff --git a/src/test/java/com/comphenix/protocol/injector/WirePacketTest.java b/src/test/java/com/comphenix/protocol/injector/WirePacketTest.java index 4de997f2..e660fd5d 100644 --- a/src/test/java/com/comphenix/protocol/injector/WirePacketTest.java +++ b/src/test/java/com/comphenix/protocol/injector/WirePacketTest.java @@ -3,32 +3,27 @@ */ package com.comphenix.protocol.injector; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.injector.netty.WirePacket; -import com.comphenix.protocol.wrappers.EnumWrappers.ChatType; - import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author dmulloy2 */ public class WirePacketTest { - - @BeforeClass + + @BeforeAll public static void beforeClass() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } // @Test @@ -36,8 +31,9 @@ public class WirePacketTest { List failures = new ArrayList<>(); for (PacketType type : PacketType.values()) { - if (type.isDeprecated()) + if (type.isDeprecated()) { continue; + } try { PacketContainer packet = new PacketContainer(type); @@ -57,7 +53,7 @@ public class WirePacketTest { @Test public void testSerialization() { int id = 42; - byte[] array = { 1, 3, 7, 21, 88, 67, 8 }; + byte[] array = {1, 3, 7, 21, 88, 67, 8}; WirePacket packet = new WirePacket(id, array); diff --git a/src/test/java/com/comphenix/protocol/injector/server/TemporaryPlayerFactoryTest.java b/src/test/java/com/comphenix/protocol/injector/server/TemporaryPlayerFactoryTest.java index 8fe0db80..cc336c8f 100644 --- a/src/test/java/com/comphenix/protocol/injector/server/TemporaryPlayerFactoryTest.java +++ b/src/test/java/com/comphenix/protocol/injector/server/TemporaryPlayerFactoryTest.java @@ -1,42 +1,42 @@ package com.comphenix.protocol.injector.server; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.bukkit.Server; import org.bukkit.entity.Player; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.junit.Assert.*; - public class TemporaryPlayerFactoryTest { - private static final TemporaryPlayerFactory temporaryPlayerFactory = new TemporaryPlayerFactory(); + private static final TemporaryPlayerFactory temporaryPlayerFactory = new TemporaryPlayerFactory(); - @Mock - Server server; - @Mock - SocketInjector socketInjector; + @Mock + Server server; + @Mock + SocketInjector socketInjector; - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } + @BeforeEach + public void initMocks() { + MockitoAnnotations.openMocks(this); + } - @Test - public void testUnavailableSocketInjector() - { - Player player = temporaryPlayerFactory.createTemporaryPlayer(server); - assertThrows(IllegalStateException.class, player::getPlayer); - } + @Test + public void testUnavailableSocketInjector() { + Player player = temporaryPlayerFactory.createTemporaryPlayer(this.server); + assertThrows(IllegalStateException.class, player::getPlayer); + } - @Test - public void createTemporaryPlayer() { + @Test + public void createTemporaryPlayer() { - Player player = temporaryPlayerFactory.createTemporaryPlayer(server, socketInjector); - assertEquals(server, player.getServer()); + Player player = temporaryPlayerFactory.createTemporaryPlayer(this.server, this.socketInjector); + assertEquals(this.server, player.getServer()); - // May seem dumb, but this makes sure that the .equals method is still instact. - assertEquals(player, player); - } + // May seem dumb, but this makes sure that the .equals method is still instact. + assertEquals(player, player); + } } diff --git a/src/test/java/com/comphenix/protocol/reflect/accessors/AccessorsTest.java b/src/test/java/com/comphenix/protocol/reflect/accessors/AccessorsTest.java index aec4fe38..d8cc176c 100644 --- a/src/test/java/com/comphenix/protocol/reflect/accessors/AccessorsTest.java +++ b/src/test/java/com/comphenix/protocol/reflect/accessors/AccessorsTest.java @@ -1,52 +1,21 @@ package com.comphenix.protocol.reflect.accessors; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AccessorsTest { - // --- Some classes we can use for testing --- - private static class Entity { - private int id; - - public Entity(int id) { - this.id = id; - } - public int getId() { - return id; - } - - @SuppressWarnings("unused") - private void setId(int value) { - this.id = value; - } - } - - private static class Player extends Entity { - private String name; - - public Player(int id, String name) { - super(id); - this.name = name; - } - - public String getName() { - return name; - } - } - // --- Test classes --- - @Test public void testField() { Player player = new Player(123, "ABC"); - + Accessors.getFieldAccessor(player.getClass(), "id", true).set(player, 0); Accessors.getFieldAccessor(player.getClass(), "name", true).set(player, "MODIFIED"); assertEquals(0, player.getId()); assertEquals("MODIFIED", player.getName()); } - + @Test public void testMethod() { Player player = new Player(123, "ABC"); @@ -54,4 +23,37 @@ public class AccessorsTest { Accessors.getMethodAccessor(player.getClass(), "setId", int.class).invoke(player, 0); assertEquals(0, player.getId()); } + + // --- Some classes we can use for testing --- + private static class Entity { + + private int id; + + public Entity(int id) { + this.id = id; + } + + public int getId() { + return this.id; + } + + @SuppressWarnings("unused") + private void setId(int value) { + this.id = value; + } + } + + private static class Player extends Entity { + + private final String name; + + public Player(int id, String name) { + super(id); + this.name = name; + } + + public String getName() { + return this.name; + } + } } diff --git a/src/test/java/com/comphenix/protocol/reflect/cloning/AggregateClonerTest.java b/src/test/java/com/comphenix/protocol/reflect/cloning/AggregateClonerTest.java index ca10131f..9c541c8b 100644 --- a/src/test/java/com/comphenix/protocol/reflect/cloning/AggregateClonerTest.java +++ b/src/test/java/com/comphenix/protocol/reflect/cloning/AggregateClonerTest.java @@ -1,31 +1,27 @@ package com.comphenix.protocol.reflect.cloning; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.List; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; - +import java.util.Arrays; +import java.util.List; import net.minecraft.core.NonNullList; import net.minecraft.world.item.ItemStack; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class AggregateClonerTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } - + @Test - public void testArrays() { + public void testArrays() { List input = Arrays.asList(1, 2, 3); assertEquals(input, AggregateCloner.DEFAULT.clone(input)); } @@ -44,6 +40,6 @@ public class AggregateClonerTest { NonNullList list1 = (NonNullList) cloned.getModifier().read(1); assertEquals(list.size(), list1.size()); - assertArrayEquals(list.toArray(), list1.toArray()); + Assertions.assertArrayEquals(list.toArray(), list1.toArray()); } } diff --git a/src/test/java/com/comphenix/protocol/updater/UpdaterTest.java b/src/test/java/com/comphenix/protocol/updater/UpdaterTest.java index cd6b2ffc..54b38756 100644 --- a/src/test/java/com/comphenix/protocol/updater/UpdaterTest.java +++ b/src/test/java/com/comphenix/protocol/updater/UpdaterTest.java @@ -3,46 +3,47 @@ */ package com.comphenix.protocol.updater; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.comphenix.protocol.updater.Updater.UpdateType; import java.util.logging.Logger; - import org.bukkit.Server; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; -import org.junit.BeforeClass; -import org.junit.Test; - -import com.comphenix.protocol.updater.Updater.UpdateType; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author dmulloy2 */ - public class UpdaterTest { + private static final int BUKKIT_DEV_ID = 45564; private static Plugin plugin; - // @BeforeClass + @BeforeAll public static void preparePlugin() { Server server = mock(Server.class); when(server.getUpdateFolder()).thenReturn(null); plugin = mock(Plugin.class); String version = System.getProperty("projectVersion"); - if (version == null) version = "4.4.0"; + if (version == null) { + version = "4.4.0"; + } when(plugin.getDescription()).thenReturn(new PluginDescriptionFile("ProtocolLib", version, null)); when(plugin.getLogger()).thenReturn(Logger.getLogger("ProtocolLib")); when(plugin.getDataFolder()).thenReturn(null); when(plugin.getServer()).thenReturn(server); } - - // @Test + + @Test public void testUpdaterType() { - assertEquals(Updater.create(plugin, BUKKIT_DEV_ID, null, UpdateType.NO_DOWNLOAD, true).getClass(), SpigotUpdater.class); + assertEquals(Updater.create(plugin, BUKKIT_DEV_ID, null, UpdateType.NO_DOWNLOAD, true).getClass(), + SpigotUpdater.class); } // @Test @@ -54,23 +55,10 @@ public class UpdaterTest { try { remote = updater.getSpigotVersion(); } catch (Throwable ex) { - ex.printStackTrace(); - fail("Failed to check for updates"); + fail("Failed to check for updates", ex); } System.out.println("Determined remote Spigot version: " + remote); System.out.println("Update available: " + updater.versionCheck(remote)); } - - // @Test - public void testBukkitUpdater() { - BukkitUpdater updater = new BukkitUpdater(plugin, BUKKIT_DEV_ID, null, UpdateType.NO_DOWNLOAD, true); - if (! updater.read()) { - fail("Failed to check for updates"); - } - - String remote = updater.getLatestName(); - System.out.println("Determined remote Bukkit Dev version: " + remote); - System.out.println("Update available: " + updater.versionCheck(remote)); - } } diff --git a/src/test/java/com/comphenix/protocol/utility/MinecraftMethodsTest.java b/src/test/java/com/comphenix/protocol/utility/MinecraftMethodsTest.java index c37cd456..c65bbe74 100644 --- a/src/test/java/com/comphenix/protocol/utility/MinecraftMethodsTest.java +++ b/src/test/java/com/comphenix/protocol/utility/MinecraftMethodsTest.java @@ -1,19 +1,17 @@ package com.comphenix.protocol.utility; -import static org.junit.Assert.assertNotNull; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.comphenix.protocol.BukkitInitialization; - import java.lang.reflect.Field; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class MinecraftMethodsTest { - @BeforeClass + @BeforeAll public static void initializeReflection() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } @Test @@ -30,8 +28,8 @@ public class MinecraftMethodsTest { @Test public void initializePacket() throws NoSuchFieldException, IllegalAccessException { - setNull("packetReadByteBuf"); - setNull("packetWriteByteBuf"); + this.setNull("packetReadByteBuf"); + this.setNull("packetWriteByteBuf"); assertNotNull(MinecraftMethods.getPacketWriteByteBufMethod()); // TODO it's now a constructor diff --git a/src/test/java/com/comphenix/protocol/utility/MinecraftReflectionTest.java b/src/test/java/com/comphenix/protocol/utility/MinecraftReflectionTest.java index 81dcf41e..3b953576 100644 --- a/src/test/java/com/comphenix/protocol/utility/MinecraftReflectionTest.java +++ b/src/test/java/com/comphenix/protocol/utility/MinecraftReflectionTest.java @@ -1,25 +1,16 @@ package com.comphenix.protocol.utility; import static com.comphenix.protocol.utility.TestUtils.assertItemsEqual; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemStack; -import org.bukkit.entity.Entity; -import org.bukkit.inventory.ItemStack; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; - import com.comphenix.protocol.BukkitInitialization; import com.mojang.authlib.GameProfile; - import net.minecraft.nbt.NBTCompressedStreamTools; import net.minecraft.network.chat.ChatComponentText; import net.minecraft.network.chat.IChatBaseComponent; @@ -29,26 +20,23 @@ import net.minecraft.network.syncher.DataWatcher; import net.minecraft.server.network.PlayerConnection; import net.minecraft.world.level.ChunkCoordIntPair; import net.minecraft.world.level.block.state.IBlockData; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemStack; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -@RunWith(org.powermock.modules.junit4.PowerMockRunner.class) -@PowerMockIgnore({ "org.apache.logging.log4j.core.config.xml.*", "javax.management.*" }) public class MinecraftReflectionTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } - // Mocking objects - private interface FakeEntity { - Entity getBukkitEntity(); - } - - private interface FakeBlock { - Block getBukkitEntity(); - } - - @AfterClass + @AfterAll public static void undoMocking() { // NOP MinecraftReflection.minecraftPackage = null; @@ -66,9 +54,9 @@ public class MinecraftReflectionTest { verify(block, times(1)).getBukkitEntity(); } - @Test(expected = IllegalArgumentException.class) + @Test public void testIllegalClass() { - MinecraftReflection.getBukkitEntity("Hello"); + assertThrows(IllegalArgumentException.class, () -> MinecraftReflection.getBukkitEntity("Hello")); } @Test @@ -78,7 +66,8 @@ public class MinecraftReflectionTest { @Test public void testAttributeSnapshot() { - assertEquals(PacketPlayOutUpdateAttributes.AttributeSnapshot.class, MinecraftReflection.getAttributeSnapshotClass()); + assertEquals(PacketPlayOutUpdateAttributes.AttributeSnapshot.class, + MinecraftReflection.getAttributeSnapshotClass()); } @Test @@ -156,4 +145,15 @@ public class MinecraftReflectionTest { // this class is package-private in PacketPlayInUseEntity, so we can only check if no exception is thrown during retrieval MinecraftReflection.getEnumEntityUseActionClass(); } + + // Mocking objects + private interface FakeEntity { + + Entity getBukkitEntity(); + } + + private interface FakeBlock { + + Block getBukkitEntity(); + } } diff --git a/src/test/java/com/comphenix/protocol/utility/SnapshotVersionTest.java b/src/test/java/com/comphenix/protocol/utility/SnapshotVersionTest.java index 226e45a7..d06dc1c9 100644 --- a/src/test/java/com/comphenix/protocol/utility/SnapshotVersionTest.java +++ b/src/test/java/com/comphenix/protocol/utility/SnapshotVersionTest.java @@ -1,37 +1,38 @@ package com.comphenix.protocol.utility; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Calendar; import java.util.Date; import java.util.Locale; - -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SnapshotVersionTest { + @Test public void testDates() { SnapshotVersion a = new SnapshotVersion("12w50b"); SnapshotVersion b = new SnapshotVersion("13w05a"); - - expect(a.getSnapshotDate(), 12, 50); - expect(b.getSnapshotDate(), 13, 5); - + + this.expect(a.getSnapshotDate(), 12, 50); + this.expect(b.getSnapshotDate(), 13, 5); + // Test equality assertEquals(a, new SnapshotVersion("12w50b")); } - - @Test(expected=IllegalArgumentException.class) + + @Test public void testDateParsingProblem() { // This date is not valid - new SnapshotVersion("12w80a"); + assertThrows(IllegalArgumentException.class, () -> new SnapshotVersion("12w80a")); } - - @Test(expected=IllegalArgumentException.class) + + @Test public void testMissingWeekVersion() { - new SnapshotVersion("13w05"); + assertThrows(IllegalArgumentException.class, () -> new SnapshotVersion("13w05")); } - + private void expect(Date date, int year, int week) { Calendar calendar = Calendar.getInstance(Locale.US); calendar.setTime(date); diff --git a/src/test/java/com/comphenix/protocol/utility/StreamSerializerTest.java b/src/test/java/com/comphenix/protocol/utility/StreamSerializerTest.java index 9ff6eb86..576a0e54 100644 --- a/src/test/java/com/comphenix/protocol/utility/StreamSerializerTest.java +++ b/src/test/java/com/comphenix/protocol/utility/StreamSerializerTest.java @@ -1,38 +1,30 @@ package com.comphenix.protocol.utility; +import static com.comphenix.protocol.utility.TestUtils.assertItemsEqual; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.wrappers.nbt.NbtCompound; import com.comphenix.protocol.wrappers.nbt.NbtFactory; - +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -import java.io.*; - -import static com.comphenix.protocol.utility.TestUtils.assertItemsEqual; -import static org.junit.Assert.assertEquals; - -@RunWith(org.powermock.modules.junit4.PowerMockRunner.class) -@PowerMockIgnore({ "org.apache.logging.log4j.core.config.xml.*", "org.bukkit.craftbukkit.libs.jline.*" }) -//@PrepareForTest(CraftItemFactory.class) public class StreamSerializerTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } - /*@Test - public void testMinecraftReflection() { - assertEquals(IntHashMap.class, MinecraftReflection.getIntHashMapClass()); - }*/ - @Test public void testStrings() throws IOException { StreamSerializer serializer = new StreamSerializer(); diff --git a/src/test/java/com/comphenix/protocol/utility/TestUtils.java b/src/test/java/com/comphenix/protocol/utility/TestUtils.java index b4e10656..12359ba2 100644 --- a/src/test/java/com/comphenix/protocol/utility/TestUtils.java +++ b/src/test/java/com/comphenix/protocol/utility/TestUtils.java @@ -1,15 +1,16 @@ package com.comphenix.protocol.utility; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.comphenix.protocol.reflect.accessors.Accessors; import java.lang.reflect.Field; import java.util.List; - -import sun.misc.Unsafe; import org.bukkit.Bukkit; import org.bukkit.inventory.ItemStack; -import static org.junit.Assert.*; -import static org.junit.Assert.assertEquals; - public class TestUtils { public static void assertItemCollectionsEqual(List first, List second) { @@ -45,12 +46,7 @@ public class TestUtils { } } - public static void setFinalField(Object obj, Field field, Object newValue) throws ReflectiveOperationException { - Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe"); - unsafeField.setAccessible(true); - Unsafe unsafe = (Unsafe) unsafeField.get(null); - - long offset = unsafe.objectFieldOffset(field); - unsafe.putObject(obj, offset, newValue); + public static void setFinalField(Object obj, Field field, Object newValue) { + Accessors.getFieldAccessor(field, true).set(obj, newValue); } } diff --git a/src/test/java/com/comphenix/protocol/wrappers/AutoWrapperTest.java b/src/test/java/com/comphenix/protocol/wrappers/AutoWrapperTest.java index 614c5ec3..f1d48021 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/AutoWrapperTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/AutoWrapperTest.java @@ -1,10 +1,10 @@ package com.comphenix.protocol.wrappers; import static com.comphenix.protocol.utility.MinecraftReflection.getMinecraftClass; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; import com.comphenix.protocol.BukkitInitialization; import net.minecraft.advancements.AdvancementDisplay; @@ -13,12 +13,12 @@ import net.minecraft.network.chat.ChatComponentText; import net.minecraft.world.item.Items; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class AutoWrapperTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { BukkitInitialization.initializeAll(); } diff --git a/src/test/java/com/comphenix/protocol/wrappers/BukkitConvertersTest.java b/src/test/java/com/comphenix/protocol/wrappers/BukkitConvertersTest.java index a52cc044..a978a49c 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/BukkitConvertersTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/BukkitConvertersTest.java @@ -1,25 +1,24 @@ package com.comphenix.protocol.wrappers; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.reflect.EquivalentConverter; - import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.junit.BeforeClass; -import org.junit.Test; - -import static com.comphenix.protocol.utility.TestUtils.assertItemsEqual; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class BukkitConvertersTest { - @BeforeClass + + @BeforeAll public static void beforeClass() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } @Test diff --git a/src/test/java/com/comphenix/protocol/wrappers/ChunkCoordIntPairTest.java b/src/test/java/com/comphenix/protocol/wrappers/ChunkCoordIntPairTest.java index 39d25feb..9b6101ac 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/ChunkCoordIntPairTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/ChunkCoordIntPairTest.java @@ -1,17 +1,16 @@ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class ChunkCoordIntPairTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } @Test @@ -23,8 +22,8 @@ public class ChunkCoordIntPairTest { assertEquals(2, specific.getChunkZ()); net.minecraft.world.level.ChunkCoordIntPair roundtrip = - (net.minecraft.world.level.ChunkCoordIntPair) ChunkCoordIntPair.getConverter(). - getGeneric(specific); + (net.minecraft.world.level.ChunkCoordIntPair) ChunkCoordIntPair.getConverter(). + getGeneric(specific); assertEquals(1, roundtrip.c); assertEquals(2, roundtrip.d); diff --git a/src/test/java/com/comphenix/protocol/wrappers/CloningTest.java b/src/test/java/com/comphenix/protocol/wrappers/CloningTest.java index bcf63336..248df0f7 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/CloningTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/CloningTest.java @@ -1,27 +1,26 @@ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.reflect.cloning.AggregateCloner; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class CloningTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } - + @Test public void cloneGameProfile() { WrappedGameProfile profile = new WrappedGameProfile("8817d9ec-72e6-4abe-a496-cda667c3efe1", "name"); WrappedGameProfile copy = WrappedGameProfile.fromHandle( - AggregateCloner.DEFAULT.clone(profile.getHandle()) + AggregateCloner.DEFAULT.clone(profile.getHandle()) ); - + assertEquals(profile, copy); } } diff --git a/src/test/java/com/comphenix/protocol/wrappers/EnumWrappersTest.java b/src/test/java/com/comphenix/protocol/wrappers/EnumWrappersTest.java index 40436484..cb9e2edb 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/EnumWrappersTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/EnumWrappersTest.java @@ -1,40 +1,31 @@ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; - -import com.google.common.collect.Sets; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.reflect.EquivalentConverter; import com.comphenix.protocol.reflect.accessors.Accessors; import com.comphenix.protocol.reflect.accessors.FieldAccessor; - +import com.google.common.collect.Sets; import java.util.Set; - import net.minecraft.network.EnumProtocol; import net.minecraft.network.protocol.game.PacketPlayInClientCommand.EnumClientCommand; -import net.minecraft.world.EnumHand; import net.minecraft.world.EnumDifficulty; +import net.minecraft.world.EnumHand; import net.minecraft.world.entity.player.EnumChatVisibility; import net.minecraft.world.level.EnumGamemode; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class EnumWrappersTest { - private static class EnumClass { - public EnumProtocol protocol; - public EnumClientCommand command; - public EnumChatVisibility visibility; - public EnumDifficulty difficulty; - public EnumHand hand; - // public EnumEntityUseAction action; // moved to PacketPlayInUseEntity but is private - public EnumGamemode mode; - } - @BeforeClass + private static final Set KNOWN_INVALID = Sets.newHashSet( + "Particle", "WorldBorderAction", "CombatEventType", "TitleAction" + ); + + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } @Test @@ -48,13 +39,13 @@ public class EnumWrappersTest { // obj.action = EnumEntityUseAction.INTERACT; obj.mode = EnumGamemode.e; - assertEquals(obj.protocol, roundtrip(obj, "protocol", EnumWrappers.getProtocolConverter()) ); - assertEquals(obj.command, roundtrip(obj, "command", EnumWrappers.getClientCommandConverter()) ); - assertEquals(obj.visibility, roundtrip(obj, "visibility", EnumWrappers.getChatVisibilityConverter()) ); - assertEquals(obj.difficulty, roundtrip(obj, "difficulty", EnumWrappers.getDifficultyConverter()) ); - assertEquals(obj.hand, roundtrip(obj, "hand", EnumWrappers.getHandConverter()) ); + assertEquals(obj.protocol, this.roundtrip(obj, "protocol", EnumWrappers.getProtocolConverter())); + assertEquals(obj.command, this.roundtrip(obj, "command", EnumWrappers.getClientCommandConverter())); + assertEquals(obj.visibility, this.roundtrip(obj, "visibility", EnumWrappers.getChatVisibilityConverter())); + assertEquals(obj.difficulty, this.roundtrip(obj, "difficulty", EnumWrappers.getDifficultyConverter())); + assertEquals(obj.hand, this.roundtrip(obj, "hand", EnumWrappers.getHandConverter())); // assertEquals(obj.action, roundtrip(obj, "action", EnumWrappers.getEntityUseActionConverter()) ); - assertEquals(obj.mode, roundtrip(obj, "mode", EnumWrappers.getGameModeConverter()) ); + assertEquals(obj.mode, this.roundtrip(obj, "mode", EnumWrappers.getGameModeConverter())); } @SuppressWarnings("unchecked") @@ -62,16 +53,23 @@ public class EnumWrappersTest { FieldAccessor accessor = Accessors.getFieldAccessor(target.getClass(), fieldName, true); return (T) converter.getGeneric( - converter.getSpecific(accessor.get(target)) + converter.getSpecific(accessor.get(target)) ); } - private static final Set KNOWN_INVALID = Sets.newHashSet( - "Particle", "WorldBorderAction", "CombatEventType", "TitleAction" - ); - @Test public void testValidity() { assertEquals(EnumWrappers.INVALID, KNOWN_INVALID); } + + private static class EnumClass { + + public EnumProtocol protocol; + public EnumClientCommand command; + public EnumChatVisibility visibility; + public EnumDifficulty difficulty; + public EnumHand hand; + // public EnumEntityUseAction action; // moved to PacketPlayInUseEntity but is private + public EnumGamemode mode; + } } diff --git a/src/test/java/com/comphenix/protocol/wrappers/MultiBlockChangeTest.java b/src/test/java/com/comphenix/protocol/wrappers/MultiBlockChangeTest.java index 92e74d82..4c79fcac 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/MultiBlockChangeTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/MultiBlockChangeTest.java @@ -1,44 +1,35 @@ /** - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2015 dmulloy2 - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA + * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. Copyright (C) 2015 dmulloy2 + *

+ * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later + * version. + *

+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + *

+ * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; - -import org.bukkit.Location; -import org.bukkit.Material; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.reflect.EquivalentConverter; import com.comphenix.protocol.utility.MinecraftReflection; +import org.bukkit.Location; +import org.bukkit.Material; /** * @author dmulloy2 */ -@RunWith(org.powermock.modules.junit4.PowerMockRunner.class) -@PowerMockIgnore({ "org.apache.logging.log4j.core.config.xml.*", "javax.management.*" }) public class MultiBlockChangeTest { - // @BeforeClass + // @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } // @Test @@ -55,7 +46,7 @@ public class MultiBlockChangeTest { // Make sure the location is correct assertEquals(loc, info.getLocation(null)); - MultiBlockChangeInfo[] array = { info, info }; + MultiBlockChangeInfo[] array = {info, info}; EquivalentConverter converter = Converters.array( MinecraftReflection.getMultiBlockChangeInfoClass(), diff --git a/src/test/java/com/comphenix/protocol/wrappers/PlayerInfoDataTest.java b/src/test/java/com/comphenix/protocol/wrappers/PlayerInfoDataTest.java index a5bc63a1..ba7c8b5a 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/PlayerInfoDataTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/PlayerInfoDataTest.java @@ -1,40 +1,35 @@ /** - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2015 dmulloy2 - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA + * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. Copyright (C) 2015 dmulloy2 + *

+ * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later + * version. + *

+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + *

+ * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; - -import java.util.UUID; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; -import com.comphenix.protocol.utility.MinecraftReflection; import com.comphenix.protocol.wrappers.EnumWrappers.NativeGameMode; +import java.util.UUID; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author dmulloy2 */ public class PlayerInfoDataTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } @Test diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedAttributeTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedAttributeTest.java index 7ae44a98..fcc0c9dd 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedAttributeTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/WrappedAttributeTest.java @@ -1,93 +1,92 @@ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedAttributeModifier.Operation; import com.google.common.collect.Lists; - +import java.util.List; import net.minecraft.core.IRegistry; import net.minecraft.network.protocol.game.PacketPlayOutUpdateAttributes.AttributeSnapshot; +import net.minecraft.resources.MinecraftKey; import net.minecraft.world.entity.ai.attributes.AttributeBase; import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import net.minecraft.resources.MinecraftKey; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class WrappedAttributeTest { + private WrappedAttributeModifier doubleModifier; private WrappedAttributeModifier constantModifier; private WrappedAttribute attribute; - - @BeforeClass + + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } - @Before + @BeforeEach public void setUp() { // Create a couple of modifiers - doubleModifier = - WrappedAttributeModifier.newBuilder(). - name("Double Damage"). - amount(1). - operation(Operation.ADD_PERCENTAGE). - build(); - constantModifier = - WrappedAttributeModifier.newBuilder(). - name("Damage Bonus"). - amount(5). - operation(Operation.ADD_NUMBER). - build(); + this.doubleModifier = + WrappedAttributeModifier.newBuilder(). + name("Double Damage"). + amount(1). + operation(Operation.ADD_PERCENTAGE). + build(); + this.constantModifier = + WrappedAttributeModifier.newBuilder(). + name("Damage Bonus"). + amount(5). + operation(Operation.ADD_NUMBER). + build(); // Create attribute - attribute = WrappedAttribute.newBuilder(). + this.attribute = WrappedAttribute.newBuilder(). attributeKey("generic.attackDamage"). baseValue(2). packet(new PacketContainer(PacketType.Play.Server.UPDATE_ATTRIBUTES)). - modifiers(Lists.newArrayList(constantModifier, doubleModifier)). + modifiers(Lists.newArrayList(this.constantModifier, this.doubleModifier)). build(); } - + @Test public void testEquality() { // Check wrapped equality - assertEquals(doubleModifier, doubleModifier); - assertNotSame(constantModifier, doubleModifier); - - assertEquals(doubleModifier.getHandle(), getModifierCopy(doubleModifier)); - assertEquals(constantModifier.getHandle(), getModifierCopy(constantModifier)); + assertEquals(this.doubleModifier, this.doubleModifier); + assertNotSame(this.constantModifier, this.doubleModifier); + + assertEquals(this.doubleModifier.getHandle(), this.getModifierCopy(this.doubleModifier)); + assertEquals(this.constantModifier.getHandle(), this.getModifierCopy(this.constantModifier)); } - + @Test public void testAttribute() { - assertEquals(attribute, WrappedAttribute.fromHandle(getAttributeCopy(attribute))); - - assertTrue(attribute.hasModifier(doubleModifier.getUUID())); - assertTrue(attribute.hasModifier(constantModifier.getUUID())); + assertEquals(this.attribute, WrappedAttribute.fromHandle(this.getAttributeCopy(this.attribute))); + + assertTrue(this.attribute.hasModifier(this.doubleModifier.getUUID())); + assertTrue(this.attribute.hasModifier(this.constantModifier.getUUID())); } @Test public void testFromTemplate() { - assertEquals(attribute, WrappedAttribute.newBuilder(attribute).build()); + assertEquals(this.attribute, WrappedAttribute.newBuilder(this.attribute).build()); } - + /** * Retrieve the equivalent NMS attribute. + * * @param attribute - the wrapped attribute. * @return The equivalent NMS attribute. */ private AttributeSnapshot getAttributeCopy(WrappedAttribute attribute) { List modifiers = Lists.newArrayList(); - + for (WrappedAttributeModifier wrapper : attribute.getModifiers()) { modifiers.add((AttributeModifier) wrapper.getHandle()); } diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedBlockDataTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedBlockDataTest.java index 2a5265da..95ff6b1c 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedBlockDataTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/WrappedBlockDataTest.java @@ -1,35 +1,31 @@ /** - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2015 dmulloy2 - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA + * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. Copyright (C) 2015 dmulloy2 + *

+ * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later + * version. + *

+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + *

+ * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.comphenix.protocol.wrappers; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.comphenix.protocol.BukkitInitialization; - import net.minecraft.world.level.block.state.IBlockData; - import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.block.data.type.GlassPane; import org.bukkit.craftbukkit.v1_18_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_18_R1.block.impl.CraftStainedGlassPane; import org.bukkit.craftbukkit.v1_18_R1.util.CraftMagicNumbers; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author dmulloy2 @@ -37,9 +33,9 @@ import static org.junit.Assert.assertEquals; public class WrappedBlockDataTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } @Test diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedChatComponentTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedChatComponentTest.java index b5e1233b..30d0847d 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedChatComponentTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/WrappedChatComponentTest.java @@ -1,20 +1,19 @@ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import com.comphenix.protocol.BukkitInitialization; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class WrappedChatComponentTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } - + @Test public void testText() { WrappedChatComponent test = WrappedChatComponent.fromText("Hello."); diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedDataWatcherTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedDataWatcherTest.java index 43289042..9784b67f 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedDataWatcherTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/WrappedDataWatcherTest.java @@ -1,46 +1,44 @@ /** - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2016 dmulloy2 - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA + * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. Copyright (C) 2016 dmulloy2 + *

+ * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later + * version. + *

+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + *

+ * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.comphenix.protocol.wrappers; -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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry; import com.comphenix.protocol.wrappers.WrappedDataWatcher.Serializer; import com.comphenix.protocol.wrappers.WrappedDataWatcher.WrappedDataWatcherObject; - +import java.util.UUID; import net.minecraft.world.entity.projectile.EntityEgg; - import org.bukkit.craftbukkit.v1_18_R1.entity.CraftEgg; import org.bukkit.craftbukkit.v1_18_R1.entity.CraftEntity; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author dmulloy2 */ - public class WrappedDataWatcherTest { - - @BeforeClass + + @BeforeAll public static void prepare() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } @Test diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedGameProfileTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedGameProfileTest.java index 766f0a0e..85d611e0 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedGameProfileTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/WrappedGameProfileTest.java @@ -1,11 +1,8 @@ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertEquals; - -import java.util.UUID; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.comphenix.protocol.BukkitInitialization; import com.google.common.base.Charsets; @@ -13,17 +10,21 @@ import com.google.common.collect.Multimap; import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; +import java.util.UUID; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class WrappedGameProfileTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } @Test public void testWrapper() { - GameProfile profile = new GameProfile(UUID.nameUUIDFromBytes("ProtocolLib".getBytes(Charsets.UTF_8)), "ProtocolLib"); + GameProfile profile = new GameProfile(UUID.nameUUIDFromBytes("ProtocolLib".getBytes(Charsets.UTF_8)), + "ProtocolLib"); WrappedGameProfile wrapper = WrappedGameProfile.fromHandle(profile); assertEquals(profile.getId(), wrapper.getUUID()); @@ -34,20 +35,21 @@ public class WrappedGameProfileTest { @SuppressWarnings("deprecation") public void testSkinUpdate() { final UUID uuid = UUID.nameUUIDFromBytes("123".getBytes(Charsets.UTF_8)); - - assertEquals(null, new WrappedGameProfile((String)null, "Test").getId()); + + assertNull(new WrappedGameProfile((String) null, "Test").getId()); assertEquals(uuid, new WrappedGameProfile("123", "Test").getUUID()); } - + @SuppressWarnings("deprecation") - @Test(expected = RuntimeException.class) + @Test public void testNullFailure() { - new WrappedGameProfile((String)null, null); + assertThrows(RuntimeException.class, () -> new WrappedGameProfile((String) null, null)); } @Test public void testGetProperties() { - GameProfile profile = new GameProfile(UUID.nameUUIDFromBytes("ProtocolLib".getBytes(Charsets.UTF_8)), "ProtocolLib"); + GameProfile profile = new GameProfile(UUID.nameUUIDFromBytes("ProtocolLib".getBytes(Charsets.UTF_8)), + "ProtocolLib"); String name = "test"; String value = "test"; @@ -70,7 +72,8 @@ public class WrappedGameProfileTest { String value = "test"; String signature = null; - WrappedGameProfile wrapper = new WrappedGameProfile(UUID.nameUUIDFromBytes("ProtocolLib".getBytes(Charsets.UTF_8)), "ProtocolLib"); + WrappedGameProfile wrapper = new WrappedGameProfile(UUID.nameUUIDFromBytes("ProtocolLib".getBytes(Charsets.UTF_8)), + "ProtocolLib"); wrapper.getProperties().put(name, new WrappedSignedProperty(name, value, signature)); GameProfile profile = (GameProfile) wrapper.getHandle(); diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedIntHashMapTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedIntHashMapTest.java deleted file mode 100644 index 3719144d..00000000 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedIntHashMapTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.comphenix.protocol.wrappers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import org.junit.BeforeClass; -import org.junit.Test; - -import com.comphenix.protocol.BukkitInitialization; - -public class WrappedIntHashMapTest { - - //@BeforeClass - public static void initializeBukkit() { - BukkitInitialization.initializePackage(); - } - - //@Test - public void testIntMap() { - WrappedIntHashMap test = WrappedIntHashMap.newMap(); - test.put(1, "hello"); - - assertNull(test.get(0)); - assertEquals(test.get(1), "hello"); - } -} diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedParticleTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedParticleTest.java index a3ef2701..02ca84f5 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedParticleTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/WrappedParticleTest.java @@ -1,24 +1,24 @@ package com.comphenix.protocol.wrappers; +import static com.comphenix.protocol.utility.TestUtils.assertItemsEqual; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; - import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.Particle.DustOptions; import org.bukkit.inventory.ItemStack; -import org.junit.BeforeClass; -import org.junit.Test; - -import static com.comphenix.protocol.utility.TestUtils.assertItemsEqual; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class WrappedParticleTest { - @BeforeClass + + @BeforeAll public static void beforeClass() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } @Test diff --git a/src/test/java/com/comphenix/protocol/wrappers/WrappedServerPingTest.java b/src/test/java/com/comphenix/protocol/wrappers/WrappedServerPingTest.java index b2c02657..e9bd8df8 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/WrappedServerPingTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/WrappedServerPingTest.java @@ -1,22 +1,21 @@ package com.comphenix.protocol.wrappers; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.wrappers.WrappedServerPing.CompressedImage; import com.google.common.io.Resources; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; public class WrappedServerPingTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } @Test @@ -47,8 +46,7 @@ public class WrappedServerPingTest { // There was a global package seal for a while, but not anymore System.err.println("Encountered a SecurityException, update your Spigot jar!"); } else { - ex.printStackTrace(); - fail("Encountered an exception testing ServerPing"); + fail("Encountered an exception testing ServerPing", ex); } } } diff --git a/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtCompoundTest.java b/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtCompoundTest.java index a06a5256..120ab2f8 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtCompoundTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtCompoundTest.java @@ -2,75 +2,75 @@ * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * You should have received a copy of the GNU General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ package com.comphenix.protocol.wrappers.nbt; -import static org.junit.Assert.assertEquals; - -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class NbtCompoundTest { - @BeforeClass + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } - + @Test public void testCustomTags() { NbtCustomTag test = new NbtCustomTag("hello", 12); WrappedCompound map = WrappedCompound.fromName("test"); map.put(test); - + // Note that the custom tag will be cloned assertEquals(12, map.getInteger("hello")); } - + /** * Represents a custom NBT tag. - * - * @author Kristian * * @param - the value of the tag. + * @author Kristian */ public static class NbtCustomTag implements NbtBase { + private String name; private TValue value; - private NbtType type; - + private final NbtType type; + public NbtCustomTag(String name, TValue value) { - if (value == null) + if (value == null) { throw new IllegalArgumentException("Cannot create a custom tag from NULL."); + } this.value = value; this.name = name; this.type = NbtType.getTypeFromClass(value.getClass()); - + } @Override public NbtType getType() { - return type; + return this.type; } @Override public String getName() { - return name; + return this.name; } @Override @@ -80,7 +80,7 @@ public class NbtCompoundTest { @Override public TValue getValue() { - return value; + return this.value; } @Override @@ -90,12 +90,12 @@ public class NbtCompoundTest { @Override public NbtBase deepClone() { - return new NbtCustomTag(name, value); + return new NbtCustomTag(this.name, this.value); } @Override public boolean accept(NbtVisitor visitor) { return visitor.visit(this); - } + } } } diff --git a/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtFactoryTest.java b/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtFactoryTest.java index d96e3c0f..d5e2ccd7 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtFactoryTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/nbt/NbtFactoryTest.java @@ -17,51 +17,35 @@ package com.comphenix.protocol.wrappers.nbt; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import com.comphenix.protocol.BukkitInitialization; +import com.comphenix.protocol.utility.MinecraftReflection; +import com.comphenix.protocol.wrappers.nbt.io.NbtBinarySerializer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; -import java.lang.reflect.Constructor; -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; - -import com.comphenix.protocol.BukkitInitialization; -import com.comphenix.protocol.reflect.FuzzyReflection; -import com.comphenix.protocol.reflect.fuzzy.FuzzyMethodContract; -import com.comphenix.protocol.reflect.instances.DefaultInstances; -import com.comphenix.protocol.utility.Constants; -import com.comphenix.protocol.utility.MinecraftReflection; -import com.comphenix.protocol.utility.MinecraftVersion; -import com.comphenix.protocol.wrappers.nbt.io.NbtBinarySerializer; - import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -@RunWith(org.powermock.modules.junit4.PowerMockRunner.class) -@PowerMockIgnore({ "org.apache.logging.log4j.core.config.xml.*", "javax.management.*" }) -//@PrepareForTest(CraftItemFactory.class) public class NbtFactoryTest { - @BeforeClass + + @BeforeAll public static void initializeBukkit() throws IllegalAccessException { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } - + @Test public void testFromStream() { WrappedCompound compound = WrappedCompound.fromName("tag"); compound.put("name", "Test Testerson"); compound.put("age", 42); - + compound.put(NbtFactory.ofList("nicknames", "a", "b", "c")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); @@ -70,9 +54,9 @@ public class NbtFactoryTest { ByteArrayInputStream source = new ByteArrayInputStream(buffer.toByteArray()); DataInput input = new DataInputStream(source); - + NbtCompound cloned = NbtBinarySerializer.DEFAULT.deserializeCompound(input); - + assertEquals(compound.getString("name"), cloned.getString("name")); assertEquals(compound.getInteger("age"), cloned.getInteger("age")); assertEquals(compound.getList("nicknames"), cloned.getList("nicknames")); @@ -82,13 +66,13 @@ public class NbtFactoryTest { public void testItemTag() { ItemStack test = new ItemStack(Items.L); org.bukkit.inventory.ItemStack craftTest = MinecraftReflection.getBukkitItemStack(test); - + NbtCompound compound = NbtFactory.ofCompound("tag"); compound.put("name", "Test Testerson"); compound.put("age", 42); - + NbtFactory.setItemTag(craftTest, compound); - + assertEquals(compound, NbtFactory.fromItemTag(craftTest)); } diff --git a/src/test/java/com/comphenix/protocol/wrappers/nbt/TileEntityTest.java b/src/test/java/com/comphenix/protocol/wrappers/nbt/TileEntityTest.java index bf2f3961..86514ddc 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/nbt/TileEntityTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/nbt/TileEntityTest.java @@ -1,35 +1,32 @@ /** - * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. - * Copyright (C) 2016 dmulloy2 - * - * This program is free software; you can redistribute it and/or modify it under the terms of the - * GNU General Public License as published by the Free Software Foundation; either version 2 of - * the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA - * 02111-1307 USA + * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. Copyright (C) 2016 dmulloy2 + *

+ * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later + * version. + *

+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + *

+ * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free + * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.comphenix.protocol.wrappers.nbt; -import org.bukkit.block.BlockState; -import org.junit.BeforeClass; -import org.junit.Test; - import com.comphenix.protocol.BukkitInitialization; +import org.bukkit.block.BlockState; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * @author dmulloy2 */ public class TileEntityTest { - @BeforeClass + @BeforeAll public static void beforeClass() { - BukkitInitialization.initializePackage(); + BukkitInitialization.initializeAll(); } @Test diff --git a/src/test/java/com/comphenix/protocol/wrappers/nbt/io/NbtConfigurationSerializerTest.java b/src/test/java/com/comphenix/protocol/wrappers/nbt/io/NbtConfigurationSerializerTest.java index 590cdd83..60c6d81c 100644 --- a/src/test/java/com/comphenix/protocol/wrappers/nbt/io/NbtConfigurationSerializerTest.java +++ b/src/test/java/com/comphenix/protocol/wrappers/nbt/io/NbtConfigurationSerializerTest.java @@ -1,20 +1,19 @@ package com.comphenix.protocol.wrappers.nbt.io; -import static org.junit.Assert.assertEquals; - -import org.bukkit.configuration.file.YamlConfiguration; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.comphenix.protocol.BukkitInitialization; import com.comphenix.protocol.wrappers.nbt.NbtCompound; import com.comphenix.protocol.wrappers.nbt.NbtFactory; +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class NbtConfigurationSerializerTest { - - @BeforeClass + + @BeforeAll public static void initializeBukkit() { - BukkitInitialization.initializeItemMeta(); + BukkitInitialization.initializeAll(); } @Test @@ -22,16 +21,16 @@ public class NbtConfigurationSerializerTest { NbtCompound compound = NbtFactory.ofCompound("hello"); compound.put("age", (short) 30); compound.put("name", "test"); - compound.put("values", new int[] { 1, 2, 3 }); + compound.put("values", new int[]{1, 2, 3}); compound.put(NbtFactory.ofList("telephone", "12345678", "81549300")); - + compound.put(NbtFactory.ofList("lists", NbtFactory.ofList("", "a", "a", "b", "c"))); - + YamlConfiguration yaml = new YamlConfiguration(); NbtConfigurationSerializer.DEFAULT.serialize(compound, yaml); - + NbtCompound result = NbtConfigurationSerializer.DEFAULT.deserializeCompound(yaml, "hello"); - + assertEquals(compound, result); } } diff --git a/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 00000000..ca6ee9ce --- /dev/null +++ b/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file